Branchwell

AI Resource Pro / website · airesourcepro.com / scripts / covers / og.mjs

Raw 1.5 KB on 5069836c1e4c4e369ebe86b13dc7d299c5bed8c0
1// Share images for links on social sites and chat apps: every cover in public/covers becomes a
2// 1200 x 630 JPEG at the same path in public/og (e.g. covers/claude/x.webp -> og/claude/x.jpg),
3// cropped to the middle of the 5:3 cover. `npm run covers` runs this after rendering; run it on its own
4// with `node scripts/covers/og.mjs` to redo the share images from the covers already in public/covers.
5import fs from "node:fs/promises";
6import path from "node:path";
7import { fileURLToPath } from "node:url";
8import sharp from "sharp";
9
10const COVERS_DIR = path.join(process.cwd(), "public", "covers");
11const OG_DIR = path.join(process.cwd(), "public", "og");
12
13async function coverFiles(dir) {
14 const entries = await fs.readdir(dir, { withFileTypes: true });
15 const nested = await Promise.all(
16 entries.map((e) => (e.isDirectory() ? coverFiles(path.join(dir, e.name)) : e.name.endsWith(".webp") ? [path.join(dir, e.name)] : []))
17 );
18 return nested.flat();
19}
20
21export async function writeOgImages() {
22 for (const cover of await coverFiles(COVERS_DIR)) {
23 const out = path.join(OG_DIR, path.relative(COVERS_DIR, cover)).replace(/\.webp$/, ".jpg");
24 await fs.mkdir(path.dirname(out), { recursive: true });
25 await sharp(cover).resize(1200, 630, { fit: "cover", position: "centre" }).jpeg({ quality: 84, mozjpeg: true }).toFile(out);
26 console.log(`og: wrote ${path.relative(process.cwd(), out)}`);
27 }
28}
29
30if (process.argv[1] === fileURLToPath(import.meta.url)) {
31 writeOgImages().catch((e) => {
32 console.error("og: failed:", e);
33 process.exitCode = 1;
34 });
35}