diff --git a/docs/packages/producer.mdx b/docs/packages/producer.mdx index aa4dafe81c..af586852b4 100644 --- a/docs/packages/producer.mdx +++ b/docs/packages/producer.mdx @@ -190,6 +190,22 @@ await executeRenderJob( An aborted render throws `RenderCancelledError`. Correctness warnings can also block a render when `strictness: "strict"` is enabled. +## Remote scripts and stylesheets + +Before rendering, the producer downloads a composition's remote ``).join("")}`; +const linkTags = (hrefs: string[]) => + hrefs.map((href) => ``).join("\n"); +const FONT_CSS = '@font-face { font-family: "F"; src: local("F"); }'; + +function project(head: string): string { + const dir = mkdtempSync(join(tmpdir(), "hf-remote-fetch-")); + writeFileSync( + join(dir, "index.html"), + `${head} +
+`, + ); + return dir; +} + +const realVendorDir = process.env[GSAP_VENDOR_DIR_ENV]; +afterEach(() => { + _setDownloadFetchForTests(); + vi.restoreAllMocks(); + if (realVendorDir === undefined) delete process.env[GSAP_VENDOR_DIR_ENV]; + else process.env[GSAP_VENDOR_DIR_ENV] = realVendorDir; +}); +const deadlineStarts = () => + vi.mocked(AbortSignal.timeout).mock.calls.filter(([ms]) => ms === REMOTE_FETCH_DEADLINE_MS) + .length; + +describe("remote downloads at compile time", () => { + // fails without the fix: every distinct address was downloaded, however many. + it("refuses more distinct remote scripts than it downloads, before any request", async () => { + const seen = serve("void 0;"); + await expect( + inlineExternalScripts(scriptTags(urls(MAX_REMOTE_FETCHES + 1, "js"))), + ).rejects.toThrow(`links ${MAX_REMOTE_FETCHES + 1} remote scripts`); + expect(seen.requests).toEqual([]); + }); + + // fails without the fix: the host's copy that fails its tag's integrity is downloaded but was not counted. + it("counts a bundled script whose integrity sends it to the network", async () => { + const vendor = mkdtempSync(join(tmpdir(), "hf-gsap-vendor-")); + writeFileSync(join(vendor, "gsap.min.js"), "var gsap = 1;"); + process.env[GSAP_VENDOR_DIR_ENV] = vendor; + const seen = serve("void 0;"); + const html = scriptTags(urls(MAX_REMOTE_FETCHES, "js")).replace( + "", + ``, + ); + await expect(inlineExternalScripts(html)).rejects.toThrow( + `links ${MAX_REMOTE_FETCHES + 1} remote scripts`, + ); + expect(seen.requests).toEqual([]); + }); + + // fails without the fix: each tag read and held its own copy of the host's bytes before any charge. + it("reads the host's copy of a script once however many tags name it", async () => { + const vendor = mkdtempSync(join(tmpdir(), "hf-gsap-vendor-")); + writeFileSync(join(vendor, "gsap.min.js"), "var gsap = 1;"); + process.env[GSAP_VENDOR_DIR_ENV] = vendor; + vi.mocked(bundledScript).mockClear(); + const tag = ``; + + const inlined = await inlineExternalScripts(`${tag.repeat(5)}`); + + expect(vi.mocked(bundledScript)).toHaveBeenCalledTimes(1); + expect(inlined.match(/var gsap = 1;/g)).toHaveLength(5); + }); + + // fails without the fix: every distinct stylesheet was downloaded, however many. + it("refuses more distinct remote font stylesheets than it downloads, before any request", async () => { + const seen = serve(FONT_CSS); + await expect( + localizeRemoteFontFaces(linkTags(urls(MAX_REMOTE_FETCHES + 1, "css")), tmpdir()), + ).rejects.toThrow(`links ${MAX_REMOTE_FETCHES + 1} remote stylesheets`); + expect(seen.requests).toEqual([]); + }); + + // fails without the fix: the downloads ignored the deadline and ran to their own timeouts. + it("stops pending script downloads once its time is up and leaves their tags", async () => { + const deadline = new AbortController(); + const seen = serve("void 0;", { holdMs: 2_000, onRequest: () => deadline.abort() }); + const html = scriptTags(urls(8, "js")); + + const inlined = await inlineExternalScripts(html, undefined, deadline.signal); + + expect(seen.aborted).toBeGreaterThan(0); + expect(seen.requests.length).toBeLessThan(8); + expect(inlined.match(/', "void 0;"], + ["a font stylesheet", '', FONT_CSS], + ])("stops a compile whose render is cancelled while it downloads %s", async (_, head, body) => { + const cancel = new AbortController(); + const seen = serve(body, { + holdMs: 2_000, + onRequest: () => cancel.abort(new Error("cancelled")), + }); + const dir = project(head); + + await expect( + compileForRender(dir, join(dir, "index.html"), dir, { abortSignal: cancel.signal }), + ).rejects.toThrow("cancelled"); + expect(seen.aborted).toBe(1); + }); + + // fails without the fix: the shared deadline started when compile began, downloads or not. + it("starts the shared deadline with the first download, never for a page without one", async () => { + vi.spyOn(AbortSignal, "timeout"); + let startsAtRequest = -1; + serve("void 0;", { onRequest: () => (startsAtRequest = deadlineStarts()) }); + const local = project(""); + await compileForRender(local, join(local, "index.html"), local); + expect(deadlineStarts()).toBe(0); + + const remote = project(''); + await compileForRender(remote, join(remote, "index.html"), remote); + expect([startsAtRequest, deadlineStarts()]).toEqual([1, 1]); + }); +}); diff --git a/packages/producer/src/services/htmlCompiler.sizeLimit.test.ts b/packages/producer/src/services/htmlCompiler.sizeLimit.test.ts index 067c88818e..6e0c051af7 100644 --- a/packages/producer/src/services/htmlCompiler.sizeLimit.test.ts +++ b/packages/producer/src/services/htmlCompiler.sizeLimit.test.ts @@ -14,6 +14,7 @@ import { compileForRender, inlineExternalScripts, localizeRemoteFontFaces, + MAX_REMOTE_FETCHES, MAX_VARIABLE_MEDIA_SRC_BYTES, } from "./htmlCompiler.js"; import { extractSafeRenderErrorCode } from "./safeRenderErrorCode.js"; @@ -349,22 +350,30 @@ describe("local font embedding", () => { (_, i) => `@font-face { font-family: "F${i}"; src: url("big.ttf"); }`, ).join("\n"); - it("inlines a font that many rules name only while the page stays within the limit", async () => { - const dir = project({ - "index.html": ROOT.replace( - "", - ``, - ), - "scene.html": SCENE, - }); - writeFileSync(join(dir, "big.ttf"), Buffer.alloc(LARGEST_INLINED_FONT_BYTES, 1)); - const { html } = await compileForRender(dir, join(dir, "index.html"), dir); - const inlined = html.split("data:font/ttf;base64,").length - 1; - expect(inlined).toBeGreaterThan(0); - expect(html.length).toBeLessThan(MAX_EXPANDED_COMPOSITION_BYTES + 64 * 1024); - expect(html.split('url("big.ttf")').length - 1).toBe(8 - inlined + 1); - expect(html).toContain('.mark { background: url("big.ttf"); }'); - }); + // Compiles a page at the full limit, so it gets more than the default time. + it( + "inlines a font that many rules name only while the page stays within the limit", + { timeout: 30_000 }, + async () => { + const dataUriChars = Math.ceil(LARGEST_INLINED_FONT_BYTES / 3) * 4; + const rules = Math.ceil(MAX_EXPANDED_COMPOSITION_BYTES / dataUriChars) + 2; + const dir = project({ + "index.html": ROOT.replace( + "", + ``, + ), + "scene.html": SCENE, + }); + writeFileSync(join(dir, "big.ttf"), Buffer.alloc(LARGEST_INLINED_FONT_BYTES, 1)); + const { html } = await compileForRender(dir, join(dir, "index.html"), dir); + const inlined = html.split("data:font/ttf;base64,").length - 1; + expect(inlined).toBeGreaterThan(0); + expect(inlined).toBeLessThan(rules); + expect(html.length).toBeLessThan(MAX_EXPANDED_COMPOSITION_BYTES + 64 * 1024); + expect(html.split('url("big.ttf")').length - 1).toBe(rules - inlined + 1); + expect(html).toContain('.mark { background: url("big.ttf"); }'); + }, + ); }); describe("asset paths rebased from a composition's folder", () => { @@ -462,7 +471,10 @@ describe("remote scripts and stylesheets inlined at compile time", () => { it("stops queued downloads once a script fails its integrity check", async () => { const seen = serve(() => `/*${"x".repeat(MiB)}*/`); - const urls = Array.from({ length: 40 }, (_, i) => `https://cdn.example.com/i${i}.js`); + const urls = Array.from( + { length: MAX_REMOTE_FETCHES }, + (_, i) => `https://cdn.example.com/i${i}.js`, + ); const html = scriptTags(urls).replaceAll("