Skip to content

Commit 3b79b18

Browse files
fix(producer): inline a local font only while the page stays within its size limit (#8152)
* test(producer): a font many rules name stays within the page's size limit * fix(producer): inline a local font only while the page stays within its size limit Only url() sources inside @font-face rules are replaced, and every inlined copy is charged to the render's expansion budget. Once the budget is spent, the remaining references keep loading the font from its file. * fix(producer): keep the font anchoring test and name the fit-or-skip charge
1 parent e623031 commit 3b79b18

4 files changed

Lines changed: 153 additions & 111 deletions

File tree

‎packages/producer/src/services/compositionSizeLimit.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,12 @@ export class CompositionExpansionBudget {
8787
});
8888
}
8989

90+
chargeGeneratedIfItFits(bytes: number): boolean {
91+
if (this.generated + bytes > MAX_EXPANDED_COMPOSITION_BYTES) return false;
92+
this.generated += bytes;
93+
return true;
94+
}
95+
9096
charge(file: string, bytes: number): void {
9197
this.bytes += bytes;
9298
this.mounts += 1;
Lines changed: 31 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,41 @@
1+
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
2+
import { tmpdir } from "node:os";
3+
import { dirname, join } from "node:path";
14
import { describe, expect, it } from "vitest";
2-
import { urlOccurrenceRe } from "./htmlCompiler.js";
5+
import { compileForRender } from "./htmlCompiler.js";
36

47
/**
5-
* The embed step used `result.replaceAll(localPath, dataUri)` — a bare
6-
* substring rewrite over the whole compiled document. These pin the collision
7-
* that made unsafe: it is invisible in ordinary projects and easy to
8-
* reintroduce, because the naive form passes every test that uses one font.
8+
* A whole-document substring rewrite of a font path also rewrote the tail of a longer path and the
9+
* same text in a comment. These are invisible in a project with one font.
910
*/
1011
describe("font embed url() anchoring", () => {
11-
const DATA_URI = "data:font/woff2;base64,AAAA";
12-
const replace = (html: string, path: string) =>
13-
html.replace(urlOccurrenceRe(path), `url("${DATA_URI}")`);
12+
const fonts = {
13+
"img/logo.ttf": "short",
14+
"assets/img/logo.ttf": "long",
15+
"fonts/x+y[1].ttf": "meta",
16+
};
17+
const dataUri = (text: string) =>
18+
`url("data:font/ttf;base64,${Buffer.from(text).toString("base64")}")`;
1419

15-
it("rewrites the exact occurrence, quoted or bare", () => {
16-
expect(replace(`src: url("fonts/x.ttf")`, "fonts/x.ttf")).toBe(`src: url("${DATA_URI}")`);
17-
expect(replace(`src: url(fonts/x.ttf)`, "fonts/x.ttf")).toBe(`src: url("${DATA_URI}")`);
18-
expect(replace(`src: url('fonts/x.ttf')`, "fonts/x.ttf")).toBe(`src: url("${DATA_URI}")`);
19-
});
20-
21-
it("does not corrupt a longer url whose tail matches the embedded path", () => {
22-
// The reported corruption: embedding `fonts/x.ttf` rewrote the tail of an
23-
// untouched absolute rule, producing `url("file:///abs/<data-uri>")`.
24-
const html = `a { src: url("fonts/x.ttf") } b { src: url("file:///abs/fonts/x.ttf") }`;
25-
const out = replace(html, "fonts/x.ttf");
26-
expect(out).toContain(`a { src: url("${DATA_URI}") }`);
27-
expect(out).toContain(`b { src: url("file:///abs/fonts/x.ttf") }`);
28-
});
20+
it("replaces each @font-face source with its own file and nothing else", async () => {
21+
const dir = mkdtempSync(join(tmpdir(), "hf-font-anchor-"));
22+
for (const [path, text] of Object.entries(fonts)) {
23+
mkdirSync(dirname(join(dir, path)), { recursive: true });
24+
writeFileSync(join(dir, path), text);
25+
}
26+
const faces = Object.keys(fonts)
27+
.map((path, i) => `@font-face { font-family: "F${i}"; src: url("${path}"); }`)
28+
.join("\n");
29+
writeFileSync(
30+
join(dir, "index.html"),
31+
`<!doctype html><html><head><style>/* see img/logo.ttf */\n${faces}</style></head><body>
32+
<div data-composition-id="root" data-width="640" data-height="360" data-duration="1">Text</div>
33+
</body></html>`,
34+
);
2935

30-
it("does not corrupt a sibling whose path is a suffix of another project path", () => {
31-
// No file:// needed. Any two paths where one is a suffix of the other
32-
// collide under a bare substring replace.
33-
const html = `a { src: url("img/logo.ttf") } b { src: url("assets/img/logo.ttf") }`;
34-
const out = replace(html, "img/logo.ttf");
35-
expect(out).toContain(`a { src: url("${DATA_URI}") }`);
36-
expect(out).toContain(`b { src: url("assets/img/logo.ttf") }`);
37-
});
38-
39-
it("leaves the path alone outside a url() wrapper", () => {
40-
const html = `/* see fonts/x.ttf for the source */ a { src: url("fonts/x.ttf") }`;
41-
const out = replace(html, "fonts/x.ttf");
42-
expect(out).toContain("/* see fonts/x.ttf for the source */");
43-
});
36+
const { html } = await compileForRender(dir, join(dir, "index.html"), dir);
4437

45-
it("treats regex metacharacters in a path literally", () => {
46-
const html = `a { src: url("fonts/x+y(1).ttf") }`;
47-
expect(replace(html, "fonts/x+y(1).ttf")).toBe(`a { src: url("${DATA_URI}") }`);
38+
for (const text of Object.values(fonts)) expect(html).toContain(dataUri(text));
39+
expect(html).toContain("/* see img/logo.ttf */");
4840
});
4941
});

‎packages/producer/src/services/htmlCompiler.sizeLimit.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,3 +319,29 @@ describe("variable-driven composition styles and media sources", () => {
319319
expect(await srcFor("https://example.com/x.mp4\n")).toBe("https://example.com/x.mp4");
320320
});
321321
});
322+
323+
describe("local font embedding", () => {
324+
const LARGEST_INLINED_FONT_BYTES = 5 * 1024 * 1024;
325+
const faces = (count: number) =>
326+
Array.from(
327+
{ length: count },
328+
(_, i) => `@font-face { font-family: "F${i}"; src: url("big.ttf"); }`,
329+
).join("\n");
330+
331+
it("inlines a font that many rules name only while the page stays within the limit", async () => {
332+
const dir = project({
333+
"index.html": ROOT.replace(
334+
"<html>",
335+
`<html><head><style>${faces(8)}\n.mark { background: url("big.ttf"); }</style></head>`,
336+
),
337+
"scene.html": SCENE,
338+
});
339+
writeFileSync(join(dir, "big.ttf"), Buffer.alloc(LARGEST_INLINED_FONT_BYTES, 1));
340+
const { html } = await compileForRender(dir, join(dir, "index.html"), dir);
341+
const inlined = html.split("data:font/ttf;base64,").length - 1;
342+
expect(inlined).toBeGreaterThan(0);
343+
expect(html.length).toBeLessThan(MAX_EXPANDED_COMPOSITION_BYTES + 64 * 1024);
344+
expect(html.split('url("big.ttf")').length - 1).toBe(8 - inlined + 1);
345+
expect(html).toContain('.mark { background: url("big.ttf"); }');
346+
});
347+
});

‎packages/producer/src/services/htmlCompiler.ts‎

Lines changed: 90 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -2043,15 +2043,6 @@ function localizeFontFaceUrls(
20432043
);
20442044
}
20452045

