diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc
index a56de95095..54c31b0a65 100644
--- a/.fallowrc.jsonc
+++ b/.fallowrc.jsonc
@@ -1,5 +1,8 @@
{
"$schema": "https://raw.githubusercontent.com/fallow-rs/fallow/main/config-schema.json",
+ // Resolve workspace exports as bun does, to their source: without it fallow took Studio's vite alias for
+ // @hyperframes/core/runtime-script in player source and reported a player -> studio package cycle.
+ "resolve": { "conditions": ["bun"] },
"entry": [
// IconButton, Tabs and cn are exported before their first consumer exists.
"packages/studio/src/components/ui/index.ts",
@@ -47,6 +50,8 @@
"packages/core/stubs/audio-fx-runtime-entry.ts",
// And for the SVG selector alias installer compiled scene scripts carry.
"packages/core/stubs/svg-selector-aliases-entry.ts",
+ // The player's cjs and iife builds alias @hyperframes/core/runtime-script to it in tsup.config.ts.
+ "packages/player/src/runtime-beside-bundle.ts",
// In-page audit scripts read as raw strings and injected via
// page.addScriptTag (see layout.ts / validate.ts) — referenced by file
// path, never imported, so they have no import-graph referrer.
diff --git a/.github/workflows/player-perf.yml b/.github/workflows/player-perf.yml
index a0e6cefa4d..1b5638e94c 100644
--- a/.github/workflows/player-perf.yml
+++ b/.github/workflows/player-perf.yml
@@ -129,6 +129,20 @@ jobs:
PUPPETEER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
run: bun run test:browser-security
+ - name: Verify a sealed film plays on a host with or without CORS (load shard only)
+ if: matrix.shard == 'load'
+ working-directory: packages/player
+ env:
+ PUPPETEER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
+ run: bun run test:browser-sealed-media
+
+ - name: Verify a sealed same-site film plays with the runtime the player ships (load shard only)
+ if: matrix.shard == 'load'
+ working-directory: packages/player
+ env:
+ PUPPETEER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
+ run: bun run test:browser-sealed-runtime
+
- name: Verify the preview rasters at its shown size (load shard only)
if: matrix.shard == 'load'
working-directory: packages/player
diff --git a/docs/developers/overview.mdx b/docs/developers/overview.mdx
index e240e327c3..ef4e2c6785 100644
--- a/docs/developers/overview.mdx
+++ b/docs/developers/overview.mdx
@@ -95,7 +95,7 @@ Start with the [SDK quickstart](/sdk/quickstart).
```html title="index.html"
-
+
+
${html}`).document;
}
-/** ASCII-only chunks bound match arrays; starting at uppercase preserves unchanged spans. */
-function lowerAscii(text: string): string {
- return text.replace(/[A-Z][\s\S]{0,65535}/g, (chunk) =>
- chunk.replace(/[A-Z]+/g, (letters) => letters.toLowerCase()),
- );
-}
-
-function startsWithLower(text: string, token: string, at: number): boolean {
- if (at < 0 || at + token.length > text.length) return false;
- for (let i = 0; i < token.length; i += 1) {
- const code = text.charCodeAt(at + i);
- if ((code >= 65 && code <= 90 ? code + 32 : code) !== token.charCodeAt(i)) return false;
- }
- return true;
-}
-
-function indexOfLower(text: string, token: string, from: number): number {
- for (
- let at = text.indexOf(token.charAt(0), from);
- at !== -1;
- at = text.indexOf(token.charAt(0), at + 1)
- ) {
- if (startsWithLower(text, token, at)) return at;
- }
- return -1;
-}
-
function lastIndexOfLower(text: string, token: string): number {
for (
let at = text.lastIndexOf(token.charAt(0));
@@ -225,38 +204,6 @@ function isHtmlWhitespace(char: string): boolean {
return char === " " || char === "\n" || char === "\t" || char === "\r" || char === "\f";
}
-export function escapeInlineScriptSource(source: string): string {
- return escapeCaseInsensitiveToken(
- escapeCaseInsensitiveToken(source, " `<\\/${match.slice(2)}`),
- "", comment + 4);
+ if (closed < 0) return null;
+ from = closed + 3;
+ continue;
+ }
const boundary = lower[index + prefix.length];
if (OPENING_TAG_BOUNDARIES.has(boundary)) {
const close = lower.indexOf(">", index + prefix.length);
@@ -56,8 +130,56 @@ function findOpeningTag(html: string, tagName: string): OpeningTag | null {
export function ensureRuntimeBeforeBodyScripts(html: string, runtimeUrl: string): string {
if (!html || alreadyHasRuntime(html, runtimeUrl)) return html;
+ return insertAtHeadStart(html, ``);
+}
- const tag = ``;
+/** The same placement with the runtime's own text, for a sealed frame: it then loads nothing from another origin. */
+export function inlineRuntimeBeforeBodyScripts(html: string, escapedSource: string): string {
+ if (!html || alreadyHasRuntime(html, null)) return html;
+ return insertAtHeadStart(html, ``);
+}
+
+/**
+ * A document fetched from `url` and shown as srcdoc still resolves its relative paths there. The first
+ * `` wins, so the page's own one is resolved against `url` and put first.
+ */
+export function withBaseHref(html: string, url: string): string {
+ return insertAtHeadStart(html, ``);
+}
+
+function baseOf(html: string, url: string): string {
+ for (let tag = findOpeningTag(html, "base"); tag; tag = findOpeningTag(html, "base", tag.end)) {
+ const href = /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(
+ html.slice(tag.index, tag.end),
+ );
+ if (!href) continue;
+ try {
+ return new URL(href[1] ?? href[2] ?? href[3] ?? "", url).href;
+ } catch {
+ return url;
+ }
+ }
+ return url;
+}
+
+/** The bytes of a fetched page as the browser would read them: the response's charset, else the page's own. */
+export function decodePage(bytes: ArrayBuffer, contentType: string | null): string {
+ const declared =
+ /charset=["']?([\w-]+)/i.exec(contentType ?? "")?.[1] ??
+ /]{0,200}charset=["']?([\w-]+)/i.exec(
+ new TextDecoder("latin1").decode(bytes.slice(0, 1024)),
+ )?.[1];
+ try {
+ return new TextDecoder(declared ?? "utf-8").decode(bytes);
+ } catch {
+ return new TextDecoder().decode(bytes);
+ }
+}
+
+const escapeAttr = (value: string): string =>
+ value.replace(/&/g, "&").replace(/"/g, """).replace(/ | undefined;
+
+export function sealedRuntimeSource(): Promise {
+ // esm: the bundler resolves this, else the file beside the module; cjs/iife alias it.
+ source ??= import("@hyperframes/core/runtime-script")
+ .then(
+ (runtime) => runtime.getHyperframeRuntimeScript(),
+ (error: unknown) =>
+ import.meta.url ? runtimeBeside(import.meta.url) : Promise.reject(error),
+ )
+ .then(escapeInlineScriptSource);
+ source.catch(() => (source = undefined));
+ return source;
+}
diff --git a/packages/player/src/sealedLateTimeline.test.ts b/packages/player/src/sealedLateTimeline.test.ts
index fd700aec47..b939deb786 100644
--- a/packages/player/src/sealedLateTimeline.test.ts
+++ b/packages/player/src/sealedLateTimeline.test.ts
@@ -1,8 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { loadLimitMs } from "./composition-probe.js";
+import { loadLimitMs, timelineNotFound } from "./composition-probe.js";
const LIMIT = loadLimitMs();
-const TIMED_OUT = `error Composition timeline not found after ${LIMIT / 1000}s`;
+const TIMED_OUT = `error ${timelineNotFound(LIMIT, true)}`;
type Player = HTMLElement & {
ready: boolean;
diff --git a/packages/player/src/sealedRuntime.test.ts b/packages/player/src/sealedRuntime.test.ts
new file mode 100644
index 0000000000..2588e7bd88
--- /dev/null
+++ b/packages/player/src/sealedRuntime.test.ts
@@ -0,0 +1,289 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { loadLimitMs, timelineNotFound } from "./composition-probe.js";
+
+const LIMIT = loadLimitMs();
+
+// The player's own runtime, standing in for core's 750 KB build. Its "" must not end the inlined script.
+const RUNTIME = 'window.__hyperframes = { built: "" };';
+vi.mock("@hyperframes/core/runtime-script", () => ({ getHyperframeRuntimeScript: () => RUNTIME }));
+
+type Player = HTMLElement & { iframeElement: HTMLIFrameElement };
+
+const page = (head = "", body = "") =>
+ `${head}${body}`;
+const sameSite = () => `${location.origin}/films/one/index.html?take=2`;
+
+/** A response from the player's own site, as fetch gives it: every header readable. */
+function siteResponse(body?: BodyInit | null, init?: ResponseInit, type: ResponseType = "basic") {
+ const response = new Response(body, init);
+ Object.defineProperty(response, "type", { value: type });
+ return response;
+}
+
+function player(attributes: Record): Player {
+ const el = document.createElement("hyperframes-player") as Player;
+ for (const [name, value] of Object.entries(attributes)) el.setAttribute(name, value);
+ document.body.appendChild(el);
+ return el;
+}
+
+const srcdocOf = async (el: Player) => {
+ await vi.waitFor(() => expect(el.iframeElement.getAttribute("srcdoc")).toBeTruthy());
+ return el.iframeElement.getAttribute("srcdoc")!;
+};
+
+describe("a sealed player brings its own runtime", () => {
+ let fetchMock: ReturnType;
+
+ beforeEach(async () => {
+ await import("./hyperframes-player.js");
+ fetchMock = vi.fn(async () => siteResponse(page()));
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ afterEach(() => {
+ document.body.replaceChildren();
+ vi.unstubAllGlobals();
+ });
+
+ it("shows a composition from its own site with the runtime inlined, resolving paths at its URL", async () => {
+ const el = player({ "sandbox-origin": "", src: sameSite() });
+ const doc = await srcdocOf(el);
+
+ expect(fetchMock).toHaveBeenCalledWith(sameSite(), { credentials: "same-origin" });
+ expect(doc).not.toContain("cdn.jsdelivr.net");
+ expect(doc).toContain('built: "<\\/script>"');
+ // Base first, then the runtime, both ahead of the composition's own script.
+ expect(doc.indexOf(``)).toBeGreaterThan(-1);
+ expect(doc.indexOf(" {
+ fetchMock.mockResolvedValueOnce(
+ siteResponse(page('')),
+ );
+ const el = player({ "sandbox-origin": "", src: sameSite() });
+
+ await vi.waitFor(() => expect(el.iframeElement.src).toBe(sameSite()));
+ expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
+ });
+
+ it("loads a preview that links the runtime by its marker, as Studio's does, by src", async () => {
+ fetchMock.mockResolvedValueOnce(
+ siteResponse(
+ page(''),
+ ),
+ );
+ const el = player({ "sandbox-origin": "", src: sameSite() });
+
+ await vi.waitFor(() => expect(el.iframeElement.src).toBe(sameSite()));
+ expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
+ });
+
+ it("still adds the runtime when a script only mentions Studio's marker", async () => {
+ for (const head of [
+ '',
+ '',
+ '',
+ '',
+ ]) {
+ fetchMock.mockResolvedValueOnce(siteResponse(page(head)));
+ expect(await srcdocOf(player({ "sandbox-origin": "", src: sameSite() }))).toContain("built:");
+ document.body.replaceChildren();
+ }
+ });
+
+ it("still adds the runtime when a page only compares or names it", async () => {
+ fetchMock.mockResolvedValueOnce(
+ siteResponse(
+ page(
+ "",
+ ),
+ ),
+ );
+ expect(await srcdocOf(player({ "sandbox-origin": "", src: sameSite() }))).toContain("built:");
+ });
+
+ it("resolves paths at the URL a redirect landed on", async () => {
+ const landed = `${location.origin}/films/one/`;
+ const response = siteResponse(page());
+ Object.defineProperty(response, "url", { value: landed });
+ fetchMock.mockResolvedValueOnce(response);
+ const doc = await srcdocOf(
+ player({ "sandbox-origin": "", src: `${location.origin}/films/one` }),
+ );
+
+ expect(doc).toContain(``);
+ });
+
+ it("resolves the composition's own relative base against its URL, ahead of it", async () => {
+ fetchMock.mockResolvedValueOnce(
+ siteResponse(page('')),
+ );
+ const doc = await srcdocOf(player({ "sandbox-origin": "", src: sameSite() }));
+
+ const ours = doc.indexOf(``);
+ expect(ours).toBeGreaterThan(-1);
+ expect(ours).toBeLessThan(doc.indexOf(''));
+ });
+
+ it("puts the runtime in the real head, not one named in a comment", async () => {
+ fetchMock.mockResolvedValueOnce(
+ siteResponse(""),
+ );
+ const doc = await srcdocOf(player({ "sandbox-origin": "", src: sameSite() }));
+
+ expect(doc.indexOf("built:")).toBeGreaterThan(doc.indexOf(""));
+ });
+
+ it("reads the page in the charset its response names", async () => {
+ const encode = (text: string) => [...new TextEncoder().encode(text)];
+ const [before, after] = page("", "caf\u00e9
").split("\u00e9");
+ const bytes = new Uint8Array([...encode(before!), 0xe9, ...encode(after!)]);
+ fetchMock.mockResolvedValueOnce(
+ siteResponse(bytes, { headers: { "content-type": "text/html; charset=windows-1252" } }),
+ );
+ expect(await srcdocOf(player({ "sandbox-origin": "", src: sameSite() }))).toContain("café");
+ });
+
+ it("carries the shader options a src would have carried in its query", async () => {
+ const doc = await srcdocOf(
+ player({ "sandbox-origin": "", "shader-capture-scale": "0.5", src: sameSite() }),
+ );
+
+ expect(doc).toContain('window.__HF_SHADER_CAPTURE_SCALE="0.5";');
+ });
+
+ it("inlines the runtime in a sealed srcdoc instead of linking the CDN", async () => {
+ const doc = await srcdocOf(player({ "sandbox-origin": "", srcdoc: page() }));
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(doc).not.toContain("cdn.jsdelivr.net");
+ expect(doc).toContain("built:");
+ });
+
+ it("loads a composition from another site as before", () => {
+ const el = player({ "sandbox-origin": "", src: "https://films.example/one.html" });
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(el.iframeElement.src).toBe("https://films.example/one.html");
+ expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
+ });
+
+ it("loads src as before when its own site refuses the fetch", async () => {
+ fetchMock.mockResolvedValueOnce(siteResponse("", { status: 404 }));
+ const el = player({ "sandbox-origin": "", src: sameSite() });
+
+ await vi.waitFor(() => expect(el.iframeElement.src).toBe(sameSite()));
+ expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
+ });
+
+ // fails without the fix: the page was shown as srcdoc, under the embedding page's policy instead of its own.
+ it("loads a page whose response sets its own security policy by src, under that policy", async () => {
+ for (const header of [
+ ["content-security-policy", "script-src 'self'"],
+ ["x-frame-options", "SAMEORIGIN"],
+ ] satisfies [string, string][]) {
+ fetchMock.mockResolvedValueOnce(siteResponse(page(), { headers: [header] }));
+ const el = player({ "sandbox-origin": "", src: sameSite() });
+
+ await vi.waitFor(() => expect(el.iframeElement.src).toBe(sameSite()));
+ expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
+ document.body.replaceChildren();
+ }
+ });
+
+ // fails without the fix: a redirect to another site that allows CORS hides that page's policy headers from
+ // the fetch, so the page was shown as srcdoc although its own policy could not be read.
+ it("loads by src when the page's headers can't all be read, as after a redirect to another site", async () => {
+ fetchMock.mockResolvedValueOnce(siteResponse(page(), {}, "cors"));
+ const el = player({ "sandbox-origin": "", src: sameSite() });
+
+ await vi.waitFor(() => expect(el.iframeElement.src).toBe(sameSite()));
+ expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
+ });
+
+ // fails without the fix: the load clock started only once the frame was written, so a fetch that never answered
+ // left a blank player with no error at all.
+ it("reports the load limit once while its own site's fetch is still pending", async () => {
+ vi.useFakeTimers();
+ try {
+ let answer: (response: Response) => void = () => {};
+ fetchMock.mockReturnValueOnce(new Promise((resolve) => (answer = resolve)));
+ const el = player({ "sandbox-origin": "", src: sameSite() });
+ const errors: string[] = [];
+ el.addEventListener("error", (event: Event) =>
+ errors.push((event as CustomEvent<{ message: string }>).detail.message),
+ );
+
+ await vi.advanceTimersByTimeAsync(LIMIT - 1);
+ expect(errors).toEqual([]);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(errors).toEqual([timelineNotFound(LIMIT, true)]);
+
+ answer(siteResponse(page()));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(el.iframeElement.getAttribute("srcdoc")).toContain("built:");
+ await vi.advanceTimersByTimeAsync(LIMIT);
+ expect(errors).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("shows nothing from a fetch that answers after the player moved to another composition", async () => {
+ let answer: (response: Response) => void = () => {};
+ fetchMock.mockReturnValueOnce(new Promise((resolve) => (answer = resolve)));
+ const el = player({ "sandbox-origin": "", src: sameSite() });
+ el.setAttribute("src", "https://films.example/two.html");
+ answer(siteResponse(page()));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(el.iframeElement.src).toBe("https://films.example/two.html");
+ expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
+ });
+
+ it("hands a src that is not a URL to the frame as before, without throwing", () => {
+ const el = player({ "sandbox-origin": "", src: "http://[not a host" });
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(el.iframeElement.getAttribute("src")).toContain("[not a host");
+ });
+
+ it("unloads a sealed composition when the player switches to a video", async () => {
+ const el = player({ "sandbox-origin": "", src: sameSite() });
+ await srcdocOf(el);
+ el.setAttribute("type", "video/mp4");
+ el.setAttribute("src", `${location.origin}/clip.mp4`);
+
+ expect(el.iframeElement.hasAttribute("srcdoc")).toBe(false);
+ });
+
+ // fails without the fix: the pending fetch's load limit still fired, over the playing video.
+ it("reports no load limit after a player waiting on its own site's fetch switches to a video", async () => {
+ vi.useFakeTimers();
+ try {
+ fetchMock.mockReturnValueOnce(new Promise(() => {}));
+ const el = player({ "sandbox-origin": "", src: sameSite() });
+ const errors: string[] = [];
+ el.addEventListener("error", (event: Event) =>
+ errors.push((event as CustomEvent<{ message: string }>).detail.message),
+ );
+ el.setAttribute("type", "video/mp4");
+ el.setAttribute("src", `${location.origin}/clip.mp4`);
+
+ await vi.advanceTimersByTimeAsync(LIMIT);
+ expect(errors).toEqual([]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("leaves an unsealed player's src load as it was", () => {
+ const el = player({ src: sameSite() });
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(el.iframeElement.src).toBe(sameSite());
+ });
+});
diff --git a/packages/player/src/sealedRuntimeFailure.test.ts b/packages/player/src/sealedRuntimeFailure.test.ts
new file mode 100644
index 0000000000..0067081922
--- /dev/null
+++ b/packages/player/src/sealedRuntimeFailure.test.ts
@@ -0,0 +1,51 @@
+import { afterEach, expect, it, vi } from "vitest";
+
+vi.mock("@hyperframes/core/runtime-script", () => ({
+ getHyperframeRuntimeScript: () => {
+ throw new Error("chunk missing");
+ },
+}));
+
+afterEach(() => {
+ document.body.replaceChildren();
+ vi.unstubAllGlobals();
+});
+
+it("names a runtime that failed to load instead of showing a sealed frame that never plays", async () => {
+ await import("./hyperframes-player.js");
+ const el = document.createElement("hyperframes-player");
+ el.setAttribute("sandbox-origin", "");
+ el.setAttribute("srcdoc", "");
+ const errors: string[] = [];
+ el.addEventListener("error", (event: Event) =>
+ errors.push((event as CustomEvent<{ message: string }>).detail.message),
+ );
+ document.body.appendChild(el);
+
+ await vi.waitFor(() =>
+ expect(errors).toEqual(["The HyperFrames runtime this player ships with failed to load"]),
+ );
+});
+
+it("names it on a same-site src too, instead of loading the bare src", async () => {
+ await import("./hyperframes-player.js");
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response("")),
+ );
+ const el = document.createElement("hyperframes-player") as HTMLElement & {
+ iframeElement: HTMLIFrameElement;
+ };
+ el.setAttribute("sandbox-origin", "");
+ el.setAttribute("src", `${location.origin}/films/one/index.html`);
+ const errors: string[] = [];
+ el.addEventListener("error", (event: Event) =>
+ errors.push((event as CustomEvent<{ message: string }>).detail.message),
+ );
+ document.body.appendChild(el);
+
+ await vi.waitFor(() =>
+ expect(errors).toEqual(["The HyperFrames runtime this player ships with failed to load"]),
+ );
+ expect(el.iframeElement.getAttribute("src")).toBeNull();
+});
diff --git a/packages/player/src/sealedStaticComposition.test.ts b/packages/player/src/sealedStaticComposition.test.ts
index 80641b2518..467844d31e 100644
--- a/packages/player/src/sealedStaticComposition.test.ts
+++ b/packages/player/src/sealedStaticComposition.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { loadLimitMs } from "./composition-probe.js";
+import { loadLimitMs, timelineNotFound } from "./composition-probe.js";
const LIMIT = loadLimitMs();
@@ -77,7 +77,7 @@ describe("a sealed film whose runtime boots late", () => {
const { player, events, postStatic } = framedPlayer();
postStatic(over);
vi.advanceTimersByTime(LIMIT);
- expect(events).toEqual([`error Composition timeline not found after ${LIMIT / 1000}s`]);
+ expect(events).toEqual([`error ${timelineNotFound(LIMIT, true)}`]);
expect(player.ready).toBe(false);
});
@@ -85,7 +85,7 @@ describe("a sealed film whose runtime boots late", () => {
const { player, events, postStatic } = framedPlayer();
postStatic({}, window);
vi.advanceTimersByTime(LIMIT);
- expect(events).toEqual([`error Composition timeline not found after ${LIMIT / 1000}s`]);
+ expect(events).toEqual([`error ${timelineNotFound(LIMIT, true)}`]);
expect(player.ready).toBe(false);
});
diff --git a/packages/player/src/shader-options.test.ts b/packages/player/src/shader-options.test.ts
new file mode 100644
index 0000000000..ee75f452a4
--- /dev/null
+++ b/packages/player/src/shader-options.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import { getShaderModeFromElement, SHADER_LOADING_ATTR } from "./shader-options.js";
+
+const modeOf = (value: string | null) => {
+ const el = document.createElement("div");
+ if (value !== null) el.setAttribute(SHADER_LOADING_ATTR, value);
+ return getShaderModeFromElement(el);
+};
+
+describe("getShaderModeFromElement", () => {
+ it.each([
+ [null, "composition"],
+ ["", "composition"],
+ [" ", "composition"],
+ ["none", "none"],
+ [" OFF ", "none"],
+ ["false", "none"],
+ ["0", "none"],
+ ["player", "player"],
+ ["True", "player"],
+ ["1", "player"],
+ ["on", "player"],
+ ["composition", "composition"],
+ ["sometimes", "composition"],
+ ["constructor", "composition"],
+ ["__proto__", "composition"],
+ ])("reads %j as %s", (value, mode) => {
+ expect(modeOf(value)).toBe(mode);
+ });
+});
diff --git a/packages/player/src/shader-options.ts b/packages/player/src/shader-options.ts
index b7e6ca0a7f..5bcdd23306 100644
--- a/packages/player/src/shader-options.ts
+++ b/packages/player/src/shader-options.ts
@@ -4,7 +4,13 @@
* URLs and srcdoc HTML.
*/
-import { ensureRuntimeBeforeBodyScripts } from "./runtime-in-srcdoc.js";
+import {
+ carriesRuntime,
+ ensureRuntimeBeforeBodyScripts,
+ inlineRuntimeBeforeBodyScripts,
+ withBaseHref,
+} from "./runtime-in-srcdoc.js";
+import { sealedRuntimeSource } from "./sealed-runtime.js";
import { RUNTIME_CDN_URL } from "./runtime-url.js";
export const SHADER_CAPTURE_SCALE_ATTR = "shader-capture-scale";
@@ -42,26 +48,19 @@ function normalizeShaderCaptureScale(value: string | null): string | null {
return String(Math.min(1, Math.max(0.25, parsed)));
}
+const SHADER_LOADING_WORDS = new Map([
+ ["none", "none"],
+ ["false", "none"],
+ ["0", "none"],
+ ["off", "none"],
+ ["player", "player"],
+ ["true", "player"],
+ ["1", "player"],
+ ["on", "player"],
+]);
+
function normalizeShaderLoadingMode(value: string | null): ShaderLoadingMode {
- if (value === null || value.trim() === "") return "composition";
- const normalized = value.trim().toLowerCase();
- if (
- normalized === "none" ||
- normalized === "false" ||
- normalized === "0" ||
- normalized === "off"
- ) {
- return "none";
- }
- if (
- normalized === "player" ||
- normalized === "true" ||
- normalized === "1" ||
- normalized === "on"
- ) {
- return "player";
- }
- return "composition";
+ return SHADER_LOADING_WORDS.get(value?.trim().toLowerCase() ?? "") ?? "composition";
}
/** Drop one of our own keys from raw `a=1&b=2` pairs, matched by name so that
@@ -158,6 +157,34 @@ export function prepareSrcdocForElement(el: Element, srcdoc: string): string {
);
}
+/**
+ * `prepareSrcdocForElement` for a sealed frame, which the player cannot reach into after it loads:
+ * the runtime goes in as text, unless the embedder named its own `runtime-src`.
+ */
+export async function prepareSealedSrcdocForElement(
+ el: Element,
+ html: string,
+ base?: string,
+): Promise {
+ const doc =
+ runtimeSrcFromElement(el) !== RUNTIME_CDN_URL
+ ? prepareSrcdocForElement(el, html)
+ : await withSealedRuntime(
+ injectShaderOptionsIntoSrcdoc(
+ html,
+ normalizeShaderCaptureScale(el.getAttribute(SHADER_CAPTURE_SCALE_ATTR)),
+ getShaderModeFromElement(el),
+ ),
+ );
+ return base ? withBaseHref(doc, base) : doc;
+}
+
+async function withSealedRuntime(page: string): Promise {
+ return carriesRuntime(page)
+ ? page
+ : inlineRuntimeBeforeBodyScripts(page, await sealedRuntimeSource());
+}
+
export function runtimeSrcFromElement(el: Element): string {
const configured = el.getAttribute(RUNTIME_SRC_ATTR)?.trim();
if (!configured) return RUNTIME_CDN_URL;
diff --git a/packages/player/tests/browser/sandbox-origin.ts b/packages/player/tests/browser/sandbox-origin.ts
index 45cd932689..c645a84cf1 100644
--- a/packages/player/tests/browser/sandbox-origin.ts
+++ b/packages/player/tests/browser/sandbox-origin.ts
@@ -47,6 +47,69 @@ try {
true,
"removing the policy must reload into the documented trusted mode",
);
+ // A sealed player adds the runtime to a composition from its own site, so the missing-runtime
+ // error belongs to one from another origin (localhost against 127.0.0.1).
+ const direct = await browser.newPage();
+ await direct.goto(`${server.origin}/host.html?fixture=direct-timeline&sealed=1`, {
+ waitUntil: "domcontentloaded",
+ });
+ await direct.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
+ await direct.evaluate(
+ (url) => {
+ document.querySelector("hyperframes-player")!.setAttribute("src", url);
+ },
+ `${server.origin.replace("127.0.0.1", "localhost")}/fixtures/direct-timeline/index.html`,
+ );
+ // Linux's 30 s load limit, as on CI, plus slack.
+ await direct.waitForFunction(() => window.__playerError !== undefined, { timeout: 36_000 });
+ const sealedError = String(await direct.evaluate(() => window.__playerError));
+ assert.match(
+ sealedError,
+ /include the runtime script/,
+ "a sealed timeout must name the runtime script",
+ );
+ assert.match(sealedError, /without sandbox-origin/, "a sealed timeout must name the trusted way");
+
+ const elsewhere = await browser.newPage();
+ await elsewhere.goto(`${server.origin}/host.html?fixture=direct-timeline`, {
+ waitUntil: "domcontentloaded",
+ });
+ await elsewhere.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
+ await elsewhere.evaluate(
+ (url) => {
+ document.querySelector("hyperframes-player")!.setAttribute("src", url);
+ },
+ `${server.origin.replace("127.0.0.1", "localhost")}/fixtures/direct-timeline/index.html`,
+ );
+ // Linux's 30 s load limit, as on CI, plus slack.
+ await elsewhere.waitForFunction(() => window.__playerError !== undefined, { timeout: 36_000 });
+ assert.doesNotMatch(
+ String(await elsewhere.evaluate(() => window.__playerError)),
+ /sandbox-origin/,
+ "a default player with a composition on another origin is not told it is sealed",
+ );
+
+ const trusted = await browser.newPage();
+ await trusted.goto(`${server.origin}/host.html?fixture=direct-timeline`, {
+ waitUntil: "domcontentloaded",
+ });
+ await trusted.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
+ assert.equal(
+ await trusted.evaluate(() => window.__playerDuration),
+ 5,
+ "a default player must still add the runtime to a composition that has none",
+ );
+
+ const bundled = await browser.newPage();
+ await bundled.goto(`${server.origin}/host.html?fixture=direct-timeline-runtime&sealed=1`, {
+ waitUntil: "domcontentloaded",
+ });
+ await bundled.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
+ assert.equal(
+ await bundled.evaluate(() => window.__playerDuration),
+ 5,
+ "a sealed player must play a composition that brings the runtime script",
+ );
// fails without the fix: the old document's timeline, landing after a switch, made the new load skip its probe.
const switched = await browser.newPage();
@@ -70,21 +133,25 @@ try {
() => (window as { __lastTimeline?: unknown }).__lastTimeline !== undefined,
{ timeout: 15_000 },
);
- const lateError = await switched.evaluate(async () => {
- const w = window as { __lastTimeline?: unknown; __playerError?: string };
- const player = document.querySelector("hyperframes-player")!;
- const frame = player.shadowRoot!.querySelector("iframe")!;
- w.__playerError = undefined;
- player.setAttribute("src", "/fixtures/sandbox-probe/index.html");
- dispatchEvent(
- new MessageEvent("message", { data: w.__lastTimeline, source: frame.contentWindow }),
- );
- const started = performance.now();
- // Linux's 30 s load limit, as on CI, plus slack.
- while (performance.now() - started < 36_000 && w.__playerError === undefined)
- await new Promise((resolve) => setTimeout(resolve, 100));
- return w.__playerError ?? null;
- });
+ // From another origin, since a same-site film gets the runtime added.
+ const lateError = await switched.evaluate(
+ async (url) => {
+ const w = window as { __lastTimeline?: unknown; __playerError?: string };
+ const player = document.querySelector("hyperframes-player")!;
+ const frame = player.shadowRoot!.querySelector("iframe")!;
+ w.__playerError = undefined;
+ player.setAttribute("src", url);
+ dispatchEvent(
+ new MessageEvent("message", { data: w.__lastTimeline, source: frame.contentWindow }),
+ );
+ const started = performance.now();
+ // Linux's 30 s load limit, as on CI, plus slack.
+ while (performance.now() - started < 36_000 && w.__playerError === undefined)
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ return w.__playerError ?? null;
+ },
+ `${server.origin.replace("127.0.0.1", "localhost")}/fixtures/sandbox-probe/index.html`,
+ );
assert.ok(
lateError,
"a sealed player switched to a film with no runtime must fail, even after a late old timeline",
diff --git a/packages/player/tests/browser/sealed-audio.ts b/packages/player/tests/browser/sealed-audio.ts
index 72b2108c27..ad681d3ce7 100644
--- a/packages/player/tests/browser/sealed-audio.ts
+++ b/packages/player/tests/browser/sealed-audio.ts
@@ -6,9 +6,15 @@ import { startServer } from "../perf/server.js";
const server = startServer();
const browser = await launchBrowser({ autoplay: "gesture" });
-try {
+type Player = HTMLElement & {
+ play: () => void;
+ _audioOwner: string;
+ _parentMedia: { el: HTMLMediaElement }[];
+};
+
+async function copiesOf(fixture: string) {
const page = await browser.newPage();
- await page.goto(`${server.origin}/host.html?fixture=sealed-audio`, {
+ await page.goto(`${server.origin}/host.html?fixture=${fixture}`, {
waitUntil: "domcontentloaded",
});
await page.waitForFunction(() => window.__playerReady || window.__playerError, {
@@ -23,11 +29,6 @@ try {
await page.waitForFunction(() => window.__playerReady || window.__playerError, {
timeout: 60_000,
});
- type Player = HTMLElement & {
- play: () => void;
- _audioOwner: string;
- _parentMedia: { el: HTMLMediaElement }[];
- };
await page.evaluate(() => (document.getElementById("player") as Player).play());
await page.waitForFunction(
() => (document.getElementById("player") as Player)._audioOwner === "parent",
@@ -36,11 +37,21 @@ try {
const copies = await page.evaluate(() =>
(document.getElementById("player") as Player)._parentMedia.map((m) => m.el.src),
);
+ await page.close();
+ return copies;
+}
+
+try {
assert.deepEqual(
- copies,
+ await copiesOf("sealed-audio"),
[`${server.origin}/fixtures/sealed-audio/tone.m4a`],
"a sealed player loaded by src copies its film's sound into the page when the frame may not start it",
);
+ assert.deepEqual(
+ await copiesOf("sealed-audio-bare"),
+ [`${server.origin}/fixtures/sealed-audio-bare/tone.m4a`],
+ "a film without the runtime, shown sealed as srcdoc, still has its sound copied once",
+ );
console.log("[sealed-audio] a refused sealed frame's sound plays from a copy in the page");
} finally {
await browser.close();
diff --git a/packages/player/tests/browser/sealed-media-table.ts b/packages/player/tests/browser/sealed-media-table.ts
new file mode 100644
index 0000000000..bc943318ee
--- /dev/null
+++ b/packages/player/tests/browser/sealed-media-table.ts
@@ -0,0 +1,1086 @@
+import assert from "node:assert/strict";
+
+import type { Frame } from "puppeteer-core";
+
+import { launchBrowser } from "../perf/runner.js";
+import { startServer } from "../perf/server.js";
+
+/**
+ * Seeded sequences of media edits, each run in the sealed film, in the sealed film with the CORS helper off (the
+ * control for source and playback), and in the film unsealed (the control for pixels).
+ */
+
+type Kind =
+ | "cors"
+ | "nocors"
+ | "unsupported"
+ | "missing"
+ | "flaky"
+ | "foreignCors"
+ | "foreignNocors"
+ | "foreignUnsupported"
+ | "foreignMissing"
+ | "unmatched"
+ | "down"
+ | "outage"
+ | "lapse"
+ | "lapseCors"
+ | "slowNocors";
+type Source = { id: string; kind: Kind; start?: number; delay?: number };
+type Step =
+ | { do: "create"; el: number; sources: Source[]; attr?: true }
+ | { do: "prepend" | "append"; el: number; source: Source }
+ | { do: "remove"; el: number; index: number }
+ | { do: "reverse" | "reload"; el: number }
+ | { do: "author"; el: number; value: string; duringRetry?: boolean; replace?: Source }
+ | { do: "play"; el: number; rate: number; pauseOnReject?: true }
+ | { do: "interrupt"; el: number; action: Interrupt; source?: Source }
+ | { do: "recover"; el: number; source: Source };
+// Interrupt: done by the composition right after the runtime's next load of that element, or at the round's end.
+// Recover: the source's host comes back (without CORS headers unless lapseCors), then the composition reloads el.
+type Interrupt = "pause" | "seek" | "seekPlaying" | "rate" | "source" | "author";
+type Sequence = { name: string; rounds: Step[][]; keepsCors?: number[]; upgradesAtMost?: number };
+
+const KINDS: Kind[] = [
+ "cors",
+ "nocors",
+ "unsupported",
+ "missing",
+ "flaky",
+ "foreignCors",
+ "foreignNocors",
+ "foreignUnsupported",
+ "foreignMissing",
+ "unmatched",
+ "down",
+ "lapse",
+ "lapseCors",
+ "slowNocors",
+];
+const PLAYABLE = new Set(["cors", "nocors", "slowNocors", "foreignCors", "foreignNocors"]);
+// A host that fails some requests plays only if a later selection asks it again, as in unsealed Studio.
+const MAY_PLAY = new Set([...PLAYABLE, "flaky", "outage", "lapse", "lapseCors"]);
+const SENDS_CORS = new Set(["cors", "foreignCors", "flaky", "outage", "lapseCors"]);
+const lapses = (kind: Kind) => kind === "lapse" || kind === "lapseCors";
+const NOT_SELECTABLE = new Set(["unsupported", "foreignUnsupported", "unmatched"]);
+const foreign = (kind: Kind) => kind.startsWith("foreign");
+// The accepted gap: a list whose selectable sources name another host is left as authored, so own media is not read.
+const mixed = (list: Source[]) => {
+ const selectable = list.filter((source) => !NOT_SELECTABLE.has(source.kind));
+ return selectable.some((x) => foreign(x.kind)) && selectable.some((x) => !foreign(x.kind));
+};
+
+function mulberry32(seed: number) {
+ return () => {
+ seed = (seed + 0x6d2b79f5) | 0;
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+function generated(seed: number): Sequence {
+ const random = mulberry32(seed);
+ const pick = (list: readonly T[]) => list[Math.floor(random() * list.length)]!;
+ const pool = Array.from({ length: 4 }, (_, k) => ({ id: `g${seed}-${k}`, kind: pick(KINDS) }));
+ const lists: Source[][] = [];
+ const rounds: Step[][] = [];
+ const elements = 2 + Math.floor(random() * 2);
+ const recovered = new Set();
+ for (let round = 0; round < 4; round++) {
+ const steps: Step[] = [];
+ for (let el = 0; el < elements; el++) {
+ if (!lists[el]) {
+ if (round > 0 && random() < 0.5) continue;
+ const sources = Array.from({ length: 1 + Math.floor(random() * 3) }, () => pick(pool));
+ lists[el] = [...new Map(sources.map((s) => [s.id, s])).values()];
+ steps.push({ do: "create", el, sources: lists[el] });
+ if (random() < 0.5)
+ steps.push({
+ do: "play",
+ el,
+ rate: pick([1, 1.5]),
+ ...(random() < 0.5 ? { pauseOnReject: true as const } : {}),
+ });
+ continue;
+ }
+ const list = lists[el];
+ const lapsed = list.find((s) => lapses(s.kind) && !recovered.has(s.id));
+ if (lapsed && random() < 0.5) {
+ recovered.add(lapsed.id);
+ steps.push({ do: "recover", el, source: lapsed });
+ continue;
+ }
+ const action = pick(["prepend", "append", "remove", "reverse", "reload", "author", "none"]);
+ const fresh = pool.filter((s) => !list.some((listed) => listed.id === s.id));
+ if ((action === "prepend" || action === "append") && fresh.length) {
+ const source = pick(fresh);
+ lists[el] = action === "prepend" ? [source, ...list] : [...list, source];
+ steps.push({ do: action, el, source });
+ } else if (action === "remove" && list.length > 1) {
+ const index = Math.floor(random() * list.length);
+ lists[el] = list.filter((_, i) => i !== index);
+ steps.push({ do: "remove", el, index });
+ } else if (action === "reverse" && list.length > 1) {
+ lists[el] = [...list].reverse();
+ steps.push({ do: "reverse", el });
+ } else if (action === "reload") steps.push({ do: "reload", el });
+ else if (action === "author" && random() < 0.4)
+ steps.push({ do: "author", el, value: pick(["anonymous", "use-credentials"]) });
+ }
+ rounds.push(steps);
+ }
+ return { name: `seed ${seed}`, rounds };
+}
+
+const own = (id: string, kind: Kind, at: { start?: number; delay?: number } = {}): Source => ({
+ id,
+ kind,
+ ...at,
+});
+// Earlier review repros, written in the same steps.
+const FIXED: Sequence[] = [
+ {
+ name: "a CORS source prepended after a fallback, then load()",
+ rounds: [
+ [{ do: "create", el: 0, sources: [own("f1-a", "nocors")] }],
+ [{ do: "prepend", el: 0, source: own("f1-b", "cors") }],
+ ],
+ },
+ {
+ name: "the source that fell back removed beside a CORS source",
+ rounds: [
+ [{ do: "create", el: 0, sources: [own("f2-a", "nocors")] }],
+ [{ do: "append", el: 0, source: own("f2-b", "cors") }],
+ [{ do: "remove", el: 0, index: 0 }],
+ ],
+ },
+ {
+ name: "a foreign source the browser cannot play before an own playable one",
+ rounds: [
+ [
+ {
+ do: "create",
+ el: 0,
+ sources: [own("f3-a", "foreignUnsupported"), own("f3-b", "cors")],
+ },
+ ],
+ ],
+ },
+ {
+ name: "the composition sets crossorigin during the retry, then a fresh element plays that URL",
+ rounds: [
+ [
+ { do: "create", el: 0, sources: [own("f4-a", "flaky")] },
+ { do: "author", el: 0, value: "anonymous", duringRetry: true },
+ ],
+ [{ do: "create", el: 1, sources: [own("f4-a", "flaky")] }],
+ ],
+ keepsCors: [1],
+ },
+ {
+ name: "a no-CORS source beside one whose media never matches, reloaded",
+ rounds: [
+ [{ do: "create", el: 0, sources: [own("f5-a", "nocors"), own("f5-b", "unmatched")] }],
+ [{ do: "reload", el: 0 }],
+ ],
+ },
+ {
+ name: "a host down with and without CORS, then back, the same element reloaded twice",
+ // The second reload is the one every film's host answers, so the unsealed film always has a frame to compare.
+ rounds: [
+ [{ do: "create", el: 0, sources: [own("f6-a", "outage")] }],
+ [{ do: "reload", el: 0 }],
+ [{ do: "reload", el: 0 }],
+ ],
+ keepsCors: [0],
+ },
+ {
+ name: "a host down for the whole run, reloaded",
+ rounds: [[{ do: "create", el: 0, sources: [own("f7-a", "down")] }], [{ do: "reload", el: 0 }]],
+ },
+ {
+ name: "the composition sets crossorigin in the same task as a new source",
+ rounds: [
+ [{ do: "create", el: 0, sources: [own("f8-a", "cors")] }],
+ [{ do: "author", el: 0, value: "use-credentials", replace: own("f8-b", "nocors") }],
+ ],
+ },
+ {
+ name: "an outside MP4 without CORS prepended to a playing own source, then load()",
+ rounds: [
+ [
+ { do: "create", el: 0, sources: [own("r7a-a", "cors")] },
+ { do: "play", el: 0, rate: 1 },
+ ],
+ [{ do: "prepend", el: 0, source: own("r7a-b", "foreignNocors") }],
+ ],
+ },
+ {
+ name: "an unavailable outside source before a playable own one, played",
+ rounds: [
+ [
+ { do: "create", el: 0, sources: [own("r7b-a", "foreignMissing"), own("r7b-b", "cors")] },
+ { do: "play", el: 0, rate: 1.5 },
+ ],
+ ],
+ },
+ {
+ name: "an own URL played again after the element played an outside clip",
+ rounds: [
+ [
+ { do: "create", el: 0, sources: [own("r7c-a", "foreignMissing"), own("r7c-b", "cors")] },
+ { do: "play", el: 0, rate: 1 },
+ ],
+ [{ do: "prepend", el: 0, source: own("r7c-c", "foreignNocors") }],
+ [{ do: "remove", el: 0, index: 0 }],
+ ],
+ },
+ {
+ name: "an own CORS URL played again, all own, after the element played another own clip",
+ rounds: [
+ [{ do: "create", el: 0, sources: [own("r7g-n", "nocors")] }],
+ [{ do: "prepend", el: 0, source: own("r7g-a", "cors") }],
+ [{ do: "remove", el: 0, index: 0 }],
+ [{ do: "prepend", el: 0, source: own("r7g-a", "cors") }],
+ ],
+ },
+ {
+ name: "an own source without CORS prepended to a playing own CORS source, then load()",
+ rounds: [
+ [
+ { do: "create", el: 0, sources: [own("r7d-a", "cors")] },
+ { do: "play", el: 0, rate: 1 },
+ ],
+ [{ do: "prepend", el: 0, source: own("r7d-b", "nocors") }],
+ ],
+ },
+ {
+ name: "a host down for good before a source without CORS: one upgrade, refused, none after",
+ rounds: [[{ do: "create", el: 0, sources: [own("r7e-a", "down"), own("r7e-b", "nocors")] }]],
+ upgradesAtMost: 1,
+ },
+ {
+ name: "a host down for good before a playing CORS source: playback goes on after the upgrade",
+ rounds: [
+ [
+ { do: "create", el: 0, sources: [own("r7f-a", "down"), own("r7f-b", "cors")] },
+ { do: "play", el: 0, rate: 1.5 },
+ ],
+ ],
+ },
+ ...(["pause", "seek", "rate", "source", "author"] as const).map(
+ (action): Sequence => ({
+ name: `a ${action} by the composition during the runtime's load wins`,
+ rounds: [
+ [
+ {
+ do: "create",
+ el: 0,
+ sources: [own(`r7${action}-a`, "down"), own(`r7${action}-b`, "cors")],
+ },
+ { do: "play", el: 0, rate: 1.5 },
+ { do: "interrupt", el: 0, action, source: own(`r7${action}-c`, "cors") },
+ ],
+ ],
+ }),
+ ),
+ {
+ name: "a seek by the composition during the runtime's load of a playing clip wins",
+ rounds: [
+ [
+ {
+ do: "create",
+ el: 0,
+ sources: [
+ own("r7seekPlaying-a", "down"),
+ own("r7seekPlaying-b", "cors", { start: 1.5, delay: 4000 }),
+ ],
+ },
+ { do: "play", el: 0, rate: 1.5 },
+ { do: "interrupt", el: 0, action: "seekPlaying", source: own("r7seekPlaying-c", "cors") },
+ ],
+ ],
+ },
+ ...(["lapse", "lapseCors"] as const).map(
+ (kind): Sequence => ({
+ name: `a playing element whose first own source was down and came back (${kind}), reloaded`,
+ rounds: [
+ [
+ { do: "create", el: 0, sources: [own(`r8${kind}-a`, kind), own(`r8${kind}-b`, "cors")] },
+ { do: "play", el: 0, rate: 1 },
+ ],
+ [{ do: "recover", el: 0, source: own(`r8${kind}-a`, kind) }],
+ ],
+ }),
+ ),
+ {
+ name: "an own source without CORS on a slow host, played",
+ rounds: [
+ [
+ { do: "create", el: 0, sources: [own("r8b-a", "slowNocors")] },
+ { do: "play", el: 0, rate: 1 },
+ ],
+ ],
+ },
+ {
+ name: "an own src attribute without CORS on a slow host, played",
+ rounds: [
+ [
+ { do: "create", el: 0, sources: [own("r8c-a", "slowNocors")], attr: true },
+ { do: "play", el: 0, rate: 1 },
+ ],
+ ],
+ },
+];
+
+// Generated sequences that found a fault by themselves: the composition's play() rejected for a fallback
+// (1, 24, 36, 43, 74) and a recovered source skipped (241, 346). Run on every count of seeds.
+const PINNED = [1, 24, 36, 43, 74, 241, 346];
+
+const server = startServer();
+const foreignOrigin = server.origin.replace("127.0.0.1", "localhost");
+
+type SourceAttrs = { src: string; type?: string; media?: string };
+
+// Each run asks for its own URLs, so the server's per-URL failures and request counts stay apart.
+// A trimmed clip's source opens past 0 (#t=), as a media-start does; a slow host answers its first request late.
+function urlFor(source: Source, run: string): SourceAttrs {
+ const attrs = urlForKind(source, run);
+ const slow = source.delay ? `&delay=${source.delay}` : "";
+ return { ...attrs, src: `${attrs.src}${slow}${source.start ? `#t=${source.start}` : ""}` };
+}
+
+function urlForKind(source: Source, run: string): SourceAttrs {
+ const query = `?id=${run}.${source.id}&no-store`;
+ const path = (dir: string) => `${dir}/10-video-grid/sample.mp4${query}`;
+ switch (source.kind) {
+ case "cors":
+ return { src: `${server.origin}${path("/fixtures")}` };
+ case "nocors":
+ return { src: `${server.origin}${path("/fixtures-no-cors")}` };
+ case "unsupported":
+ return { src: `${server.origin}${path("/fixtures")}`, type: "video/x-nope" };
+ case "missing":
+ return { src: `${server.origin}/fixtures/10-video-grid/missing.mp4${query}` };
+ case "flaky":
+ return { src: `${server.origin}${path("/fixtures-flaky")}` };
+ case "foreignCors":
+ return { src: `${foreignOrigin}${path("/fixtures")}` };
+ case "foreignNocors":
+ return { src: `${foreignOrigin}${path("/fixtures-no-cors")}` };
+ case "foreignUnsupported":
+ return { src: `${foreignOrigin}${path("/fixtures")}`, type: "video/x-nope" };
+ case "foreignMissing":
+ return { src: `${foreignOrigin}/fixtures/10-video-grid/missing.mp4${query}` };
+ case "unmatched":
+ return { src: `${server.origin}${path("/fixtures")}`, media: "(max-width: 1px)" };
+ case "down":
+ return { src: `${server.origin}${path("/fixtures-flaky")}&fail=1000` };
+ case "outage":
+ return { src: `${server.origin}${path("/fixtures-flaky")}&fail=2` };
+ case "slowNocors":
+ return { src: `${server.origin}${path("/fixtures-no-cors")}&delay=1500` };
+ case "lapse":
+ return { src: `${server.origin}${path("/fixtures-lapse")}` };
+ case "lapseCors":
+ return { src: `${server.origin}${path("/fixtures-lapse")}&cors` };
+ }
+}
+
+type Seen = {
+ crossOrigin: string | null;
+ playing: boolean;
+ paused: boolean;
+ rate: number;
+ upgrades: number;
+ savedRate?: string;
+ restartGap?: string;
+ restartRate?: string;
+ seekAt?: string;
+ seekCarry?: string;
+ seekPaused?: string;
+ extraSeeks?: string;
+ loops: number;
+ restores: number;
+ interrupted?: string;
+ play?: string;
+ pixels: string;
+ currentSrc: string;
+ loads: number;
+ ours: number;
+ corsLoads: number;
+ selections: number;
+};
+
+async function installDriver(frame: Frame) {
+ await frame.evaluate(() => {
+ const state = new Map();
+ const touch = (video: HTMLVideoElement) => {
+ const entry = state.get(video.dataset.table ?? "");
+ if (entry) entry.last = performance.now();
+ };
+ // The composition here is this driver: every other load() of a table video is the runtime's.
+ let driving = false;
+ const driven = (video: HTMLMediaElement) => {
+ driving = true;
+ try {
+ video.load();
+ } finally {
+ driving = false;
+ }
+ video.dataset.selections = String(Number(video.dataset.selections ?? 1) + 1);
+ };
+ const sourceEl = (src: { src: string; type?: string; media?: string }) => {
+ const el = document.createElement("source");
+ el.src = src.src;
+ if (src.type) el.type = src.type;
+ if (src.media) el.media = src.media;
+ return el;
+ };
+ // The clip's own events decide; the bound only ends a clip that never sends the one asked for.
+ const untilEvent = (
+ video: HTMLVideoElement,
+ events: string[],
+ decide: () => boolean | undefined,
+ ) =>
+ new Promise((resolve) => {
+ const check = () => {
+ const verdict = decide();
+ if (verdict !== undefined) finish(verdict);
+ };
+ const finish = (verdict: boolean) => {
+ clearTimeout(bound);
+ for (const name of events) video.removeEventListener(name, check);
+ resolve(verdict);
+ };
+ const bound = setTimeout(() => finish(false), 10_000);
+ for (const name of events) video.addEventListener(name, check);
+ check();
+ });
+ const pending = new Map();
+ const interrupt = (video: HTMLMediaElement) => {
+ const step = pending.get(video);
+ if (!step) return;
+ pending.delete(video);
+ video.dataset.interrupted = step.action;
+ if (step.action === "pause") video.pause();
+ else if (step.action === "seek" || step.action === "seekPlaying") {
+ video.dataset.seekTo = "0.5";
+ video.dataset.seekIssued = String(performance.now());
+ video.currentTime = 0.5;
+ } else if (step.action === "rate") video.playbackRate = 2;
+ else if (step.action === "author") video.setAttribute("crossorigin", "anonymous");
+ else {
+ video.prepend(sourceEl(step.src!));
+ driven(video);
+ }
+ };
+ const load = HTMLMediaElement.prototype.load;
+ HTMLMediaElement.prototype.load = function (this: HTMLMediaElement) {
+ const data = this.dataset;
+ const cors = String(this.getAttribute("crossorigin"));
+ // The CORS handling writes crossorigin, then loads; the runtime's preload loads leave it as it was.
+ const corsReload = data.corsAtLoad !== undefined && data.corsAtLoad !== cors;
+ if (data.table) data.corsAtLoad = cors;
+ if (data.table && !driving) {
+ data.ours = String(Number(data.ours ?? 0) + 1);
+ if (data.corsAtFetch !== undefined && data.corsAtFetch !== cors)
+ data.corsLoads = String(Number(data.corsLoads ?? 0) + 1);
+ data.loadedAt = String(this.currentTime);
+ if (this.hasAttribute("crossorigin"))
+ data.upgrades = String(Number(data.upgrades ?? 0) + 1);
+ delete data.restartGap;
+ if (!this.paused) {
+ data.savedTime = String(this.currentTime);
+ data.savedRate = String(this.playbackRate);
+ data.watch = "1";
+ }
+ const races =
+ pending.get(this)?.action !== "seekPlaying" ||
+ (this.currentTime > 0 && data.play !== undefined);
+ if (pending.has(this) && corsReload && races) setTimeout(() => interrupt(this));
+ }
+ return load.call(this);
+ };
+ window.addEventListener(
+ "loadstart",
+ (event) => {
+ const video = event.target as HTMLVideoElement;
+ if (video.dataset?.table)
+ video.dataset.corsAtFetch = String(video.getAttribute("crossorigin"));
+ },
+ true,
+ );
+ window.addEventListener(
+ "error",
+ (event) => {
+ const target = event.target as Element | null;
+ const video = target?.closest?.("video[data-table]") as HTMLVideoElement | null;
+ if (!video) return;
+ touch(video);
+ const during = video.dataset.authorDuringRetry;
+ if (during) {
+ delete video.dataset.authorDuringRetry;
+ setTimeout(() => video.setAttribute("crossorigin", during));
+ }
+ },
+ true,
+ );
+ Object.assign(window, {
+ __table: {
+ create(
+ key: string,
+ sources: Array<{ src: string; type?: string; media?: string }>,
+ attr?: boolean,
+ duringRetry?: string,
+ seekOnReload?: boolean,
+ ) {
+ const video = document.createElement("video");
+ video.dataset.table = key;
+ if (duringRetry) video.dataset.authorDuringRetry = duringRetry;
+ if (seekOnReload) pending.set(video, { action: "seekPlaying" });
+ video.muted = true;
+ video.loop = true;
+ // The runtime binds new media with preload auto and a load() of its own, at a time of its choosing.
+ video.preload = "metadata";
+ // Where a load of ours starts the video again: its metadata places the playhead before it plays.
+ video.addEventListener("loadedmetadata", () => {
+ const data = video.dataset;
+ if (data.watch) {
+ delete data.watch;
+ data.restartGap = String(Math.abs(video.currentTime - Number(data.savedTime)));
+ data.restartRate = String(video.playbackRate);
+ }
+ });
+ // Where the composition's seek settles, and any seek after it other than the loop starting over.
+ video.addEventListener(
+ "timeupdate",
+ () => (video.dataset.lastTime = String(video.currentTime)),
+ );
+ // A seek fires timeupdate at its new time before seeked; where it came from is read at seeking.
+ video.addEventListener(
+ "seeking",
+ () => (video.dataset.seekFrom = video.dataset.lastTime),
+ );
+ video.addEventListener("seeked", () => {
+ const data = video.dataset;
+ const looped = Number(data.seekFrom ?? 0) > 2 && video.currentTime < 1;
+ if (looped) data.loops = String(Number(data.loops ?? 0) + 1);
+ // A load of ours puts the playhead back where it was; within a frame of that, it is not a jump.
+ const restored = Math.abs(video.currentTime - Number(data.loadedAt)) <= 1 / 30 + 0.01;
+ if (data.seekAt !== undefined && !looped && restored)
+ data.restores = String(Number(data.restores ?? 0) + 1);
+ else if (data.seekAt !== undefined && !looped)
+ data.extraSeeks =
+ `${data.extraSeeks ?? ""} ${data.seekFrom}->${video.currentTime}`.trim();
+ if (!data.seekTo) return;
+ data.seekAt = String(video.currentTime);
+ data.seekCarry = String(
+ (video.playbackRate * (performance.now() - Number(data.seekIssued))) / 1000,
+ );
+ data.seekPaused = String(video.paused);
+ delete data.seekTo;
+ });
+ for (const name of ["loadstart", "loadeddata", "emptied", "stalled"])
+ video.addEventListener(name, () => touch(video));
+ video.addEventListener(
+ "loadstart",
+ () => (video.dataset.loads = String(Number(video.dataset.loads ?? 0) + 1)),
+ );
+ if (attr) video.src = sources[0]!.src;
+ else video.append(...sources.map(sourceEl));
+ state.set(key, { video, last: performance.now() });
+ document.body.append(video);
+ },
+ edit(
+ key: string,
+ step: {
+ do: string;
+ src?: { src: string; type?: string; media?: string };
+ index?: number;
+ value?: string;
+ duringRetry?: boolean;
+ rate?: number;
+ action?: string;
+ pauseOnReject?: boolean;
+ },
+ ) {
+ const { video } = state.get(key)!;
+ if (step.do === "play") {
+ // After the runtime's binding load, which would otherwise cancel this play() in either film.
+ const since = performance.now();
+ return new Promise((resolve) => {
+ const ready = () => video.preload === "auto" || performance.now() - since > 3000;
+ const check = () => (ready() ? resolve() : setTimeout(check, 10));
+ check();
+ }).then(() => {
+ video.playbackRate = step.rate!;
+ video.dataset.play = "pending";
+ video.play().then(
+ () => (video.dataset.play = "resolved"),
+ (error: Error) => {
+ video.dataset.play = `rejected ${error.name}`;
+ if (step.pauseOnReject) video.pause();
+ },
+ );
+ });
+ }
+ if (step.do === "interrupt") {
+ pending.set(video, { action: step.action!, src: step.src });
+ return;
+ }
+ if (step.do === "prepend") video.prepend(sourceEl(step.src!));
+ else if (step.do === "append") video.append(sourceEl(step.src!));
+ else if (step.do === "remove") video.querySelectorAll("source")[step.index!]!.remove();
+ else if (step.do === "reverse")
+ video.append(...[...video.querySelectorAll("source")].reverse());
+ else if (step.do === "author" && step.duringRetry) {
+ video.dataset.authorDuringRetry = step.value!;
+ return;
+ } else if (step.do === "author") {
+ if (step.src) video.replaceChildren(sourceEl(step.src));
+ video.setAttribute("crossorigin", step.value!);
+ }
+ driven(video);
+ },
+ flush() {
+ const any = pending.size > 0;
+ for (const video of [...pending.keys()]) interrupt(video);
+ return any;
+ },
+ advancing(key: string) {
+ const { video } = state.get(key)!;
+ if (video.paused || video.readyState < 2) return Promise.resolve(false);
+ const at = video.currentTime;
+ return untilEvent(video, ["timeupdate", "pause"], () =>
+ video.currentTime !== at ? true : video.paused ? false : undefined,
+ );
+ },
+ // Every film alike: a looping clip at its end has no frame until the loop's seek lands.
+ async loopRestart(key: string, loops: number) {
+ const { video } = state.get(key)!;
+ for (let waited = 0; waited < 2000; waited += 50) {
+ if (Number(video.dataset.loops ?? 0) > loops) return true;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ return false;
+ },
+ keys: () => [...state.keys()],
+ settled: () =>
+ [...state.values()].every(
+ ({ video, last }) =>
+ performance.now() - last > 400 &&
+ (video.readyState >= 2 || video.error !== null || video.networkState === 3),
+ ),
+ read(key: string) {
+ const { video } = state.get(key)!;
+ let pixels = "none";
+ if (video.readyState >= 2) {
+ const context = document.createElement("canvas").getContext("2d")!;
+ context.drawImage(video, 0, 0, 1, 1);
+ try {
+ context.getImageData(0, 0, 1, 1);
+ pixels = "readable";
+ } catch {
+ pixels = "refused";
+ }
+ }
+ const data = video.dataset;
+ return {
+ crossOrigin: video.getAttribute("crossorigin"),
+ playing: video.readyState >= 2,
+ paused: video.paused,
+ rate: video.playbackRate,
+ upgrades: Number(data.upgrades ?? 0),
+ savedRate: data.savedRate,
+ restartGap: data.restartGap,
+ restartRate: data.restartRate,
+ seekAt: data.seekAt,
+ seekCarry: data.seekCarry,
+ seekPaused: data.seekPaused,
+ extraSeeks: data.extraSeeks,
+ interrupted: data.interrupted,
+ loops: Number(data.loops ?? 0),
+ restores: Number(data.restores ?? 0),
+ play: data.play,
+ pixels,
+ currentSrc: video.currentSrc,
+ loads: Number(video.dataset.loads ?? 0),
+ ours: Number(video.dataset.ours ?? 0),
+ corsLoads: Number(video.dataset.corsLoads ?? 0),
+ selections: Number(video.dataset.selections ?? 1),
+ };
+ },
+ },
+ });
+ });
+}
+
+type Table = {
+ create: (
+ key: string,
+ sources: SourceAttrs[],
+ attr: boolean,
+ duringRetry?: string,
+ seekOnReload?: boolean,
+ ) => void;
+ edit: (key: string, step: object) => unknown;
+ settled: () => boolean;
+ flush: () => boolean;
+ keys: () => string[];
+ advancing: (key: string) => Promise;
+ loopRestart: (key: string, loops: number) => Promise;
+ read: (key: string) => Seen;
+};
+declare global {
+ interface Window {
+ __table: Table;
+ }
+}
+
+async function runAll(frame: Frame, sequences: Sequence[], run: string) {
+ const rounds = Math.max(...sequences.map((s) => s.rounds.length));
+ const readings: Readings[] = [];
+ for (let round = 0; round < rounds; round++) {
+ for (const [index, sequence] of sequences.entries()) {
+ const steps = sequence.rounds[round] ?? [];
+ // A write during the retry is registered with its element: as a later call, a fast failure could beat it.
+ const duringRetry = (el: number) =>
+ steps.find((step) => step.do === "author" && step.duringRetry && step.el === el);
+ // So is a seek on a playing clip's reload past 0: that reload can come while the play step waits.
+ const seekOnReload = (el: number) =>
+ steps.some(
+ (step) => step.do === "interrupt" && step.action === "seekPlaying" && step.el === el,
+ );
+ for (const step of steps) {
+ const key = `${index}-${step.el}`;
+ if (step.do === "recover") server.recover(`${run}.${step.source.id}`);
+ if (step.do === "create") {
+ const during = duringRetry(step.el);
+ await frame.evaluate(
+ (k, s, a, d, o) => window.__table.create(k, s, a, d, o),
+ key,
+ step.sources.map((source) => urlFor(source, run)),
+ step.attr ?? false,
+ during?.do === "author" ? during.value : undefined,
+ seekOnReload(step.el),
+ );
+ } else if (
+ ((step.do === "author" && step.duringRetry) ||
+ (step.do === "interrupt" && step.action === "seekPlaying")) &&
+ steps.some((s) => s.do === "create" && s.el === step.el)
+ )
+ continue;
+ else {
+ const listed =
+ "source" in step ? step.source : step.do === "author" ? step.replace : undefined;
+ const src = listed && urlFor(listed, run);
+ await frame.evaluate((k, s) => window.__table.edit(k, s), key, { ...step, src });
+ }
+ }
+ }
+ const settle = () =>
+ frame
+ .waitForFunction(() => window.__table.settled(), { timeout: 20_000, polling: 100 })
+ .catch(() => undefined);
+ await settle();
+ if (await frame.evaluate(() => window.__table.flush())) await settle();
+ readings.push(await readAll(frame));
+ }
+ return readings;
+}
+
+const describe = (sequence: Sequence) =>
+ sequence.rounds
+ .map((steps) =>
+ steps
+ .map((step) => {
+ const listed = "sources" in step ? step.sources : "source" in step ? [step.source] : [];
+ const what =
+ step.do === "interrupt"
+ ? ` ${step.action}`
+ : step.do === "play"
+ ? ` ${step.rate}${step.pauseOnReject ? " pausing-on-reject" : ""}`
+ : "";
+ return `${step.do}${step.el}${what}${listed.map((x) => ` ${x.kind}`).join("")}`;
+ })
+ .join(", "),
+ )
+ .join(" | ");
+
+type Reading = Seen & { moves: boolean };
+type Readings = Map;
+
+// Every element of a run, read while its film is still the page in front.
+async function readAll(frame: Frame) {
+ const keys = await frame.evaluate(() => window.__table.keys());
+ const readings: Readings = new Map();
+ await Promise.all(
+ keys.map(async (key) => {
+ const readOnce = () =>
+ Promise.all([
+ frame.evaluate((k) => window.__table.read(k), key),
+ frame.evaluate((k) => window.__table.advancing(k), key),
+ ]);
+ let [seen, moves] = await readOnce();
+ const restarting = !seen.playing && !seen.paused;
+ if (
+ restarting &&
+ (await frame.evaluate((k, l) => window.__table.loopRestart(k, l), key, seen.loops))
+ )
+ [seen, moves] = await readOnce();
+ readings.set(key, { ...seen, moves });
+ }),
+ );
+ return readings;
+}
+const idOf = (src: string) => (src ? new URL(src).searchParams.get("id")!.slice(2) : "");
+// One frame at 30 fps, with room for the timer that reads it.
+const FRAME = 1 / 30 + 0.01;
+
+function history(sequence: Sequence, upTo = sequence.rounds.length - 1) {
+ const lists = new Map();
+ const everListed = new Map>();
+ const authored = new Map();
+ for (const steps of sequence.rounds.slice(0, upTo + 1))
+ for (const step of steps) {
+ const list = lists.get(step.el) ?? [];
+ if (step.do === "create") lists.set(step.el, [...step.sources]);
+ else if (step.do === "prepend") lists.set(step.el, [step.source, ...list]);
+ else if (step.do === "append") lists.set(step.el, [...list, step.source]);
+ else if (step.do === "remove")
+ lists.set(
+ step.el,
+ list.filter((_, i) => i !== step.index),
+ );
+ else if (step.do === "reverse") lists.set(step.el, [...list].reverse());
+ else if (step.do === "author") authored.set(step.el, step.value);
+ else if (step.do === "interrupt" && step.action === "author")
+ authored.set(step.el, "anonymous");
+ else if (step.do === "interrupt" && step.action === "source")
+ lists.set(step.el, [step.source!, ...list]);
+ if (step.do === "author" && step.replace) lists.set(step.el, [step.replace]);
+ const kinds = everListed.get(step.el) ?? new Map();
+ for (const source of lists.get(step.el)!) kinds.set(source.id, source.kind);
+ everListed.set(step.el, kinds);
+ }
+ return { lists, everListed, authored };
+}
+
+// Per element, against the helper off: the same source, playing state and moving playhead; after a load of ours
+// while it played, it resumes where it was at the same rate. Pixels readable wherever the unsealed film reads them
+// from a source that sends CORS, except the known gap.
+// Each round of each sequence, so a wrong middle step is not hidden by a right end; an element is reported once.
+function judge(sequences: Sequence[], sealed: Readings[], control: Readings[], open: Readings[]) {
+ const budget = new Map();
+ const playback = { judged: 0, skipped: 0 };
+ const landings: string[] = [];
+ const gaps: string[] = [];
+ const reported = new Set();
+ const all = sequences.flatMap((sequence, index) =>
+ sequence.rounds.map((_, round) => judgeRound(sequence, index, round)),
+ );
+ function judgeRound(sequence: Sequence, index: number, round: number) {
+ const { lists, everListed, authored } = history(sequence, round);
+ const last = round === sequence.rounds.length - 1;
+ const problems: string[] = [];
+ const starts: Array<[string, number]> = [];
+ for (const [el, list] of lists) {
+ const key = `${index}-${el}`;
+ if (reported.has(key)) continue;
+ starts.push([key, problems.length]);
+ const seen = sealed[round]!.get(key)!;
+ const plain = control[round]!.get(key)!;
+ const unsealed = open[round]!.get(key)!;
+ const { moves } = seen;
+ const movesPlain = plain.moves;
+ const where = `${sequence.name} (${describe(sequence)}), element ${el} after round ${round + 1}`;
+ const kinds = everListed.get(el)!;
+ // The helper changes crossorigin, then loads; the runtime's own loads vary per run.
+ const helper = seen.corsLoads;
+ // Every load the runtime's CORS handling did not make starts a selection: the driver's and the runtime's own.
+ const selections = seen.selections + seen.ours - seen.corsLoads;
+ const most = 2 * kinds.size * selections;
+ if (helper > most)
+ problems.push(
+ `${where}: ${helper} loads of the helper, at most ${most} for ${selections} selections`,
+ );
+ if (sequence.upgradesAtMost !== undefined && seen.upgrades > sequence.upgradesAtMost)
+ problems.push(`${where}: ${seen.upgrades} upgrades, at most ${sequence.upgradesAtMost}`);
+ // An authored crossorigin is the composition's, and an opaque origin loads it differently by design.
+ const value = authored.get(el);
+ if (value !== undefined) {
+ if (seen.crossOrigin !== value)
+ problems.push(`${where}: the composition's ${value} became ${seen.crossOrigin}`);
+ continue;
+ }
+ // A host failing some requests may play after the runtime's extra request and not without it.
+ const variable = [...kinds.values()].some((kind) => kind === "flaky" || kind === "outage");
+ // A control that resolved play() and was not paused but has no frame is buffering: it says nothing.
+ const stalled = !plain.playing && !plain.paused && plain.play === "resolved";
+ if (!variable) playback[stalled ? "skipped" : "judged"]++;
+ if (!variable && !stalled) {
+ if (idOf(seen.currentSrc) !== idOf(plain.currentSrc))
+ problems.push(
+ `${where}: plays ${idOf(seen.currentSrc)}, without the helper ${idOf(plain.currentSrc)}`,
+ );
+ if (seen.playing !== plain.playing || (plain.playing && seen.paused !== plain.paused))
+ problems.push(
+ `${where}: ${JSON.stringify(seen)}, without the helper ${JSON.stringify(plain)}`,
+ );
+ if (movesPlain && !moves)
+ problems.push(`${where}: the playhead stopped ${JSON.stringify(seen)}`);
+ // A play() still pending is rejected by whichever load comes next, ours or the runtime's binding load.
+ // The composition's own pause or load rejects a pending play() in either film, at different moments.
+ const ownAbort = seen.interrupted === "pause" || seen.interrupted === "source";
+ if (plain.play === "resolved" && seen.play !== "resolved" && !ownAbort)
+ problems.push(`${where}: play() ${seen.play}, without the helper resolved`);
+ }
+ const action = seen.interrupted;
+ if (action === "pause" && !seen.paused)
+ problems.push(`${where}: plays after the composition paused it`);
+ if (action === "rate" && seen.rate !== 2)
+ problems.push(`${where}: rate ${seen.rate}, set to 2`);
+ const settled = ({ seekAt, seekCarry, seekPaused, extraSeeks }: Reading) => ({
+ seekAt,
+ seekCarry,
+ seekPaused,
+ extraSeeks,
+ });
+ // Its seek won where the playhead sits between the target and what playback carried it to before seeked ran.
+ const landed = ({ seekAt, seekCarry }: Reading) =>
+ Number(seekAt) >= 0.5 - FRAME && Number(seekAt) <= 0.5 + Number(seekCarry) + FRAME;
+ // Past the target at seeked, and how far playback could carry it: sealed beside unsealed, the parity bar.
+ const past = ({ seekAt, seekCarry }: Reading) =>
+ `+${(Number(seekAt) - 0.5).toFixed(3)} of ${Number(seekCarry).toFixed(3)}`;
+ const seeks = action === "seek" || action === "seekPlaying";
+ if (seeks) landings.push(`sealed ${past(seen)}, unsealed ${past(unsealed)}`);
+ if (
+ seeks &&
+ (!landed(seen) ||
+ seen.seekPaused !== plain.seekPaused ||
+ seen.extraSeeks !== plain.extraSeeks)
+ )
+ problems.push(
+ `${where}: after the composition's seek ${JSON.stringify(settled(seen))}, without the helper ${JSON.stringify(settled(plain))}`,
+ );
+ if (seen.savedRate !== undefined && !action && !variable && movesPlain) {
+ if (!(Number(seen.restartGap ?? 1) <= FRAME))
+ problems.push(`${where}: after our load it resumed ${seen.restartGap ?? "never"} s off`);
+ else if (seen.restartRate !== seen.savedRate)
+ problems.push(`${where}: rate ${seen.restartRate} after our load, was ${seen.savedRate}`);
+ }
+ const canPlay =
+ list.some((s) => PLAYABLE.has(s.kind)) ||
+ (last && Boolean(sequence.keepsCors?.includes(el)));
+ const mayPlay = canPlay || list.some((s) => MAY_PLAY.has(s.kind));
+ if (seen.playing ? !mayPlay : canPlay)
+ problems.push(`${where}: ${canPlay ? "does not play" : "plays"} ${JSON.stringify(seen)}`);
+ if (!seen.playing) continue;
+ const kind = kinds.get(idOf(seen.currentSrc))!;
+ const readable = unsealed.pixels === "readable" && !foreign(kind) && SENDS_CORS.has(kind);
+ if (!readable || seen.pixels === "readable") continue;
+ const line = `${where}: plays ${idOf(seen.currentSrc)} unreadable ${JSON.stringify(seen)}`;
+ if (mixed(list) && !foreign(kind)) {
+ if (last) gaps.push(line);
+ } else problems.push(line);
+ }
+ starts.forEach(([key, start], i) => {
+ if ((starts[i + 1]?.[1] ?? problems.length) > start) reported.add(key);
+ });
+ return problems;
+ }
+ const final = sealed.at(-1)!;
+ sequences.forEach((sequence, index) => {
+ for (const [el, kinds] of history(sequence).everListed) {
+ const tryAndRangePerLoad = 2 * final.get(`${index}-${el}`)!.loads;
+ const corsQuestion = 1;
+ for (const id of kinds.keys())
+ budget.set(id, (budget.get(id) ?? 0) + tryAndRangePerLoad + corsQuestion);
+ }
+ });
+ // A skip that grows past a tenth of the comparisons would weaken the oracle without saying so.
+ if (playback.skipped > 0.1 * (playback.judged + playback.skipped))
+ all.push([
+ `${playback.skipped} of ${playback.judged + playback.skipped} playback comparisons skipped`,
+ ]);
+ return { problems: all.flat(), gaps, budget, playback, landings };
+}
+
+async function filmFrame(page: import("puppeteer-core").Page, query: string) {
+ await page.goto(`${server.origin}/host.html?fixture=10-video-grid${query}`, {
+ waitUntil: "domcontentloaded",
+ });
+ await page.waitForFunction(() => window.__playerReady || window.__playerError, {
+ timeout: 60_000,
+ });
+ // A sealed same-site film is shown as srcdoc: reach its frame through the player, not by URL.
+ const frame = await (
+ await page.evaluateHandle(
+ () => document.getElementById("player")!.shadowRoot!.querySelector("iframe")!,
+ )
+ )
+ .asElement()!
+ .contentFrame();
+ assert.ok(frame, "the film's frame must load");
+ return frame;
+}
+
+const browser = await launchBrowser();
+try {
+ const seeds = Number(process.env.SEALED_MEDIA_SEEDS ?? 40);
+ const from = Number(process.env.SEALED_MEDIA_SEED_FROM ?? 1);
+ const numbers = [...new Set([...Array.from({ length: seeds }, (_, n) => n + from), ...PINNED])];
+ const sequences = [...FIXED, ...numbers.map(generated)];
+ // One page at a time: a page behind another one has its media held back.
+ const run = async (query: string, prefix: string, helperOff = false) => {
+ const page = await browser.newPage();
+ // The helper starts only where window.origin reads "null"; the other two readers touch no table video.
+ if (helperOff)
+ await page.evaluateOnNewDocument(() => {
+ if (window.origin === "null")
+ Object.defineProperty(window, "origin", { value: "helper-off" });
+ });
+ const frame = await filmFrame(page, query);
+ await installDriver(frame);
+ const readings = await runAll(frame, sequences, prefix);
+ await page.close();
+ return readings;
+ };
+ const sealed = await run("&sealed=1", "s");
+ const control = await run("&sealed=1", "c", true);
+ const open = await run("", "o");
+ const { problems, gaps, budget, playback, landings } = judge(sequences, sealed, control, open);
+ console.log(
+ `[sealed-media-table] seek landings past 0.5 (of what playback carried): ${landings.join("; ")}`,
+ );
+ const loops = (film: Readings[]) =>
+ [...film.at(-1)!.values()].reduce((sum, reading) => sum + reading.loops, 0);
+ const restores = (film: Readings[]) =>
+ [...film.at(-1)!.values()].reduce((sum, reading) => sum + reading.restores, 0);
+ console.log(
+ `[sealed-media-table] playback comparisons ${playback.judged}, skipped for a buffering control ${playback.skipped}; ` +
+ `loop restarts not counted as seeks: sealed ${loops(sealed)}, without the helper ${loops(control)}; ` +
+ `restores by our loads after a composition seek: ${restores(sealed)}`,
+ );
+ const requests = new Map();
+ for (const url of server.requested) {
+ const id = new URL(url).searchParams.get("id");
+ if (id?.startsWith("s.")) requests.set(id.slice(2), (requests.get(id.slice(2)) ?? 0) + 1);
+ }
+ for (const [id, asked] of requests) {
+ const most = budget.get(id) ?? 0;
+ if (asked > most) problems.push(`source ${id}: ${asked} requests, at most ${most} expected`);
+ }
+ console.log(
+ `[sealed-media-table] ${gaps.length} known gaps: own media in a list naming another host`,
+ );
+ for (const gap of gaps) console.log(` gap: ${gap}`);
+ console.log(`[sealed-media-table] ${sequences.length} sequences, ${problems.length} problems`);
+ assert.deepEqual(problems, [], problems.join("\n"));
+ console.log("[sealed-media-table] every element matches the film without the helper");
+} finally {
+ await browser.close();
+ await server.stop();
+}
diff --git a/packages/player/tests/browser/sealed-media.ts b/packages/player/tests/browser/sealed-media.ts
new file mode 100644
index 0000000000..075f96bcdd
--- /dev/null
+++ b/packages/player/tests/browser/sealed-media.ts
@@ -0,0 +1,95 @@
+import assert from "node:assert/strict";
+
+import { launchBrowser } from "../perf/runner.js";
+import { startServer } from "../perf/server.js";
+
+const server = startServer();
+const browser = await launchBrowser();
+
+type VideoState = { crossOrigin: string | null; readyState: number; error: number | null };
+
+/** A sealed player playing the 10-video film from a host with or without CORS headers. */
+async function play(cors: boolean) {
+ const page = await browser.newPage();
+ const warnings: string[] = [];
+ page.on("console", (message) => {
+ if (message.type() === "warn") warnings.push(message.text());
+ });
+ await page.goto(
+ `${server.origin}/host.html?fixture=10-video-grid&sealed=1${cors ? "" : "&cors=0"}`,
+ {
+ waitUntil: "domcontentloaded",
+ },
+ );
+ await page.waitForFunction(() => window.__playerReady || window.__playerError, {
+ timeout: 60_000,
+ });
+ await page.evaluate(() =>
+ (document.getElementById("player") as HTMLElement & { play: () => void }).play(),
+ );
+ // A sealed same-site film is shown as srcdoc: reach its frame through the player, not by URL.
+ const frame = await (
+ await page.evaluateHandle(
+ () => document.getElementById("player")!.shadowRoot!.querySelector("iframe")!,
+ )
+ )
+ .asElement()!
+ .contentFrame();
+ assert.ok(frame, "the film's frame must load");
+ await frame.waitForFunction(
+ () => [...document.querySelectorAll("video")].every((v) => v.readyState >= 2 || v.error),
+ { timeout: 30_000 },
+ );
+ const videos: VideoState[] = await frame.evaluate(() =>
+ [...document.querySelectorAll("video")].map((v) => ({
+ crossOrigin: v.getAttribute("crossorigin"),
+ readyState: v.readyState,
+ error: v.error?.code ?? null,
+ })),
+ );
+ const pixels = await frame.evaluate(() => {
+ const video = document.querySelector("video")!;
+ const canvas = document.createElement("canvas");
+ const context = canvas.getContext("2d")!;
+ context.drawImage(video, 0, 0, 1, 1);
+ try {
+ context.getImageData(0, 0, 1, 1);
+ return "readable";
+ } catch {
+ return "refused";
+ }
+ });
+ await page.close();
+ return { videos, pixels, warnings };
+}
+
+try {
+ const plain = await play(false);
+ assert.equal(
+ plain.videos.filter((v) => v.readyState >= 2 && v.error === null).length,
+ 10,
+ `a sealed film on a host without CORS must still play all 10 videos: ${JSON.stringify(plain.videos)}`,
+ );
+ assert.ok(
+ plain.videos.every((v) => v.crossOrigin === null),
+ "a video whose CORS load failed plays without crossorigin",
+ );
+ const named = plain.warnings.filter((w) => w.includes("10-video-grid/sample.mp4"));
+ assert.equal(named.length, 10, `the fallback is said once per video: ${JSON.stringify(named)}`);
+
+ const shared = await play(true);
+ assert.equal(
+ shared.videos.filter((v) => v.crossOrigin === "anonymous" && v.readyState >= 2).length,
+ 10,
+ `a sealed film on a CORS host keeps crossorigin: ${JSON.stringify(shared.videos)}`,
+ );
+ assert.equal(shared.pixels, "readable", "a CORS-loaded video's pixels can be read");
+ assert.deepEqual(
+ shared.warnings.filter((w) => w.includes("sample.mp4")),
+ [],
+ );
+ console.log("[sealed-media] a host without CORS plays; a CORS host keeps pixel access");
+} finally {
+ await browser.close();
+ await server.stop();
+}
diff --git a/packages/player/tests/browser/sealed-runtime.ts b/packages/player/tests/browser/sealed-runtime.ts
new file mode 100644
index 0000000000..1d96be8054
--- /dev/null
+++ b/packages/player/tests/browser/sealed-runtime.ts
@@ -0,0 +1,150 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { launchBrowser } from "../perf/runner.js";
+import { startServer } from "../perf/server.js";
+
+const PLAYER_DIST = join(import.meta.dirname, "../../dist");
+const server = startServer();
+const browser = await launchBrowser();
+
+type Player = HTMLElement & { play(): void; currentTime: number };
+
+/** A sealed player given a same-site composition by URL, as an embedder writes it, with nothing added. */
+async function play(fixture: string) {
+ const page = await browser.newPage();
+ const elsewhere: string[] = [];
+ page.on("request", (request) => {
+ const url = request.url();
+ if (/^https?:/.test(url) && new URL(url).origin !== server.origin) elsewhere.push(url);
+ });
+ await page.goto(`${server.origin}/host.html?fixture=${fixture}&sealed=1`, {
+ waitUntil: "domcontentloaded",
+ });
+ await page.waitForFunction(() => window.__playerReady || window.__playerError, {
+ timeout: 60_000,
+ });
+ const error = await page.evaluate(() => window.__playerError ?? null);
+ await page.evaluate(() => (document.getElementById("player") as Player).play());
+ await page
+ .waitForFunction(() => (document.getElementById("player") as Player).currentTime > 0.3, {
+ timeout: 10_000,
+ })
+ .catch(() => {});
+ const time = await page.evaluate(() => (document.getElementById("player") as Player).currentTime);
+ const iframe = await page.evaluateHandle(
+ () => document.getElementById("player")!.shadowRoot!.querySelector("iframe")!,
+ );
+ const frame = await iframe.asElement()!.contentFrame();
+ const inFrame = await frame!.evaluate(() => ({
+ origin: window.origin,
+ runtimes: [...document.scripts].filter(
+ (s) => s.src.includes("hyperframe.runtime") || s.text.includes("__hyperframes"),
+ ).length,
+ moved: getComputedStyle(document.getElementById("box")!).transform,
+ }));
+ await page.close();
+ return { error, time, elsewhere, ...inFrame };
+}
+
+/** A page with its scripts inlined, as a CLI render carries the runtime: a sealed srcdoc can't fetch loopback files. */
+async function inlinedScripts(path: string): Promise {
+ const read = async (url: string) => (await fetch(`${server.origin}${url}`)).text();
+ let html = await read(path);
+ for (const src of ["/vendor/gsap.min.js", "/vendor/hyperframe.runtime.iife.js"]) {
+ const code = (await read(src)).replace(/<\/script/gi, "<\\/script");
+ html = html.replace(` src="${src}">`, () => `>${code}`);
+ }
+ return html;
+}
+
+async function playAsModule(sealed: boolean, load: { src: string } | { srcdocFrom: string }) {
+ const page = await browser.newPage();
+ const asked: string[] = [];
+ await page.setRequestInterception(true);
+ page.on("request", (request) => {
+ const path = new URL(request.url()).pathname;
+ asked.push(path);
+ const options = sealed ? ' sandbox-origin="opaque"' : "";
+ if (path === "/module-host.html") {
+ void request.respond({
+ contentType: "text/html",
+ body: `
+`,
+ });
+ } else if (path.startsWith("/module/")) {
+ void request.respond({
+ contentType: "text/javascript",
+ body: readFileSync(join(PLAYER_DIST, path.slice("/module/".length))),
+ });
+ } else void request.continue();
+ });
+ await page.goto(`${server.origin}/module-host.html`, { waitUntil: "domcontentloaded" });
+ await page.waitForFunction(() => customElements.get("hyperframes-player") !== undefined);
+ const srcdoc = "srcdocFrom" in load ? await inlinedScripts(load.srcdocFrom) : null;
+ const outcome = await page.evaluate(
+ (src, html) =>
+ new Promise((resolve) => {
+ const el = document.getElementById("player")!;
+ el.addEventListener("ready", () => resolve("ready"));
+ el.addEventListener("error", (e) => resolve(String((e as CustomEvent).detail?.message)));
+ if (html === null) el.setAttribute("src", src!);
+ else el.setAttribute("srcdoc", html);
+ }),
+ "src" in load ? load.src : null,
+ srcdoc,
+ );
+ let time = 0;
+ if (outcome === "ready") {
+ await page.evaluate(() => (document.getElementById("player") as Player).play());
+ await page
+ .waitForFunction(() => (document.getElementById("player") as Player).currentTime > 0.3, {
+ timeout: 10_000,
+ })
+ .catch(() => {});
+ time = await page.evaluate(() => (document.getElementById("player") as Player).currentTime);
+ }
+ await page.close();
+ return { outcome, time, readRuntime: asked.includes("/module/hyperframe.runtime.iife.js") };
+}
+
+try {
+ const bare = await play("direct-timeline");
+ assert.equal(bare.error, null, `a sealed composition with no runtime must load: ${bare.error}`);
+ assert.equal(bare.origin, "null", "the frame stays sealed");
+ assert.ok(bare.time > 0.3, `it plays: currentTime ${bare.time}`);
+ assert.notEqual(bare.moved, "none", "its animation runs");
+ assert.equal(bare.runtimes, 1, "the player adds the runtime once");
+ assert.deepEqual(bare.elsewhere, [], "nothing is fetched from another origin");
+
+ const carried = await play("direct-timeline-runtime");
+ assert.equal(
+ carried.error,
+ null,
+ `a sealed composition with its own runtime loads: ${carried.error}`,
+ );
+ assert.equal(carried.runtimes, 1, "a composition carrying the runtime gets no second copy");
+ // fails without the fix: the ES build's bare runtime import can't resolve without a bundler.
+ for (const load of [
+ { src: "/fixtures/direct-timeline/index.html" },
+ { srcdocFrom: "/fixtures/direct-timeline-runtime/index.html" },
+ ]) {
+ const open = await playAsModule(false, load);
+ const sealed = await playAsModule(true, load);
+ assert.equal(open.outcome, "ready", `unsealed, the module page plays ${JSON.stringify(load)}`);
+ assert.equal(sealed.outcome, "ready", `sealed, it plays as unsealed: ${sealed.outcome}`);
+ assert.ok(sealed.time > 0.3, `sealed, it plays: currentTime ${sealed.time}`);
+ assert.equal(
+ sealed.readRuntime,
+ "src" in load,
+ "only a composition without its own runtime reads the file beside the module",
+ );
+ }
+ console.log(
+ "[sealed-runtime] a sealed same-site composition plays with the runtime the player ships",
+ );
+} finally {
+ await browser.close();
+ await server.stop();
+}
diff --git a/packages/player/tests/perf/fixtures/direct-timeline-runtime/index.html b/packages/player/tests/perf/fixtures/direct-timeline-runtime/index.html
new file mode 100644
index 0000000000..f65e4153b9
--- /dev/null
+++ b/packages/player/tests/perf/fixtures/direct-timeline-runtime/index.html
@@ -0,0 +1,25 @@
+
+
+
+
+ Direct GSAP timeline with the runtime
+
+
+
+
+
+
+
+
diff --git a/packages/player/tests/perf/fixtures/direct-timeline/index.html b/packages/player/tests/perf/fixtures/direct-timeline/index.html
new file mode 100644
index 0000000000..b23da0122d
--- /dev/null
+++ b/packages/player/tests/perf/fixtures/direct-timeline/index.html
@@ -0,0 +1,16 @@
+
+
+
+
+ Direct GSAP timeline, no runtime
+
+
+
+
+
+
+
diff --git a/packages/player/tests/perf/fixtures/sealed-audio-bare/index.html b/packages/player/tests/perf/fixtures/sealed-audio-bare/index.html
new file mode 100644
index 0000000000..895a9ce3b6
--- /dev/null
+++ b/packages/player/tests/perf/fixtures/sealed-audio-bare/index.html
@@ -0,0 +1,27 @@
+
+
+
+
+ perf fixture: sealed-audio-bare
+
+
+
+
+
+
+
diff --git a/packages/player/tests/perf/fixtures/sealed-audio-bare/tone.m4a b/packages/player/tests/perf/fixtures/sealed-audio-bare/tone.m4a
new file mode 100644
index 0000000000..d9df5b0feb
Binary files /dev/null and b/packages/player/tests/perf/fixtures/sealed-audio-bare/tone.m4a differ
diff --git a/packages/player/tests/perf/server.ts b/packages/player/tests/perf/server.ts
index be7eb671d1..b2e8c4df76 100644
--- a/packages/player/tests/perf/server.ts
+++ b/packages/player/tests/perf/server.ts
@@ -14,10 +14,17 @@ import { fileURLToPath } from "node:url";
* URL routes:
* / → host.html (default fixture: gsap-heavy)
* /host.html?fixture= → embed page hosting
+ * /host.html?...&sealed=1 → the same with sandbox-origin="opaque"
+ * /host.html?...&cors=0 → the film from /fixtures-no-cors/, a host that sends no CORS headers
* /player/hyperframes-player.global.js
+ * /player/hyperframe.runtime.iife.js → the runtime file shipped beside it
* /vendor/gsap.min.js
* /vendor/hyperframe.runtime.iife.js
* /fixtures// → fixture HTML + assets
+ * /fixtures-flaky// → as /fixtures/, but a 503 the first time each URL is asked (?fail=N: N times)
+ * /fixtures-lapse//?id=… → a 503 until recover(id), then the file (CORS headers only with ?cors)
+ * ...?delay=ms → the first answer for that URL comes that much later
+ * ...?no-store → never cached, so every load reaches the server
*/
const HERE = dirname(fileURLToPath(import.meta.url));
@@ -33,6 +40,7 @@ function firstExisting(candidates: string[]): string {
const PATHS = {
player: join(PLAYER_PKG, "dist/hyperframes-player.global.js"),
+ playerRuntime: join(PLAYER_PKG, "dist/hyperframe.runtime.iife.js"),
runtime: join(REPO_ROOT, "packages/core/dist/hyperframe.runtime.iife.js"),
// bun installs gsap into the package's node_modules in workspace mode, but
// hoists it to the repo root if multiple packages share the same version.
@@ -53,6 +61,9 @@ export type ServeOptions = {
export type RunningServer = {
port: number;
origin: string;
+ /** Every URL asked for, in order. */
+ requested: string[];
+ recover(id: string): void;
stop(): Promise;
};
@@ -79,9 +90,15 @@ function mimeFor(path: string): string {
return MIME_TYPES[path.slice(dot).toLowerCase()] ?? "application/octet-stream";
}
-function buildHostHtml(fixtureName: string, width: number, height: number): string {
+function buildHostHtml(
+ fixtureName: string,
+ width: number,
+ height: number,
+ sealed: boolean,
+ cors = true,
+): string {
const playerSrc = "/player/hyperframes-player.global.js";
- const fixtureSrc = `/fixtures/${fixtureName}/index.html`;
+ const fixtureSrc = `/${cors ? "fixtures" : "fixtures-no-cors"}/${fixtureName}/index.html`;
return `
@@ -94,7 +111,7 @@ function buildHostHtml(fixtureName: string, width: number, height: number): stri
();
+ const requested: string[] = [];
+ const recovered = new Set();
+ const delayed = new Set();
const server = Bun.serve({
port: options.port ?? 0,
async fetch(req) {
const url = new URL(req.url);
+ requested.push(url.href);
const path = url.pathname;
if (path === "/" || path === "/host.html") {
const fixture = url.searchParams.get("fixture") || "gsap-heavy";
const width = Number(url.searchParams.get("width") || "1920");
const height = Number(url.searchParams.get("height") || "1080");
- const html = buildHostHtml(fixture, width, height);
+ const params = url.searchParams;
+ const html = buildHostHtml(
+ fixture,
+ width,
+ height,
+ params.get("sealed") === "1",
+ params.get("cors") !== "0",
+ );
return applyCacheHeaders(
new Response(html, { headers: { "Content-Type": "text/html; charset=utf-8" } }),
noCache,
@@ -180,6 +209,11 @@ export function startServer(options: ServeOptions = {}): RunningServer {
return applyCacheHeaders(await readBunFile(PATHS.player), noCache);
}
+ // Beside the bundle, as an embedder hosting the player's dist serves it: a sealed player loads it.
+ if (path === "/player/hyperframe.runtime.iife.js") {
+ return applyCacheHeaders(await readBunFile(PATHS.playerRuntime), noCache);
+ }
+
if (path === "/vendor/hyperframe.runtime.iife.js") {
return applyCacheHeaders(await readBunFile(PATHS.runtime), noCache);
}
@@ -188,15 +222,38 @@ export function startServer(options: ServeOptions = {}): RunningServer {
return applyCacheHeaders(await readBunFile(PATHS.gsap), noCache);
}
- if (path.startsWith("/fixtures/")) {
- const rel = path.replace(/^\/fixtures\//, "");
- const filePath = join(PATHS.fixturesDir, rel);
+ const served = /^\/(fixtures|fixtures-no-cors|fixtures-flaky|fixtures-lapse)\//.exec(path);
+ const failed = failures.get(url.href) ?? 0;
+ const delay = Number(url.searchParams.get("delay") ?? 0);
+ if (served && delay > 0 && !delayed.has(url.href)) {
+ delayed.add(url.href);
+ await new Promise((wake) => setTimeout(wake, delay));
+ }
+ const lapsed =
+ served?.[1] === "fixtures-lapse" && !recovered.has(url.searchParams.get("id") ?? "");
+ if (
+ lapsed ||
+ (served?.[1] === "fixtures-flaky" && failed < Number(url.searchParams.get("fail") ?? 1))
+ ) {
+ failures.set(url.href, failed + 1);
+ return new Response("Busy", {
+ status: 503,
+ headers: { "Access-Control-Allow-Origin": "*" },
+ });
+ }
+ if (served) {
+ const filePath = join(PATHS.fixturesDir, path.slice(served[0].length));
if (!filePath.startsWith(PATHS.fixturesDir)) {
return new Response("Forbidden", { status: 403 });
}
+ // A sealed player's film has an opaque origin and loads its own media with CORS, as from a CORS-capable host.
const res = applyCacheHeaders(await readBunFile(filePath), noCache);
- // A sealed film has an opaque origin, so it reads its own media as from a CORS host.
- res.headers.set("Access-Control-Allow-Origin", "*");
+ const cors =
+ served[1] === "fixtures-lapse"
+ ? url.searchParams.has("cors")
+ : served[1] !== "fixtures-no-cors";
+ if (cors) res.headers.set("Access-Control-Allow-Origin", "*");
+ if (url.searchParams.has("no-store")) res.headers.set("Cache-Control", "no-store");
return res;
}
@@ -214,6 +271,8 @@ export function startServer(options: ServeOptions = {}): RunningServer {
return {
port,
origin: `http://127.0.0.1:${port}`,
+ requested,
+ recover: (id: string) => void recovered.add(id),
async stop() {
server.stop(true);
},
diff --git a/packages/player/tsup.config.ts b/packages/player/tsup.config.ts
index 033147592f..4c771ee13a 100644
--- a/packages/player/tsup.config.ts
+++ b/packages/player/tsup.config.ts
@@ -1,20 +1,51 @@
import { defineConfig } from "tsup";
-import { readFileSync } from "node:fs";
+import { copyFileSync, readFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { dirname, join } from "node:path";
const packageVersion = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"))
.version as string;
-export default defineConfig({
+const RUNTIME_FILE = "hyperframe.runtime.iife.js";
+const coreDist = join(
+ dirname(createRequire(import.meta.url).resolve("@hyperframes/core/package.json")),
+ "dist",
+);
+
+const shared = {
entry: ["src/hyperframes-player.ts", "src/slideshow/hyperframes-slideshow.ts"],
- format: ["esm", "cjs", "iife"],
globalName: "HyperframesPlayer",
noExternal: ["@hyperframes/core"],
- dts: true,
- clean: true,
minify: true,
define: {
__HYPERFRAMES_RUNTIME_CDN_URL__: JSON.stringify(
- `https://cdn.jsdelivr.net/npm/@hyperframes/core@${packageVersion}/dist/hyperframe.runtime.iife.js`,
+ `https://cdn.jsdelivr.net/npm/@hyperframes/core@${packageVersion}/dist/${RUNTIME_FILE}`,
),
},
-});
+};
+
+export default defineConfig([
+ // An app's bundler takes the runtime from core, which the player depends on, as a chunk loaded only when needed.
+ {
+ ...shared,
+ format: ["esm"],
+ dts: true,
+ clean: true,
+ esbuildOptions: (options) => {
+ options.external = [...(options.external ?? []), "@hyperframes/core/runtime-script"];
+ },
+ },
+ {
+ ...shared,
+ format: ["cjs", "iife"],
+ // These formats cannot split a chunk out, so the runtime stays a file beside them.
+ esbuildOptions: (options) => {
+ options.alias = {
+ ...options.alias,
+ "@hyperframes/core/runtime-script": "./src/runtime-beside-bundle.ts",
+ };
+ options.define = { ...options.define, "import.meta.url": "undefined" };
+ },
+ onSuccess: async () => copyFileSync(join(coreDist, RUNTIME_FILE), join("dist", RUNTIME_FILE)),
+ },
+]);
diff --git a/packages/studio/src/shims/runtimeScriptFromStudio.ts b/packages/studio/src/shims/runtimeScriptFromStudio.ts
new file mode 100644
index 0000000000..5a088badd1
--- /dev/null
+++ b/packages/studio/src/shims/runtimeScriptFromStudio.ts
@@ -0,0 +1,7 @@
+import { studioApiFetch } from "../utils/studioApiFetch";
+
+export async function getHyperframeRuntimeScript(): Promise {
+ const response = await studioApiFetch("/api/runtime.js");
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ return response.text();
+}
diff --git a/packages/studio/vite.config.ts b/packages/studio/vite.config.ts
index f0b50a7502..b0d6ec6a46 100644
--- a/packages/studio/vite.config.ts
+++ b/packages/studio/vite.config.ts
@@ -376,6 +376,11 @@ export default defineConfig({
// openComposition and silently loses its SDK session. See the stub.
canvas: resolve(__dirname, "src/shims/canvasBrowserStub.js"),
"@hyperframes/player": resolve(__dirname, "../player/src/hyperframes-player.ts"),
+ // Studio serves the runtime itself, so the player it bundles carries no second copy.
+ "@hyperframes/core/runtime-script": resolve(
+ __dirname,
+ "src/shims/runtimeScriptFromStudio.ts",
+ ),
"@hyperframes/studio-server/source-mutation": resolve(
__dirname,
"../studio-server/src/helpers/sourceMutation.ts",
diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json
index 7222a8fde9..bcf682ec4e 100644
--- a/scripts/package-size-budgets.json
+++ b/scripts/package-size-budgets.json
@@ -32,8 +32,8 @@
"unpacked": 915000
},
"@hyperframes/player": {
- "packed": 172000,
- "unpacked": 590000
+ "packed": 437000,
+ "unpacked": 1396000
},
"@hyperframes/producer": {
"packed": 1065767,