saturn
- 187 commits
- 2 branches
- 0 tags
- updated
- CI 2/2
posts.js
15.3 KB · 385 lines
1// my bluesky posts on the site: the newest 3 on /, the newest one as a card2// on /blog/, all of them on /posts/. my posts and reposts, newest first,3// replies dropped. which posts exist comes from my pds; bluesky's appview4// fills in what the pds doesn't hold (reposted and quoted text, image5// thumbnails on bluesky's cdn). nothing here runs in the browser.6//7// the pages never wait on my pds. the posts come from cloudflare's cache;8// once they're FRESH seconds old the next visitor still gets the cached copy9// and a refresh runs after the response is sent. only an empty cache waits,10// and never more than WAIT ms: past that the page goes out with its fallback11// text and the refresh carries on in the background for the next visitor.12// see README "posts"1314const PDS = "https://home.daum.dev";15const DID = "did:plc:e3z5gj5iyuwgqao562bo4bdf";16const HANDLE = "daum.dev";17const APPVIEW = "https://public.api.bsky.app";18const TZ = "America/Los_Angeles";1920const FRESH = 300; // seconds21const WAIT = 800; // ms, empty cache only22const FETCH_TIMEOUT = 8000; // ms, the background refresh23const CACHE_KEY = "/__posts/v2"; // bump when the cached data's shape changes2425// the pages that show posts, and the only ones that ever cause a pds fetch.26// each also needs its path in /_routes.json27export const POST_PAGES = new Set(["/", "/blog/", "/posts/"]);2829// fills each [data-posts] on the page: "highlight" (the newest, as a card),30// "all", or a number. what's inside it is the fallback, kept if the pds31// can't be read32export async function withPosts(context) {33 const { request } = context;3435 // the file never changes, so a 304 would show stale posts36 const fresh = new Request(request);37 fresh.headers.delete("If-None-Match");38 fresh.headers.delete("If-Modified-Since");39 const response = await context.next(fresh);40 if (!(response.headers.get("content-type") || "").includes("text/html")) return response;4142 let items = null;43 try {44 items = await cachedItems(context);45 } catch {}46 if (items === null) return response;4748 const page = new HTMLRewriter()49 .on("[data-posts]", {50 element(el) {51 el.setInnerContent(render(items, el.getAttribute("data-posts")), { html: true });52 },53 })54 .transform(response);5556 const out = new Response(page.body, page);57 out.headers.set("Cache-Control", "public, max-age=0, must-revalidate");58 out.headers.delete("ETag");59 return out;60}6162function render(items, mode) {63 if (items.length === 0) return `<p class="meta">nothing posted yet.</p>`;64 if (mode === "highlight") return renderHighlight(items[0]);65 const shown = mode === "all" ? items : items.slice(0, Number(mode) || 3);66 return shown.map(renderItem).join("\n");67}6869// ---------------------------------------------------------------------------70// cache7172// every post, or null for the fallback73async function cachedItems(context) {74 const cache = caches.default;75 const key = new Request(new URL(CACHE_KEY, context.request.url));76 const hit = await cache.match(key);77 const age = hit ? (Date.now() - Number(hit.headers.get("X-Fetched-At"))) / 1000 : Infinity;78 if (hit && age < FRESH) return hit.json();7980 const refresh = loadItems(AbortSignal.timeout(FETCH_TIMEOUT)).then(async (items) => {81 // kept a day so a pds outage serves old posts, not the fallback82 const stored = new Response(JSON.stringify(items), {83 headers: {84 "Content-Type": "application/json",85 "Cache-Control": "public, max-age=86400",86 "X-Fetched-At": String(Date.now()),87 },88 });89 await cache.put(key, stored);90 return items;91 });92 context.waitUntil(refresh.catch(() => {}));9394 if (hit) return hit.json();95 const timeout = new Promise((resolve) => setTimeout(() => resolve(null), WAIT));96 return Promise.race([refresh.catch(() => null), timeout]);97}9899// ---------------------------------------------------------------------------100// data101102// every post and repost, newest first, each with the appview's copy of the103// post (`view`, missing if the appview failed). throws if the pds can't be read104async function loadItems(signal) {105 const [posts, reposts] = await Promise.all([106 listRecords("app.bsky.feed.post", signal),107 listRecords("app.bsky.feed.repost", signal),108 ]);109110 const items = [111 ...posts112 .filter((r) => typeof r.value?.text === "string" && !r.value.reply)113 .map((r) => ({ rkey: rkeyOf(r.uri), uri: r.uri, createdAt: r.value.createdAt, record: r.value })),114 ...reposts115 .filter((r) => typeof r.value?.subject?.uri === "string")116 .map((r) => ({ rkey: rkeyOf(r.uri), uri: r.value.subject.uri, createdAt: r.value.createdAt, repost: true })),117 ].sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));118119 const views = await getPosts(items.map((i) => i.uri), signal);120 for (const item of items) item.view = views.get(item.uri);121 return items;122}123124async function listRecords(collection, signal) {125 const records = [];126 let cursor;127 do {128 const url = new URL("/xrpc/com.atproto.repo.listRecords", PDS);129 url.searchParams.set("repo", DID);130 url.searchParams.set("collection", collection);131 url.searchParams.set("limit", "100");132 if (cursor) url.searchParams.set("cursor", cursor);133 const res = await fetch(url, { signal });134 if (!res.ok) throw new Error(`listRecords ${collection}: ${res.status}`);135 const page = await res.json();136 records.push(...(page.records ?? []));137 cursor = page.records?.length ? page.cursor : undefined;138 } while (cursor);139 return records;140}141142// the appview's hydrated copy of each post, by uri, 25 per call. whatever143// it returned before failing144async function getPosts(uris, signal) {145 const views = new Map();146 try {147 for (let i = 0; i < uris.length; i += 25) {148 const url = new URL("/xrpc/app.bsky.feed.getPosts", APPVIEW);149 for (const uri of uris.slice(i, i + 25)) url.searchParams.append("uris", uri);150 const res = await fetch(url, { signal });151 if (!res.ok) break;152 for (const view of (await res.json()).posts ?? []) views.set(view.uri, view);153 }154 } catch {}155 return views;156}157158function rkeyOf(uri) {159 return uri.split("/").pop();160}161162// ---------------------------------------------------------------------------163// rendering164165// one post on / or /posts/. the time is its permalink on /posts/; replying166// happens on bluesky. a repost shows the original in a panel167function renderItem(item) {168 const { view } = item;169 const href = postHref(item.uri);170 const lines = [171 `<article class="post-item${item.repost ? " post-item--repost" : ""}" id="${esc(item.rkey)}">`,172 ` <p class="post-item-meta">`,173 ` <span>${item.repost ? `<span class="post-item-label">reposted</span> ` : ""}<a class="post-item-time" href="/posts/#${esc(item.rkey)}"><time datetime="${esc(item.createdAt)}">${formatDate(item.createdAt)}</time></a></span>`,174 ` <a class="post-item-reply" href="${href}">reply on bluesky</a>`,175 ` </p>`,176 ];177178 if (!item.repost) {179 lines.push(...body(item.record, view, href));180 } else if (typeof view?.record?.text !== "string") {181 lines.push(` <p class="post-item-note"><a href="${href}">reposted post → view on bluesky</a></p>`);182 } else {183 lines.push(184 ` <div class="post-item-repost">`,185 ` <p class="post-item-card-meta">${author(view.author)}</p>`,186 ...body(view.record, view, href).map((l) => ` ${l}`),187 ` </div>`,188 );189 }190191 lines.push(`</article>`);192 return lines.join("\n");193}194195// the newest post on /blog/: a small card, text only, linking to it on /posts/196function renderHighlight(item) {197 const record = item.repost ? item.view?.record : item.record;198 const who = item.repost ? `${item.view?.author?.displayName || item.view?.author?.handle || ""}: ` : "";199 const extras = attachments(item.view?.embed);200 const text = record?.text?.trim() || extras.join(", ") || "view post";201 return [202 `<a class="post-card" href="/posts/#${esc(item.rkey)}">`,203 ` <span class="post-card-meta">`,204 ` <span>${item.repost ? "↻ reposted" : "@" + HANDLE}</span>`,205 ` <time datetime="${esc(item.createdAt)}">${formatDate(item.createdAt)}</time>`,206 ` </span>`,207 ` <span class="post-card-text">${escText(who + text)}</span>`,208 extras.length ? ` <span class="post-card-extra">${escText(extras.join(" · "))}</span>` : null,209 `</a>`,210 ].filter((l) => l !== null).join("\n");211}212213// "2 images", "video", "link", "quote"214function attachments(embed) {215 switch (embed?.$type) {216 case "app.bsky.embed.images#view": {217 const n = embed.images?.length || 0;218 return n ? [n === 1 ? "1 image" : `${n} images`] : [];219 }220 case "app.bsky.embed.video#view":221 return ["video"];222 case "app.bsky.embed.external#view":223 return ["link"];224 case "app.bsky.embed.record#view":225 return ["quote"];226 case "app.bsky.embed.recordWithMedia#view":227 return [...attachments(embed.media), "quote"];228 default:229 return [];230 }231}232233// text, then whatever is attached. with no appview copy, attachments are a link234function body(record, view, href) {235 const lines = [];236 if (record.text.trim()) {237 lines.push(` <p class="post-item-body">${renderText(record.text, record.facets)}</p>`);238 }239 if (view?.embed) {240 lines.push(...renderEmbed(view.embed, href).map((l) => ` ${l}`));241 } else if (record.embed) {242 lines.push(` <p class="post-item-note"><a href="${href}">attachment → view on bluesky</a></p>`);243 }244 return lines;245}246247// facets index the text by utf-8 byte offset, not by js string index248function renderText(text, facets = []) {249 const bytes = new TextEncoder().encode(text);250 const decode = (from, to) => new TextDecoder().decode(bytes.slice(from, to));251 const sorted = facets252 .filter((f) => f.index && f.features?.length)253 .sort((a, b) => a.index.byteStart - b.index.byteStart);254255 let out = "";256 let pos = 0;257 for (const facet of sorted) {258 const { byteStart, byteEnd } = facet.index;259 if (byteStart < pos) continue;260 out += escText(decode(pos, byteStart));261 const label = escText(decode(byteStart, byteEnd));262 const link = facetHref(facet.features[0]);263 out += link ? `<a href="${esc(link)}">${label}</a>` : label;264 pos = byteEnd;265 }266 return out + escText(decode(pos));267}268269function facetHref(feature) {270 switch (feature.$type) {271 case "app.bsky.richtext.facet#link":272 return /^https?:\/\//.test(feature.uri) ? feature.uri : null;273 case "app.bsky.richtext.facet#mention":274 return `https://bsky.app/profile/${feature.did}`;275 case "app.bsky.richtext.facet#tag":276 return `https://bsky.app/hashtag/${encodeURIComponent(feature.tag)}`;277 default:278 return null;279 }280}281282// the appview's embed views. images are its thumbnails, never full size283function renderEmbed(embed, href) {284 switch (embed.$type) {285 case "app.bsky.embed.images#view":286 return renderImages(embed.images);287 case "app.bsky.embed.video#view":288 return renderVideo(embed, href);289 case "app.bsky.embed.external#view":290 return renderCard(embed.external);291 case "app.bsky.embed.record#view":292 return renderQuote(embed.record);293 case "app.bsky.embed.recordWithMedia#view":294 return [...renderEmbed(embed.media, href), ...renderQuote(embed.record?.record)];295 default:296 return [];297 }298}299300// one image keeps its shape; two or more go in a cropped grid301function renderImages(images = []) {302 const imgs = images303 .filter((img) => isHttps(img.thumb))304 .map((img) => `<img src="${esc(img.thumb)}" alt="${esc(img.alt || "")}"${sizeAttrs(img.aspectRatio)} loading="lazy" decoding="async" />`);305 if (imgs.length === 0) return [];306 const cls = imgs.length === 1 ? "post-item-media" : "post-item-media post-item-media--grid";307 return [`<div class="${cls}">`, ...imgs.map((i) => ` ${i}`), `</div>`];308}309310// the thumbnail with a play mark; it plays on bluesky311function renderVideo(embed, href) {312 if (!isHttps(embed.thumbnail)) {313 return [`<p class="post-item-note"><a href="${href}">video → watch on bluesky</a></p>`];314 }315 const alt = embed.alt ? `${embed.alt} (video, plays on bluesky)` : "video, plays on bluesky";316 return [317 `<a class="post-item-video" href="${href}">`,318 ` <img src="${esc(embed.thumbnail)}" alt="${esc(alt)}"${sizeAttrs(embed.aspectRatio)} loading="lazy" decoding="async" />`,319 `</a>`,320 ];321}322323function renderCard(external) {324 if (!isHttps(external?.uri, true)) return [];325 const domain = new URL(external.uri).hostname.replace(/^www\./, "");326 return [327 `<a class="post-item-card" href="${esc(external.uri)}">`,328 ` <span class="post-item-card-title">${escText(external.title || domain)}</span>`,329 external.description ? ` <span class="post-item-card-desc">${escText(external.description)}</span>` : null,330 ` <span class="post-item-card-meta">${escText(domain)}</span>`,331 `</a>`,332 ].filter((l) => l !== null);333}334335function renderQuote(record) {336 const href = postHref(record?.uri);337 if (!href) return [];338 if (record.$type !== "app.bsky.embed.record#viewRecord" || typeof record.value?.text !== "string") {339 return [`<p class="post-item-note"><a href="${href}">quoting →</a></p>`];340 }341 return [342 `<a class="post-item-card post-item-quote" href="${href}">`,343 ` <span class="post-item-card-meta">${author(record.author)}</span>`,344 ` <span class="post-item-quote-text">${escText(record.value.text)}</span>`,345 `</a>`,346 ];347}348349function author(a = {}) {350 const name = a.displayName || a.handle || "";351 return `${escText(name)} <span>@${escText(a.handle || "")}</span>`;352}353354// at://did/app.bsky.feed.post/rkey -> https://bsky.app/profile/<handle or did>/post/rkey355function postHref(uri) {356 const match = /^at:\/\/([^/]+)\/app\.bsky\.feed\.post\/([^/]+)$/.exec(uri || "");357 if (!match) return null;358 const who = match[1] === DID ? HANDLE : match[1];359 return `https://bsky.app/profile/${who}/post/${match[2]}`;360}361362function isHttps(url, orHttp = false) {363 return typeof url === "string" && (orHttp ? /^https?:\/\// : /^https:\/\//).test(url);364}365366function sizeAttrs(ratio) {367 return ratio?.width && ratio?.height ? ` width="${ratio.width}" height="${ratio.height}"` : "";368}369370// 8 Oct 2026, 1:42 pm371function formatDate(iso) {372 const d = new Date(iso);373 if (Number.isNaN(d.getTime())) return "";374 const day = d.toLocaleDateString("en-GB", { timeZone: TZ, day: "numeric", month: "short", year: "numeric" });375 const time = d.toLocaleTimeString("en-US", { timeZone: TZ, hour: "numeric", minute: "2-digit" }).toLowerCase();376 return `${day}, ${time}`;377}378379function escText(s) {380 return esc(s).replace(/\n/g, "<br />");381}382383function esc(s) {384 return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);385}