1 import { Resvg } from "@resvg/resvg-js"
2 import satori from "satori"
3
4 import { bannerFor, type BannerInput } from "./banners/index.js"
5 import { loadFonts } from "./fonts.js"
6 import { mergeSpec } from "./spec.js"
7 import type { BaseSpec } from "./types.js"
8
9 /** Resolves an input against its definition, spec overrides merged in. */
10 function prepare(input: BannerInput): {
11 spec: BaseSpec & Record<string, unknown>
12 tree: unknown
13 } {
14 const definition = bannerFor(input)
15 const normalized = definition.normalize(input)
16 const spec = mergeSpec(definition.spec, normalized.spec)
17
18 return { spec, tree: definition.build(normalized, spec) }
19 }
20
21 /**
22 * Renders a banner to an SVG string.
23 *
24 * Satori's element type comes from React, which this package does not depend on,
25 * so the tree is cast at the boundary.
26 */
27 export async function renderSvg(input: BannerInput): Promise<string> {
28 const { spec, tree } = prepare(input)
29
30 return await toSvg(spec, tree)
31 }
32
33 async function toSvg(spec: BaseSpec, tree: unknown): Promise<string> {
34 return await satori(tree as never, {
35 width: spec.width,
36 height: spec.height,
37 fonts: await loadFonts(),
38 })
39 }
40
41 /**
42 * Renders a banner to a PNG buffer.
43 *
44 * Satori lays the template out and emits SVG; resvg rasterises it. Neither step
45 * needs a browser, which keeps this runnable as a plain step in CI.
46 */
47 export async function renderPng(input: BannerInput): Promise<Buffer> {
48 const { spec, tree } = prepare(input)
49 const svg = await toSvg(spec, tree)
50
51 return new Resvg(svg, {
52 fitTo: { mode: "width", value: spec.width },
53 // Everything is drawn with the fonts passed to satori; falling back to the
54 // host's fonts would make output differ between machines and CI.
55 font: { loadSystemFonts: false },
56 })
57 .render()
58 .asPng()
59 }