-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfonthelper.js
40 lines (33 loc) · 1.12 KB
/
fonthelper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// https://github.com/kvnang/workers-og/blob/main/packages/workers-og/src/font.ts
const fs = require("fs");
async function loadGoogleFont({ family, weight, text }) {
const params = {
family: `${encodeURIComponent(family)}${weight ? `:wght@${weight}` : ""}`,
};
if (text) {
params.text = text;
} else {
params.subset = "latin";
}
const url = `https://fonts.googleapis.com/css2?${Object.keys(params)
.map((key) => `${key}=${params[key]}`)
.join("&")}`;
let res = await fetch(`${url}`, {
headers: {
// construct user agent to get TTF font
"User-Agent":
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1",
},
});
res = new Response(res.body, res);
res.headers.append("Cache-Control", "s-maxage=3600");
const body = await res.text();
// Get the font URL from the CSS text
const fontUrl = body.match(
/src: url\((.+)\) format\('(opentype|truetype)'\)/,
)?.[1];
if (!fontUrl) {
throw new Error("Could not find font URL");
}
return fetch(fontUrl).then((res) => res.arrayBuffer());
}