mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 19:46:11 +00:00
fix(producer): cap compile-time remote downloads, give them one deadline and stop them on cancel (#8195)
* test(producer): compile-time remote downloads are capped, timed and stop with the render * fix(producer): cap compile-time remote downloads, give them one deadline and stop them on cancel * test(producer): size-limit tests stay under the remote download cap * test(producer): count a refetched bundled script; start the deadline at the first download * test(producer): export the download deadline so its test reads the real value * fix(producer): count every downloaded script and start the download deadline at the first one * test(producer): read the host's script copy once however many tags name it * fix(producer): read a bundled script once per address; document the compile download limits * test(producer): size the shared-font test from the 64 MB limit so it reaches it
This commit is contained in:
@@ -0,0 +1,167 @@
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
|
||||
import { _setDownloadFetchForTests } from "@hyperframes/engine";
|
||||
import { bundledScript, GSAP_VENDOR_DIR_ENV } from "./bundledScripts.js";
|
||||
import {
|
||||
compileForRender,
|
||||
inlineExternalScripts,
|
||||
localizeRemoteFontFaces,
|
||||
MAX_REMOTE_FETCHES,
|
||||
REMOTE_FETCH_DEADLINE_MS,
|
||||
} from "./htmlCompiler.js";
|
||||
|
||||
// The real loader, counted: how many times a compile reads the host's own copy.
|
||||
vi.mock("./bundledScripts.js", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("./bundledScripts.js")>();
|
||||
return { ...real, bundledScript: vi.fn(real.bundledScript) };
|
||||
});
|
||||
|
||||
/** Answers each request after `holdMs` unless its signal aborts first; records both. */
|
||||
function serve(body: string, { holdMs = 0, onRequest = () => {} } = {}) {
|
||||
const seen = { requests: [] as string[], aborted: 0 };
|
||||
_setDownloadFetchForTests(async (url: string, init?: RequestInit) => {
|
||||
seen.requests.push(url);
|
||||
onRequest();
|
||||
await new Promise<void>((resolve) => {
|
||||
const stop = () => {
|
||||
clearTimeout(timer);
|
||||
seen.aborted += 1;
|
||||
resolve();
|
||||
};
|
||||
const timer = setTimeout(resolve, holdMs);
|
||||
if (init?.signal?.aborted) stop();
|
||||
else init?.signal?.addEventListener("abort", stop);
|
||||
});
|
||||
init?.signal?.throwIfAborted();
|
||||
return new Response(body);
|
||||
});
|
||||
return seen;
|
||||
}
|
||||
|
||||
const urls = (count: number, ext: string) =>
|
||||
Array.from({ length: count }, (_, i) => `https://cdn.example.com/f${i}.${ext}`);
|
||||
const scriptTags = (srcs: string[]) =>
|
||||
`<html><body>${srcs.map((src) => `<script src="${src}"></script>`).join("")}</body></html>`;
|
||||
const linkTags = (hrefs: string[]) =>
|
||||
hrefs.map((href) => `<link rel="stylesheet" href="${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"),
|
||||
`<!doctype html><html><head>${head}</head><body>
|
||||
<div data-composition-id="root" data-width="320" data-height="180" data-duration="1"></div>
|
||||
</body></html>`,
|
||||
);
|
||||
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(
|
||||
"<body>",
|
||||
`<body><script src="${gsapCdnDist()}gsap.min.js" integrity="sha384-YQ=="></script>`,
|
||||
);
|
||||
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 = `<script src="${gsapCdnDist()}gsap.min.js"></script>`;
|
||||
|
||||
const inlined = await inlineExternalScripts(`<html><body>${tag.repeat(5)}</body></html>`);
|
||||
|
||||
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(/<script src=/g)).toHaveLength(8);
|
||||
});
|
||||
|
||||
// fails without the fix: compile kept downloading after the render was cancelled.
|
||||
it.each([
|
||||
["a script", '<script src="https://cdn.example.com/a.js"></script>', "void 0;"],
|
||||
["a font stylesheet", '<link rel="stylesheet" href="https://cdn.example.com/a.css">', 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('<script src="https://cdn.example.com/a.js"></script>');
|
||||
await compileForRender(remote, join(remote, "index.html"), remote);
|
||||
expect([startsAtRequest, deadlineStarts()]).toEqual([1, 1]);
|
||||
});
|
||||
});
|
||||
@@ -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(
|
||||
"<html>",
|
||||
`<html><head><style>${faces(8)}\n.mark { background: url("big.ttf"); }</style></head>`,
|
||||
),
|
||||
"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(
|
||||
"<html>",
|
||||
`<html><head><style>${faces(rules)}\n.mark { background: url("big.ttf"); }</style></head>`,
|
||||
),
|
||||
"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("<script ", '<script integrity="sha384-YQ==" ');
|
||||
await expect(inlineExternalScripts(html)).rejects.toThrow("integrity mismatch");
|
||||
expect(seen.requests.length).toBeLessThan(urls.length);
|
||||
@@ -493,18 +505,16 @@ describe("remote scripts and stylesheets inlined at compile time", () => {
|
||||
expect(html.split("<p>after</p>").length - 1).toBe(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["distinct", (i: number) => `https://cdn.example.com/f${i}.css`],
|
||||
["repeated", () => "https://cdn.example.com/f.css"],
|
||||
])("refuses %s remote font stylesheets that add up past the render's limit", async (_, url) => {
|
||||
// Distinct sheets cannot get there: at most MAX_REMOTE_FETCHES are downloaded, each at most 2 MiB.
|
||||
it("refuses a repeated remote font stylesheet whose copies add up past the render's limit", async () => {
|
||||
const face = `@font-face { font-family: "F"; src: local("${"x".repeat(MiB)}"); }`;
|
||||
const seen = serve(() => face);
|
||||
const urls = Array.from({ length: pastLimitMiB }, (_, i) => url(i));
|
||||
const urls = Array(pastLimitMiB).fill("https://cdn.example.com/f.css");
|
||||
const error = await localizeRemoteFontFaces(
|
||||
linkTags(urls),
|
||||
mkdtempSync(join(tmpdir(), "hf-remote-sheet-")),
|
||||
).catch((e) => e);
|
||||
expect(extractSafeRenderErrorCode(error)).toBe("COMPOSITION_TOO_LARGE");
|
||||
expect(seen.requests.length).toBeLessThan(urls.length);
|
||||
expect(seen.requests).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1488,28 +1488,59 @@ function operatorGsapMirror(): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadScript(src: string, mirror: string | undefined): Promise<Uint8Array> {
|
||||
async function downloadScript(
|
||||
src: string,
|
||||
mirror: string | undefined,
|
||||
signal: AbortSignal,
|
||||
): Promise<Uint8Array> {
|
||||
if (mirror && new URL(src).href.startsWith(mirror)) {
|
||||
const response = await fetch(src, { redirect: "error", signal: AbortSignal.timeout(15_000) });
|
||||
const response = await fetch(src, {
|
||||
redirect: "error",
|
||||
signal: AbortSignal.any([AbortSignal.timeout(15_000), signal]),
|
||||
});
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status} for ${src}`);
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
if (bytes.byteLength > MAX_SCRIPT_BYTES) throw new Error(`Script over 16 MiB: ${src}`);
|
||||
return bytes;
|
||||
}
|
||||
return fetchPublicHttpsBytes(src, { maxBytes: MAX_SCRIPT_BYTES, timeoutMs: 15_000 });
|
||||
return fetchPublicHttpsBytes(src, { maxBytes: MAX_SCRIPT_BYTES, timeoutMs: 15_000, signal });
|
||||
}
|
||||
|
||||
const MAX_CONCURRENT_SCRIPT_FETCHES = 4;
|
||||
/**
|
||||
* Distinct remote addresses one compile downloads, per kind: scripts, and non-Google stylesheets (counted before
|
||||
* their contents are read, so a stylesheet with no font rules counts too).
|
||||
*/
|
||||
export const MAX_REMOTE_FETCHES = 32;
|
||||
/**
|
||||
* The script and stylesheet inliners' downloads share this much time, from the first one; what is still pending then
|
||||
* counts as failed. Fonts and other assets keep their own per-request limits.
|
||||
*/
|
||||
export const REMOTE_FETCH_DEADLINE_MS = 60_000;
|
||||
/** A signal, or a getter that starts one when the first download asks for it. */
|
||||
type FetchSignal = AbortSignal | (() => AbortSignal);
|
||||
const fetchSignalOf = (signal: FetchSignal | undefined) =>
|
||||
typeof signal === "function" ? signal() : signal;
|
||||
|
||||
function assertRemoteFetchCount(kind: string, count: number): void {
|
||||
if (count > MAX_REMOTE_FETCHES) {
|
||||
throw new Error(
|
||||
`The composition links ${count} remote ${kind}; at most ${MAX_REMOTE_FETCHES} are downloaded at compile time`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Download external CDN scripts and inline them into the HTML so rendering
|
||||
* works without network access (Docker, CI, restricted environments). Each URL
|
||||
* is fetched once, a few at a time, and every inlined copy is charged to the
|
||||
* render's budget as it arrives, so going over stops the downloads still queued.
|
||||
* Once `signal` aborts, pending downloads fail and their tags are left as they are.
|
||||
*/
|
||||
export async function inlineExternalScripts(
|
||||
html: string,
|
||||
budget = new CompositionExpansionBudget(),
|
||||
signal?: FetchSignal,
|
||||
): Promise<string> {
|
||||
const fullHtml = ensureFullDocument(html);
|
||||
const wrappedFragment = fullHtml !== html;
|
||||
@@ -1525,10 +1556,24 @@ export async function inlineExternalScripts(
|
||||
}
|
||||
|
||||
if (externalScripts.length === 0) return html;
|
||||
// The host's own copy needs no network; one that fails the tag's integrity metadata is downloaded instead.
|
||||
// It is read once per address: repeated tags share those bytes, and each is still charged as it is placed.
|
||||
const bundled = new Map<string, Uint8Array | null>();
|
||||
const local = externalScripts.map(({ el, src }) => {
|
||||
if (!bundled.has(src)) bundled.set(src, bundledScript(src));
|
||||
const bytes = bundled.get(src);
|
||||
return bytes && matchesScriptIntegrity(bytes, el.getAttribute("integrity") || "")
|
||||
? bytes
|
||||
: null;
|
||||
});
|
||||
const remote = new Set(externalScripts.filter((_, i) => !local[i]).map(({ src }) => src));
|
||||
assertRemoteFetchCount("scripts", remote.size);
|
||||
|
||||
const mirror = operatorGsapMirror();
|
||||
const limit = createConcurrencyLimit(MAX_CONCURRENT_SCRIPT_FETCHES);
|
||||
const stop = new AbortController();
|
||||
const shared = remote.size > 0 ? fetchSignalOf(signal) : undefined;
|
||||
const fetchSignal = shared ? AbortSignal.any([stop.signal, shared]) : stop.signal;
|
||||
const fail = (error: unknown): never => {
|
||||
stop.abort(error);
|
||||
throw error;
|
||||
@@ -1546,22 +1591,21 @@ export async function inlineExternalScripts(
|
||||
let bytes = fetches.get(src);
|
||||
if (!bytes) {
|
||||
bytes = limit(async () => {
|
||||
if (stop.signal.aborted) throw stop.signal.reason;
|
||||
const downloaded = await downloadScript(src, mirror);
|
||||
fetchSignal.throwIfAborted();
|
||||
const downloaded = await downloadScript(src, mirror, fetchSignal);
|
||||
charge(downloaded.byteLength);
|
||||
return downloaded;
|
||||
}, stop.signal);
|
||||
}, fetchSignal);
|
||||
fetches.set(src, bytes);
|
||||
}
|
||||
return bytes;
|
||||
};
|
||||
const placed = new Set<string>();
|
||||
const downloads = await Promise.allSettled(
|
||||
externalScripts.map(async ({ el, src }) => {
|
||||
externalScripts.map(async ({ el, src }, i) => {
|
||||
const integrity = el.getAttribute("integrity") || "";
|
||||
// The host's own copy needs no network; one that fails the tag's integrity metadata is not used.
|
||||
let bytes = bundledScript(src);
|
||||
if (bytes && matchesScriptIntegrity(bytes, integrity)) {
|
||||
let bytes = local[i];
|
||||
if (bytes) {
|
||||
charge(bytes.byteLength);
|
||||
} else {
|
||||
bytes = await fetchOnce(src);
|
||||
@@ -1901,12 +1945,16 @@ function isGoogleFontsUrl(href: string): boolean {
|
||||
|
||||
const MAX_STYLESHEET_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
async function fetchExternalStylesheetCss(href: string): Promise<string | null> {
|
||||
async function fetchExternalStylesheetCss(
|
||||
href: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<string | null> {
|
||||
const identity = safeDownloadUrlIdentity(href);
|
||||
try {
|
||||
return await fetchPublicHttpsText(href, {
|
||||
maxBytes: MAX_STYLESHEET_BYTES,
|
||||
timeoutMs: 15_000,
|
||||
signal,
|
||||
});
|
||||
} catch (err) {
|
||||
defaultLogger.warn("[Compiler] External stylesheet fetch failed, preserving link tag.", {
|
||||
@@ -1975,6 +2023,7 @@ function remoteFontStylesheetHref(tag: string): string | undefined {
|
||||
async function inlineExternalFontStylesheets(
|
||||
html: string,
|
||||
budget = new CompositionExpansionBudget(),
|
||||
signal?: FetchSignal,
|
||||
): Promise<string> {
|
||||
const hrefs = new Set<string>();
|
||||
for (const { parts } of stylesheetLinkMatches(html)) {
|
||||
@@ -1982,29 +2031,35 @@ async function inlineExternalFontStylesheets(
|
||||
if (href) hrefs.add(href);
|
||||
}
|
||||
if (hrefs.size === 0) return html;
|
||||
assertRemoteFetchCount("stylesheets", hrefs.size);
|
||||
|
||||
// Each sheet is fetched once and only its font rules are kept, charged as they arrive.
|
||||
const MAX_CONCURRENT_STYLESHEET_FETCHES = 4;
|
||||
// Each sheet is fetched once, a few at a time, and only its font rules are kept, charged as they arrive.
|
||||
const limit = createConcurrencyLimit(MAX_CONCURRENT_SCRIPT_FETCHES);
|
||||
const stop = new AbortController();
|
||||
const shared = fetchSignalOf(signal);
|
||||
const fetchSignal = shared ? AbortSignal.any([stop.signal, shared]) : stop.signal;
|
||||
const inlineByHref = new Map<string, string>();
|
||||
const unique = [...hrefs];
|
||||
for (let i = 0; i < unique.length; i += MAX_CONCURRENT_STYLESHEET_FETCHES) {
|
||||
const batch = unique.slice(i, i + MAX_CONCURRENT_STYLESHEET_FETCHES);
|
||||
const sheets = await Promise.all(batch.map(fetchExternalStylesheetCss));
|
||||
batch.forEach((href, index) => {
|
||||
const css = sheets[index];
|
||||
const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
|
||||
if (fontFaceBlocks.length === 0) return;
|
||||
const inlineStyle = `<style>/* Inlined external font stylesheet */\n${fontFaceBlocks.join("\n")}\n</style>`;
|
||||
const inlineSheet = async (href: string) => {
|
||||
const css = await fetchExternalStylesheetCss(href, fetchSignal);
|
||||
const fontFaceBlocks = css ? extractFontFaceBlocks(css) : [];
|
||||
if (fontFaceBlocks.length === 0) return;
|
||||
const inlineStyle = `<style>/* Inlined external font stylesheet */\n${fontFaceBlocks.join("\n")}\n</style>`;
|
||||
try {
|
||||
budget.chargeGenerated(REMOTE_STYLESHEETS, inlineStyle.length);
|
||||
inlineByHref.set(href, inlineStyle);
|
||||
const identity = safeDownloadUrlIdentity(href);
|
||||
defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
|
||||
count: fontFaceBlocks.length,
|
||||
urlFingerprint: identity.urlFingerprint,
|
||||
host: identity.host,
|
||||
});
|
||||
} catch (error) {
|
||||
stop.abort(error);
|
||||
throw error;
|
||||
}
|
||||
inlineByHref.set(href, inlineStyle);
|
||||
const identity = safeDownloadUrlIdentity(href);
|
||||
defaultLogger.debug("[Compiler] Inlined external @font-face rule(s)", {
|
||||
count: fontFaceBlocks.length,
|
||||
urlFingerprint: identity.urlFingerprint,
|
||||
host: identity.host,
|
||||
});
|
||||
}
|
||||
};
|
||||
await Promise.allSettled([...hrefs].map((href) => limit(() => inlineSheet(href), fetchSignal)));
|
||||
if (stop.signal.aborted) throw stop.signal.reason;
|
||||
|
||||
const placed = new Set<string>();
|
||||
return replaceMatches(html, stylesheetLinkMatches(html), (tag) => {
|
||||
@@ -2258,7 +2313,7 @@ export interface CompileForRenderOptions {
|
||||
* prevent host-specific font capture from leaking into the planDir.
|
||||
*/
|
||||
allowSystemFontCapture?: boolean;
|
||||
/** Caller cancellation propagated through compile-time font fetches. */
|
||||
/** Caller cancellation propagated through compile-time font, stylesheet and script fetches. */
|
||||
abortSignal?: AbortSignal;
|
||||
/** Persistent cache directory for the animated GIF and HEIC prep transcodes; defaults to downloadDir. */
|
||||
animatedGifCacheDir?: string;
|
||||
@@ -2504,11 +2559,19 @@ export async function compileForRender(
|
||||
const usesThreeDTransforms = detectThreeDTransformUsage(sanitizedHtml);
|
||||
const hasAncestorBackgroundImage = detectAncestorBackgroundImage(sanitizedHtml);
|
||||
|
||||
let deadline: AbortSignal | undefined;
|
||||
const remoteFetches = () =>
|
||||
(deadline ??= AbortSignal.any([
|
||||
AbortSignal.timeout(REMOTE_FETCH_DEADLINE_MS),
|
||||
...(options.abortSignal ? [options.abortSignal] : []),
|
||||
]));
|
||||
// Remote font stylesheets join the page first, or the font check below cannot see them.
|
||||
const fontSheetHtml = await inlineExternalFontStylesheets(
|
||||
promoteCssImportsToLinkTags(sanitizedHtml),
|
||||
budget,
|
||||
remoteFetches,
|
||||
);
|
||||
options.abortSignal?.throwIfAborted();
|
||||
const normalizedFontHtml = normalizeSystemFontPrimaryFamilies(
|
||||
injectTextRenderingRule(coalesceHeadStylesAndBodyScripts(fontSheetHtml)),
|
||||
);
|
||||
@@ -2522,7 +2585,8 @@ export async function compileForRender(
|
||||
});
|
||||
|
||||
// CDN scripts are inlined after coalescing so they stay separate from the merged inline runs.
|
||||
const assembledHtml = await inlineExternalScripts(coalescedHtml, budget);
|
||||
const assembledHtml = await inlineExternalScripts(coalescedHtml, budget, remoteFetches);
|
||||
options.abortSignal?.throwIfAborted();
|
||||
|
||||
// Inject studio position seek re-apply script when positions are baked into HTML.
|
||||
// GSAP overwrites the `translate` CSS property on every frame seek; this script
|
||||
|
||||
Reference in New Issue
Block a user