@timber-js/app 0.2.0-alpha.247 → 0.2.0-alpha.249

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 (38) hide show
  1. package/dist/fonts/ast.d.ts.map +1 -1
  2. package/dist/fonts/bundle.d.ts +26 -8
  3. package/dist/fonts/bundle.d.ts.map +1 -1
  4. package/dist/fonts/fallbacks.d.ts +46 -8
  5. package/dist/fonts/fallbacks.d.ts.map +1 -1
  6. package/dist/fonts/font-metrics.d.ts +54 -0
  7. package/dist/fonts/font-metrics.d.ts.map +1 -0
  8. package/dist/fonts/local-fallback.d.ts +64 -0
  9. package/dist/fonts/local-fallback.d.ts.map +1 -0
  10. package/dist/fonts/local.d.ts.map +1 -1
  11. package/dist/fonts/sfnt.d.ts +30 -0
  12. package/dist/fonts/sfnt.d.ts.map +1 -0
  13. package/dist/fonts/transform.d.ts.map +1 -1
  14. package/dist/fonts/types.d.ts +29 -0
  15. package/dist/fonts/types.d.ts.map +1 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1262 -351
  18. package/dist/index.js.map +1 -1
  19. package/dist/plugins/build-manifest.d.ts +5 -0
  20. package/dist/plugins/build-manifest.d.ts.map +1 -1
  21. package/dist/plugins/fonts.d.ts.map +1 -1
  22. package/dist/plugins/route-css.d.ts +63 -0
  23. package/dist/plugins/route-css.d.ts.map +1 -0
  24. package/package.json +1 -1
  25. package/src/fonts/ast.ts +35 -2
  26. package/src/fonts/bundle.ts +71 -17
  27. package/src/fonts/fallbacks.ts +92 -28
  28. package/src/fonts/font-metrics.ts +236 -0
  29. package/src/fonts/local-fallback.ts +249 -0
  30. package/src/fonts/local.ts +14 -1
  31. package/src/fonts/pipeline.ts +6 -3
  32. package/src/fonts/sfnt.ts +185 -0
  33. package/src/fonts/transform.ts +4 -1
  34. package/src/fonts/types.ts +29 -0
  35. package/src/index.ts +2 -0
  36. package/src/plugins/build-manifest.ts +1 -1
  37. package/src/plugins/fonts.ts +28 -2
  38. package/src/plugins/route-css.ts +237 -0
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Read the vertical and horizontal metrics a size-adjusted fallback needs
3
+ * from a font file (TTF / OTF / WOFF / WOFF2).
4
+ *
5
+ * Fields read:
6
+ *
7
+ * - `head.unitsPerEm`
8
+ * - ascent / descent / lineGap — from `hhea`, or from `OS/2` sTypo* when
9
+ * `fsSelection` bit 7 (USE_TYPO_METRICS) is set, which is what browsers
10
+ * do with such fonts
11
+ * - `OS/2.xAvgCharWidth`, and the advance widths of a letter-frequency
12
+ * weighted Latin sample (`cmap` → glyph id → `hmtx`), the same sample
13
+ * Next.js's `adjustFontFallback` and capsize use
14
+ * - whether the font is monospace: `post.isFixedPitch`, `OS/2` PANOSE
15
+ * proportion = monospaced, or every sampled glyph sharing one advance
16
+ * - whether it is serif or sans, from PANOSE / IBM font class, when the
17
+ * font declares it
18
+ *
19
+ * Design doc: 24-fonts.md §"Step 4: Size-Adjusted Fallbacks"
20
+ */
21
+
22
+ import { readSfntTables } from './sfnt.ts';
23
+
24
+ /** The generic CSS family a font belongs to. */
25
+ export type FontCategory = 'sans-serif' | 'serif' | 'monospace';
26
+
27
+ export interface FontMetrics {
28
+ unitsPerEm: number;
29
+ /** Positive, in font units. */
30
+ ascent: number;
31
+ /** Positive (distance below the baseline), in font units. */
32
+ descent: number;
33
+ lineGap: number;
34
+ /** `OS/2.xAvgCharWidth`, or `undefined` when the table is absent / zero. */
35
+ xAvgCharWidth?: number;
36
+ /**
37
+ * Mean advance of `AVG_WIDTH_SAMPLE` in font units, or `undefined` when
38
+ * the font lacks a sampled character or its `hmtx` is unreadable.
39
+ */
40
+ sampleAvgWidth?: number;
41
+ /** True for fixed-pitch fonts. */
42
+ monospace: boolean;
43
+ /**
44
+ * `serif` / `sans-serif` when the font's PANOSE or IBM class says so;
45
+ * `undefined` when it does not (caller falls back to a name heuristic).
46
+ */
47
+ declaredCategory?: 'serif' | 'sans-serif';
48
+ }
49
+
50
+ /**
51
+ * Letter-frequency weighted Latin sample, with spaces for word length.
52
+ * Identical to Next.js's `calcAverageWidth` (packages/font/src/local/
53
+ * get-fallback-metrics-from-font-file.ts) so the reference widths of the
54
+ * fallback bases are comparable.
55
+ */
56
+ export const AVG_WIDTH_SAMPLE = 'aaabcdeeeefghiijklmnnoopqrrssttuvwxyz ';
57
+
58
+ /** Characters whose advances must all match for a font to count as monospace. */
59
+ const MONO_PROBE = 'abcdefghijklmnopqrstuvwxyz0123456789 ';
60
+
61
+ const TABLES = ['head', 'hhea', 'OS/2', 'post', 'cmap', 'hmtx'] as const;
62
+
63
+ /** Parse metrics from font bytes. `null` when the file can't be read. */
64
+ export function readFontMetrics(data: Uint8Array): FontMetrics | null {
65
+ const tables = readSfntTables(data, TABLES);
66
+ if (!tables) return null;
67
+ const head = tables.get('head');
68
+ const hhea = tables.get('hhea');
69
+ if (!head || !hhea || head.byteLength < 54 || hhea.byteLength < 36) return null;
70
+
71
+ try {
72
+ const unitsPerEm = head.getUint16(18);
73
+ if (unitsPerEm === 0) return null;
74
+
75
+ let ascent = hhea.getInt16(4);
76
+ let descent = hhea.getInt16(6);
77
+ let lineGap = hhea.getInt16(8);
78
+ const numberOfHMetrics = hhea.getUint16(34);
79
+
80
+ const os2 = tables.get('OS/2');
81
+ let xAvgCharWidth: number | undefined;
82
+ let declaredCategory: FontMetrics['declaredCategory'];
83
+ let panoseMono = false;
84
+ if (os2 && os2.byteLength >= 78) {
85
+ const avg = os2.getInt16(2);
86
+ if (avg > 0) xAvgCharWidth = avg;
87
+ const fsSelection = os2.getUint16(62);
88
+ if (fsSelection & (1 << 7)) {
89
+ ascent = os2.getInt16(68);
90
+ descent = os2.getInt16(70);
91
+ lineGap = os2.getInt16(72);
92
+ }
93
+ const panose = (i: number) => os2.getUint8(32 + i);
94
+ // PANOSE family kind 2 = Latin Text; only then do the digits below
95
+ // mean serif style (byte 1) and proportion (byte 3).
96
+ if (panose(0) === 2) {
97
+ const serifStyle = panose(1);
98
+ if (serifStyle >= 2 && serifStyle <= 10) declaredCategory = 'serif';
99
+ else if (serifStyle >= 11 && serifStyle <= 13) declaredCategory = 'sans-serif';
100
+ panoseMono = panose(3) === 9;
101
+ }
102
+ if (!declaredCategory) {
103
+ // IBM font class (high byte of sFamilyClass): 1–5 and 7 are serif
104
+ // classes, 8 is sans serif.
105
+ const ibmClass = os2.getInt16(30) >> 8;
106
+ if ((ibmClass >= 1 && ibmClass <= 5) || ibmClass === 7) declaredCategory = 'serif';
107
+ else if (ibmClass === 8) declaredCategory = 'sans-serif';
108
+ }
109
+ }
110
+
111
+ const post = tables.get('post');
112
+ const isFixedPitch = post !== undefined && post.byteLength >= 16 && post.getUint32(12) !== 0;
113
+
114
+ const advanceOf = buildAdvanceLookup(tables.get('cmap'), tables.get('hmtx'), numberOfHMetrics);
115
+ const sampleAvgWidth = advanceOf ? averageAdvance(AVG_WIDTH_SAMPLE, advanceOf) : undefined;
116
+ const sameAdvance = advanceOf ? allSameAdvance(MONO_PROBE, advanceOf) : false;
117
+
118
+ return {
119
+ unitsPerEm,
120
+ ascent,
121
+ descent: Math.abs(descent),
122
+ lineGap,
123
+ xAvgCharWidth,
124
+ sampleAvgWidth,
125
+ monospace: isFixedPitch || panoseMono || sameAdvance,
126
+ declaredCategory,
127
+ };
128
+ } catch {
129
+ return null;
130
+ }
131
+ }
132
+
133
+ type AdvanceLookup = (codePoint: number) => number | undefined;
134
+
135
+ function averageAdvance(sample: string, advanceOf: AdvanceLookup): number | undefined {
136
+ let total = 0;
137
+ for (const ch of sample) {
138
+ const advance = advanceOf(ch.codePointAt(0)!);
139
+ if (advance === undefined) return undefined;
140
+ total += advance;
141
+ }
142
+ return total / sample.length;
143
+ }
144
+
145
+ function allSameAdvance(sample: string, advanceOf: AdvanceLookup): boolean {
146
+ let first: number | undefined;
147
+ for (const ch of sample) {
148
+ const advance = advanceOf(ch.codePointAt(0)!);
149
+ if (advance === undefined) return false;
150
+ if (first === undefined) first = advance;
151
+ else if (advance !== first) return false;
152
+ }
153
+ return true;
154
+ }
155
+
156
+ /** Code point → advance width, via `cmap` and `hmtx`. */
157
+ function buildAdvanceLookup(
158
+ cmap: DataView | undefined,
159
+ hmtx: DataView | undefined,
160
+ numberOfHMetrics: number
161
+ ): AdvanceLookup | null {
162
+ if (!cmap || !hmtx || numberOfHMetrics === 0) return null;
163
+ if (hmtx.byteLength < numberOfHMetrics * 4) return null;
164
+ const glyphOf = buildGlyphLookup(cmap);
165
+ if (!glyphOf) return null;
166
+ return (codePoint) => {
167
+ const gid = glyphOf(codePoint);
168
+ if (!gid) return undefined; // 0 is .notdef — the character is missing
169
+ // Glyphs past numberOfHMetrics share the last advance (monospace tail).
170
+ const index = Math.min(gid, numberOfHMetrics - 1);
171
+ return hmtx.getUint16(index * 4);
172
+ };
173
+ }
174
+
175
+ /**
176
+ * Pick a Unicode `cmap` subtable (format 4 or 12) and return a lookup.
177
+ * Preference: (3,10) / (0,4+) full repertoire, then (3,1) / (0,x) BMP.
178
+ */
179
+ function buildGlyphLookup(cmap: DataView): ((codePoint: number) => number) | null {
180
+ const numSubtables = cmap.getUint16(2);
181
+ let best: { offset: number; rank: number } | null = null;
182
+ for (let i = 0; i < numSubtables; i++) {
183
+ const rec = 4 + i * 8;
184
+ const platform = cmap.getUint16(rec);
185
+ const encoding = cmap.getUint16(rec + 2);
186
+ const offset = cmap.getUint32(rec + 4);
187
+ if (offset + 4 > cmap.byteLength) continue;
188
+ const format = cmap.getUint16(offset);
189
+ if (format !== 4 && format !== 12) continue;
190
+ const unicode = platform === 0 || (platform === 3 && (encoding === 1 || encoding === 10));
191
+ if (!unicode) continue;
192
+ const rank = format === 12 ? 2 : 1;
193
+ if (!best || rank > best.rank) best = { offset, rank };
194
+ }
195
+ if (!best) return null;
196
+ const offset = best.offset;
197
+ return cmap.getUint16(offset) === 12 ? cmapFormat12(cmap, offset) : cmapFormat4(cmap, offset);
198
+ }
199
+
200
+ function cmapFormat4(cmap: DataView, offset: number): (codePoint: number) => number {
201
+ const segCount = cmap.getUint16(offset + 6) / 2;
202
+ const endCodes = offset + 14;
203
+ const startCodes = endCodes + segCount * 2 + 2;
204
+ const idDeltas = startCodes + segCount * 2;
205
+ const idRangeOffsets = idDeltas + segCount * 2;
206
+ return (cp) => {
207
+ if (cp > 0xffff) return 0;
208
+ for (let s = 0; s < segCount; s++) {
209
+ if (cp > cmap.getUint16(endCodes + s * 2)) continue;
210
+ const start = cmap.getUint16(startCodes + s * 2);
211
+ if (cp < start) return 0;
212
+ const delta = cmap.getInt16(idDeltas + s * 2);
213
+ const rangeOffsetPos = idRangeOffsets + s * 2;
214
+ const rangeOffset = cmap.getUint16(rangeOffsetPos);
215
+ if (rangeOffset === 0) return (cp + delta) & 0xffff;
216
+ const glyphPos = rangeOffsetPos + rangeOffset + (cp - start) * 2;
217
+ if (glyphPos + 2 > cmap.byteLength) return 0;
218
+ const glyph = cmap.getUint16(glyphPos);
219
+ return glyph === 0 ? 0 : (glyph + delta) & 0xffff;
220
+ }
221
+ return 0;
222
+ };
223
+ }
224
+
225
+ function cmapFormat12(cmap: DataView, offset: number): (codePoint: number) => number {
226
+ const numGroups = cmap.getUint32(offset + 12);
227
+ return (cp) => {
228
+ for (let g = 0; g < numGroups; g++) {
229
+ const rec = offset + 16 + g * 12;
230
+ const start = cmap.getUint32(rec);
231
+ const end = cmap.getUint32(rec + 4);
232
+ if (cp >= start && cp <= end) return cmap.getUint32(rec + 8) + (cp - start);
233
+ }
234
+ return 0;
235
+ };
236
+ }
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Size-adjusted fallbacks for local fonts, computed from the font files.
3
+ *
4
+ * Google fonts ship with a precomputed metrics table (`fallbacks.ts`); a
5
+ * local font can be anything, so its metrics are read from the font file
6
+ * itself (`font-metrics.ts`) when the transform registers it — at build
7
+ * time in production, on first transform in dev.
8
+ *
9
+ * From those metrics this module decides:
10
+ *
11
+ * 1. The generic family. Fixed-pitch fonts are `monospace`; otherwise the
12
+ * font's own PANOSE / IBM class, otherwise the family-name heuristic.
13
+ * `adjustFontFallback: 'Arial' | 'Times New Roman' | 'monospace'`
14
+ * overrides it.
15
+ * 2. The fallback base: Arial (sans), Times New Roman (serif), or a list
16
+ * of ~0.600em monospace system fonts (mono). Each base lists
17
+ * metric-compatible Linux equivalents as later `local()` sources.
18
+ * 3. The overrides, computed the way Next.js's `adjustFontFallback` does:
19
+ * `size-adjust` = font average width / base average width, then each
20
+ * vertical metric divided by `unitsPerEm × size-adjust` (the overrides
21
+ * apply to the *adjusted* size).
22
+ *
23
+ * A bold (700) face is emitted when the font has its own 700 source, using
24
+ * the base's bold system font and the bold file's metrics. Without it the
25
+ * browser would synthesize bold from the regular fallback, which changes
26
+ * glyph widths and re-wraps text on swap.
27
+ *
28
+ * Design doc: 24-fonts.md §"Step 4: Size-Adjusted Fallbacks"
29
+ */
30
+
31
+ import { readFileSync, statSync } from 'node:fs';
32
+ import type { LocalFontSrc } from './types.ts';
33
+ import { readFontMetrics, type FontCategory, type FontMetrics } from './font-metrics.ts';
34
+ import { fallbackFamilyName, getGenericFamily, type FallbackFace } from './fallbacks.ts';
35
+
36
+ /** `next/font/local`'s `adjustFontFallback` option. */
37
+ export type AdjustFontFallback = boolean | 'Arial' | 'Times New Roman' | 'monospace';
38
+
39
+ /** A system font's reference metrics, measured from the font file. */
40
+ interface BaseFace {
41
+ local: string[];
42
+ unitsPerEm: number;
43
+ /** Mean advance of `AVG_WIDTH_SAMPLE` (font-metrics.ts). */
44
+ sampleAvgWidth: number;
45
+ /** `OS/2.xAvgCharWidth`, for fonts whose sample can't be measured. */
46
+ xAvgCharWidth: number;
47
+ }
48
+
49
+ /**
50
+ * Reference metrics, measured with `readFontMetrics` on the macOS system
51
+ * fonts. Arial's and Times New Roman's sample widths match Next.js's
52
+ * constants (934.51 and 854.40 per 2048). Every listed monospace font is
53
+ * 1229–1233/2048 wide (Courier New, Liberation Mono, Cousine, Droid Sans
54
+ * Mono and Roboto Mono are 1229; Menlo and DejaVu Sans Mono 1233), so one
55
+ * reference serves the list.
56
+ */
57
+ const BASES: Record<FontCategory, { regular: BaseFace; bold: BaseFace }> = {
58
+ 'sans-serif': {
59
+ regular: {
60
+ local: ['Arial', 'ArialMT', 'Liberation Sans', 'Arimo'],
61
+ unitsPerEm: 2048,
62
+ sampleAvgWidth: 934.5116279069767,
63
+ xAvgCharWidth: 904,
64
+ },
65
+ bold: {
66
+ local: ['Arial Bold', 'Arial-BoldMT', 'Liberation Sans Bold', 'Arimo Bold'],
67
+ unitsPerEm: 2048,
68
+ sampleAvgWidth: 1011.046511627907,
69
+ xAvgCharWidth: 980,
70
+ },
71
+ },
72
+ 'serif': {
73
+ regular: {
74
+ local: ['Times New Roman', 'TimesNewRomanPSMT', 'Liberation Serif', 'Tinos'],
75
+ unitsPerEm: 2048,
76
+ sampleAvgWidth: 854.3953488372093,
77
+ xAvgCharWidth: 821,
78
+ },
79
+ bold: {
80
+ local: [
81
+ 'Times New Roman Bold',
82
+ 'TimesNewRomanPS-BoldMT',
83
+ 'Liberation Serif Bold',
84
+ 'Tinos Bold',
85
+ ],
86
+ unitsPerEm: 2048,
87
+ sampleAvgWidth: 907.5581395348837,
88
+ xAvgCharWidth: 874,
89
+ },
90
+ },
91
+ 'monospace': {
92
+ regular: {
93
+ local: [
94
+ 'Menlo',
95
+ 'DejaVu Sans Mono',
96
+ 'Liberation Mono',
97
+ 'Cousine',
98
+ 'Droid Sans Mono',
99
+ 'Roboto Mono',
100
+ 'Courier New',
101
+ ],
102
+ unitsPerEm: 2048,
103
+ sampleAvgWidth: 1229,
104
+ xAvgCharWidth: 1229,
105
+ },
106
+ bold: {
107
+ local: [
108
+ 'Menlo Bold',
109
+ 'Menlo-Bold',
110
+ 'DejaVu Sans Mono Bold',
111
+ 'Liberation Mono Bold',
112
+ 'Cousine Bold',
113
+ 'Roboto Mono Bold',
114
+ 'Courier New Bold',
115
+ 'CourierNewPS-BoldMT',
116
+ ],
117
+ unitsPerEm: 2048,
118
+ sampleAvgWidth: 1229,
119
+ xAvgCharWidth: 1229,
120
+ },
121
+ },
122
+ };
123
+
124
+ const ADJUST_CATEGORY: Record<Exclude<AdjustFontFallback, boolean>, FontCategory> = {
125
+ 'Arial': 'sans-serif',
126
+ 'Times New Roman': 'serif',
127
+ 'monospace': 'monospace',
128
+ };
129
+
130
+ /** What a local font's stack and fallback CSS are built from. */
131
+ export interface LocalFallback {
132
+ generic: FontCategory;
133
+ faces: FallbackFace[];
134
+ }
135
+
136
+ /** Metrics by absolute path, invalidated by mtime/size (dev edits). */
137
+ const metricsCache = new Map<
138
+ string,
139
+ { mtimeMs: number; size: number; metrics: FontMetrics | null }
140
+ >();
141
+
142
+ /** Read a font file's metrics, or `null` when it is missing or unreadable. */
143
+ export function readFontFileMetrics(path: string): FontMetrics | null {
144
+ let stat;
145
+ try {
146
+ stat = statSync(path);
147
+ } catch {
148
+ return null;
149
+ }
150
+ const cached = metricsCache.get(path);
151
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
152
+ return cached.metrics;
153
+ }
154
+ let metrics: FontMetrics | null;
155
+ try {
156
+ metrics = readFontMetrics(readFileSync(path));
157
+ } catch {
158
+ metrics = null;
159
+ }
160
+ metricsCache.set(path, { mtimeMs: stat.mtimeMs, size: stat.size, metrics });
161
+ return metrics;
162
+ }
163
+
164
+ const isBold = (weight: string | undefined) => weight === '700' || weight === 'bold';
165
+ const isRegular = (weight: string | undefined) =>
166
+ weight === undefined || weight === '400' || weight === 'normal';
167
+ const isUpright = (style: string | undefined) => style === undefined || style === 'normal';
168
+
169
+ /** The source fallback metrics come from: 400 normal, else the first. */
170
+ export function pickRegularSource(sources: LocalFontSrc[]): LocalFontSrc | undefined {
171
+ return sources.find((s) => isRegular(s.weight) && isUpright(s.style)) ?? sources[0];
172
+ }
173
+
174
+ function pickBoldSource(sources: LocalFontSrc[]): LocalFontSrc | undefined {
175
+ return (
176
+ sources.find((s) => isBold(s.weight) && isUpright(s.style)) ??
177
+ sources.find((s) => isBold(s.weight))
178
+ );
179
+ }
180
+
181
+ /** Round to the 2-decimal percentage a CSS descriptor carries. */
182
+ function percent(ratio: number): number {
183
+ return Math.round(Math.abs(ratio) * 10000) / 100;
184
+ }
185
+
186
+ /** Compute one fallback face from a font's metrics against a base face. */
187
+ export function computeFallbackFace(
188
+ family: string,
189
+ metrics: FontMetrics,
190
+ base: BaseFace,
191
+ weight?: string
192
+ ): FallbackFace {
193
+ // Compare like with like: the weighted sample when the font has every
194
+ // sampled glyph, else OS/2's average, else leave the size alone.
195
+ let sizeAdjust = 1;
196
+ if (metrics.sampleAvgWidth) {
197
+ sizeAdjust =
198
+ metrics.sampleAvgWidth / metrics.unitsPerEm / (base.sampleAvgWidth / base.unitsPerEm);
199
+ } else if (metrics.xAvgCharWidth) {
200
+ sizeAdjust =
201
+ metrics.xAvgCharWidth / metrics.unitsPerEm / (base.xAvgCharWidth / base.unitsPerEm);
202
+ }
203
+ const scale = metrics.unitsPerEm * sizeAdjust;
204
+ return {
205
+ family: fallbackFamilyName(family),
206
+ local: base.local,
207
+ ...(weight ? { weight } : {}),
208
+ sizeAdjust: percent(sizeAdjust),
209
+ ascentOverride: percent(metrics.ascent / scale),
210
+ descentOverride: percent(metrics.descent / scale),
211
+ lineGapOverride: percent(metrics.lineGap / scale),
212
+ };
213
+ }
214
+
215
+ /**
216
+ * Work out a local font's generic family and fallback faces.
217
+ *
218
+ * `sources` must already be resolved to absolute paths. Missing or
219
+ * unreadable files produce no faces (the stack then skips the fallback
220
+ * family) and the name heuristic for the generic family.
221
+ */
222
+ export function resolveLocalFallback(
223
+ family: string,
224
+ sources: LocalFontSrc[],
225
+ adjust: AdjustFontFallback = true
226
+ ): LocalFallback {
227
+ const regularSrc = pickRegularSource(sources);
228
+ const metrics = regularSrc ? readFontFileMetrics(regularSrc.path) : null;
229
+
230
+ const generic: FontCategory =
231
+ typeof adjust === 'string'
232
+ ? ADJUST_CATEGORY[adjust]
233
+ : metrics?.monospace
234
+ ? 'monospace'
235
+ : (metrics?.declaredCategory ?? getGenericFamily(family));
236
+
237
+ if (adjust === false || !metrics) return { generic, faces: [] };
238
+
239
+ const base = BASES[generic];
240
+ const faces = [computeFallbackFace(family, metrics, base.regular)];
241
+
242
+ const boldSrc = pickBoldSource(sources);
243
+ if (boldSrc && boldSrc !== regularSrc) {
244
+ const boldMetrics = readFontFileMetrics(boldSrc.path) ?? metrics;
245
+ faces.push(computeFallbackFace(family, boldMetrics, base.bold, '700'));
246
+ }
247
+
248
+ return { generic, faces };
249
+ }
@@ -16,6 +16,7 @@
16
16
  import { resolve, dirname, extname } from 'node:path';
