Files
solon/scripts/media-render.ts
CatoandClaude Opus 5.5 5b8fac2fa7 Photos straight from Cloudflare R2; the box does no image work (#620)
* feat(photos): serve photographs straight from R2, no image work on the box

With NEXT_PUBLIC_MEDIA_BASE set at build time, the app box sends no
photograph bytes and resizes nothing; unset, everything is as before.

- src/lib/media: self-contained pipeline (no app imports, for a later move
  into @bitbaum/sitekit alongside Heidi's copy). media:render renders the
  bundled photographs at 640/960/1280/1920/2560 as AVIF and WebP with
  sharp and writes a committed manifest; media:upload (dry run by default,
  idempotent, immutable Cache-Control) sends them to the PHOTOS_S3_* bucket.
  A custom next/image loader, switched on only when the base is set, names
  the nearest variant; MediaImage draws AVIF with a WebP fallback and keeps
  the blur placeholder. ThemedPhoto, the menu feature and the ideas page
  use it. A test fails while the manifest lags an original.
- Place photographs: with a base set, photoUrl points at the bucket object
  (place-photos/<file>@<width>) instead of /api/place-photo, which stays
  for the fallback and for PLACE_PHOTOS_VIA_APP=1 while the bucket fills.
  places:photos:to-r2 is now dry run by default; --apply copies what is
  only in place_photo_bytes and reads the rest of the shown widths from
  Commons straight into the bucket. Nothing is dropped.
- places:photos:warm checks the bucket first and only falls back to the
  route for a miss.
- .env.example and AGENTS.md document the variables and the order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T

* feat(photos): the box's build fills the bucket and switches it on itself

Nobody runs manual steps on the box, so `pnpm run build` now starts with
scripts/media-ensure.ts. On the box's build (SELF_HOST=1, or MEDIA_ENSURE=1)
with PHOTOS_S3_* and MEDIA_PUBLIC_BASE set, it HEADs every manifest variant,
renders (sharp, concurrency 1, no cache) and uploads only the missing ones,
reads one back through the public base, and only on a 200 with the image's
content type writes NEXT_PUBLIC_MEDIA_BASE into .env.production.local
(gitignored) for next build. Anything missing or failing is one log line,
takes back a base an earlier build wrote, and exits 0: the build never
fails because of media. An explicit NEXT_PUBLIC_MEDIA_BASE still overrides.

Place photographs stay on /api/place-photo by default (it copies DB-only
photographs into the bucket on first request); PLACE_PHOTOS_DIRECT=1 is
the later, explicit switch to direct addresses.

The decision logic (src/lib/media/ensure.ts) is pure and tested; sharp's
settings are shared by media:render and the build. AGENTS.md and
.env.example: an operator only gives the bucket a public domain and puts
the five variables in /opt/fleet/env.

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>
2026-11-26 12:53:30 +01:00

102 lines
3.4 KiB
TypeScript

/**
* Renders every photograph in src/assets/images at fixed widths as AVIF and
* WebP, for the bucket (src/lib/media/variants.ts), and writes the manifest
* next/image's loader reads:
*
* pnpm run media:render render what is missing into .media/, write the manifest
* pnpm run media:render --check exit 1 if the manifest does not match the originals
*
* A variant already rendered is skipped, so a rerun only does what changed.
* Runs on a developer's machine or in CI, never on the app box; the manifest
* is committed, the variants are not (`pnpm run media:upload` sends them).
*/
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { dirname, extname, join } from "node:path";
import sharp, { type Sharp } from "sharp";
import {
MEDIA_ENCODE,
MEDIA_FORMATS,
variantKey,
widthsFor,
type MediaEntry,
type MediaFormat,
type MediaManifest,
} from "../src/lib/media/variants";
const ROOT = process.cwd();
const SOURCE = join(ROOT, "src/assets/images");
const OUT = join(ROOT, ".media");
const MANIFEST = join(ROOT, "src/lib/media/manifest.json");
const IMAGE = /\.(webp|jpe?g|png|avif)$/i;
const ENCODE: Record<MediaFormat, (s: Sharp) => Sharp> = {
avif: (s) => s.avif(MEDIA_ENCODE.avif),
webp: (s) => s.webp(MEDIA_ENCODE.webp),
};
export async function describe(file: string): Promise<MediaEntry> {
const bytes = readFileSync(join(SOURCE, file));
const meta = await sharp(bytes).metadata();
if (!meta.width || !meta.height) throw new Error(`${file}: no dimensions`);
return {
hash: createHash("sha256").update(bytes).digest("hex").slice(0, 12),
width: meta.width,
height: meta.height,
widths: widthsFor(meta.width),
};
}
async function main() {
const check = process.argv.includes("--check");
const files = readdirSync(SOURCE)
.filter((f) => IMAGE.test(f))
.sort();
const manifest: MediaManifest = { photos: {} };
for (const file of files) {
const name = file.slice(0, -extname(file).length);
if (manifest.photos[name]) throw new Error(`two originals named ${name}`);
manifest.photos[name] = await describe(file);
}
const text = JSON.stringify(manifest, null, 2) + "\n";
if (check) {
const held = existsSync(MANIFEST) ? readFileSync(MANIFEST, "utf8") : "";
if (held !== text) {
console.error("src/lib/media/manifest.json is stale: run pnpm run media:render");
process.exit(1);
}
console.log(`manifest matches ${files.length} originals`);
return;
}
let rendered = 0;
let kept = 0;
for (const file of files) {
const name = file.slice(0, -extname(file).length);
const entry = manifest.photos[name];
const original = readFileSync(join(SOURCE, file));
for (const width of entry.widths) {
for (const format of MEDIA_FORMATS) {
const out = join(OUT, variantKey(name, entry, width, format));
if (existsSync(out)) {
kept++;
continue;
}
mkdirSync(dirname(out), { recursive: true });
await ENCODE[format](sharp(original).resize({ width, withoutEnlargement: true })).toFile(
out,
);
rendered++;
}
}
}
writeFileSync(MANIFEST, text);
console.log(`${files.length} photographs: rendered ${rendered}, already there ${kept} (.media/)`);
}
main().catch((error) => {
console.error(error);
process.exit(1);
});