@hamur/fonts 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +14 -2
  3. package/dist/src/index.js +2472 -0
  4. package/dist/src/providers/index.js +386 -0
  5. package/dist/src/server/index.js +22 -0
  6. package/dist/types/src/build/cache.d.ts +17 -0
  7. package/dist/types/src/build/data.d.ts +19 -0
  8. package/dist/types/src/build/fallbacks.d.ts +49 -0
  9. package/dist/types/src/build/files.d.ts +7 -0
  10. package/dist/types/src/build/global.d.ts +3 -0
  11. package/dist/types/src/build/preload.d.ts +25 -0
  12. package/dist/types/src/build/providers.d.ts +5 -0
  13. package/dist/types/src/build/public-url.d.ts +2 -0
  14. package/dist/types/src/build/scan.d.ts +6 -0
  15. package/dist/types/src/build/subset.d.ts +7 -0
  16. package/dist/types/src/index.d.ts +18 -0
  17. package/dist/types/src/inject.d.ts +21 -0
  18. package/dist/types/src/module.d.ts +3 -0
  19. package/dist/types/src/options.d.ts +46 -0
  20. package/dist/types/src/providers/adobe.d.ts +2 -0
  21. package/dist/types/src/providers/bunny.d.ts +4 -0
  22. package/dist/types/src/providers/css.d.ts +27 -0
  23. package/dist/types/src/providers/fontshare.d.ts +4 -0
  24. package/dist/types/src/providers/fontsource.d.ts +18 -0
  25. package/dist/types/src/providers/google.d.ts +4 -0
  26. package/dist/types/src/providers/googleicons.d.ts +2 -0
  27. package/dist/types/src/providers/index.d.ts +3 -0
  28. package/dist/types/src/providers/local.d.ts +17 -0
  29. package/dist/types/src/providers/npm.d.ts +5 -0
  30. package/dist/types/src/resolve.d.ts +32 -0
  31. package/dist/types/src/runtime/global.d.ts +3 -0
  32. package/dist/types/src/scan.d.ts +29 -0
  33. package/dist/types/src/server/data.d.ts +11 -0
  34. package/dist/types/src/server/door.d.ts +2 -0
  35. package/dist/types/src/server/index.d.ts +9 -0
  36. package/dist/types/src/server/preload.d.ts +2 -0
  37. package/dist/types/src/subset/cmap.d.ts +2 -0
  38. package/dist/types/src/subset/glyf.d.ts +15 -0
  39. package/dist/types/src/subset/sfnt.d.ts +21 -0
  40. package/dist/types/src/subset/woff2.d.ts +7 -0
  41. package/dist/types/src/types.d.ts +71 -0
  42. package/package.json +32 -4
  43. package/src/build/cache.ts +50 -0
  44. package/src/build/data.ts +145 -0
  45. package/src/build/fallbacks.ts +384 -0
  46. package/src/build/files.ts +102 -0
  47. package/src/build/global.ts +14 -0
  48. package/src/build/preload.ts +104 -0
  49. package/src/build/providers.ts +19 -0
  50. package/src/build/public-url.ts +21 -0
  51. package/src/build/scan.ts +172 -0
  52. package/src/build/subset.ts +74 -0
  53. package/src/env.d.ts +13 -0
  54. package/src/index.ts +25 -0
  55. package/src/inject.ts +59 -0
  56. package/src/module.ts +29 -0
  57. package/src/options.ts +375 -0
  58. package/src/providers/adobe.ts +18 -0
  59. package/src/providers/bunny.ts +35 -0
  60. package/src/providers/css.ts +154 -0
  61. package/src/providers/fontshare.ts +37 -0
  62. package/src/providers/fontsource.ts +53 -0
  63. package/src/providers/google.ts +31 -0
  64. package/src/providers/googleicons.ts +20 -0
  65. package/src/providers/index.ts +17 -0
  66. package/src/providers/local.ts +141 -0
  67. package/src/providers/npm.ts +96 -0
  68. package/src/resolve.ts +134 -0
  69. package/src/runtime/global.ts +5 -0
  70. package/src/scan.ts +275 -0
  71. package/src/server/data.ts +20 -0
  72. package/src/server/door.ts +13 -0
  73. package/src/server/index.ts +9 -0
  74. package/src/server/preload.ts +50 -0
  75. package/src/subset/cmap.ts +79 -0
  76. package/src/subset/glyf.ts +93 -0
  77. package/src/subset/sfnt.ts +196 -0
  78. package/src/subset/woff2.ts +68 -0
  79. package/src/types.ts +71 -0
