From af0c815c72b14bb3d70f6ef762012e87927dff6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Wed, 4 Nov 2026 21:42:59 +0000 Subject: [PATCH] fix(fonts): stop failing cloud renders on var() shorthands, font-X-400 names and linked font sheets (#7166) * fix(fonts): stop failing cloud renders on var() shorthands, font-X-400 names and linked font sheets * style(producer): shorten the project font sheet comment * style(core): shorten the field font families test header * fix(fonts): split font size parsing and fit the CLI size budget * fix(producer): read project font sheets for family names only, never fetch from them --- .../deterministicFonts-fieldFamilies.test.ts | 73 ++++++++++++++ packages/core/src/fonts/deterministicFonts.ts | 27 +++++- .../htmlCompiler.projectFonts.test.ts | 94 +++++++++++++++++++ .../producer/src/services/htmlCompiler.ts | 56 ++++++++--- 4 files changed, 236 insertions(+), 14 deletions(-) create mode 100644 packages/core/src/fonts/deterministicFonts-fieldFamilies.test.ts create mode 100644 packages/producer/src/services/htmlCompiler.projectFonts.test.ts diff --git a/packages/core/src/fonts/deterministicFonts-fieldFamilies.test.ts b/packages/core/src/fonts/deterministicFonts-fieldFamilies.test.ts new file mode 100644 index 0000000000..c1888a9fae --- /dev/null +++ b/packages/core/src/fonts/deterministicFonts-fieldFamilies.test.ts @@ -0,0 +1,73 @@ +// @vitest-environment node +// Family spellings that failed distributed renders closed although the browser draws them. + +import { afterAll, beforeEach, describe, expect, it } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { EMBEDDED_FONT_DATA } from "./fontData.generated.js"; +import { + _clearGoogleFontCssCacheForTests, + injectDeterministicFontFaces, +} from "./deterministicFonts.js"; + +const FONT_CACHE_ENV = "HYPERFRAMES_FONT_CACHE_DIR"; +const originalFontCache = process.env[FONT_CACHE_ENV]; +const fontCache = mkdtempSync(join(tmpdir(), "hf-font-field-families-")); + +beforeEach(() => { + process.env[FONT_CACHE_ENV] = fontCache; + _clearGoogleFontCssCacheForTests(); +}); + +afterAll(() => { + rmSync(fontCache, { recursive: true, force: true }); + if (originalFontCache !== undefined) process.env[FONT_CACHE_ENV] = originalFontCache; + else delete process.env[FONT_CACHE_ENV]; +}); + +// Google Fonts answers 400 for a name it does not know; here it knows none. +const noGoogleFonts = (async () => new Response("", { status: 400 })) as unknown as typeof fetch; + +const inject = (html: string) => + injectDeterministicFontFaces(html, { + failClosedFontFetch: true, + allowSystemFontCapture: false, + fetchImpl: noGoogleFonts, + }); + +const MONTSERRAT_400 = EMBEDDED_FONT_DATA.get("@fontsource/montserrat:400:normal"); + +describe("field font families under fail-closed", () => { + it("reads a font shorthand whose weight is a var() ahead of the size", async () => { + const html = `

hi

`; + + const out = await inject(html); + + expect(out).toContain('font-family: "Montserrat"'); + }); + + it("still takes a lone var() as the size when no literal size follows", async () => { + const html = `

hi

`; + + expect(await inject(html)).toContain('font-family: "Montserrat"'); + }); + + it("serves a class-style family name from the family it names", async () => { + const html = ` +
hi
+ `; + + const out = await inject(html); + + expect(MONTSERRAT_400).toBeDefined(); + expect(out).toContain('font-family: "font-Montserrat-400"'); + expect(out).toContain(`url("${MONTSERRAT_400}")`); + }); +}); diff --git a/packages/core/src/fonts/deterministicFonts.ts b/packages/core/src/fonts/deterministicFonts.ts index 3202c90f5c..ac42839ea8 100644 --- a/packages/core/src/fonts/deterministicFonts.ts +++ b/packages/core/src/fonts/deterministicFonts.ts @@ -990,6 +990,27 @@ function findDeclaredFamilyAlias( return match; } +// Design exports name a family by class, `font--`; serve all faces under that name. +const WEIGHTED_CLASS_FAMILY = /^font-(.+)-[1-9]00$/i; + +async function resolveWeightedClassFamily( + authoredFamily: string, + optional: boolean, + options: InternalFontFetchOptions, + fontText?: string, +): Promise { + const family = WEIGHTED_CLASS_FAMILY.exec(authoredFamily)?.[1]; + if (!family) return null; + return resolveFamilyFaceRules( + normalizeFamilyName(family), + family, + authoredFamily, + optional, + options, + fontText, + ); +} + // Emits under the authored name instead of rewriting usages, as FONT_ALIASES does, // so script-assigned and var()-indirected usages match too. async function resolveDeclaredFamilyAlias( @@ -1065,7 +1086,8 @@ async function buildFontFaceCss( optional, options, fontText, - )); + )) ?? + (await resolveWeightedClassFamily(originalCaseFamily, optional, options, fontText)); options.diag.endFamily(Boolean(familyRules)); if (familyRules) { rules.push(...familyRules); @@ -1823,6 +1845,7 @@ export interface InjectDeterministicFontFacesOptions { * planning; tests may lower delays and timeouts without replacing timers. */ fontFetchRetryPolicy?: Partial; + projectFontFamilies?: readonly string[]; /** * When `true` (default for local renders), fonts that aren't resolved by * the bundled alias map or Google Fonts are located on the local filesystem, @@ -2029,6 +2052,8 @@ export async function injectDeterministicFontFaces( }; const existingFaces = extractExistingFontFaces(html); + for (const family of options.projectFontFamilies ?? []) + existingFaces.add(normalizeFamilyName(family)); const requestedFamilies = extractRequestedFontFamilies(html); const pendingFamilies = new Map(); diff --git a/packages/producer/src/services/htmlCompiler.projectFonts.test.ts b/packages/producer/src/services/htmlCompiler.projectFonts.test.ts new file mode 100644 index 0000000000..edb3faa557 --- /dev/null +++ b/packages/producer/src/services/htmlCompiler.projectFonts.test.ts @@ -0,0 +1,94 @@ +// @vitest-environment node +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { compileForRender } from "./htmlCompiler.js"; + +vi.mock("../utils/urlDownloader.js", async (importOriginal) => ({ + ...(await importOriginal()), + downloadToTemp: async () => { + throw new Error("offline test"); + }, + fetchPublicHttpsText: async () => + `@font-face { font-family: "Project Display"; src: url("https://cdn.example.com/display.woff2"); }`, +})); + +// A distributed render must never ask the network for a font the project itself ships. +const FONT_FILE = join( + __dirname, + "../../tests/heygen-promo-preview-assets/src/TT_Norms_Pro_Medium.woff2", +); + +const page = (head: string, body = "") => ` +${head} +
+

hello

${body} +
`; + +const FACE = `@font-face { font-family: "Project Display"; src: url("fonts/display.woff2") format("woff2"); }`; + +describe("compileForRender with fonts shipped in the project", () => { + let projectDir: string; + let fetchSpy: ReturnType; + + beforeEach(() => { + projectDir = mkdtempSync(join(tmpdir(), "hf-project-fonts-")); + mkdirSync(join(projectDir, "fonts")); + copyFileSync(FONT_FILE, join(projectDir, "fonts/display.woff2")); + fetchSpy = vi.fn(async () => new Response("", { status: 400 })); + vi.stubGlobal("fetch", fetchSpy); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + rmSync(projectDir, { recursive: true, force: true }); + }); + + const compile = (html: string) => { + writeFileSync(join(projectDir, "index.html"), html); + return compileForRender(projectDir, join(projectDir, "index.html"), join(projectDir, ".dl"), { + failClosedFontFetch: true, + allowSystemFontCapture: false, + }); + }; + + it("accepts a family whose @font-face in the page points at a project file", async () => { + const { html } = await compile(page(``)); + expect(html).toContain("Project Display"); + expect(html).not.toContain('url("fonts/display.woff2")'); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it("accepts a family whose @font-face lives in a project stylesheet", async () => { + writeFileSync(join(projectDir, "fonts.css"), FACE); + const { html } = await compile(page(``)); + expect(html).toContain(''); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it("resolves a project stylesheet's font urls against the stylesheet's folder", async () => { + mkdirSync(join(projectDir, "css")); + writeFileSync(join(projectDir, "css/fonts.css"), FACE.replace("fonts/", "../fonts/")); + const { html } = await compile(page(``)); + expect(html).toContain(''); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it("still fails closed when a project stylesheet names a font file the project lacks", async () => { + writeFileSync( + join(projectDir, "fonts.css"), + FACE.replace("fonts/display.woff2", "fonts/missing.woff2"), + ); + await expect(compile(page(``))).rejects.toThrow( + /Unresolved fonts in fail-closed mode: Project Display/, + ); + }); + + it("accepts a family whose @font-face lives in a remote stylesheet", async () => { + const { html } = await compile( + page(``), + ); + expect(html).toContain("Project Display"); + }); +}); diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index e6991ad708..325e791f33 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -12,7 +12,7 @@ import { decodedUrlPath } from "@hyperframes/parsers/asset-paths"; */ import { createHash } from "node:crypto"; -import { createReadStream, existsSync, mkdirSync } from "fs"; +import { createReadStream, existsSync, mkdirSync, readFileSync } from "fs"; import { join, dirname, resolve, basename, relative } from "path"; import { parseHTML } from "linkedom"; import { @@ -1747,6 +1747,32 @@ async function inlineExternalFontStylesheets(html: string): Promise { return result; } +// Families a linked project stylesheet declares with an @font-face file the project ships. +function projectStylesheetFontFamilies(html: string, projectDir: string): string[] { + const families: string[] = []; + for (const [tag] of html.matchAll(/]*\brel=["']stylesheet["'][^>]*>/gi)) { + const href = /\bhref=["']([^"']+)["']/i.exec(tag)?.[1]; + if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) continue; + const sheet = resolve(projectDir, decodedUrlPath(href).replace(/^(?:\.?\/)+/, "")); + if (!isPathInside(sheet, projectDir) || !existsSync(sheet)) continue; + for (const face of extractFontFaceBlocks(readFileSync(sheet, "utf8"))) { + const family = /font-family\s*:\s*([^;}]+)/i + .exec(face)?.[1] + ?.trim() + .replace(/^['"]|['"]$/g, ""); + const shipsFile = [...face.matchAll(LOCAL_FONTFACE_URL_RE)].some(([, url = ""]) => { + const path = decodedUrlPath(url); + const file = path.startsWith("/") + ? resolve(projectDir, `.${path}`) + : resolve(dirname(sheet), path); + return isPathInside(file, projectDir) && existsSync(file); + }); + if (family && shipsFile) families.push(family); + } + } + return families; +} + /** * Collect all remote `url(https://...)` references inside `@font-face` blocks * found in `