@hamur/fonts 0.0.0-stage → 0.0.2

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 +41 -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
@@ -0,0 +1,27 @@
1
+ import type { FontFaceData, ResolveFontOptions } from "../types.ts";
2
+ export interface ParsedFace {
3
+ family: string;
4
+ face: FontFaceData;
5
+ }
6
+ /** The woff2-capable user agent: Google and Bunny answer by it. */
7
+ export declare const CHROME_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36";
8
+ export declare const normalizeFamily: (name: string) => string;
9
+ /** The characters of `glyphs`, each once, in first-seen order. */
10
+ export declare const uniqueGlyphs: (glyphs: string) => string;
11
+ /** The `&text=` suffix of a Google CSS2 request, empty without glyphs. */
12
+ export declare const glyphsParam: (glyphs: string | undefined) => string;
13
+ /** The `@font-face` rules of a provider's CSS; the `/* latin *\/` comment before a rule is its subset. */
14
+ export declare function parseFontFaces(css: string): ParsedFace[];
15
+ /** A face of a service with no subsets: a leading `/* Satoshi *\/` comment is not one. */
16
+ export declare function withoutSubset({ subset: _subset, ...face }: FontFaceData): FontFaceData;
17
+ /** A request that is not 2xx throws; `missing` statuses mean the service has no such family. */
18
+ export declare function requestText(fetchFn: typeof fetch, url: string, options?: {
19
+ missing?: number[];
20
+ headers?: Record<string, string>;
21
+ }): Promise<string | undefined>;
22
+ export declare const weightRange: (weight: string) => [number, number];
23
+ export declare const isRange: (weight: string) => boolean;
24
+ /** The faces a request asked for: styles, formats and the subsets a face names (a numbered `[0]` subset is a slice of a large family and stays). */
25
+ export declare function keepRequested(faces: FontFaceData[], options: Pick<ResolveFontOptions, "styles" | "subsets" | "formats">, only?: {
26
+ subsets?: boolean;
27
+ }): FontFaceData[];
@@ -0,0 +1,4 @@
1
+ import type { FontProvider, ResolveFontOptions } from "../types.ts";
2
+ /** `satoshi@400;400i;700`; a range is `300..900`. */
3
+ export declare function fontshareParam(family: string, options: Pick<ResolveFontOptions, "weights" | "styles">): string;
4
+ export declare const fontshare: FontProvider;
@@ -0,0 +1,18 @@
1
+ import type { FontFaceData, FontFormat, FontProvider } from "../types.ts";
2
+ type Variants = Record<string, Record<string, Record<string, {
3
+ url?: Partial<Record<FontFormat, string>>;
4
+ }>>>;
5
+ interface FontsourceFont {
6
+ variants?: Variants;
7
+ unicodeRange?: Record<string, string>;
8
+ }
9
+ export declare const fontsourceId: (family: string) => string;
10
+ /** The faces of `api.fontsource.org/v1/fonts/<id>`; a weight range takes every static weight inside it. */
11
+ export declare function parseFontsource(answer: FontsourceFont, options: {
12
+ weights: string[];
13
+ styles: string[];
14
+ subsets: string[];
15
+ formats: FontFormat[];
16
+ }): FontFaceData[];
17
+ export declare const fontsource: FontProvider;
18
+ export {};
@@ -0,0 +1,4 @@
1
+ import type { FontProvider, ResolveFontOptions } from "../types.ts";
2
+ /** The `family=` value of the CSS2 API: axes and tuples sorted, as the API requires. */
3
+ export declare function googleFamilyParam(family: string, options: Pick<ResolveFontOptions, "weights" | "styles">): string;
4
+ export declare const google: FontProvider;
@@ -0,0 +1,2 @@
1
+ import type { FontProvider } from "../types.ts";
2
+ export declare const googleicons: FontProvider;
@@ -0,0 +1,3 @@
1
+ import type { FontProvider } from "../types.ts";
2
+ export declare const remoteProviders: Record<string, FontProvider>;
3
+ export { createNpmProvider } from "./npm.ts";
@@ -0,0 +1,17 @@
1
+ import type { FontFormat, FontProvider } from "../types.ts";
2
+ export interface LocalScope {
3
+ /** `<srcDir>/assets/fonts` of the app and each layer: files the asset pipeline hashes. */
4
+ assetDirs: string[];
5
+ /** `public/` of the app and each layer: files that keep their public URL. */
6
+ publicDirs: string[];
7
+ baseURL: string;
8
+ /** Whether Bun leaves a root-absolute `url(/x.woff2)` alone; when it does not, a public file is written with its absolute path, which the asset pipeline resolves. */
9
+ publicUrlsKept(): Promise<boolean>;
10
+ }
11
+ /** `local`: `<Family>.<ext>` or `<Family>-<weight>[-<style>].<ext>`, the family compared without case, spaces and hyphens; a weight is a number or `thin` to `black`. */
12
+ export declare function parseFontFile(file: string, family: string): {
13
+ weight?: string;
14
+ style: string;
15
+ format: FontFormat;
16
+ } | undefined;
17
+ export declare function createLocalProvider(scope: LocalScope): FontProvider;
@@ -0,0 +1,5 @@
1
+ import type { FontProvider } from "../types.ts";
2
+ /** `npm`: the app's installed `@fontsource/<id>` and `@fontsource-variable/<id>`; a weight range takes the variable package when it is installed. */
3
+ export declare function createNpmProvider(scope: {
4
+ rootDir: string;
5
+ }): FontProvider;
@@ -0,0 +1,32 @@
1
+ import { type MetaCache } from "./build/cache.ts";
2
+ import type { ResolvedFamily, ResolvedFontsOptions } from "./options.ts";
3
+ import type { FontFaceData, FontProvider } from "./types.ts";
4
+ export interface ResolvedFamilyFaces {
5
+ /** The name written in the `font-family` descriptor. */
6
+ name: string;
7
+ faces: FontFaceData[];
8
+ entry?: ResolvedFamily;
9
+ /** The provider that answered; none for a family with `src`. */
10
+ provider?: string;
11
+ }
12
+ export interface FontResolver {
13
+ /** The faces of a family the CSS names, or `undefined` when none are found or the family is left to the app. */
14
+ resolve(name: string): Promise<ResolvedFamilyFaces | undefined>;
15
+ /** The family's options when `fonts.families` lists it. */
16
+ listed(name: string): ResolvedFamily | undefined;
17
+ /** Changes when an answer is added, for the dev cache of the transform chain. */
18
+ version(): number;
19
+ }
20
+ export interface ResolverScope {
21
+ options: ResolvedFontsOptions;
22
+ builtIn: Record<string, FontProvider>;
23
+ /** A warning; the caller logs it once or, with `throwOnError`, throws it. */
24
+ report(message: string): void;
25
+ fetch?: typeof fetch;
26
+ /** Provider answers of these providers are kept between builds; the others are asked each time. */
27
+ cache?: {
28
+ store: MetaCache;
29
+ providers: ReadonlySet<string>;
30
+ };
31
+ }
32
+ export declare function createResolver({ options, builtIn, report, fetch: given, cache, }: ResolverScope): FontResolver;
@@ -0,0 +1,3 @@
1
+ import "#hamur/fonts/global.css";
2
+ declare const _default: import("hamur/app").AppPlugin<{}>;
3
+ export default _default;
@@ -0,0 +1,29 @@
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
+ export interface FamilyUse {
8
+ /** Generic families and CSS-wide keywords are left out. */
9
+ names: FamilyName[];
10
+ /** The generic family the list ends with. */
11
+ generic?: string;
12
+ }
13
+ export interface CssScan {
14
+ /** One per `font-family`, `font` or custom property declaration that names families, in source order. */
15
+ uses: FamilyUse[];
16
+ /** The families, lower-cased, that an `@font-face` of the text declares. */
17
+ declared: string[];
18
+ /** Where a rule may be inserted: after the leading `@charset`, `@import` and `@layer <names>;` statements. */
19
+ insertAt: number;
20
+ }
21
+ export interface ScanOptions {
22
+ /** Which custom properties are read as family lists; default `"font-prefixed-only"`. */
23
+ customProperties?: boolean | "font-prefixed-only";
24
+ }
25
+ export declare const SYSTEM_FAMILIES: string[];
26
+ export declare const familyKey: (name: string) => string;
27
+ export declare const isSystemFamily: (name: string) => boolean;
28
+ /** 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`). */
29
+ export declare function scanCss(css: string, options?: ScanOptions): CssScan;
@@ -0,0 +1,11 @@
1
+ export interface FontData {
2
+ src: string;
3
+ weight: string;
4
+ style: string;
5
+ format: string;
6
+ }
7
+ export interface HamurFontFamilies {
8
+ }
9
+ export type FontFamilyName = keyof HamurFontFamilies extends never ? string : Extract<keyof HamurFontFamilies, string>;
10
+ /** `getFontData` over the table of the template `fonts/data`. */
11
+ export declare function createFontData(table: Record<string, FontData[]>): (family: FontFamilyName) => FontData[];
@@ -0,0 +1,2 @@
1
+ declare const _default: import("hamur/server").ServerDefinition;
2
+ export default _default;
@@ -0,0 +1,9 @@
1
+ import "hamur/server-only";
2
+ export type { FontData, FontFamilyName, HamurFontFamilies } from "./data.ts";
3
+ export declare const fonts: Record<string, {
4
+ src: string;
5
+ weight: string;
6
+ style: string;
7
+ format: string;
8
+ }[]>;
9
+ export declare const getFontData: (family: import("./data.ts").FontFamilyName) => import("./data.ts").FontData[];
@@ -0,0 +1,2 @@
1
+ /** Puts a `<link rel="preload" as="font">` for each font file of the stylesheets in `head`, each URL once, before the first of them. */
2
+ export declare function insertFontPreloads(head: string[], table: Record<string, string[]>): void;
@@ -0,0 +1,2 @@
1
+ /** 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. */
2
+ export declare function writeCmap(entries: ReadonlyArray<readonly [number, number]>): Uint8Array;
@@ -0,0 +1,15 @@
1
+ /** The `numGlyphs + 1` byte offsets of `loca` into `glyf`. */
2
+ export declare function glyphOffsets(loca: Uint8Array, indexToLocFormat: number, numGlyphs: number, glyfLength: number): number[];
3
+ /** 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. */
4
+ export declare function components(glyph: Uint8Array): Array<{
5
+ at: number;
6
+ glyph: number;
7
+ }>;
8
+ /** Glyph 0, `roots` and every component they use, resolved recursively, in glyph order. */
9
+ export declare function glyphClosure(glyf: Uint8Array, offsets: number[], roots: number[]): number[];
10
+ /** `glyf` and `loca` of the `kept` glyphs, renumbered by their place in `kept`, with each composite's component ids rewritten. */
11
+ export declare function subsetGlyf(glyf: Uint8Array, offsets: number[], kept: number[]): {
12
+ glyf: Uint8Array;
13
+ loca: Uint8Array;
14
+ indexToLocFormat: 0 | 1;
15
+ };
@@ -0,0 +1,21 @@
1
+ export type SubsetResult = {
2
+ outlines: "cff";
3
+ } | {
4
+ outlines: "gvar";
5
+ } | {
6
+ outlines: "glyf";
7
+ tables: Map<string, Uint8Array>;
8
+ };
9
+ export declare const AUTOHINT_LATIN: string;
10
+ /** The sum of a table's bytes as big-endian 32-bit words, the last word padded with zeros. */
11
+ export declare function checksum(bytes: Uint8Array): number;
12
+ /** A TrueType file of `tables`, each 4-byte aligned, with its directory checksums and `head.checkSumAdjustment`. */
13
+ export declare function writeSfnt(tables: Map<string, Uint8Array>): Uint8Array;
14
+ /** The format 0 subtables of a version 0 `kern` table with the pairs of kept glyphs, renumbered; `undefined` when none is left. */
15
+ export declare function subsetKern(kern: Uint8Array, id: ReadonlyMap<number, number>): Uint8Array | undefined;
16
+ /**
17
+ * The tables of a TrueType font (TTF, WOFF, or WOFF2 with null-transformed `glyf`, `loca` and `hmtx`)
18
+ * cut to glyph 0, the glyphs `text` maps to (with `AUTOHINT_LATIN` when `text` holds a Latin letter) and their composite parts, renumbered. A CFF font and a font with `gvar`
19
+ * are not cut. Throws when the file cannot be read.
20
+ */
21
+ export declare function subsetFont(bytes: Uint8Array, text: string): SubsetResult;
@@ -0,0 +1,7 @@
1
+ /** UIntBase128: big-endian groups of 7 bits, the high bit set on every byte but the last, no leading zero byte. */
2
+ export declare function base128(value: number): number[];
3
+ /**
4
+ * WOFF2 of a TrueType font's tables: every table under its null transform (version 3 for `glyf` and `loca`, 0 for the
5
+ * others, so no `transformLength`), the table data concatenated in directory order and compressed with Brotli in font mode.
6
+ */
7
+ export declare function writeWoff2(tables: Map<string, Uint8Array>): Uint8Array;
@@ -0,0 +1,71 @@
1
+ export type FontFormat = "woff2" | "woff" | "ttf" | "otf";
2
+ export type FontStyle = "normal" | "italic" | "oblique";
3
+ export type FontDisplay = "auto" | "block" | "swap" | "fallback" | "optional";
4
+ export type FontWeight = number | `${number}` | `${number} ${number}`;
5
+ export interface FontDefaults {
6
+ weights: FontWeight[];
7
+ styles: FontStyle[];
8
+ subsets: string[];
9
+ display: FontDisplay;
10
+ formats: FontFormat[];
11
+ preload: boolean;
12
+ }
13
+ export interface FontFamilyOptions extends Partial<FontDefaults> {
14
+ name: string;
15
+ provider?: string;
16
+ src?: string | string[];
17
+ unicodeRange?: string;
18
+ stretch?: string;
19
+ featureSettings?: string;
20
+ variationSettings?: string;
21
+ glyphs?: string;
22
+ global?: boolean;
23
+ }
24
+ export interface FontsOptions {
25
+ enabled?: boolean;
26
+ priority?: string[];
27
+ providers?: Record<string, false | string | {
28
+ options?: Record<string, unknown>;
29
+ }>;
30
+ defaults?: Partial<FontDefaults>;
31
+ families?: FontFamilyOptions[];
32
+ processCSSVariables?: boolean | "font-prefixed-only";
33
+ fallbacks?: false | Record<string, string[]>;
34
+ localSources?: boolean;
35
+ cache?: boolean;
36
+ throwOnError?: boolean;
37
+ }
38
+ export interface ResolveFontOptions {
39
+ weights: string[];
40
+ styles: FontStyle[];
41
+ subsets: string[];
42
+ formats: FontFormat[];
43
+ glyphs?: string;
44
+ options?: Record<string, unknown>;
45
+ fetch: typeof fetch;
46
+ }
47
+ export interface FontFaceData {
48
+ src: Array<{
49
+ url: string;
50
+ format?: FontFormat;
51
+ } | {
52
+ name: string;
53
+ }>;
54
+ weight?: string;
55
+ style?: string;
56
+ stretch?: string;
57
+ unicodeRange?: string;
58
+ display?: string;
59
+ featureSettings?: string;
60
+ variationSettings?: string;
61
+ subset?: string;
62
+ }
63
+ export interface FontResolution {
64
+ fonts: FontFaceData[];
65
+ fallbacks?: string[];
66
+ }
67
+ export interface FontProvider {
68
+ name: string;
69
+ /** The faces of `family` for `options`, or `undefined` when this provider does not have it. A thrown error is a failure of the provider, not of the family. */
70
+ resolveFont(family: string, options: ResolveFontOptions): Promise<FontResolution | undefined>;
71
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@hamur/fonts",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/productdevbook/hamur.git",
9
+ "directory": "packages/fonts"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/types/src/index.d.ts",
14
+ "bun": "./src/index.ts",
15
+ "hamur-source": "./src/index.ts",
16
+ "node": "./dist/src/index.js",
17
+ "default": "./src/index.ts"
18
+ },
19
+ "./server": {
20
+ "types": "./dist/types/src/server/index.d.ts",
21
+ "bun": "./src/server/index.ts",
22
+ "hamur-source": "./src/server/index.ts",
23
+ "node": "./dist/src/server/index.js",
24
+ "default": "./src/server/index.ts"
25
+ },
26
+ "./providers": {
27
+ "types": "./dist/types/src/providers/index.d.ts",
28
+ "bun": "./src/providers/index.ts",
29
+ "hamur-source": "./src/providers/index.ts",
30
+ "node": "./dist/src/providers/index.js",
31
+ "default": "./src/providers/index.ts"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "src"
38
+ ],
39
+ "dependencies": {},
40
+ "peerDependencies": {
41
+ "hamur": "^0.0.2"
42
+ }
43
+ }
@@ -0,0 +1,50 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import type { FontResolution } from "../types.ts"
4
+
5
+ export interface MetaCache {
6
+ get(key: string): Promise<FontResolution | undefined>
7
+ set(key: string, value: FontResolution): Promise<void>
8
+ }
9
+
10
+ export const sha256 = (data: string | Uint8Array): string => new Bun.CryptoHasher("sha256").update(data).digest("hex")
11
+
12
+ const sorted = (_key: string, value: unknown): unknown =>
13
+ value && typeof value === "object" && !Array.isArray(value)
14
+ ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : 1)))
15
+ : value
16
+
17
+ /** `meta/<SHA-256 of provider, family, options>.json`. */
18
+ export const metaKey = (provider: string, family: string, options: unknown): string =>
19
+ sha256(JSON.stringify([provider, family, options], sorted))
20
+
21
+ let writes = 0
22
+
23
+ export async function writeAtomic(target: string, data: string | Uint8Array): Promise<void> {
24
+ await mkdir(join(target, ".."), { recursive: true })
25
+ const part = `${target}.${process.pid}.${++writes}.part`
26
+ await writeFile(part, data)
27
+ await rename(part, target)
28
+ }
29
+
30
+ export function createMetaCache(dir: string): MetaCache {
31
+ return {
32
+ async get(key) {
33
+ try {
34
+ const value: unknown = JSON.parse(await readFile(join(dir, `${key}.json`), "utf8"))
35
+ return typeof value === "object" && value !== null && Array.isArray((value as FontResolution).fonts)
36
+ ? (value as FontResolution)
37
+ : undefined
38
+ } catch {
39
+ return undefined
40
+ }
41
+ },
42
+ async set(key, value) {
43
+ await writeAtomic(join(dir, `${key}.json`), JSON.stringify(value))
44
+ },
45
+ }
46
+ }
47
+
48
+ /** The directory of the font cache; with `fonts.cache: false` it is the build directory, which the asset pipeline needs. */
49
+ export const fontsDirOf = (cache: boolean, hamur: { options: { cacheDir: string; buildDir: string } }): string =>
50
+ join(cache ? hamur.options.cacheDir : hamur.options.buildDir, "fonts")
@@ -0,0 +1,145 @@
1
+ import { readFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { addTemplate, addTypeTemplate, type HamurContext } from "hamur/kit"
4
+ import { familyKey } from "../scan.ts"
5
+ import type { FontData } from "../server/data.ts"
6
+ import type { FontFaceData } from "../types.ts"
7
+ import { writeAtomic } from "./cache.ts"
8
+ import { fileName, FONT_FACE, manifestSheets, ORIGIN, URL_OF } from "./preload.ts"
9
+
10
+ /** The families a build resolved and the faces they were written with, as `fonts:resolved` sees them. */
11
+ export interface FontRegistry {
12
+ record(family: string, faces: FontFaceData[]): void
13
+ /** Writes the names of the families recorded so far, once, for the typegen of the next run. */
14
+ flush(): Promise<void>
15
+ }
16
+
17
+ interface Registered {
18
+ names: Map<string, string>
19
+ faces: Map<string, FontFaceData[]>
20
+ }
21
+
22
+ const FORMATS: Record<string, string> = {
23
+ woff2: "woff2",
24
+ woff: "woff",
25
+ ttf: "ttf",
26
+ otf: "otf",
27
+ truetype: "ttf",
28
+ opentype: "otf",
29
+ }
30
+ const unquote = (value: string): string => value.trim().replace(/^(["'])(.*)\1$/s, "$2")
31
+ const extensionOf = (url: string): string =>
32
+ FORMATS[/\.([a-z0-9]+)$/i.exec(url.split(/[?#]/)[0]!)?.[1]?.toLowerCase() ?? ""] ?? ""
33
+
34
+ export function createFontRegistry(dir: string): FontRegistry & Registered {
35
+ const registered: Registered = { names: new Map(), faces: new Map() }
36
+ return {
37
+ ...registered,
38
+ record(family, faces) {
39
+ const key = familyKey(family)
40
+ registered.names.set(key, family)
41
+ registered.faces.set(key, faces)
42
+ },
43
+ async flush() {
44
+ await writeAtomic(join(dir, "families.json"), JSON.stringify([...registered.names.values()].sort()))
45
+ },
46
+ }
47
+ }
48
+
49
+ function declaration(rule: string, property: string): string | undefined {
50
+ const found = new RegExp(`(?:^|[;{\\s])${property}\\s*:\\s*([^;}]*)`, "i").exec(rule)
51
+ return found?.[1]?.trim()
52
+ }
53
+
54
+ /** The `src` of each face a build wrote for the registered families, read from the CSS of the client manifest, where the asset pipeline has put the final URLs. */
55
+ export async function builtFontData(
56
+ hamur: HamurContext,
57
+ names: Map<string, string>,
58
+ ): Promise<Record<string, FontData[]>> {
59
+ const table: Record<string, FontData[]> = {}
60
+ const seen = new Set<string>()
61
+ for (const { url: sheet, text } of await manifestSheets(hamur)) {
62
+ const base = new URL(sheet, `${ORIGIN}/`)
63
+ for (const rule of text.match(FONT_FACE) ?? []) {
64
+ const family = names.get(familyKey(unquote(declaration(rule, "font-family") ?? "")))
65
+ const source = declaration(rule, "src")
66
+ if (!family || !source) continue
67
+ for (const match of source.matchAll(URL_OF)) {
68
+ const href = match[1] ?? match[2] ?? match[3] ?? ""
69
+ if (!href || /^data:/i.test(href)) continue
70
+ let resolved: URL
71
+ try {
72
+ resolved = new URL(href, base)
73
+ } catch {
74
+ continue
75
+ }
76
+ const src = resolved.origin === ORIGIN ? resolved.pathname + resolved.search : resolved.href
77
+ const format = /^\s*format\(\s*(.*?)\s*\)/i.exec(
78
+ source.slice(match.index! + match[0].length).replace(/^\s*/, ""),
79
+ )
80
+ const entry = {
81
+ src,
82
+ weight: declaration(rule, "font-weight") ?? "400",
83
+ style: declaration(rule, "font-style") ?? "normal",
84
+ format: (format && FORMATS[unquote(format[1]!).toLowerCase()]) || extensionOf(fileName(src)),
85
+ }
86
+ const id = `${family}\0${entry.src}\0${entry.weight}\0${entry.style}`
87
+ if (seen.has(id)) continue
88
+ seen.add(id)
89
+ ;(table[family] ??= []).push(entry)
90
+ }
91
+ }
92
+ }
93
+ return table
94
+ }
95
+
96
+ function devFontData(registered: Registered): Record<string, FontData[]> {
97
+ const table: Record<string, FontData[]> = {}
98
+ for (const [key, faces] of registered.faces) {
99
+ const entries: FontData[] = []
100
+ for (const face of faces) {
101
+ for (const entry of face.src) {
102
+ if (!("url" in entry)) continue
103
+ entries.push({
104
+ src: entry.url,
105
+ weight: face.weight ?? "400",
106
+ style: face.style ?? "normal",
107
+ format: entry.format ?? extensionOf(entry.url),
108
+ })
109
+ }
110
+ }
111
+ if (entries.length) table[registered.names.get(key)!] = entries
112
+ }
113
+ return table
114
+ }
115
+
116
+ async function previousFamilies(dir: string): Promise<string[]> {
117
+ try {
118
+ const names: unknown = JSON.parse(await readFile(join(dir, "families.json"), "utf8"))
119
+ return Array.isArray(names) ? names.filter((name): name is string => typeof name === "string") : []
120
+ } catch {
121
+ return []
122
+ }
123
+ }
124
+
125
+ /** The template `fonts/data` (read at the server build, after the client build wrote the URLs; in `hamur dev` the paths of the files) and the family names in `.hamur/types/fonts.d.ts`, which are those of the last build. */
126
+ export function setupData(hamur: HamurContext, dir: string): FontRegistry {
127
+ const registry = createFontRegistry(dir)
128
+ addTemplate({
129
+ filename: "fonts/data",
130
+ getContents: async () => {
131
+ await registry.flush()
132
+ return `export default ${JSON.stringify(hamur.options.dev ? devFontData(registry) : await builtFontData(hamur, registry.names))};\n`
133
+ },
134
+ })
135
+ addTypeTemplate({
136
+ filename: "fonts.d.ts",
137
+ getContents: async () => {
138
+ const names = (await previousFamilies(dir)).map((name) => ` ${JSON.stringify(name)}: true;`)
139
+ return names.length
140
+ ? `declare module "@hamur/fonts/server" {\n interface HamurFontFamilies {\n${names.join("\n")}\n }\n}\nexport {};\n`
141
+ : "export {};\n"
142
+ },
143
+ })
144
+ return registry
145
+ }