package/src/scan.ts ADDED
@@ -0,0 +1,275 @@
1
+ export interface FamilyName {
2
+ name: string
3
+ /** The range of the name in the CSS text, quotes included. */
4
+ start: number
5
+ end: number
6
+ }
7
+
8
+ export interface FamilyUse {
9
+ /** Generic families and CSS-wide keywords are left out. */
10
+ names: FamilyName[]
11
+ /** The generic family the list ends with. */
12
+ generic?: string
13
+ }
14
+
15
+ export interface CssScan {
16
+ /** One per `font-family`, `font` or custom property declaration that names families, in source order. */
17
+ uses: FamilyUse[]
18
+ /** The families, lower-cased, that an `@font-face` of the text declares. */
19
+ declared: string[]
20
+ /** Where a rule may be inserted: after the leading `@charset`, `@import` and `@layer <names>;` statements. */
21
+ insertAt: number
22
+ }
23
+
24
+ export interface ScanOptions {
25
+ /** Which custom properties are read as family lists; default `"font-prefixed-only"`. */
26
+ customProperties?: boolean | "font-prefixed-only"
27
+ }
28
+
29
+ const GENERIC = new Set([
30
+ "serif",
31
+ "sans-serif",
32
+ "monospace",
33
+ "cursive",
34
+ "fantasy",
35
+ "system-ui",
36
+ "ui-serif",
37
+ "ui-sans-serif",
38
+ "ui-monospace",
39
+ "ui-rounded",
40
+ "emoji",
41
+ "math",
42
+ "fangsong",
43
+ ])
44
+ const CSS_WIDE = new Set(["inherit", "initial", "unset", "revert", "revert-layer", "default"])
45
+
46
+ export const SYSTEM_FAMILIES = [
47
+ "-apple-system",
48
+ "BlinkMacSystemFont",
49
+ "Arial",
50
+ "Helvetica",
51
+ "Helvetica Neue",
52
+ "Times New Roman",
53
+ "Georgia",
54
+ "Courier New",
55
+ "Verdana",
56
+ "Tahoma",
57
+ "Trebuchet MS",
58
+ "Menlo",
59
+ "Monaco",
60
+ "Consolas",
61
+ "Segoe UI",
62
+ "Roboto",
63
+ "SF Pro",
64
+ "Noto Sans",
65
+ "Ubuntu",
66
+ "Cantarell",
67
+ "Apple Color Emoji",
68
+ "Segoe UI Emoji",
69
+ "Segoe UI Symbol",
70
+ "Noto Color Emoji",
71
+ "SFMono-Regular",
72
+ "Liberation Mono",
73
+ "Courier",
74
+ "Cambria",
75
+ "Times",
76
+ ]
77
+
78
+ const SYSTEM = new Set(SYSTEM_FAMILIES.map((name) => name.toLowerCase()))
79
+
80
+ export const familyKey = (name: string): string => name.trim().replace(/\s+/g, " ").toLowerCase()
81
+ export const isSystemFamily = (name: string): boolean => SYSTEM.has(familyKey(name))
82
+
83
+ const lineOf = (text: string, index: number): number => text.slice(0, index).split("\n").length
84
+ const blank = (length: number, char: string): string => char.repeat(length)
85
+
86
+ /** `plain` has comments blanked; `shell` also has the inside of strings and unquoted `url()` blanked, so a delimiter search never lands in them. Same length as `css`. */
87
+ function mask(css: string): { plain: string; shell: string } {
88
+ let plain = ""
89
+ let shell = ""
90
+ let i = 0
91
+ while (i < css.length) {
92
+ const char = css[i]!
93
+ if (char === "/" && css[i + 1] === "*") {
94
+ const close = css.indexOf("*/", i + 2)
95
+ const end = close === -1 ? css.length : close + 2
96
+ const gap = css.slice(i, end).replace(/[^\n]/g, " ")
97
+ plain += gap
98
+ shell += gap
99
+ i = end
100
+ } else if (char === '"' || char === "'") {
101
+ let j = i + 1
102
+ for (; j < css.length && css[j] !== char; j++) {
103
+ if (css[j] === "\\") j++
104
+ else if (css[j] === "\n") break
105
+ }
106
+ if (css[j] !== char) throw new Error(`unterminated string on line ${lineOf(css, i)}`)
107
+ plain += css.slice(i, j + 1)
108
+ shell += char + blank(j - i - 1, "_") + char
109
+ i = j + 1
110
+ } else if ((char === "u" || char === "U") && /^url\(\s*[^\s"')]/i.test(css.slice(i, i + 40))) {
111
+ const open = css.indexOf("(", i) + 1
112
+ let j = open
113
+ while (j < css.length && css[j] !== ")") j += css[j] === "\\" ? 2 : 1
114
+ j = Math.min(j, css.length)
115
+ plain += css.slice(i, j)
116
+ shell += css.slice(i, open) + blank(j - open, "_")
117
+ i = j
118
+ } else {
119
+ plain += char
120
+ shell += char
121
+ i++
122
+ }
123
+ }
124
+ return { plain, shell }
125
+ }
126
+
127
+ const LEADING = /^@(?:charset|import|layer)(?![\w-])/i
128
+
129
+ function leadingEnd(shell: string): number {
130
+ let at = 0
131
+ let end = 0
132
+ for (;;) {
133
+ while (at < shell.length && /\s/.test(shell[at]!)) at++
134
+ if (!LEADING.test(shell.slice(at, at + 9))) return end
135
+ const semicolon = shell.indexOf(";", at)
136
+ const brace = shell.indexOf("{", at)
137
+ if (semicolon === -1 || (brace !== -1 && brace < semicolon)) return end
138
+ at = end = semicolon + 1
139
+ }
140
+ }
141
+
142
+ /** Bun's minifier writes `Open Sans` as `Open\ Sans`, so an escape counts as one identifier character. */
143
+ const IDENT = /^-{0,2}[A-Za-z_\u0080-￿][\w\u0080-￿-]*$/
144
+
145
+ function familyList(plain: string, shell: string, from: number, to: number): FamilyUse {
146
+ const names: FamilyName[] = []
147
+ let generic: string | undefined
148
+ let itemStart = from
149
+ let depth = 0
150
+ const item = (start: number, end: number) => {
151
+ while (start < end && /\s/.test(plain[start]!)) start++
152
+ while (end > start && /\s/.test(plain[end - 1]!)) end--
153
+ if (start >= end) return
154
+ generic = undefined
155
+ const text = plain.slice(start, end)
156
+ let name: string | undefined
157
+ if (text[0] === '"' || text[0] === "'") {
158
+ if (text.length > 1 && text.at(-1) === text[0]) name = text.slice(1, -1).replace(/\\(.)/g, "$1")
159
+ } else if (!text.includes("(")) {
160
+ const tokens = text.split(/(?<!\\)\s+/)
161
+ if (tokens.every((token) => IDENT.test(token.replace(/\\./g, "_"))))
162
+ name = tokens.map((token) => token.replace(/\\(.)/g, "$1")).join(" ")
163
+ }
164
+ if (name === undefined || name === "") return
165
+ const key = familyKey(name)
166
+ if (text[0] !== '"' && text[0] !== "'" && (GENERIC.has(key) || CSS_WIDE.has(key))) {
167
+ if (GENERIC.has(key)) generic = key
168
+ return
169
+ }
170
+ names.push({ name, start, end })
171
+ }
172
+ for (let i = from; i < to; i++) {
173
+ const char = shell[i]
174
+ if (char === "(" || char === "[") depth++
175
+ else if (char === ")" || char === "]") depth--
176
+ else if (char === "," && depth === 0) {
177
+ item(itemStart, i)
178
+ itemStart = i + 1
179
+ }
180
+ }
181
+ item(itemStart, to)
182
+ return generic ? { names, generic } : { names }
183
+ }
184
+
185
+ const LENGTH =
186
+ /^[+-]?(?:\d+\.?\d*|\.\d+)(?:px|r?em|ex|ch|cap|ic|r?lh|v[wh]|vmin|vmax|[sld]v(?:w|h|i|b|min|max)|cq(?:w|h|i|b|min|max)|cm|mm|q|in|pt|pc|%)$/i
187
+ const SIZE_KEYWORD = /^(?:xx-small|x-small|small|medium|large|x-large|xx-large|xxx-large|larger|smaller)$/i
188
+ const SIZE_FUNCTION = /^(?:calc|clamp|min|max)\(/i
189
+
190
+ const isSize = (token: string): boolean => {
191
+ const size = token.split("/")[0]!
192
+ return LENGTH.test(size) || SIZE_KEYWORD.test(size) || SIZE_FUNCTION.test(size)
193
+ }
194
+
195
+ /** The families of a `font` shorthand: the comma list after the size token and an optional `/ <line-height>`. */
196
+ function shorthandFamilies(plain: string, shell: string, from: number, to: number): FamilyUse | undefined {
197
+ const tokens: Array<{ text: string; start: number }> = []
198
+ let depth = 0
199
+ let start = -1
200
+ for (let i = from; i <= to; i++) {
201
+ const char = i < to ? shell[i]! : " "
202
+ if (start === -1 && !/\s/.test(char)) start = i
203
+ if (char === "(") depth++
204
+ else if (char === ")") depth--
205
+ if (start !== -1 && depth === 0 && /\s/.test(char)) {
206
+ tokens.push({ text: shell.slice(start, i), start })
207
+ start = -1
208
+ }
209
+ }
210
+ const size = tokens.findIndex((token) => isSize(token.text))
211
+ if (size === -1) return undefined
212
+ let next = size + 1
213
+ const withLineHeight = tokens[size]!.text.includes("/") && !tokens[size]!.text.endsWith("/")
214
+ if (!withLineHeight && tokens[next]?.text.startsWith("/")) next += tokens[next]!.text === "/" ? 2 : 1
215
+ else if (tokens[size]!.text.endsWith("/")) next += 1
216
+ const first = tokens[next]
217
+ return first ? familyList(plain, shell, first.start, to) : undefined
218
+ }
219
+
220
+ const PROPERTY = /^\s*([\w\\-]+)\s*:/
221
+ const IMPORTANT = /\s*!\s*important\s*$/i
222
+
223
+ /** Reads the font families a stylesheet's declarations name and where its leading statements end. Throws on text it cannot read (`unterminated string on line 4`). */
224
+ export function scanCss(css: string, options: ScanOptions = {}): CssScan {
225
+ const { plain, shell } = mask(css)
226
+ const custom = options.customProperties ?? "font-prefixed-only"
227
+ const uses: FamilyUse[] = []
228
+ const declared: string[] = []
229
+ const blocks: boolean[] = []
230
+
231
+ const declaration = (from: number, to: number) => {
232
+ if (blocks.length === 0) return
233
+ const match = PROPERTY.exec(shell.slice(from, to))
234
+ if (!match) return
235
+ const property = match[1]!
236
+ const lower = property.toLowerCase()
237
+ const valueFrom = from + match[0].length
238
+ const valueTo = to - (IMPORTANT.exec(shell.slice(valueFrom, to))?.[0].length ?? 0)
239
+ if (blocks.at(-1)) {
240
+ if (lower === "font-family")
241
+ for (const name of familyList(plain, shell, valueFrom, valueTo).names) declared.push(familyKey(name.name))
242
+ return
243
+ }
244
+ let use: FamilyUse | undefined
245
+ if (lower === "font-family") use = familyList(plain, shell, valueFrom, valueTo)
246
+ else if (lower === "font") use = shorthandFamilies(plain, shell, valueFrom, valueTo)
247
+ else if (
248
+ property.startsWith("--") &&
249
+ (custom === true || (custom === "font-prefixed-only" && lower.startsWith("--font-")))
250
+ )
251
+ use = familyList(plain, shell, valueFrom, valueTo)
252
+ if (use?.names.length) uses.push(use)
253
+ }
254
+
255
+ let statement = 0
256
+ let depth = 0
257
+ for (let i = 0; i < shell.length; i++) {
258
+ const char = shell[i]
259
+ if (char === "(" || char === "[") depth++
260
+ else if (char === ")" || char === "]") depth = Math.max(0, depth - 1)
261
+ else if (depth > 0) continue
262
+ else if (char === "{") {
263
+ blocks.push(/^\s*@font-face(?![\w-])/i.test(shell.slice(statement, i)))
264
+ statement = i + 1
265
+ } else if (char === ";") {
266
+ declaration(statement, i)
267
+ statement = i + 1
268
+ } else if (char === "}") {
269
+ declaration(statement, i)
270
+ blocks.pop()
271
+ statement = i + 1
272
+ }
273
+ }
274
+ return { uses, declared, insertAt: leadingEnd(shell) }
275
+ }
@@ -0,0 +1,20 @@
1
+ export interface FontData {
2
+ src: string
3
+ weight: string
4
+ style: string
5
+ format: string
6
+ }
7
+
8
+ export interface HamurFontFamilies {}
9
+
10
+ export type FontFamilyName = keyof HamurFontFamilies extends never ? string : Extract<keyof HamurFontFamilies, string>
11
+
12
+ /** `getFontData` over the table of the template `fonts/data`. */
13
+ export function createFontData(table: Record<string, FontData[]>): (family: FontFamilyName) => FontData[] {
14
+ return (family) => {
15
+ const faces = Object.hasOwn(table, family) ? table[family] : undefined
16
+ if (!faces)
17
+ throw new Error(`fonts: "${family}" is not a resolved family (${Object.keys(table).join(", ") || "none"})`)
18
+ return faces.map((face) => ({ ...face }))
19
+ }
20
+ }
@@ -0,0 +1,13 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import preloads from "#hamur/fonts/preloads"
3
+ import { definePlugin, defineServer } from "hamur/server"
4
+ import { insertFontPreloads } from "./preload.ts"
5
+
6
+ export default defineServer({
7
+ plugins: [
8
+ definePlugin((server) => {
9
+ if (Object.keys(preloads).length === 0) return
10
+ server.hooks.hook("render:html", (parts) => insertFontPreloads(parts.head, preloads))
11
+ }),
12
+ ],
13
+ })
@@ -0,0 +1,9 @@
1
+ /// <reference path="../env.d.ts" />
2
+ import "hamur/server-only"
3
+ import table from "#hamur/fonts/data"
4
+ import { createFontData } from "./data.ts"
5
+
6
+ export type { FontData, FontFamilyName, HamurFontFamilies } from "./data.ts"
7
+
8
+ export const fonts = table
9
+ export const getFontData = createFontData(table)
@@ -0,0 +1,50 @@
1
+ const TYPES: Record<string, string> = { woff2: "font/woff2", woff: "font/woff", ttf: "font/ttf", otf: "font/otf" }
2
+ const TAG = /<link\b[^>]*>|<style\b[^>]*>/gi
3
+ const ENTITIES: Record<string, string> = { "&amp;": "&", "&quot;": '"', "&#39;": "'", "&lt;": "<", "&gt;": ">" }
4
+
5
+ const unescape = (text: string): string => text.replace(/&(?:amp|quot|#39|lt|gt);/g, (entity) => ENTITIES[entity]!)
6
+ const escape = (text: string): string =>
7
+ text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
8
+
9
+ function attribute(tag: string, name: string): string | undefined {
10
+ const found = new RegExp(`\\s${name}=(?:"([^"]*)"|'([^']*)')`, "i").exec(tag)
11
+ const value = found?.[1] ?? found?.[2]
12
+ return value === undefined ? undefined : unescape(value)
13
+ }
14
+
15
+ function stylesheetURLs(entry: string): string[] {
16
+ const urls: string[] = []
17
+ for (const tag of entry.match(TAG) ?? []) {
18
+ const url =
19
+ tag[1] === "l" || tag[1] === "L"
20
+ ? /\srel=["']?stylesheet\b/i.test(tag)
21
+ ? attribute(tag, "href")
22
+ : undefined
23
+ : attribute(tag, "data-hamur-href")
24
+ if (url) urls.push(url)
25
+ }
26
+ return urls
27
+ }
28
+
29
+ function fontType(url: string): string | undefined {
30
+ return TYPES[/\.([a-z0-9]+)$/i.exec(url.split(/[?#]/)[0]!)?.[1]?.toLowerCase() ?? ""]
31
+ }
32
+
33
+ /** Puts a `<link rel="preload" as="font">` for each font file of the stylesheets in `head`, each URL once, before the first of them. */
34
+ export function insertFontPreloads(head: string[], table: Record<string, string[]>): void {
35
+ let first = -1
36
+ const seen = new Set<string>()
37
+ const links: string[] = []
38
+ head.forEach((entry, index) => {
39
+ for (const sheet of stylesheetURLs(entry)) {
40
+ if (first < 0) first = index
41
+ for (const font of table[sheet] ?? []) {
42
+ const type = fontType(font)
43
+ if (!type || seen.has(font)) continue
44
+ seen.add(font)
45
+ links.push(`<link rel="preload" as="font" type="${type}" href="${escape(font)}" crossorigin>`)
46
+ }
47
+ }
48
+ })
49
+ if (links.length) head.splice(first, 0, ...links)
50
+ }
@@ -0,0 +1,79 @@
1
+ interface Run {
2
+ start: number
3
+ end: number
4
+ glyph: number
5
+ }
6
+
7
+ /** Consecutive code points that map to consecutive glyphs. */
8
+ function runs(entries: ReadonlyArray<readonly [number, number]>): Run[] {
9
+ const found: Run[] = []
10
+ for (const [codePoint, glyph] of entries) {
11
+ const last = found[found.length - 1]
12
+ if (last && codePoint === last.end + 1 && glyph === last.glyph + codePoint - last.start) last.end = codePoint
13
+ else found.push({ start: codePoint, end: codePoint, glyph })
14
+ }
15
+ return found
16
+ }
17
+
18
+ function format4(entries: ReadonlyArray<readonly [number, number]>): Uint8Array {
19
+ const segments = [
20
+ ...runs(entries.filter(([codePoint]) => codePoint < 0xffff)).map((run) => ({
21
+ ...run,
22
+ delta: (run.glyph - run.start) & 0xffff,
23
+ })),
24
+ { start: 0xffff, end: 0xffff, delta: 1 },
25
+ ]
26
+ const count = segments.length
27
+ const length = 16 + 8 * count
28
+ const data = new DataView(new ArrayBuffer(length))
29
+ const power = 2 ** Math.floor(Math.log2(count))
30
+ data.setUint16(0, 4)
31
+ data.setUint16(2, length)
32
+ data.setUint16(6, 2 * count)
33
+ data.setUint16(8, 2 * power)
34
+ data.setUint16(10, Math.log2(power))
35
+ data.setUint16(12, 2 * count - 2 * power)
36
+ const ends = 14
37
+ const starts = ends + 2 * count + 2
38
+ const deltas = starts + 2 * count
39
+ segments.forEach((segment, i) => {
40
+ data.setUint16(ends + 2 * i, segment.end)
41
+ data.setUint16(starts + 2 * i, segment.start)
42
+ data.setUint16(deltas + 2 * i, segment.delta)
43
+ })
44
+ return new Uint8Array(data.buffer)
45
+ }
46
+
47
+ function format12(entries: ReadonlyArray<readonly [number, number]>): Uint8Array {
48
+ const groups = runs(entries)
49
+ const length = 16 + 12 * groups.length
50
+ const data = new DataView(new ArrayBuffer(length))
51
+ data.setUint16(0, 12)
52
+ data.setUint32(4, length)
53
+ data.setUint32(12, groups.length)
54
+ groups.forEach((group, i) => {
55
+ data.setUint32(16 + 12 * i, group.start)
56
+ data.setUint32(20 + 12 * i, group.end)
57
+ data.setUint32(24 + 12 * i, group.glyph)
58
+ })
59
+ return new Uint8Array(data.buffer)
60
+ }
61
+
62
+ /** A `cmap` of `[codePoint, glyph]` pairs sorted by code point: format 4 (3, 1), and format 12 (3, 10) when a code point is above U+FFFF. */
63
+ export function writeCmap(entries: ReadonlyArray<readonly [number, number]>): Uint8Array {
64
+ const subtables: Array<[number, Uint8Array]> = [[1, format4(entries)]]
65
+ if (entries.some(([codePoint]) => codePoint > 0xffff)) subtables.push([10, format12(entries)])
66
+ const header = 4 + 8 * subtables.length
67
+ const out = new Uint8Array(header + subtables.reduce((sum, [, table]) => sum + table.byteLength, 0))
68
+ const data = new DataView(out.buffer)
69
+ data.setUint16(2, subtables.length)
70
+ let offset = header
71
+ subtables.forEach(([encoding, table], i) => {
72
+ data.setUint16(4 + 8 * i, 3)
73
+ data.setUint16(6 + 8 * i, encoding)
74
+ data.setUint32(8 + 8 * i, offset)
75
+ out.set(table, offset)
76
+ offset += table.byteLength
77
+ })
78
+ return out
79
+ }
@@ -0,0 +1,93 @@
1
+ const view = (bytes: Uint8Array): DataView => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
2
+ const pad4 = (length: number): number => (length + 3) & ~3
3
+
4
+ const ARG_1_AND_2_ARE_WORDS = 0x0001
5
+ const WE_HAVE_A_SCALE = 0x0008
6
+ const MORE_COMPONENTS = 0x0020
7
+ const WE_HAVE_AN_X_AND_Y_SCALE = 0x0040
8
+ const WE_HAVE_A_TWO_BY_TWO = 0x0080
9
+
10
+ /** The `numGlyphs + 1` byte offsets of `loca` into `glyf`. */
11
+ export function glyphOffsets(
12
+ loca: Uint8Array,
13
+ indexToLocFormat: number,
14
+ numGlyphs: number,
15
+ glyfLength: number,
16
+ ): number[] {
17
+ const data = view(loca)
18
+ const width = indexToLocFormat === 0 ? 2 : 4
19
+ if (loca.byteLength < width * (numGlyphs + 1)) throw new Error("loca is shorter than maxp.numGlyphs")
20
+ const offsets: number[] = []
21
+ for (let i = 0; i <= numGlyphs; i++) {
22
+ const offset = width === 2 ? 2 * data.getUint16(2 * i) : data.getUint32(4 * i)
23
+ if (offset > glyfLength || (i > 0 && offset < offsets[i - 1]!))
24
+ throw new Error(`loca entry ${i} is out of order or past glyf`)
25
+ offsets.push(offset)
26
+ }
27
+ return offsets
28
+ }
29
+
30
+ /** Each component of a composite glyph: the byte offset of its glyph index and the glyph it names; none for a simple or empty glyph. */
31
+ export function components(glyph: Uint8Array): Array<{ at: number; glyph: number }> {
32
+ if (glyph.byteLength < 10) return []
33
+ const data = view(glyph)
34
+ if (data.getInt16(0) >= 0) return []
35
+ const found: Array<{ at: number; glyph: number }> = []
36
+ let at = 10
37
+ for (;;) {
38
+ const flags = data.getUint16(at)
39
+ found.push({ at: at + 2, glyph: data.getUint16(at + 2) })
40
+ at +=
41
+ 4 +
42
+ (flags & ARG_1_AND_2_ARE_WORDS ? 4 : 2) +
43
+ (flags & WE_HAVE_A_SCALE ? 2 : flags & WE_HAVE_AN_X_AND_Y_SCALE ? 4 : flags & WE_HAVE_A_TWO_BY_TWO ? 8 : 0)
44
+ if (!(flags & MORE_COMPONENTS)) return found
45
+ }
46
+ }
47
+
48
+ const glyphAt = (glyf: Uint8Array, offsets: number[], glyph: number): Uint8Array =>
49
+ glyf.subarray(offsets[glyph]!, offsets[glyph + 1]!)
50
+
51
+ /** Glyph 0, `roots` and every component they use, resolved recursively, in glyph order. */
52
+ export function glyphClosure(glyf: Uint8Array, offsets: number[], roots: number[]): number[] {
53
+ const numGlyphs = offsets.length - 1
54
+ const kept = new Set<number>()
55
+ const pending = [0, ...roots]
56
+ while (pending.length > 0) {
57
+ const glyph = pending.pop()!
58
+ if (glyph >= numGlyphs) throw new Error(`glyph ${glyph} is past maxp.numGlyphs`)
59
+ if (kept.has(glyph)) continue
60
+ kept.add(glyph)
61
+ for (const part of components(glyphAt(glyf, offsets, glyph))) pending.push(part.glyph)
62
+ }
63
+ return [...kept].sort((a, b) => a - b)
64
+ }
65
+
66
+ /** `glyf` and `loca` of the `kept` glyphs, renumbered by their place in `kept`, with each composite's component ids rewritten. */
67
+ export function subsetGlyf(
68
+ glyf: Uint8Array,
69
+ offsets: number[],
70
+ kept: number[],
71
+ ): { glyf: Uint8Array; loca: Uint8Array; indexToLocFormat: 0 | 1 } {
72
+ const id = new Map(kept.map((glyph, index) => [glyph, index]))
73
+ const parts = kept.map((glyph) => {
74
+ const copy = glyphAt(glyf, offsets, glyph).slice()
75
+ for (const part of components(copy)) view(copy).setUint16(part.at, id.get(part.glyph)!)
76
+ return copy
77
+ })
78
+ const total = parts.reduce((sum, part) => sum + pad4(part.byteLength), 0)
79
+ const indexToLocFormat = total <= 0x1fffe ? 0 : 1
80
+ const out = new Uint8Array(total)
81
+ const loca = new Uint8Array((kept.length + 1) * (indexToLocFormat === 0 ? 2 : 4))
82
+ const locaView = view(loca)
83
+ const setOffset = (index: number, offset: number) =>
84
+ indexToLocFormat === 0 ? locaView.setUint16(2 * index, offset / 2) : locaView.setUint32(4 * index, offset)
85
+ let at = 0
86
+ parts.forEach((part, index) => {
87
+ setOffset(index, at)
88
+ out.set(part, at)
89
+ at += pad4(part.byteLength)
90
+ })
91
+ setOffset(kept.length, at)
92
+ return { glyf: out, loca, indexToLocFormat }
93
+ }