|
| 1 | +import { render } from "svelte/server"; |
| 2 | +import { read } from "$app/server"; |
| 3 | +import DMSerifDisplay from "@fontsource/dm-serif-display/files/dm-serif-display-latin-400-normal.woff"; |
| 4 | +import Pretendard from "@fontsource/pretendard/files/pretendard-latin-400-normal.woff"; |
| 5 | +import PretendardSemibold from "@fontsource/pretendard/files/pretendard-latin-600-normal.woff"; |
| 6 | +import { Resvg } from "@resvg/resvg-js"; |
| 7 | +import satori from "satori"; |
| 8 | +import { html } from "satori-html"; |
| 9 | +import type { RequestHandler } from "./$types"; |
| 10 | +import Thumbnail from "./Thumbnail.svelte"; |
| 11 | +import { OG_HEIGHT, OG_WIDTH } from "./constants"; |
| 12 | + |
| 13 | +const sansFont = read(Pretendard).arrayBuffer(); |
| 14 | +const sansFontSemibold = read(PretendardSemibold).arrayBuffer(); |
| 15 | +const displayFont = read(DMSerifDisplay).arrayBuffer(); |
| 16 | + |
| 17 | +// Sources: https://github.com/huggingface/chat-ui/blob/ebeff50ac0ac4367a8e1a32b46dcc5ac2e8fc43f/src/routes/assistant/%5BassistantId%5D/thumbnail.png/%2Bserver.ts#L44-L82 |
| 18 | +// https://geoffrich.net/posts/svelte-social-image/ |
| 19 | +export const GET: RequestHandler = async ({ url }) => { |
| 20 | + const renderedComponent = render(Thumbnail, { |
| 21 | + props: { |
| 22 | + title: url.searchParams.get("title") ?? "", |
| 23 | + description: url.searchParams.get("description") ?? undefined |
| 24 | + } |
| 25 | + }); |
| 26 | + |
| 27 | + const reactLike = html(`<style>${renderedComponent.head}</style>${renderedComponent.body}`); |
| 28 | + |
| 29 | + const svg = await satori(reactLike, { |
| 30 | + width: OG_WIDTH, |
| 31 | + height: OG_HEIGHT, |
| 32 | + fonts: [ |
| 33 | + { |
| 34 | + name: "SansFont", |
| 35 | + data: await sansFont, |
| 36 | + weight: 400, |
| 37 | + style: "normal" |
| 38 | + }, |
| 39 | + { |
| 40 | + name: "SansFontSemibold", |
| 41 | + data: await sansFontSemibold, |
| 42 | + weight: 600, |
| 43 | + style: "normal" |
| 44 | + }, |
| 45 | + { |
| 46 | + name: "DisplayFont", |
| 47 | + data: await displayFont, |
| 48 | + weight: 400, |
| 49 | + style: "normal" |
| 50 | + } |
| 51 | + ] |
| 52 | + }); |
| 53 | + |
| 54 | + const png = new Resvg(svg, { |
| 55 | + fitTo: { |
| 56 | + mode: "original" |
| 57 | + } |
| 58 | + }) |
| 59 | + .render() |
| 60 | + .asPng(); |
| 61 | + |
| 62 | + // `png` is not usable directly inside `new Response()` for some reason, TS says |
| 63 | + let bodyData; |
| 64 | + if (png instanceof ArrayBuffer) { |
| 65 | + bodyData = png; |
| 66 | + } else if (png.buffer instanceof ArrayBuffer) { |
| 67 | + bodyData = png.buffer; |
| 68 | + } else { |
| 69 | + bodyData = new Uint8Array(png); |
| 70 | + } |
| 71 | + |
| 72 | + return new Response(bodyData, { |
| 73 | + headers: { |
| 74 | + "Content-Type": "image/png", |
| 75 | + "Cache-Control": "public, max-age=31536000, immutable" |
| 76 | + } |
| 77 | + }); |
| 78 | +}; |
0 commit comments