2046-
/**
2047-
* Match one `url(<path>)` occurrence, with or without quotes, for a literal
2048-
* path. Exported for tests: the suffix-collision it prevents is invisible in
2049-
* ordinary projects and easy to reintroduce.
2050-
*/
2051-
export function urlOccurrenceRe(localPath: string): RegExp {
2052-
const escaped = localPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2053-
return new RegExp(`url\\((["']?)${escaped}\\1\\)`, "g");
2054-
}
20552046
// Base64 expands bytes by ~33%, then immutable HTML replacements retain more
20562047
// string copies while compiling. Files up to and including 5 MiB remain inline;
20572048
// the first byte above that stays file-backed. This conservative ceiling keeps
@@ -2075,81 +2066,107 @@ async function readLocalFont(absPath: string): Promise<LocalFontRead> {
20752066
return { kind: "inline", buffer: Buffer.concat(chunks, totalBytes) };
20762067
}
20772068

2078-
// fallow-ignore-next-line complexity
2069+
/** The data URI a project font path embeds as, or undefined when it stays a file. */
2070+
async function localFontDataUri(
2071+
localPath: string,
2072+
projectDir: string,
2073+
assetRoot: string | undefined,
2074+
dataUriByAbsolutePath: Map<string, string | undefined>,
2075+
log: ProducerLogger,
2076+
): Promise<string | undefined> {
2077+
const absPath = localPath.startsWith("/") ? localPath : resolve(projectDir, localPath);
2078+
if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) return undefined;
2079+
// A project font that is a link leading outside obeys the same policy as the file server.
2080+
if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
2081+
return undefined;
2082+
}
2083+
if (isPrivateCompositionFile(projectDir, absPath)) return undefined;
2084+
if (dataUriByAbsolutePath.has(absPath)) return dataUriByAbsolutePath.get(absPath);
2085+
const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
2086+
try {
2087+
const font = await readLocalFont(absPath);
2088+
if (font.kind === "file-backed") {
2089+
dataUriByAbsolutePath.set(absPath, undefined);
2090+
defaultLogger.debug(
2091+
`[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`,
2092+
);
2093+
return undefined;
2094+
}
2095+
const { fontToDataUri } = await import("@hyperframes/core/fonts/embed");
2096+
const dataUri = await fontToDataUri(font.buffer, ext, { compressToWoff2: false });
2097+
dataUriByAbsolutePath.set(absPath, dataUri);
2098+
defaultLogger.debug(
2099+
`[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB → data URI)`,
2100+
);
2101+
return dataUri;
2102+
} catch (error) {
2103+
// Keep the original path: a font that cannot be read must not fail the render, but say why
2104+
// it renders in a fallback typeface.
2105+
defaultLogger.warn(
2106+
`[Compiler] Could not embed local font ${localPath}: ${
2107+
error instanceof Error ? error.message : String(error)
2108+
}`,
2109+
);
2110+
return undefined;
2111+
}
2112+
}
2113+
2114+
/** `whole` with its `inner` text, which ends `tail` characters before its end, replaced. */
2115+
const replaceInner = (whole: string, inner: string, tail: number, next: string) =>
2116+
whole.slice(0, whole.length - tail - inner.length) + next + whole.slice(whole.length - tail);
2117+
2118+
/**
2119+
* Inline the project fonts that `<style>` `@font-face` sources name as data URIs. Every copy is
2120+
* charged to the render's budget, so a font named by many rules stops being inlined once the
2121+
* budget is spent and the rest keep loading it from its file.
2122+
*/
20792123
async function embedLocalFontFaces(
20802124
html: string,
20812125
projectDir: string,
20822126
assetRoot: string | undefined,
2127+
budget: CompositionExpansionBudget,
20832128
log: ProducerLogger = defaultLogger,
20842129
): Promise<string> {
2085-
const { fontToDataUri: toDataUri } = await import("@hyperframes/core/fonts/embed");
2086-
let result = html;
2087-
const embeddedPaths = new Set<string>();
2088-
const dataUriByAbsolutePath = new Map<string, string>();
2089-
const fileBackedAbsolutePaths = new Set<string>();
2090-
2130+
const dataUriByPath = new Map<string, string | undefined>();
2131+
const dataUriByAbsolutePath = new Map<string, string | undefined>();
20912132
for (const { parts: style } of styleBlockMatches(html)) {
20922133
for (const { parts: face } of fontFaceBlockMatches(style[1])) {
2093-
const block = face[1];
2094-
for (const { parts } of localFontFaceUrlMatches(block)) {
2134+
for (const { parts } of localFontFaceUrlMatches(face[1])) {
20952135
const localPath = parts[1];
2096-
if (!localPath || embeddedPaths.has(localPath)) continue;
2097-
const absPath = localPath.startsWith("/") ? localPath : resolve(projectDir, localPath);
2098-
if (!isPathInside(absPath, projectDir) || escapesAssetRoot(absPath, assetRoot)) continue;
2099-
// A project font that is a link leading outside obeys the same policy as the file server.
2100-
if (refusesOutsideLink(projectDir, absPath, (line) => log.warn(`[Compiler] ${line}`))) {
2101-
embeddedPaths.add(localPath);
2102-
continue;
2103-
}
2104-
if (isPrivateCompositionFile(projectDir, absPath)) continue;
2105-
const ext = absPath.match(/\.(woff2?|ttf|otf|ttc)$/i)?.[1]?.toLowerCase() ?? "ttf";
2106-
try {
2107-
if (fileBackedAbsolutePaths.has(absPath)) {
2108-
embeddedPaths.add(localPath);
2109-
continue;
2110-
}
2111-
let dataUri = dataUriByAbsolutePath.get(absPath);
2112-
if (!dataUri) {
2113-
const font = await readLocalFont(absPath);
2114-
if (font.kind === "file-backed") {
2115-
fileBackedAbsolutePaths.add(absPath);
2116-
defaultLogger.debug(
2117-
`[Compiler] Kept large local font file-backed: ${localPath} (> ${(MAX_LOCAL_FONT_DATA_URI_BYTES / 1024 / 1024).toFixed(1)} MB)`,
2118-
);
2119-
embeddedPaths.add(localPath);
2120-
continue;
2121-
}
2122-
dataUri = await toDataUri(font.buffer, ext, { compressToWoff2: false });
2123-
dataUriByAbsolutePath.set(absPath, dataUri);
2124-
defaultLogger.debug(
2125-
`[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB → data URI)`,
2126-
);
2127-
}
2128-
// Anchored on the `url(...)` occurrence, not a bare substring. A
2129-
// plain replaceAll of `localPath` also rewrites that text anywhere
2130-
// else it appears -- including inside a LONGER url whose tail
2131-
// happens to match, e.g. embedding `fonts/x.ttf` would corrupt an
2132-
// untouched `url("file:///abs/fonts/x.ttf")` into
2133-
// `url("file:///abs/<data-uri>")`. Any two paths where one is a
2134-
// suffix of the other collide the same way. Every sibling rewrite
2135-
// in this file already anchors like this.
2136-
result = result.replace(urlOccurrenceRe(localPath), `url("${dataUri}")`);
2137-
embeddedPaths.add(localPath);
2138-
} catch (error) {
2139-
// Keep the original path: a font that cannot be read must not fail
2140-
// the render. Logged rather than silently swallowed -- a silent skip
2141-
// here means the composition renders in a fallback typeface and
2142-
// nothing says why.
2143-
defaultLogger.warn(
2144-
`[Compiler] Could not embed local font ${localPath}: ${
2145-
error instanceof Error ? error.message : String(error)
2146-
}`,
2147-
);
2148-
}
2136+
if (!localPath || dataUriByPath.has(localPath)) continue;
2137+
dataUriByPath.set(
2138+
localPath,
2139+
await localFontDataUri(localPath, projectDir, assetRoot, dataUriByAbsolutePath, log),
2140+
);
21492141
}
21502142
}
21512143
}
2152-
return result;
2144+
if (![...dataUriByPath.values()].some(Boolean)) return html;
2145+
2146+
let warned = false;
2147+
const embed = (source: string, localPath: string) => {
2148+
const dataUri = dataUriByPath.get(localPath);
2149+
if (!dataUri) return source;
2150+
const inlined = `url("${dataUri}")`;
2151+
if (budget.chargeGeneratedIfItFits(inlined.length - source.length)) return inlined;
2152+
if (!warned) {
2153+
warned = true;
2154+
log.warn(
2155+
`[Compiler] Kept local font ${localPath} file-backed: the page reached its inline size limit`,
2156+
);
2157+
}
2158+
return source;
2159+
};
2160+
return replaceMatches(html, styleBlockMatches(html), (style, css) =>
2161+
replaceInner(
2162+
style,
2163+
css,
2164+
"</style>".length,
2165+
replaceMatches(css, fontFaceBlockMatches(css), (face, body) =>
2166+
replaceInner(face, body, 1, replaceMatches(body, localFontFaceUrlMatches(body), embed)),
2167+
),
2168+
),
2169+
);
21532170
}
21542171

21552172
/**
@@ -2518,6 +2535,7 @@ export async function compileForRender(
25182535
htmlWithPreparedGifs,
25192536
projectDir,
25202537
assetRoot,
2538+
budget,
25212539
options.log,
25222540
);
25232541

0 commit comments

Comments
 (0)