From 9f0a4edb439bbdc9782617a433b80d3f7f9dbe76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Fri, 13 Nov 2026 15:58:02 +0000 Subject: [PATCH] perf(core): the font step parses the page once for all its readers (#7650) --- .../core/src/fonts/authoredGoogleFonts.ts | 4 +- .../deterministicFonts-parseOnce.test.ts | 62 +++++++++++++++++++ packages/core/src/fonts/deterministicFonts.ts | 18 +++--- packages/core/src/fonts/pageTree.ts | 25 ++++++++ 4 files changed, 99 insertions(+), 10 deletions(-) create mode 100644 packages/core/src/fonts/deterministicFonts-parseOnce.test.ts create mode 100644 packages/core/src/fonts/pageTree.ts diff --git a/packages/core/src/fonts/authoredGoogleFonts.ts b/packages/core/src/fonts/authoredGoogleFonts.ts index ffac007b39..cd122dc58f 100644 --- a/packages/core/src/fonts/authoredGoogleFonts.ts +++ b/packages/core/src/fonts/authoredGoogleFonts.ts @@ -1,4 +1,4 @@ -import { parseHTML } from "linkedom"; +import { readPage } from "./pageTree.js"; import postcss from "postcss"; function screenStylesheet(media: string | null): boolean { @@ -66,7 +66,7 @@ function stylesheetUrls(element: StylesheetElement): string[] { export function authoredGoogleFontStylesheets(html: string): Map { const byFamily = new Map(); - const { document } = parseHTML(html); + const document = readPage(html); for (const element of document.querySelectorAll("link, style")) { for (const url of stylesheetUrls(element)) { for (const family of googleStylesheetFamilies(url)) { diff --git a/packages/core/src/fonts/deterministicFonts-parseOnce.test.ts b/packages/core/src/fonts/deterministicFonts-parseOnce.test.ts new file mode 100644 index 0000000000..e278f0d027 --- /dev/null +++ b/packages/core/src/fonts/deterministicFonts-parseOnce.test.ts @@ -0,0 +1,62 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const parses = vi.hoisted(() => ({ count: 0 })); + +vi.mock("linkedom", async (importOriginal) => { + const original = await importOriginal(); + return { + ...original, + parseHTML: (...args: Parameters) => { + parses.count += 1; + return original.parseHTML(...args); + }, + }; +}); + +import { + injectDeterministicFontFaces, + normalizeSystemFontPrimaryFamilies, +} from "./deterministicFonts.js"; + +const page = (note: string, family: string) => + `

Hello

`; + +const offline = () => Promise.reject(new Error("offline")); + +describe("the font step parses the page once", () => { + beforeEach(() => { + parses.count = 0; + }); + + it("builds the page's tree once for normalizing and once for injecting", async () => { + const html = page("both steps", "-apple-system, Inter"); + const normalized = normalizeSystemFontPrimaryFamilies(html); + expect(parses.count).toBe(1); + parses.count = 0; + const injected = await injectDeterministicFontFaces(normalized, { fetchImpl: offline }); + expect(parses.count).toBe(1); + expect(injected).toContain("data-hyperframes-deterministic-fonts"); + }); + + it("reads a page that needs no normalizing once across both steps", async () => { + const html = page("unchanged", "Inter"); + const same = normalizeSystemFontPrimaryFamilies(html); + expect(same).toBe(html); + const injected = await injectDeterministicFontFaces(same, { fetchImpl: offline }); + expect(parses.count).toBe(1); + expect(injected).toContain("data-hyperframes-deterministic-fonts"); + }); + + it("gives the same page the same output as when each step parses on its own", async () => { + const html = page("same output", "-apple-system, Inter"); + const together = await injectDeterministicFontFaces(normalizeSystemFontPrimaryFamilies(html), { + fetchImpl: offline, + }); + // another page in between drops the shared tree, so the steps below parse for themselves + await injectDeterministicFontFaces(page("other", "Inter"), { fetchImpl: offline }); + const normalized = normalizeSystemFontPrimaryFamilies(html); + await injectDeterministicFontFaces(page("other again", "Inter"), { fetchImpl: offline }); + const apart = await injectDeterministicFontFaces(normalized, { fetchImpl: offline }); + expect(together).toBe(apart); + }); +}); diff --git a/packages/core/src/fonts/deterministicFonts.ts b/packages/core/src/fonts/deterministicFonts.ts index f33973d91c..b6a83eb194 100644 --- a/packages/core/src/fonts/deterministicFonts.ts +++ b/packages/core/src/fonts/deterministicFonts.ts @@ -15,7 +15,7 @@ import { fontShorthandFamilies } from "@hyperframes/parsers/composition"; import { FONT_ALIAS_MAP, resolveAliasDisplayName } from "./aliases.js"; import { extractSfntFace } from "./sfntNames.js"; import { locateSystemFontVariants, SYSTEM_FONT_SIZE_LIMIT } from "./systemFontLocator.js"; -import { parseHTML } from "linkedom"; +import { forgetPage, readPage, takePage } from "./pageTree.js"; import postcss, { type AtRule, type Declaration, type Rule } from "postcss"; import { EMBEDDED_FONT_DATA } from "./fontData.generated.js"; import { fontToDataUri } from "./fontCompression.js"; @@ -214,7 +214,7 @@ export function normalizeSystemFontPrimaryFamilies( html: string, deterministicPrimary = "Inter", ): string { - const { document } = parseHTML(html); + const document = readPage(html); const customProperties = collectFontFamilyCustomProperties(html); const replacePrimary: PrimaryReplacer = (value) => systemPrimaryReplacement(value, deterministicPrimary, customProperties); @@ -244,7 +244,9 @@ export function normalizeSystemFontPrimaryFamilies( changed = true; } - return changed ? document.toString() : html; + if (!changed) return html; + forgetPage(); + return document.toString(); } /** Surfaces font-family is declared on in served HTML. */ @@ -307,7 +309,7 @@ function* iterateInlineStyleFontFamilyDeclarations( * `font-family: var(--font)`. */ export function collectFontFamilyCustomProperties(html: string): Map { - const { document } = parseHTML(html); + const document = readPage(html); const customProperties = new Map(); for (const styleEl of Array.from(document.querySelectorAll("style"))) { @@ -402,7 +404,7 @@ export function resolveFontFamilyDeclarationFamilies( export function* iterateFontFamilyDeclarations( html: string, ): Generator { - const { document } = parseHTML(html); + const document = readPage(html); for (const styleEl of Array.from(document.querySelectorAll("style"))) { yield* iterateCssFontFamilyDeclarations(styleEl.textContent ?? ""); @@ -966,7 +968,7 @@ function declareLinkedFontFamilies( } function collectDeclaredFontFamilies(html: string): DeclaredFontFamilies { - const { document } = parseHTML(html); + const document = readPage(html); const declared = new Map(); const register: DeclaredFontRegister = (family, fontFaceRule) => { const key = normalizeFamilyName(family); @@ -1990,7 +1992,7 @@ function hasTextTransformKeyword(html: string, keyword: RegExp): boolean { } function extractGoogleFontsText(html: string): string | undefined { - const { document } = parseHTML(html); + const document = readPage(html); const decodedBodyText = document.body?.textContent ?? ""; const locales = collectLangAttributes(document); @@ -2119,7 +2121,7 @@ export async function injectDeterministicFontFaces( return html; } - const { document } = parseHTML(html); + const document = takePage(html); const head = document.querySelector("head"); if (!head) { return html; diff --git a/packages/core/src/fonts/pageTree.ts b/packages/core/src/fonts/pageTree.ts new file mode 100644 index 0000000000..cc917d206b --- /dev/null +++ b/packages/core/src/fonts/pageTree.ts @@ -0,0 +1,25 @@ +import { parseHTML } from "linkedom"; + +export type PageDocument = ReturnType["document"]; + +/** The tree of the page the font step read last, so its readers share one parse of it. */ +let lastPage: { html: string; document: PageDocument } | undefined; + +export function readPage(html: string): PageDocument { + if (lastPage?.html === html) return lastPage.document; + const { document } = parseHTML(html); + lastPage = { html, document }; + return document; +} + +/** The page's tree for a step that edits it: handed over, and no longer the page the readers share. */ +export function takePage(html: string): PageDocument { + const document = readPage(html); + lastPage = undefined; + return document; +} + +/** The tree handed out was edited: it no longer reads as the page it came from. */ +export function forgetPage(): void { + lastPage = undefined; +}