Skip to content

Commit 2b57809

Browse files
perf(producer): renders embed local fonts as-is instead of re-compressing them (#5865)
* perf(producer): renders embed local fonts as-is instead of re-compressing them Local ttf/otf fonts in a render were woff2-compressed on every cold font cache, which costs seconds per font. The compiled HTML is a render-time artifact, so embed them raw. fontToDataUri gains a compress: false option; its default is unchanged. * refactor(producer): name the raw local font option instead of explaining it in comments
1 parent 1d631bf commit 2b57809

4 files changed

Lines changed: 70 additions & 4 deletions

File tree

‎packages/core/src/fonts/fontCompression.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,25 @@ describe("fontToDataUri", () => {
136136
expect(uri).toMatch(/^data:font\/otf;base64,/);
137137
});
138138

139+
it("embeds ttf and otf raw without compressing or caching when compress is false", async () => {
140+
const cacheDir = mkdtempSync(join(tmpdir(), "hf-font-compression-off-"));
141+
const compressImpl = vi.fn(async () => Buffer.from("woff2"));
142+
try {
143+
const raw = Buffer.from("font-bytes");
144+
const options = { cacheDir, compressImpl, compressToWoff2: false };
145+
expect(await fontToDataUri(raw, "ttf", options)).toBe(
146+
`data:font/ttf;base64,${raw.toString("base64")}`,
147+
);
148+
expect(await fontToDataUri(raw, "otf", options)).toBe(
149+
`data:font/otf;base64,${raw.toString("base64")}`,
150+
);
151+
expect(compressImpl).not.toHaveBeenCalled();
152+
expect(readdirSync(cacheDir)).toEqual([]);
153+
} finally {
154+
rmSync(cacheDir, { recursive: true, force: true });
155+
}
156+
});
157+
139158
it("embeds ttc collections raw without attempting slow woff2 compression", async () => {
140159
const warnings: unknown[][] = [];
141160
const originalWarn = console.warn;

‎packages/core/src/fonts/fontCompression.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ function rawMimeType(format: string): string {
3333
type FontCompressionOptions = {
3434
cacheDir?: string;
3535
compressImpl?: (input: Buffer) => Promise<Buffer>;
36+
compressToWoff2?: boolean;
3637
};
3738

3839
function defaultCacheDir(): string {
@@ -94,8 +95,8 @@ export async function fontToDataUri(
9495
if (originalFormat === "woff2") {
9596
return `data:font/woff2;base64,${input.toString("base64")}`;
9697
}
97-
if (originalFormat === "ttc") {
98-
return `data:font/collection;base64,${input.toString("base64")}`;
98+
if (originalFormat === "ttc" || options.compressToWoff2 === false) {
99+
return `data:${rawMimeType(originalFormat)};base64,${input.toString("base64")}`;
99100
}
100101
try {
101102
const cachePath = cachedCompressionPath(

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

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// fallow-ignore-file code-duplication
22
import { describe, expect, it, mock, beforeAll } from "bun:test";
33
import { createHash } from "node:crypto";
4-
import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from "node:fs";
4+
import { mkdtempSync, writeFileSync, mkdirSync, rmSync, readFileSync, readdirSync } from "node:fs";
55
import { tmpdir } from "node:os";
66
import { join } from "node:path";
77
import { runInThisContext } from "node:vm";
@@ -1211,6 +1211,52 @@ describe("local font embedding", () => {
12111211
expect(embeddedMessages).toHaveLength(1);
12121212
});
12131213

1214+
it("embeds local ttf and otf fonts as-is without woff2 compression", async () => {
1215+
const projectDir = mkdtempSync(join(tmpdir(), "hf-local-font-raw-"));
1216+
const cacheDir = mkdtempSync(join(tmpdir(), "hf-local-font-cache-"));
1217+
const font = readFileSync(
1218+
join(
1219+
import.meta.dirname,
1220+
"../../../../docs/public/catalog/items/frost-sequence-camera-orbit/assets/fonts/Geist-Regular.ttf",
1221+
),
1222+
);
1223+
writeFileSync(join(projectDir, "a.ttf"), font);
1224+
writeFileSync(join(projectDir, "b.otf"), font);
1225+
writeFileSync(
1226+
join(projectDir, "index.html"),
1227+
`<!DOCTYPE html>
1228+
<html><head><style>
1229+
@font-face { font-family: "A"; src: url("a.ttf"); }
1230+
@font-face { font-family: "B"; src: url("b.otf"); }
1231+
</style></head><body>
1232+
<div data-composition-id="root" data-width="640" data-height="360" data-duration="1">Text</div>
1233+
</body></html>`,
1234+
);
1235+
1236+
const previousCacheDir = process.env.HYPERFRAMES_FONT_CACHE_DIR;
1237+
process.env.HYPERFRAMES_FONT_CACHE_DIR = cacheDir;
1238+
let html: string;
1239+
try {
1240+
({ html } = await compileForRender(projectDir, join(projectDir, "index.html"), projectDir));
1241+
} finally {
1242+
if (previousCacheDir === undefined) delete process.env.HYPERFRAMES_FONT_CACHE_DIR;
1243+
else process.env.HYPERFRAMES_FONT_CACHE_DIR = previousCacheDir;
1244+
}
1245+
1246+
const embedded = (mime: string) =>
1247+
Buffer.from(
1248+
html.match(new RegExp(`data:${mime};base64,([A-Za-z0-9+/=]+)`))?.[1] ?? "",
1249+
"base64",
1250+
);
1251+
expect(embedded("font/ttf").equals(font)).toBe(true);
1252+
expect(embedded("font/otf").equals(font)).toBe(true);
1253+
expect(html).not.toContain("data:font/woff2");
1254+
// The woff2 compressor writes every result to this cache; empty means it never ran.
1255+
expect(readdirSync(cacheDir, { recursive: true })).toEqual([]);
1256+
rmSync(projectDir, { recursive: true, force: true });
1257+
rmSync(cacheDir, { recursive: true, force: true });
1258+
});
1259+
12141260
it("keeps large local font collections file-backed instead of expanding them into HTML", async () => {
12151261
const projectDir = mkdtempSync(join(tmpdir(), "hf-large-local-font-"));
12161262
const assetsDir = join(projectDir, "assets");

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1841,7 +1841,7 @@ async function embedLocalFontFaces(html: string, projectDir: string): Promise<st
18411841
embeddedPaths.add(localPath);
18421842
continue;
18431843
}
1844-
dataUri = await toDataUri(font.buffer, ext);
1844+
dataUri = await toDataUri(font.buffer, ext, { compressToWoff2: false });
18451845
dataUriByAbsolutePath.set(absPath, dataUri);
18461846
defaultLogger.info(
18471847
`[Compiler] Embedded local font file: ${localPath} (${(font.buffer.length / 1024).toFixed(0)} KB → data URI)`,

0 commit comments

Comments
 (0)