The best way to control Claude Code, Codex and more from any computer or phone

main
ts 226 lines 8.44 KB
Raw
1 /**
2 * Static Open Graph image endpoint. During `astro build` Astro invokes this
3 * for every entry returned by `getStaticPaths`, writing a WebP into
4 * `dist/og/<slug>.webp`. Pages reference these via `<meta property="og:image">`
5 * in their layout/head.
6 *
7 * - Marketing pages (top-level `src/pages/*.{astro,mdx}`) → /og/<page>.webp
8 * (the homepage is keyed as `index`).
9 * - Starlight docs (`getCollection("docs")`) → /og/<entry.slug>.webp.
10 *
11 * The card itself lives in `src/brand/OgCard.tsx` and is rendered via
12 * Takumi. Fonts are the same families used on the website
13 * (`tokens.css`), loaded from npm bundles with full Source Serif glyph coverage —
14 * arrows, em-dashes, fancy quotes, etc. all render verbatim.
15 */
16
17 import { createHash } from "node:crypto";
18 import type { APIRoute, GetStaticPaths } from "astro";
19 import { getCollection } from "astro:content";
20 import type { ReactNode } from "react";
21 import { renderToStaticMarkup } from "react-dom/server";
22 import { jsx } from "react/jsx-runtime";
23 import { render } from "takumi-js";
24 import { brandFonts } from "../../brand/fonts.ts";
25 import { OgCard, type OgCardKind, type OgCardProps } from "../../brand/OgCard.tsx";
26
27 interface Entry extends OgCardProps {
28 slug: string;
29 }
30
31 const RENDER_CONCURRENCY = 4;
32
33 const renderOptions = {
34 width: 1200 * 2,
35 height: 630 * 2,
36 devicePixelRatio: 2,
37 format: "webp" as const,
38 emoji: "from-font" as const,
39 };
40
41 async function renderCard(entry: Entry): Promise<Uint8Array<ArrayBuffer>> {
42 return render(OgCard(entry), { ...renderOptions, fonts: brandFonts });
43 }
44
45 /**
46 * Astro's incremental builder generates routes serially, so a cold build would
47 * otherwise leave all but one native renderer idle. Keep a bounded window of
48 * upcoming cards in flight: cache hits do no rendering at all, while cold builds
49 * still use concurrent native rendering. Entries outside the window are never speculatively
50 * rendered.
51 */
52 let renderEntries: Entry[] = [];
53 const renderEntryIndexes = new Map<string, number>();
54 const pendingRenders = new Map<string, Promise<Uint8Array<ArrayBuffer>>>();
55
56 function setRenderEntries(entries: Entry[]) {
57 renderEntries = entries;
58 renderEntryIndexes.clear();
59 for (const [index, entry] of entries.entries()) {
60 renderEntryIndexes.set(entry.slug, index);
61 }
62 }
63
64 function renderWithLookahead(entry: Entry) {
65 const start = renderEntryIndexes.get(entry.slug);
66 if (start === undefined) return renderCard(entry);
67
68 const size = import.meta.env.DEV ? 1 : RENDER_CONCURRENCY;
69 for (const candidate of renderEntries.slice(start, start + size)) {
70 if (pendingRenders.has(candidate.slug)) continue;
71 const render = renderCard(candidate);
72 render.catch(() => {});
73 pendingRenders.set(candidate.slug, render);
74 }
75
76 return pendingRenders.get(entry.slug)!;
77 }
78
79 // ────────────────────────────────────────────────────────────────────────────
80 // Page enumeration
81 // ────────────────────────────────────────────────────────────────────────────
82
83 /**
84 * Fallbacks for the marketing pages — these aren't in a content collection
85 * so we hand-curate their OG metadata. Keys are URL-style slugs (e.g.
86 * `index` for `/`).
87 */
88 const MARKETING_PAGES: Record<string, Omit<Entry, "slug" | "kind">> = {
89 index: {
90 title: jsx("span", {
91 children: [
92 "Reach for the ",
93 jsx("span", {
94 style: { fontStyle: "italic", color: "#a8c47a" },
95 children: "better primitives.",
96 }),
97 ],
98 }),
99 description:
100 "Snap together cloud resources and let Alchemy take care of the wiring so you can focus on your product.",
101 eyebrow: "infrastructure as effects",
102 },
103 compare: {
104 title: "Alchemy vs SST, Pulumi & Terraform",
105 description:
106 "One TypeScript program for your infrastructure and the code that runs on it, with no wrapped engines underneath.",
107 eyebrow: "compare",
108 },
109 privacy: {
110 title: "Privacy & Telemetry",
111 description:
112 "What data the Alchemy CLI and Cloudflare State Store collect, where it goes, and how to opt out.",
113 eyebrow: "alchemy.run",
114 },
115 };
116
117 function classifyDoc(slug: string): { kind: OgCardKind; eyebrow: string } {
118 if (slug.startsWith("blog/")) return { kind: "blog", eyebrow: "blog · alchemy.run" };
119 if (slug.startsWith("guides/")) return { kind: "doc", eyebrow: "guide · alchemy" };
120 if (slug.startsWith("concepts/")) return { kind: "doc", eyebrow: "concept · alchemy" };
121 if (slug.startsWith("tutorial/")) return { kind: "doc", eyebrow: "tutorial · alchemy" };
122 if (slug.startsWith("providers/")) return { kind: "doc", eyebrow: "provider · alchemy" };
123 if (slug.startsWith("compare/")) return { kind: "doc", eyebrow: "compare · alchemy" };
124 return { kind: "doc", eyebrow: "alchemy · documentation" };
125 }
126
127 /** Hash the actual card tree, including styles and embedded SVGs, plus renderer inputs. */
128 export function createOgCacheKey(fonts: Awaited<typeof brandFonts>, options: object) {
129 const shared = createHash("sha256").update(JSON.stringify(options));
130 for (const { data, ...metadata } of fonts) {
131 shared.update(JSON.stringify(metadata));
132 shared.update(new Uint8Array(data));
133 }
134 return (card: ReactNode) => shared.copy().update(renderToStaticMarkup(card)).digest("hex");
135 }
136
137 export const getStaticPaths: GetStaticPaths = async () => {
138 // `DOCS_FAST=1` (the `docs:check` build target) skips OG image generation —
139 // rendering PNGs is unnecessary for link checking.
140 if (process.env.DOCS_FAST) return [];
141
142 const docs = await getCollection("docs");
143 const docPaths = docs.map((entry: any) => {
144 const slug = (entry as { slug?: string; id?: string }).slug ?? entry.id;
145 const meta = classifyDoc(slug);
146 const data = entry.data as {
147 title?: string;
148 description?: string;
149 excerpt?: string;
150 date?: string | Date;
151 };
152 return {
153 params: { slug },
154 props: {
155 slug,
156 title: data.title ?? slug,
157 // Blog frontmatter uses `excerpt` (starlight-blog schema). Fall
158 // back to it so the OG card has body copy to fill the layout.
159 description: data.description ?? data.excerpt,
160 kind: meta.kind,
161 eyebrow: meta.eyebrow,
162 date: data.date instanceof Date ? data.date.toISOString().slice(0, 10) : data.date,
163 } satisfies Entry,
164 };
165 });
166
167 const marketingPaths = Object.entries(MARKETING_PAGES).map(([slug, meta]) => ({
168 params: { slug },
169 props: {
170 slug,
171 title: meta.title,
172 description: meta.description,
173 kind: "marketing" as const,
174 eyebrow: meta.eyebrow,
175 } satisfies Entry,
176 }));
177
178 // Virtual routes that emit og:image metas but aren't docs entries or
179 // hand-curated marketing pages: Starlight's 404 and starlight-blog's
180 // pagination indexes (/blog, /blog/2, …). The page count is estimated
181 // generously (starlight-blog paginates at ≥5 posts/page, so dividing
182 // by 5 can only overshoot); a surplus card is harmless, and the
183 // build-output og:image check fails loudly if a rendered page ever
184 // references a card this misses.
185 const blogPosts = docs.filter((entry: any) =>
186 ((entry as { slug?: string; id?: string }).slug ?? entry.id).startsWith("blog/"),
187 );
188 const blogDescription = "Release notes and posts from the alchemy team.";
189 const virtualPaths = [
190 {
191 slug: "404",
192 title: "Page not found",
193 kind: "doc" as const,
194 eyebrow: "alchemy · documentation",
195 },
196 ...Array.from({ length: Math.max(1, Math.ceil(blogPosts.length / 5)) }, (_, i) => ({
197 slug: i === 0 ? "blog" : `blog/${i + 1}`,
198 title: "Blog",
199 description: blogDescription,
200 kind: "blog" as const,
201 eyebrow: "blog · alchemy.run",
202 })),
203 ].map((props) => ({
204 params: { slug: props.slug },
205 props,
206 }));
207
208 const paths = [...marketingPaths, ...docPaths, ...virtualPaths];
209 setRenderEntries(paths.map(({ props }) => props));
210 const cacheKey = createOgCacheKey(brandFonts, renderOptions);
211 return paths.map((path) => ({
212 ...path,
213 cacheKey: cacheKey(OgCard(path.props)),
214 }));
215 };
216
217 export const GET: APIRoute = async ({ props }) => {
218 const entry = props as Entry;
219 const png = await renderWithLookahead(entry);
220 pendingRenders.delete(entry.slug);
221 return new Response(png, {
222 headers: {
223 "Content-Type": "image/webp",
224 },
225 });
226 };