import { readFile, writeFile } from 'node:fs/promises' import path from 'node:path' import { createRequire } from 'node:module' const require = createRequire(import.meta.url) const mobileRoot = path.resolve(import.meta.dirname, '..') const outputPath = path.join(mobileRoot, 'src', 'components', 'katex-page-style.generated.ts') // KaTeX's stylesheet for the page, woff2 only: every shell WebView reads it, and the bundle // emits each imported font as a same-origin asset, which the shell's font-src allows. async function main() { const { version } = require(require.resolve('katex/package.json')) const css = await readFile(require.resolve('katex/dist/katex.min.css'), 'utf8') const fonts = [] const parts = [] let rest = css const fontSource = /src:url\(fonts\/([\w-]+)\.woff2\) format\("woff2"\)(?:,url\([^)]*\) format\("[\w]+"\))*/ for (let match = fontSource.exec(rest); match; match = fontSource.exec(rest)) { fonts.push(match[1]) parts.push(JSON.stringify(`${rest.slice(0, match.index)}src:url(`)) parts.push(`font${String(fonts.length - 1)}`) parts.push(JSON.stringify(') format("woff2")')) rest = rest.slice(match.index + match[0].length) } parts.push(JSON.stringify(rest)) if (fonts.length === 0 || rest.includes('url(fonts/')) { throw new Error( '[build-katex-page-style] katex.min.css no longer matches the expected @font-face shape' ) } const source = [ '// Generated by scripts/build-katex-page-style.mjs.', `// Package: katex@${version}, its stylesheet with woff2 fonts as page assets.`, '// Do not edit by hand; regenerate via pnpm postinstall.', ...fonts.map( (font, index) => `import font${String(index)} from 'katex/dist/fonts/${font}.woff2'` ), '', `export const KATEX_PAGE_STYLE = [\n ${parts.join(',\n ')}\n].join('')`, '' ].join('\n') await writeFile(outputPath, source) } await main()