|
1
|
import { existsSync } from "node:fs" |
|
2
|
import { readFile } from "node:fs/promises" |
|
3
|
import { dirname, join, resolve } from "node:path" |
|
4
|
import { fileURLToPath } from "node:url" |
|
5
|
|
|
6
|
/** |
|
7
|
* Inter and Roboto Mono are read from the copies the admin dashboard already |
|
8
|
* vendors, so the banners need no font download at render time and there is no |
|
9
|
* second copy of either typeface to keep in step. |
|
10
|
*/ |
|
11
|
const FONT_DIR = join( |
|
12
|
"packages", |
|
13
|
"admin", |
|
14
|
"dashboard", |
|
15
|
"src", |
|
16
|
"assets", |
|
17
|
"fonts" |
|
18
|
) |
|
19
|
|
|
20
|
const FONT_FILES: { file: string; name: string; weight: FontWeight }[] = [ |
|
21
|
{ file: "Inter-Regular.ttf", name: "Inter", weight: 400 }, |
|
22
|
{ file: "Inter-Medium.ttf", name: "Inter", weight: 500 }, |
|
23
|
{ file: "RobotoMono-Regular.ttf", name: "Roboto Mono", weight: 400 }, |
|
24
|
{ file: "RobotoMono-Medium.ttf", name: "Roboto Mono", weight: 500 }, |
|
25
|
] |
|
26
|
|
|
27
|
/** The weights satori accepts. */ |
|
28
|
type FontWeight = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 |
|
29
|
|
|
30
|
export type LoadedFont = { |
|
31
|
name: string |
|
32
|
weight: FontWeight |
|
33
|
style: "normal" |
|
34
|
data: Buffer |
|
35
|
} |
|
36
|
|
|
37
|
/** |
|
38
|
* Walks up from this module until it finds the monorepo root, identified by the |
|
39
|
* dashboard's font directory. |
|
40
|
* |
|
41
|
* Walking rather than counting `..` segments keeps this working from both `src` |
|
42
|
* (under ts-node) and `dist`, which sit at different depths. |
|
43
|
*/ |
|
44
|
function findRepoRoot(): string { |
|
45
|
let dir = dirname(fileURLToPath(import.meta.url)) |
|
46
|
|
|
47
|
for (;;) { |
|
48
|
if (existsSync(join(dir, FONT_DIR))) { |
|
49
|
return dir |
|
50
|
} |
|
51
|
|
|
52
|
const parent = resolve(dir, "..") |
|
53
|
|
|
54
|
if (parent === dir) { |
|
55
|
throw new Error( |
|
56
|
`Could not locate the monorepo root: no ancestor of ` + |
|
57
|
`${dirname(fileURLToPath(import.meta.url))} contains ${FONT_DIR}` |
|
58
|
) |
|
59
|
} |
|
60
|
|
|
61
|
dir = parent |
|
62
|
} |
|
63
|
} |
|
64
|
|
|
65
|
let cache: LoadedFont[] | undefined |
|
66
|
|
|
67
|
/** |
|
68
|
* Loads every typeface a banner might ask for, once per process. |
|
69
|
* |
|
70
|
* They are handed to satori together and picked by `fontFamily`, so a template |
|
71
|
* only has to name the one it wants. |
|
72
|
*/ |
|
73
|
export async function loadFonts(): Promise<LoadedFont[]> { |
|
74
|
if (!cache) { |
|
75
|
const fontDir = join(findRepoRoot(), FONT_DIR) |
|
76
|
|
|
77
|
cache = await Promise.all( |
|
78
|
FONT_FILES.map(async ({ file, name, weight }) => ({ |
|
79
|
name, |
|
80
|
weight, |
|
81
|
style: "normal" as const, |
|
82
|
data: await readFile(join(fontDir, file)), |
|
83
|
})) |
|
84
|
) |
|
85
|
} |
|
86
|
|
|
87
|
return cache |
|
88
|
} |