mirror of
https://github.com/bitbaum/heidi.git
synced 2026-12-05 10:08:09 +01:00
* Photos: theme-aware scenes, and served from R2 with no image work on the box - Scenes follow the theme the way Solon's do: a day photograph for light, an evening one of the same kind of place for dark where one is worth it, shown by CSS (lazy, neither preloaded when paired). The words stand on a veil of the theme's own page colour, ink >= 4.5:1 over any picture. - New station pair (hall at eye level / against the light), the tram at the blue hour, a bakery without a label, a rowing club for the Verein; the Stadthaus courtyard with its art installation removed. - lib/media/: fixed-width AVIF and WebP variants keyed by content hash, a manifest, and a next/image loader that is on only with NEXT_PUBLIC_MEDIA_BASE. scripts/media/ensure.mjs makes the deploy's build upload what the bucket lacks and turn the base on only after a probe; it never fails the build. Shaped like Solon's for the sitekit move. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T * Photos: the deploy's build uploads to R2 itself; restaurant and city pairs - scripts/media/ensure.mjs runs first in `pnpm run build` when SELF_HOST=1: with PHOTOS_S3_* and MEDIA_PUBLIC_BASE it uploads only the variants the bucket lacks (one image at a time, sharp on one thread), probes one through the public base, and only then writes NEXT_PUBLIC_MEDIA_BASE into .env.production.local. Anything missing or failing: one line, local serving, exit 0. An explicit NEXT_PUBLIC_MEDIA_BASE is the override. - Same widths, key scheme (photos/<name>.<hash12>/<w>.<fmt>), manifest shape and env names as Solon's src/lib/media/, for the sitekit move. - Restaurant and the situations index: the guild houses on the Limmatquai by day and lit at night. The tram is the blue-hour Bahnhofstrasse in both themes, wearing the dark theme (scene-night). The old-town lane with a restaurant's name is gone; the city default is the Schipfe and the Limmat on a winter evening. Apéro and small talk open on the lake. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T --------- Co-authored-by: Claude <noreply@anthropic.com>
131 lines
5.7 KiB
JavaScript
131 lines
5.7 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* Run by `pnpm run build` before `next build`: makes sure every photograph
|
|
* variant the manifest names is in the bucket, and only then turns serving
|
|
* from the bucket on. Nobody runs a step by hand on the box; the deploy's
|
|
* build does this by itself, with the box's environment loaded.
|
|
*
|
|
* WHAT THE OPERATOR DOES, ONCE: give the R2 bucket a public domain, and put
|
|
* PHOTOS_S3_ENDPOINT, PHOTOS_S3_BUCKET, PHOTOS_S3_ACCESS_KEY_ID,
|
|
* PHOTOS_S3_SECRET_ACCESS_KEY and MEDIA_PUBLIC_BASE (that public domain, e.g.
|
|
* https://media.example.ch) in /opt/fleet/env. Nothing else.
|
|
*
|
|
* WHAT IT DOES, ON A SELF-HOSTED BUILD (SELF_HOST=1):
|
|
* 1. With an explicit NEXT_PUBLIC_MEDIA_BASE: nothing — it is the override.
|
|
* 2. Without the PHOTOS_S3_* settings or MEDIA_PUBLIC_BASE: one line, and
|
|
* the photographs are served by the box as before.
|
|
* 3. Asks the bucket for every key of `lib/media/manifest.json` (HEAD), and
|
|
* renders and uploads only the missing ones: one photograph at a time,
|
|
* sharp on one thread without a cache, so a small box stays small.
|
|
* 4. Fetches one variant through the PUBLIC base. Only on a 200 with the
|
|
* right Content-Type does it write NEXT_PUBLIC_MEDIA_BASE=<base> into
|
|
* `.env.production.local` (git-ignored), which `next build` reads: the
|
|
* custom loader goes on (next.config.mjs) and the box resizes nothing.
|
|
*
|
|
* NEVER FAILS THE BUILD. Any error is one warning, the line is taken out of
|
|
* `.env.production.local` again, and the site is built serving its own photos.
|
|
*
|
|
* Imports nothing from the app (see `lib/media/variants.mjs`).
|
|
*/
|
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { CONTENT_TYPES, mediaBase } from "../../lib/media/variants.mjs";
|
|
import { MANIFEST, SOURCES, keysOf, loadSharp, renderVariant } from "./build-photos.mjs";
|
|
import { exists, missingSettings, put, settings } from "./s3.mjs";
|
|
|
|
export const ENV_FILE = fileURLToPath(new URL("../../.env.production.local", import.meta.url));
|
|
const LINE = /^NEXT_PUBLIC_MEDIA_BASE=.*$\n?/mu;
|
|
const say = (line) => console.log(`[media] ${line}`);
|
|
|
|
/**
|
|
* What to do, from the environment alone.
|
|
* @param {Record<string, string | undefined>} env
|
|
* @returns {{ action: "off" | "override" | "local" | "ensure"; reason: string; base?: string }}
|
|
*/
|
|
export function decide(env = process.env) {
|
|
if (env.SELF_HOST !== "1") return { action: "off", reason: "not a self-hosted build (SELF_HOST is not 1)" };
|
|
const override = mediaBase(env.NEXT_PUBLIC_MEDIA_BASE);
|
|
if (override) return { action: "override", reason: `NEXT_PUBLIC_MEDIA_BASE is set explicitly (${override})`, base: override };
|
|
const missing = missingSettings(env);
|
|
const base = mediaBase(env.MEDIA_PUBLIC_BASE);
|
|
if (!base) missing.push("MEDIA_PUBLIC_BASE");
|
|
if (missing.length > 0) return { action: "local", reason: `photographs served by the box: ${missing.join(", ")} not set` };
|
|
return { action: "ensure", reason: `photographs from ${base}`, base };
|
|
}
|
|
|
|
/** `.env.production.local` with the base set (or, with null, taken out), other lines kept. */
|
|
export function withBase(text, base) {
|
|
const rest = text.replace(LINE, "");
|
|
if (!base) return rest;
|
|
return `${rest}${rest && !rest.endsWith("\n") ? "\n" : ""}NEXT_PUBLIC_MEDIA_BASE=${base}\n`;
|
|
}
|
|
|
|
/** Whether a probe answered like a served variant. */
|
|
export function servedRight(status, contentType, format) {
|
|
return status === 200 && (contentType ?? "").split(";")[0].trim().toLowerCase() === CONTENT_TYPES[format];
|
|
}
|
|
|
|
function setBase(base) {
|
|
const now = existsSync(ENV_FILE) ? readFileSync(ENV_FILE, "utf8") : "";
|
|
const next = withBase(now, base);
|
|
if (next !== now) writeFileSync(ENV_FILE, next);
|
|
}
|
|
|
|
export async function ensure(env = process.env) {
|
|
const decision = decide(env);
|
|
if (decision.action === "off") return;
|
|
if (decision.action === "override") {
|
|
say(decision.reason);
|
|
return;
|
|
}
|
|
// Whatever happens below, a base written by an earlier build is not trusted.
|
|
setBase(null);
|
|
if (decision.action === "local") {
|
|
say(decision.reason);
|
|
return;
|
|
}
|
|
const s = settings(env);
|
|
const manifest = JSON.parse(readFileSync(MANIFEST, "utf8"));
|
|
let sharp = null;
|
|
let uploaded = 0;
|
|
let present = 0;
|
|
for (const [name, entry] of Object.entries(manifest.photos)) {
|
|
const keys = keysOf(name, entry);
|
|
const missing = [];
|
|
for (const k of keys) {
|
|
if (await exists(s, k.key)) present++;
|
|
else missing.push(k);
|
|
}
|
|
if (missing.length === 0) continue;
|
|
sharp ??= await loadSharp();
|
|
const bytes = readFileSync(join(SOURCES, `${name}.webp`));
|
|
for (const { key, width, format } of missing) {
|
|
await put(s, key, await renderVariant(sharp, bytes, width, format));
|
|
uploaded++;
|
|
}
|
|
}
|
|
const [name, entry] = Object.entries(manifest.photos)[0];
|
|
const probe = keysOf(name, entry).find((k) => k.format === "webp");
|
|
const response = await fetch(`${decision.base}/${probe.key}`, { signal: AbortSignal.timeout(20_000) });
|
|
if (!servedRight(response.status, response.headers.get("content-type"), "webp")) {
|
|
throw new Error(`${decision.base}/${probe.key} answered ${response.status} ${response.headers.get("content-type") ?? ""}: is the bucket's public domain set?`);
|
|
}
|
|
setBase(decision.base);
|
|
say(`${present} variants already in the bucket, ${uploaded} uploaded; photographs from ${decision.base}`);
|
|
}
|
|
|
|
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
|
|
try {
|
|
await ensure();
|
|
} catch (error) {
|
|
try {
|
|
setBase(null);
|
|
} catch {
|
|
// The build goes on either way.
|
|
}
|
|
console.warn(`[media] warning: photographs served by the box this build — ${error instanceof Error ? error.message : error}`);
|
|
}
|
|
process.exitCode = 0;
|
|
}
|