saturn
- 187 commits
- 2 branches
- 0 tags
- updated
- CI 2/2
publish.mjs
21.9 KB · 520 lines
1// publishes a finished post page: adds or updates its entry in feed.xml and2// its standard.site record on my pds, so atproto readers (leaflet, pckt, ...)3// can find and follow it. no dependencies, node 18+.4//5// mise run publish now/sep-2026/index.html feed + standard.site6// mise run publish now/sep-2026/index.html --dry-run show what would change7//8// the page is the source: its h1 is the title, the <time> in its header the9// date, the kicker (/now) the category, the meta description the summary,10// the banner photo the cover, and the <article> the feed content (classes11// dropped, urls made absolute, the header, likes and comments left out).12//13// running it again on the same page is safe. an existing feed entry keeps its14// published date and its summary (those are often hand-written); its title15// and content are replaced and `updated` moves to now, only if they changed.16// a post's record key comes from its date and path, so it always maps to the17// same record, and the page gets a <link rel="site.standard.document"> to it.18//19// publishing to standard.site needs ATPROTO_APP_PASSWORD (a bluesky app20// password). without it the feed is still updated, and a post whose record is21// already on the pds still gets its link tag; nothing is written to the pds.2223import { readFile, writeFile } from "node:fs/promises";24import { createHash } from "node:crypto";2526const SITE = "https://danieldaum.net";27const PDS = "https://home.daum.dev";28const DID = "did:plc:e3z5gj5iyuwgqao562bo4bdf";29const TZ = "America/Los_Angeles";30const FEED = "feed.xml";31const MAX_BLOB = 1_000_000;32const ASSETS = "https://assets.danieldaum.net";33const COVER_RESIZE = "width=1600,quality=80,format=webp";3435// the publication all my posts belong to. its key is fixed, so the old36// records on my pds stay the same ones37const PUBLICATION = {38 rkey: tid(Date.parse("2026-01-01T00:00:00Z") * 1000, 0),39 name: "daniel daum",40 description: "everything i write, in one place",41 icon: "assets/favicon/android-chrome-512x512.png",42};43const PUBLICATION_URI = `at://${DID}/site.standard.publication/${PUBLICATION.rkey}`;44const WELL_KNOWN = ".well-known/site.standard.publication";4546// ---------------------------------------------------------------------------47// the page4849async function readPost(arg) {50 const dir = arg.replace(/^\/+/, "").replace(/index\.html$/, "").replace(/\/*$/, "");51 if (!dir) throw new Error("give the post's page, e.g. now/sep-2026/index.html");52 const file = `${dir}/index.html`;53 const html = await readFile(file, "utf8");5455 // commented-out markup (e.g. the template's optional banner) isn't the post56 const article = /<article>([\s\S]*?)<\/article>/.exec(html)?.[1]?.replace(/<!--[\s\S]*?-->/g, "");57 if (!article) throw new Error(`${file} has no <article>`);58 const header = /<header class="page-header[^"]*">([\s\S]*?)<\/header>/.exec(article)?.[1] ?? "";5960 const post = {61 file,62 html,63 path: `/${dir}/`,64 title: text(/<h1>([\s\S]*?)<\/h1>/.exec(header)?.[1] ?? ""),65 date: /<time datetime="(\d{4}-\d{2}-\d{2})"/.exec(header)?.[1],66 category: text(/<p class="page-header-kicker">([\s\S]*?)<\/p>/.exec(header)?.[1] ?? "").replace(/^\//, ""),67 description: decode(/<meta\s+name="description"\s+content="([^"]*)"/.exec(html)?.[1] ?? ""),68 banner: banner(article),69 content: feedContent(article),70 };71 if (!post.title) throw new Error(`${file}: no <h1> in the post header`);72 if (!post.date) throw new Error(`${file}: no <time datetime="YYYY-MM-DD"> in the post header`);73 // left over from internal/template.html74 const leftover = ["ONE SENTENCE SUMMARY", "Post Title", "Section heading", "Body text."].find((t) => (article + post.description).includes(t));75 if (leftover) throw new Error(`${file}: still has the template's "${leftover}"`);76 return post;77}7879// the banner photo, if the post has one: a single photo is a link80// (<a class="post-banner">), a row of them a <figure class="post-banner">.81// the cover is the first photo; only a linked one becomes the feed's figure,82// since a row's <figure> is already in the article body83function banner(article) {84 const m = /<(a|figure) class="post-banner[^"]*"[^>]*>([\s\S]*?)<\/\1>/.exec(article);85 const img = m && /<img\b([^>]*)>/.exec(m[2])?.[1];86 if (!img) return null;87 return { src: attr(img, "src"), alt: attr(img, "alt") ?? "", linked: m[1] === "a" };88}8990// the article as feed html: banner as a figure, then the body. no header, no91// likes and comments, no classes, absolute urls, one block per line. <pre>92// keeps its whitespace93function feedContent(article) {94 const pres = [];95 let body = article96 .replace(/<!--[\s\S]*?-->/g, "")97 .replace(/<a class="post-banner[^"]*"[^>]*>[\s\S]*?<\/a>/, "")98 .replace(/<header class="page-header[^"]*">[\s\S]*?<\/header>/, "")99 .replace(/<section[^>]*\bpost-social\b[^>]*>[\s\S]*?<\/section>/, "")100 .replace(/<\/?section[^>]*>/g, "")101 .replace(/<pre\b[\s\S]*?<\/pre>/g, (pre) => `\u0000${pres.push(pre) - 1}\u0000`);102103 body = cleanTags(body)104 .replace(/\s+/g, " ")105 .replace(/\s*(<(?:p|h[1-6]|ul|ol|li|div|figure|figcaption|blockquote|hr|table|tr|\u0000)\b)/g, "\n$1")106 .replace(/\s*(\u0000\d+\u0000)/g, "\n$1")107 .replace(/\s*\n\s*/g, "\n")108 .replace(/ +(<\/(?:p|h[1-6]|li|figcaption|blockquote)>)/g, "$1")109 .replace(/(<(?:p|h[1-6]|li|figcaption|blockquote)\b[^>]*>) +/g, "$1")110 .replace(/(<\/(?:p|li|ul|ol|div|figure|figcaption|blockquote)>)\s+(?=<\/)/g, "$1")111 .replace(/(<figure>|<img\b[^>]*\/>)\s*(?=<img\b)/g, "$1\n")112 .replace(/\s+(<\/figure>)/g, "$1")113 .trim();114 body = body.replace(/\u0000(\d+)\u0000/g, (_, i) => cleanTags(pres[i]));115116 const b = banner(article);117 const figure = b?.linked ? `<figure>\n<img src="${esc(absolute(b.src))}" alt="${esc(b.alt)}" /></figure>\n` : "";118 return figure + body;119}120121// keeps only href, src, alt, title and datetime, makes them absolute, and122// unwraps the spans left with nothing on them (e.g. code highlighting)123function cleanTags(html) {124 return html125 .replace(/<([a-z][a-z0-9]*)\b([^>]*?)(\/?)>/gi, (_, tag, attrs, selfClose) => {126 const kept = [...attrs.matchAll(/([a-z-]+)\s*=\s*"([^"]*)"/gi)]127 .filter(([, name]) => ["href", "src", "alt", "title", "datetime"].includes(name.toLowerCase()))128 .map(([, name, value]) => ` ${name}="${["href", "src"].includes(name) ? absolute(value) : value}"`)129 .join("");130 return `<${tag}${kept}${selfClose ? " /" : ""}>`;131 })132 .replace(/<span>([\s\S]*?)<\/span>/g, "$1")133 .split(/(<\/?[a-z][^>]*>)/i)134 .map((part, i) => (i % 2 ? part : part.replace(/&(?![a-z]+;|#\d+;|#x[0-9a-f]+;)/gi, "&").replace(/>/g, ">")))135 .join("");136}137138function absolute(url) {139 return /^\/(?!\/)/.test(url) ? SITE + url : url;140}141142function attr(attrs, name) {143 const raw = new RegExp(`\\b${name}="([^"]*)"`).exec(attrs)?.[1];144 return raw === undefined ? undefined : decode(raw);145}146147function text(html) {148 return decode(html.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim());149}150151// ---------------------------------------------------------------------------152// feed.xml153154// entries inside <!-- --> (hidden ones) are left alone155function liveEntries(xml) {156 const comments = [...xml.matchAll(/<!--[\s\S]*?-->/g)].map((m) => [m.index, m.index + m[0].length]);157 return [...xml.matchAll(/[ \t]*<entry>[\s\S]*?<\/entry>\n?/g)]158 .filter((m) => !comments.some(([from, to]) => m.index >= from && m.index < to))159 .map((m) => ({160 start: m.index,161 end: m.index + m[0].length,162 xml: m[0],163 id: /<id>([^<]*)<\/id>/.exec(m[0])?.[1],164 link: /<link rel="alternate"[^>]*href="([^"]*)"/.exec(m[0])?.[1],165 published: /<published>([^<]*)<\/published>/.exec(m[0])?.[1],166 updated: /<updated>([^<]*)<\/updated>/.exec(m[0])?.[1],167 }));168}169170// an entry's id never changes once it's out, even if it isn't the url171// written the way it would be today (e.g. no trailing slash)172function renderEntry(post, { id, published, updated, summary }) {173 const url = SITE + post.path;174 const lines = [175 ` <entry>`,176 ` <title>${xmlEsc(post.title)}</title>`,177 ` <link rel="alternate" type="text/html" href="${url}" />`,178 ` <id>${id ?? url}</id>`,179 ` <published>${published}</published>`,180 ` <updated>${updated}</updated>`,181 post.category ? ` <category term="${xmlEsc(post.category)}" />` : null,182 summary ? ` <summary type="text">${summary}</summary>` : null,183 ` <content type="html"><![CDATA[`,184 ...indent(post.content.replaceAll("]]>", "]]]]><![CDATA[>"), " "),185 ` ]]></content>`,186 ` </entry>`,187 ];188 return lines.filter((l) => l !== null).join("\n") + "\n";189}190191// indents each line, except inside <pre>, where it would change the code192function indent(html, by) {193 let inPre = false;194 return html.split("\n").map((line) => {195 const out = inPre ? line : by + line;196 const opens = (line.match(/<pre\b/g) || []).length;197 const closes = (line.match(/<\/pre>/g) || []).length;198 if (opens !== closes) inPre = opens > closes;199 return out;200 });201}202203// the new feed, and what happened: "added", "updated" or "unchanged"204function updateFeed(xml, post, now) {205 const url = SITE + post.path;206 const entries = liveEntries(xml);207 const slash = (u) => (u ?? "").replace(/\/?$/, "/");208 const existing = entries.find((e) => slash(e.id) === url || slash(e.link) === url);209210 let next;211 let result;212 if (existing) {213 const summary = /<summary type="text">([\s\S]*?)<\/summary>/.exec(existing.xml)?.[1];214 const same = renderEntry(post, { id: existing.id, published: existing.published, updated: existing.updated, summary });215 if (same === existing.xml.replace(/\n?$/, "\n")) return { xml, result: "unchanged" };216 const entry = renderEntry(post, { id: existing.id, published: existing.published, updated: now, summary });217 next = xml.slice(0, existing.start) + entry + xml.slice(existing.end);218 result = "updated";219 } else {220 const published = localTime(post.date, "09:00");221 const entry = renderEntry(post, { published, updated: published, summary: xmlEsc(post.description) }) + "\n";222 // newest first: before the first entry published earlier, else last223 const before = entries.find((e) => Date.parse(e.published) < Date.parse(published));224 const at = before ? before.start : xml.lastIndexOf("</feed>");225 next = xml.slice(0, at) + entry + xml.slice(at);226 result = "added";227 }228229 // the feed's own <updated>: its newest entry's230 const newest = liveEntries(next)231 .map((e) => e.updated)232 .sort((a, b) => Date.parse(b) - Date.parse(a))[0];233 next = next.replace(/(<icon>[^<]*<\/icon>\s*)<updated>[^<]*<\/updated>/, `$1<updated>${newest}</updated>`);234 return { xml: next, result };235}236237// "2026-09-03", "09:00" -> 2026-09-03T09:00:00-07:00, in my timezone238function localTime(date, time) {239 const guess = new Date(`${date}T${time}:00Z`);240 const name = new Intl.DateTimeFormat("en-US", { timeZone: TZ, timeZoneName: "longOffset" })241 .formatToParts(guess)242 .find((p) => p.type === "timeZoneName").value;243 const offset = name === "GMT" ? "+00:00" : name.replace("GMT", "");244 return `${date}T${time}:00${offset}`;245}246247function nowLocal() {248 const d = new Date();249 const parts = Object.fromEntries(250 new Intl.DateTimeFormat("en-CA", {251 timeZone: TZ, year: "numeric", month: "2-digit", day: "2-digit",252 hour: "2-digit", minute: "2-digit", hourCycle: "h23",253 }).formatToParts(d).map((p) => [p.type, p.value]),254 );255 return localTime(`${parts.year}-${parts.month}-${parts.day}`, `${parts.hour}:${parts.minute}`);256}257258// ---------------------------------------------------------------------------259// standard.site260261async function documentRecord(post, session) {262 const record = {263 $type: "site.standard.document",264 site: PUBLICATION_URI,265 path: post.path,266 title: post.title,267 publishedAt: `${post.date}T12:00:00.000Z`,268 };269 if (post.description) record.description = post.description;270 if (post.category) record.tags = [post.category];271 const cover = await coverBlob(post.banner?.src, session);272 if (cover) record.coverImage = cover;273 return record;274}275276function documentKey(post) {277 return tid(Date.parse(`${post.date}T12:00:00Z`) * 1000, clockIdFor(post.path));278}279280// the banner, if it's under the 1MB limit. if it's bigger, a smaller copy281// from cloudflare's image resizing (the original on r2 is left alone)282async function coverBlob(url, session) {283 if (!url) return null;284 const candidates = [absolute(url)];285 if (candidates[0].startsWith(`${ASSETS}/`)) {286 candidates.push(candidates[0].replace(`${ASSETS}/`, `${ASSETS}/cdn-cgi/image/${COVER_RESIZE}/`));287 }288 for (const candidate of candidates) {289 const res = await fetch(candidate);290 if (!res.ok) continue;291 const bytes = new Uint8Array(await res.arrayBuffer());292 if (bytes.length <= MAX_BLOB) return blob(bytes, res.headers.get("content-type") || "image/webp", session);293 }294 console.warn(` no cover: ${url} is over 1MB and couldn't be resized`);295 return null;296}297298// a blob ref for these bytes. uploaded only if the record changes: atproto299// blob ids are a hash of the bytes, worked out here first300function blob(bytes, mimeType, session) {301 const ref = { $type: "blob", ref: { $link: cid(bytes) }, mimeType, size: bytes.length };302 session.blobs.push({ ref, bytes });303 return ref;304}305306async function getRecord(collection, rkey) {307 const url = new URL("/xrpc/com.atproto.repo.getRecord", PDS);308 url.searchParams.set("repo", DID);309 url.searchParams.set("collection", collection);310 url.searchParams.set("rkey", rkey);311 const res = await fetch(url);312 return res.ok ? (await res.json()).value : null;313}314315// create or update a record, only when it differs from what's there. the316// pds may settle on another mime type for a blob, so blobs compare by id317async function putIfChanged(collection, rkey, record, session) {318 const existing = await getRecord(collection, rkey);319 const blobsMatch = (a, b) => canonical(withoutMime(a)) === canonical(withoutMime(b));320 if (existing && blobsMatch(existing, record)) {321 session.blobs.length = 0;322 return false;323 }324 if (session.dryRun) {325 session.blobs.length = 0;326 return true;327 }328 for (const { ref, bytes } of session.blobs) {329 const res = await xrpc("com.atproto.repo.uploadBlob", session, bytes, ref.mimeType);330 const uploaded = (await res.json()).blob;331 if (uploaded.ref.$link !== ref.ref.$link) throw new Error(`blob id mismatch for ${ref.ref.$link}`);332 ref.mimeType = uploaded.mimeType;333 }334 session.blobs.length = 0;335 await xrpc("com.atproto.repo.putRecord", session, { repo: DID, collection, rkey, record });336 return true;337}338339function withoutMime(value) {340 if (Array.isArray(value)) return value.map(withoutMime);341 if (value && typeof value === "object") {342 const out = {};343 for (const [k, v] of Object.entries(value)) {344 if (!(k === "mimeType" && value.$type === "blob")) out[k] = withoutMime(v);345 }346 return out;347 }348 return value;349}350351// <link rel="site.standard.document"> in the page's <head>, added or fixed352function withLinkTag(html, uri) {353 const tag = `<link rel="site.standard.document" href="${uri}" />`;354 if (/<link rel="site\.standard\.document"[^>]*>/.test(html)) {355 return html.replace(/<link rel="site\.standard\.document"[^>]*>/, tag);356 }357 return html.replace(/\n([ \t]*)<\/head>/, (_, indent) => `\n${indent} ${tag}\n${indent}</head>`);358}359360// ---------------------------------------------------------------------------361// atproto plumbing362363async function login() {364 const res = await fetch(new URL("/xrpc/com.atproto.server.createSession", PDS), {365 method: "POST",366 headers: { "content-type": "application/json" },367 body: JSON.stringify({ identifier: DID, password: process.env.ATPROTO_APP_PASSWORD }),368 });369 if (!res.ok) throw new Error(`login failed: ${res.status} ${await res.text()}`);370 return { jwt: (await res.json()).accessJwt, blobs: [] };371}372373async function xrpc(method, session, body, contentType = "application/json") {374 const res = await fetch(new URL(`/xrpc/${method}`, PDS), {375 method: "POST",376 headers: { "content-type": contentType, authorization: `Bearer ${session.jwt}` },377 body: contentType === "application/json" ? JSON.stringify(body) : body,378 });379 if (!res.ok) throw new Error(`${method}: ${res.status} ${await res.text()}`);380 return res;381}382383// a record key: microseconds since 1970 and a 10-bit clock id, as 13 base32384// characters. same inputs, same key385function tid(micros, clockId) {386 const alphabet = "234567abcdefghijklmnopqrstuvwxyz";387 let n = (BigInt(micros) << 10n) | BigInt(clockId & 1023);388 let out = "";389 for (let i = 0; i < 13; i++) {390 out = alphabet[Number(n & 31n)] + out;391 n >>= 5n;392 }393 return out;394}395396// keeps two posts on the same day apart397function clockIdFor(path) {398 return createHash("sha256").update(path).digest().readUInt16BE(0) & 1023;399}400401// cidv1, raw codec, sha2-256, base32: how atproto names blobs402function cid(bytes) {403 const digest = createHash("sha256").update(bytes).digest();404 const raw = Uint8Array.from([0x01, 0x55, 0x12, 0x20, ...digest]);405 const alphabet = "abcdefghijklmnopqrstuvwxyz234567";406 let bits = 0;407 let value = 0;408 let out = "b";409 for (const byte of raw) {410 value = (value << 8) | byte;411 bits += 8;412 while (bits >= 5) {413 out += alphabet[(value >>> (bits - 5)) & 31];414 bits -= 5;415 }416 }417 if (bits > 0) out += alphabet[(value << (5 - bits)) & 31];418 return out;419}420421// json with sorted keys, so two records compare equal whatever their key order422function canonical(value) {423 if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;424 if (value && typeof value === "object") {425 return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`).join(",")}}`;426 }427 return JSON.stringify(value);428}429430function decode(s) {431 return s432 .replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))433 .replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)))434 .replace(/'/g, "'")435 .replace(/"/g, '"')436 .replace(/</g, "<")437 .replace(/>/g, ">")438 .replace(/—/g, "—")439 .replace(/–/g, "–")440 .replace(/→/g, "→")441 .replace(/ /g, " ")442 .replace(/&/g, "&");443}444445function esc(s) {446 return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);447}448449function xmlEsc(s) {450 return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");451}452453// ---------------------------------------------------------------------------454// run455456const args = process.argv.slice(2);457const dryRun = args.includes("--dry-run");458const target = args.find((a) => !a.startsWith("--"));459if (!target) {460 console.error("usage: mise run publish <page>/index.html [--dry-run]");461 process.exit(1);462}463464const post = await readPost(target);465console.log(`${post.title} (${post.path}, ${post.date}${post.category ? `, #${post.category}` : ""})`);466467// feed468const feed = await readFile(FEED, "utf8");469const { xml, result } = updateFeed(feed, post, nowLocal());470if (dryRun) {471 const entry = liveEntries(xml).find((e) => e.link === SITE + post.path);472 console.log(`\nfeed: would be ${result}`);473 if (result !== "unchanged") console.log(entry.xml);474} else {475 if (xml !== feed) await writeFile(FEED, xml);476 console.log(`feed: ${result}`);477}478479// standard.site. without a password nothing is written to the pds, but a480// record that's already there and up to date still gets its local half: the481// .well-known file and the page's link tag482const canWrite = Boolean(process.env.ATPROTO_APP_PASSWORD);483const session = canWrite && !dryRun ? { ...(await login()), dryRun } : { blobs: [], dryRun: true };484const would = dryRun ? "would be " : "";485486const icon = await readFile(PUBLICATION.icon);487const publication = {488 $type: "site.standard.publication",489 url: SITE,490 name: PUBLICATION.name,491 description: PUBLICATION.description,492 icon: blob(icon, "image/png", session),493};494const publicationChanged = await putIfChanged("site.standard.publication", PUBLICATION.rkey, publication, session);495if (publicationChanged) console.log(`standard.site: publication record ${canWrite || dryRun ? `${would}updated` : "differs from the pds"}`);496const publicationLive = !publicationChanged || (canWrite && !dryRun) || dryRun;497498// the other half of the publication's proof: the domain points back at it499const wellKnown = await readFile(WELL_KNOWN, "utf8").catch(() => "");500if (publicationLive && wellKnown !== PUBLICATION_URI) {501 if (!dryRun) await writeFile(WELL_KNOWN, PUBLICATION_URI);502 console.log(`standard.site: ${WELL_KNOWN} ${would}written`);503}504505const rkey = documentKey(post);506const uri = `at://${DID}/site.standard.document/${rkey}`;507const record = await documentRecord(post, session);508const changed = await putIfChanged("site.standard.document", rkey, record, session);509if (changed && !canWrite && !dryRun) {510 console.log(`standard.site: ${uri} is missing or out of date on the pds. set ATPROTO_APP_PASSWORD to publish it`);511 process.exit(0);512}513console.log(`standard.site: ${uri} ${changed ? (dryRun ? "would be published" : "published") : "unchanged"}`);514if (dryRun && changed) console.log(JSON.stringify(record, null, 2));515516const html = withLinkTag(post.html, uri);517if (html !== post.html) {518 if (!dryRun) await writeFile(post.file, html);519 console.log(`page: ${dryRun ? "would get" : "added"} its <link rel="site.standard.document">`);520}