17
17
  import type { LocalFontConfig, LocalFontSrc, FontFaceDescriptor, ExtractedFont } from './types.ts';
18
18
  import { buildFontStack } from './fallbacks.ts';
19
+ import { resolveLocalFallback } from './local-fallback.ts';
19
20
  import { extractLocalFontConfigAst } from './ast.ts';
20
21
  import { fontOutputBasename, fontUrlPrefix } from './paths.ts';
21
22
 
@@ -144,7 +145,17 @@ export function processLocalFont(config: LocalFontConfig, importerPath: string):
144
145
  const family = config.family ?? generateFamilyName(sources);
145
146
  const display = config.display ?? 'swap';
146
147
  const className = localFontClassName(family);
147
- const fontStack = buildFontStack(family);
148
+ // Reads the font file's metrics (cached by mtime) — see local-fallback.ts.
149
+ const { generic, faces } = resolveLocalFallback(
150
+ family,
151
+ resolvedSources,
152
+ config.adjustFontFallback
153
+ );
154
+ const fontStack = buildFontStack(family, {
155
+ generic,
156
+ hasFallbackFace: faces.length > 0,
157
+ fallback: config.fallback,
158
+ });
148
159
 
149
160
  const weights = [...new Set(resolvedSources.map((s) => s.weight ?? '400'))];
