|
| 1 | +// Polyfill OffscreenCanvas for Node.js environments where it's not available. |
| 2 | +// Required by @chenglou/pretext which uses canvas measureText for text width. |
| 3 | +if (typeof globalThis.OffscreenCanvas === 'undefined') { |
| 4 | + try { |
| 5 | + const { createCanvas, GlobalFonts } = await import('@napi-rs/canvas') |
| 6 | + const { existsSync } = await import('fs') |
| 7 | + const { fileURLToPath } = await import('url') |
| 8 | + const { join, dirname } = await import('path') |
| 9 | + |
| 10 | + // @napi-rs/canvas (Skia) does not automatically load system fonts on Linux. |
| 11 | + // Fonts are bundled in badge-maker/fonts/ (run `node scripts/download-fonts.js` |
| 12 | + // to populate the directory before running tests). |
| 13 | + const fontsDir = join( |
| 14 | + dirname(fileURLToPath(import.meta.url)), |
| 15 | + '..', |
| 16 | + 'fonts', |
| 17 | + ) |
| 18 | + |
| 19 | + // [filename, familyNameOverride] |
| 20 | + // familyNameOverride replaces the font's own internal family name in the |
| 21 | + // Skia registry, so that CSS font strings like 'bold 11px Helvetica' resolve |
| 22 | + // to the bundled metric-compatible substitute (Liberation Sans). |
| 23 | + const fonts = [ |
| 24 | + // Verdana — flat / plastic / for-the-badge measurement font |
| 25 | + ['Verdana.ttf'], |
| 26 | + ['Verdana_Bold.ttf'], |
| 27 | + // Liberation Sans registered as Helvetica for social-badge measurement |
| 28 | + ['LiberationSans-Regular.ttf', 'Helvetica'], |
| 29 | + ['LiberationSans-Bold.ttf', 'Helvetica'], |
| 30 | + // Liberation Sans also registered as Arial (font-family fallback in SVG) |
| 31 | + ['LiberationSans-Regular.ttf', 'Arial'], |
| 32 | + ['LiberationSans-Bold.ttf', 'Arial'], |
| 33 | + // DejaVu Sans — fallback in badge font-family lists |
| 34 | + ['DejaVuSans.ttf'], |
| 35 | + ['DejaVuSans-Bold.ttf'], |
| 36 | + ] |
| 37 | + |
| 38 | + for (const [filename, familyName] of fonts) { |
| 39 | + const fontPath = join(fontsDir, filename) |
| 40 | + if (existsSync(fontPath)) { |
| 41 | + GlobalFonts.registerFromPath(fontPath, familyName) |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + globalThis.OffscreenCanvas = class OffscreenCanvas { |
| 46 | + constructor(width, height) { |
| 47 | + this._canvas = createCanvas(width, height) |
| 48 | + } |
| 49 | + |
| 50 | + getContext(type) { |
| 51 | + return this._canvas.getContext(type) |
| 52 | + } |
| 53 | + } |
| 54 | + } catch { |
| 55 | + // @napi-rs/canvas not available; OffscreenCanvas must be provided by the runtime |
| 56 | + } |
| 57 | +} |
0 commit comments