Skip to content

Commit 918e39e

Browse files
fix(producer): embed the Google font the page linked instead of a wider cut (#4569)
* fix(producer): embed the Google font the page linked The weight-only download drops axes the page's link asked for. That file is written after the link, so the film draws a wider cut than the preview. Co-authored-by: Cursor <[email protected]> * fix(producer): keep every weight the page's font link asked for Google answers a 400..900 link as font-weight: 400 900, and only 400 was kept. Heavier text then waited on the network. Large families are limited to the characters on the page, @import is followed, and a failed link is not replaced by a font found on this machine. Co-authored-by: Cursor <[email protected]> * fix(producer): preserve italic supplements for bundled fonts * fix(producer): preserve active authored font resources * style(producer): condense font fetch comments * fix(producer): preserve authored oblique font faces --------- Co-authored-by: Cursor <[email protected]>
1 parent e8313b2 commit 918e39e

7 files changed

Lines changed: 773 additions & 26 deletions
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { expect, it } from "bun:test";
2+
import { authoredGoogleFontStylesheets, withPageText } from "./authoredGoogleFonts.js";
3+
4+
const url = "https://fonts.googleapis.com/css2?family=Fraunces:wght@400";
5+
6+
it("decodes every family parameter and retains active screen imports in document order", () => {
7+
const second = "https://fonts.googleapis.com/css2?family=Fraunces:wght@700";
8+
const html = `<link rel="stylesheet" media="screen" href="${url}&amp;family=Test+Family:wght@700">
9+
<style media="all">@import '${second}' screen;</style>`;
10+
const resources = authoredGoogleFontStylesheets(html);
11+
expect(resources.get("fraunces")).toEqual([`${url}&family=Test+Family:wght@700`, second]);
12+
expect(resources.get("test family")).toEqual([`${url}&family=Test+Family:wght@700`]);
13+
});
14+
15+
it.each([
16+
`<link rel="preload" href="${url}">`,
17+
`<link rel="stylesheet">`,
18+
`<link rel="stylesheet" type="text/plain" href="${url}">`,
19+
`<link rel="stylesheet" href="not-a-url">`,
20+
`<link rel="stylesheet" href="https://example.com/css2?family=Fraunces">`,
21+
`<link rel="stylesheet" href="http://fonts.googleapis.com/css2?family=Fraunces">`,
22+
`<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=">`,
23+
`<style>@media print { @import '${url}'; }</style>`,
24+
`<style>/* @import '${url}'; */</style>`,
25+
`<style>@import '${url}'; p {</style>`,
26+
`<style type="text/plain">@import '${url}';</style>`,
27+
])("does not collect an inactive or invalid resource: %s", (html) => {
28+
expect(authoredGoogleFontStylesheets(html).size).toBe(0);
29+
});
30+
31+
it("recognizes both families in a legacy Google Fonts URL", () => {
32+
const legacy = "https://fonts.googleapis.com/css?family=Fraunces:400|Other:700";
33+
expect([
34+
...authoredGoogleFontStylesheets(`<link rel=stylesheet href="${legacy}">`).keys(),
35+
]).toEqual(["fraunces", "other"]);
36+
});
37+
38+
it("adds a text subset before the URL fragment without replacing authored text", () => {
39+
expect(withPageText(`${url}#anchor`, "Hi")).toBe(`${url}&text=Hi#anchor`);
40+
expect(withPageText(`${url}&text=Original#anchor`, "Hi")).toBe(`${url}&text=Original#anchor`);
41+
expect(withPageText("https://fonts.googleapis.com/css2", "Hi")).toBe(
42+
"https://fonts.googleapis.com/css2?text=Hi",
43+
);
44+
expect(withPageText(url, undefined)).toBe(url);
45+
});
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import { parseHTML } from "linkedom";
2+
import postcss from "postcss";
3+
4+
function screenStylesheet(media: string | null): boolean {
5+
return !media?.trim() || media.split(",").some((query) => /^(all|screen)$/i.test(query.trim()));
6+
}
7+
8+
function googleStylesheetFamilies(urlText: string): string[] {
9+
let parsed: URL;
10+
try {
11+
parsed = new URL(urlText);
12+
} catch {
13+
return [];
14+
}
15+
if (parsed.protocol !== "https:" || parsed.hostname !== "fonts.googleapis.com") return [];
16+
return parsed.searchParams
17+
.getAll("family")
18+
.flatMap((family) => family.split("|"))
19+
.map((family) => family.split(":")[0]?.trim().toLowerCase() ?? "")
20+
.filter(Boolean);
21+
}
22+
23+
function importUrls(css: string): string[] {
24+
let root: postcss.Root;
25+
try {
26+
root = postcss.parse(css);
27+
} catch {
28+
return [];
29+
}
30+
const urls: string[] = [];
31+
for (const node of root.nodes) {
32+
if (node.type !== "atrule" || node.name.toLowerCase() !== "import") continue;
33+
const url = unconditionalImportUrl(node.params);
34+
if (url) urls.push(url);
35+
}
36+
return urls;
37+
}
38+
39+
function unconditionalImportUrl(params: string): string | undefined {
40+
const match = /^(?:url\(\s*['"]?([^'")\s]+)['"]?\s*\)|['"]([^'"]+)['"])\s*(.*)$/i.exec(params);
41+
if (!match || !screenStylesheet(match[3] ?? null)) return undefined;
42+
return match[1] ?? match[2];
43+
}
44+
45+
type StylesheetElement = Pick<
46+
Element,
47+
"getAttribute" | "hasAttribute" | "localName" | "textContent"
48+
>;
49+
50+
function activeStylesheet(element: StylesheetElement): boolean {
51+
if (element.hasAttribute("disabled") || !screenStylesheet(element.getAttribute("media")))
52+
return false;
53+
const type = element.getAttribute("type")?.trim().toLowerCase();
54+
return !type || type === "text/css";
55+
}
56+
57+
function stylesheetUrls(element: StylesheetElement): string[] {
58+
if (!activeStylesheet(element)) return [];
59+
if (element.localName !== "link") return importUrls(element.textContent ?? "");
60+
const rel = (element.getAttribute("rel") ?? "").toLowerCase().split(/\s+/);
61+
if (!rel.includes("stylesheet") || rel.includes("alternate")) return [];
62+
const href = element.getAttribute("href");
63+
return href ? [href] : [];
64+
}
65+
66+
export function authoredGoogleFontStylesheets(html: string): Map<string, string[]> {
67+
const byFamily = new Map<string, string[]>();
68+
const { document } = parseHTML(html);
69+
for (const element of document.querySelectorAll("link, style")) {
70+
for (const url of stylesheetUrls(element)) {
71+
for (const family of googleStylesheetFamilies(url)) {
72+
const previous = byFamily.get(family) ?? [];
73+
byFamily.set(family, [...previous.filter((existing) => existing !== url), url]);
74+
}
75+
}
76+
}
77+
return byFamily;
78+
}
79+
80+
export function withPageText(url: string, fontText: string | undefined): string {
81+
const parsed = new URL(url);
82+
if (!fontText || parsed.searchParams.has("text")) return url;
83+
const withoutFragment = url.split("#")[0] ?? url;
84+
const joiner = parsed.search ? "&" : "?";
85+
return `${withoutFragment}${joiner}text=${encodeURIComponent(fontText)}${parsed.hash}`;
86+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import { afterEach, beforeEach, expect, it, spyOn } from "bun:test";
2+
import { mkdtempSync, rmSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
import {
6+
_clearGoogleFontCssCacheForTests,
7+
injectDeterministicFontFaces,
8+
} from "./deterministicFonts.js";
9+
10+
let cacheDir: string;
11+
let previousCacheDir: string | undefined;
12+
const requests: string[] = [];
13+
let restoreFetch: () => void;
14+
15+
beforeEach(() => {
16+
previousCacheDir = process.env.HYPERFRAMES_FONT_CACHE_DIR;
17+
cacheDir = mkdtempSync(join(tmpdir(), "hf-authored-resources-"));
18+
process.env.HYPERFRAMES_FONT_CACHE_DIR = cacheDir;
19+
requests.length = 0;
20+
_clearGoogleFontCssCacheForTests();
21+
const mock = spyOn(globalThis, "fetch").mockImplementation(async (input) => {
22+
const url = new URL(String(input));
23+
requests.push(url.href);
24+
if (url.hostname === "fonts.googleapis.com") {
25+
const weight = url.searchParams.get("family")?.endsWith("700") ? "700" : "400";
26+
return new Response(`@font-face {
27+
font-family: 'Fraunces'; font-style: normal; font-weight: ${weight};
28+
src: url(https://fonts.gstatic.com/fraunces-${weight}.woff2) format('woff2');
29+
}`);
30+
}
31+
return new Response(url.pathname);
32+
});
33+
restoreFetch = () => mock.mockRestore();
34+
});
35+
36+
afterEach(() => {
37+
restoreFetch();
38+
_clearGoogleFontCssCacheForTests();
39+
if (previousCacheDir === undefined) delete process.env.HYPERFRAMES_FONT_CACHE_DIR;
40+
else process.env.HYPERFRAMES_FONT_CACHE_DIR = previousCacheDir;
41+
rmSync(cacheDir, { recursive: true, force: true });
42+
});
43+
44+
const normal = "https://fonts.googleapis.com/css2?family=Fraunces:wght@400";
45+
const bold = "https://fonts.googleapis.com/css2?family=Fraunces:wght@700";
46+
const page = (head: string) => `<!doctype html><html><head>${head}
47+
<style>p { font-family: Fraunces; }</style></head><body><p>Hi</p></body></html>`;
48+
49+
function requestedFamilies(): (string | null)[] {
50+
return requests
51+
.filter((url) => url.startsWith("https://fonts.googleapis.com/"))
52+
.map((url) => new URL(url).searchParams.get("family"));
53+
}
54+
55+
it("decodes HTML entities and preserves an authored text subset", async () => {
56+
await injectDeterministicFontFaces(page(`<link rel=stylesheet href="${normal}&amp;text=Hi">`));
57+
expect(requests[0]).toBe(`${normal}&text=Hi`);
58+
});
59+
60+
it("embeds every separate weight resource once in document order", async () => {
61+
const result = await injectDeterministicFontFaces(
62+
page(
63+
`<link rel=stylesheet href="${normal}"><link rel=stylesheet href="${bold}">` +
64+
`<link rel=stylesheet href="${normal}">`,
65+
),
66+
);
67+
expect(requestedFamilies()).toEqual(["Fraunces:wght@700", "Fraunces:wght@400"]);
68+
expect(result).toContain(Buffer.from("/fraunces-400.woff2").toString("base64"));
69+
expect(result).toContain(Buffer.from("/fraunces-700.woff2").toString("base64"));
70+
});
71+
72+
it.each([
73+
`<link rel="stylesheet" media="print" href="${bold}">`,
74+
`<link rel="stylesheet" disabled href="${bold}">`,
75+
`<link rel="alternate stylesheet" title="other" href="${bold}">`,
76+
`<style media="print">@import url("${bold}");</style>`,
77+
`<style>@import url("${bold}") print;</style>`,
78+
`<style>@import url("${bold}") supports(display: grid);</style>`,
79+
`<!-- <link rel="stylesheet" href="${bold}"> -->`,
80+
])("does not promote an inactive font source: %s", async (inactive) => {
81+
await injectDeterministicFontFaces(page(`${inactive}<link rel="stylesheet" href="${normal}">`));
82+
expect(requestedFamilies()).toEqual(["Fraunces:wght@400"]);
83+
});
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { afterEach, expect, it, spyOn } from "bun:test";
2+
import { mkdtempSync, rmSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
import {
6+
_clearGoogleFontCssCacheForTests,
7+
injectDeterministicFontFaces,
8+
} from "./deterministicFonts.js";
9+
10+
const previousCacheDir = process.env.HYPERFRAMES_FONT_CACHE_DIR;
11+
const cacheDir = mkdtempSync(join(tmpdir(), "hf-bundled-stylesheet-"));
12+
const fetchMock = spyOn(globalThis, "fetch");
13+
14+
afterEach(() => {
15+
fetchMock.mockRestore();
16+
_clearGoogleFontCssCacheForTests();
17+
if (previousCacheDir === undefined) delete process.env.HYPERFRAMES_FONT_CACHE_DIR;
18+
else process.env.HYPERFRAMES_FONT_CACHE_DIR = previousCacheDir;
19+
rmSync(cacheDir, { recursive: true, force: true });
20+
});
21+
22+
it("supplements bundled fonts with real italics even when the page imports only normal", async () => {
23+
process.env.HYPERFRAMES_FONT_CACHE_DIR = cacheDir;
24+
_clearGoogleFontCssCacheForTests();
25+
const italicUrl = "https://fonts.gstatic.com/s/ebgaramond/italic.woff2";
26+
const normalUrl = "https://fonts.gstatic.com/s/ebgaramond/normal.woff2";
27+
fetchMock.mockImplementation(async (input) => {
28+
const url = String(input);
29+
if (url.startsWith("https://fonts.googleapis.com/")) {
30+
const italic = url.includes("ital,wght@");
31+
return new Response(`@font-face {
32+
font-family: 'EB Garamond';
33+
font-style: ${italic ? "italic" : "normal"};
34+
font-weight: 400;
35+
src: url(${italic ? italicUrl : normalUrl}) format('woff2');
36+
unicode-range: U+0000-00FF;
37+
}`);
38+
}
39+
if (url === italicUrl) return new Response("REAL_ITALIC_FONT");
40+
if (url === normalUrl) return new Response("NORMAL_FONT");
41+
return new Response("", { status: 404 });
42+
});
43+
44+
const result = await injectDeterministicFontFaces(`<!doctype html><html><head><style>
45+
@import url("https://fonts.googleapis.com/css2?family=EB+Garamond:wght@400&display=swap");
46+
p { font-family: "EB Garamond", serif; font-style: italic; }
47+
</style></head><body><p>lack technical skills</p></body></html>`);
48+
49+
const italicFace = result.match(/@font-face\s*\{[^}]*font-style: italic[^}]*\}/)?.[0];
50+
expect(italicFace).toBeDefined();
51+
expect(italicFace).toContain('font-family: "EB Garamond"');
52+
expect(italicFace).toContain(Buffer.from("REAL_ITALIC_FONT").toString("base64"));
53+
});

0 commit comments

Comments
 (0)