150
161
  const styles = [...new Set(resolvedSources.map((s) => s.style ?? 'normal'))];
@@ -162,6 +173,8 @@ export function processLocalFont(config: LocalFontConfig, importerPath: string):
162
173
  importer: importerPath,
163
174
  className,
164
175
  fontFamily: fontStack,
176
+ fallbackFaces: faces,
177
+ preload: config.preload ?? true,
165
178
  };
166
179
  }
167
180
 
@@ -32,7 +32,7 @@ import type { ExtractedFont, FontEntry, FontFaceDescriptor } from './types.ts';
32
32
  import type { CachedFont } from './google.ts';
33
33
  import { contentHash } from './google.ts';
34
34
  import { generateVariableClass, generateFontFamilyClass, generateFontFaces } from './css.ts';
35
- import { generateFallbackCss } from './fallbacks.ts';
35
+ import { generateFallbackFaceCss, googleFallbackFaces } from './fallbacks.ts';
36
36
  import { generateLocalFontFaces } from './local.ts';
37
37
  import { hashedFontBasename, fontUrlPrefix } from './paths.ts';
38
38
  import { VirtualFontCssIdMap } from './virtual-modules.ts';
@@ -335,8 +335,11 @@ function renderEntryCss(entry: FontEntry, urlPrefix: string): string {
335
335
  if (faceCss) cssParts.push(faceCss);
336
336
  }
337
337
 
338
- const fallbackCss = generateFallbackCss(entry.family);
339
- if (fallbackCss) cssParts.push(fallbackCss);
338
+ // Local fonts carry faces measured from their files; Google fonts use
339
+ // the precomputed table, keyed by family.
340
+ const fallbackFaces =
341
+ entry.provider === 'local' ? (entry.fallbackFaces ?? []) : googleFallbackFaces(entry.family);
342
+ for (const face of fallbackFaces) cssParts.push(generateFallbackFaceCss(face));
340
343
 
341
344
  if (entry.variable) {
342
345
  cssParts.push(generateVariableClass(entry.className, entry.variable, entry.fontFamily));