// @vitest-environment node import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { beforeEach, expect, it } from "vitest"; import { _clearGoogleFontCssCacheForTests, injectDeterministicFontFaces, } from "./deterministicFonts.js"; const WOFF2 = new Uint8Array([0x77, 0x4f, 0x46, 0x32, 1, 2, 3]); const SHARED = "https://fonts.gstatic.com/s/b/v9/variable.woff2"; const ITALIC = "https://fonts.gstatic.com/s/b/v9/italic.woff2"; const face = (weight: number, style: string, url: string): string => `/* latin */\n@font-face {\n font-family: 'Bricolage Grotesque';\n font-style: ${style};\n font-weight: ${weight};\n src: url(${url}) format('woff2');\n unicode-range: U+0000-00FF;\n}\n`; beforeEach(() => { process.env.HYPERFRAMES_FONT_CACHE_DIR = mkdtempSync(join(tmpdir(), "hf-shared-file-")); _clearGoogleFontCssCacheForTests(); }); it("downloads a file once when several weights name the same address", async () => { const css = [ face(400, "normal", SHARED), face(500, "normal", SHARED), face(700, "normal", SHARED), face(400, "italic", ITALIC), ].join("\n"); const downloads: string[] = []; const fetchImpl: typeof fetch = async (input) => { const url = String(input); if (!url.startsWith("https://fonts.gstatic.com/")) return new Response(css, { status: 200 }); downloads.push(url); return new Response(WOFF2, { status: 200 }); }; const html = await injectDeterministicFontFaces( "

Hi

", { fetchImpl, allowSystemFontCapture: false, logger: { info: () => {}, warn: () => {} } }, ); expect(downloads.sort()).toEqual([ITALIC, SHARED]); const embedded = html.match(/@font-face\s*\{[^}]*\}/g) ?? []; expect(embedded.map((rule) => /font-weight:\s*(\d+)/.exec(rule)?.[1]).sort()).toEqual([ "400", "400", "500", "700", ]); expect(embedded.every((rule) => rule.includes("data:font/woff2;base64,"))).toBe(true); });