Site media manifest and import
The site’s own images, videos and PDFs stay in core/web/public/{i,v,d}, tracked in git, and are served at their own paths (/i/…, /v/…, /d/…, the Nuxt public dir). core/web/content/media.json is the reviewed metadata for them: one entry per file, with a fixed id, a human name and the owner’s title and alt text. The media catalog (SQLite + filesystem locally, DynamoDB + S3 in production) is for new and admin media, not for these files.
This page covers part 1 (PR 5): the metadata policy, the sanitizer, the manifest and the import CLI, and part 2a: rendering reads the manifest for metadata only. Part 2b added admin title / alt editing and rename, turned enforceMetaPolicy on by default and sends admin uploads through the sanitizer (media.md, admin.md). None of that touches site media: admin edits and renames work on catalog assets, and the site’s files are not in the catalog, so their paths, titles and alt text change only in public/{i,v,d} and media.json.
Owner decision 2026-10-17. Site media is not moved into the catalog: no /m/ URLs for it, no 301s from the public paths, and no site import before a deploy. CD keeps uploading public/{i,v,d} through the typed sync for good (cicd.md). The labs stay at /d/htm/…, and scripts/enrich-image-meta.mjs stays in use for content LQIPs and aspect ratios.
Intentional case-study paths (do not flag)
The tesseract images in two case studies use /i/portfolio/tesseract/… paths on purpose (owner decision, #279), although the files live at core/web/public/i/tesseract/:
core/web/content/case-studies/spatial-experiences.json:blue-8-cell-simple.pngandschlegel-wireframe-8-cell.pngcore/web/content/case-studies/innovation-prototyping.json: the video posterblue-8-cell-simple.png
The owner confirmed these paths on 2026-10-14 without a visual check. The Docker test stack (http://localhost:4300) serves no static files at all (/_nuxt/*, /i/* and /_ipx/* return 404 or 502; tracked in Phase 9b of docs/superpowers/plans/2026-10-01-prod-readiness-docker-media.md), and the deployed test environment predated #279 at the time. (Since 2026-10-19 the docker:test cdn stand-in serves public/, including /_ipx/*: docker/README.md.)
Other content still points at /i/tesseract/… (for example the spatial-experiences.json video poster, gallery.json, content/media.json legacyPath and shared/tesseract.ts). That mix is intentional as well. Don’t “align” the two prefixes in either direction.
Do not move the files, rewrite the paths, restore the file-exists checks that #279 removed from core/web/tests/portfolio-content.spec.ts and core/web/tests/work-card-media.spec.ts, or report the paths (or the mixed prefixes) as broken or inconsistent. core/web/tests/tesseract-media-paths.spec.ts keeps the paths and this note in place.
Case-study diagrams show whole
Case-study media is framed at the theme’s --media-ratio with object-fit: cover (core/web/app/pages/work/case-study.scss). On portrait screens that ratio is 9:16, which is right for photos and video but cut a 16:9 flow diagram to its middle third on a 375px phone. AppCaseStudyMedia marks SVG diagrams ("type": "diagram", which must be an SVG, or any SVG src) with data-media-kind="diagram"; the hero and the Artifacts grid show those at the file’s own ratio (aspect-ratio: auto 16 / 9, the 16:9 reserved until the file loads) with object-fit: contain. Photos and video keep the frame and the crop. Fixed 2026-10-19; core/web/tests/case-study-diagrams.spec.ts keeps it (and checks that every SVG in content/case-studies is typed diagram and every diagram is an SVG). Old styles: theme/core/scss/_archive/2026-10-19-case-study-diagrams/.
Manifest
{
"version": 1,
"entries": [
{
"id": "…uuid…",
"tenant": "portfolio",
"kind": "image",
"name": "profile-pic-1",
"ext": "jpg",
"path": "m/pf/i/profile-pic-1.jpg",
"title": "Tamara Mack portrait",
"alt": "Portrait of Tamara Mack smiling, …",
"description": null,
"credit": "Tamara Mack",
"sha256": "…of the sanitized bytes…",
"width": 1024,
"height": 1024,
"durationSec": null,
"lqip": "data:image/webp;base64,…",
"dominantColor": "#cece9f",
"variants": [],
"legacyPath": "/i/profile_pic_1.jpg",
"reviewNotes": ["check: …"]
}
]
}
| Field | Rule |
|---|---|
id |
UUIDv5 of legacyPath (siteMediaId). Stable across reruns and identical in every backend. Never edit it once imported. |
name, ext, path |
normalizeMediaFilename of the original filename (generator and camera prefixes dropped), -2, -3 on collisions; path is m/pf/{kind code}/{name}.{ext}. |
title, alt, description, credit |
Owner-reviewed text, checked by validateMediaMeta (title 3–80 characters, alt ≤150 and required for images and SVGs, description ≤300, no filenames or vendor ids). |
sha256, width, height, durationSec |
Computed from the sanitized bytes. Don’t edit by hand. |
lqip, dominantColor |
Computed for images and SVGs (ingestImage). null for video and documents. |
variants |
Ready catalog variants (t, 640, 1280, 1920) for srcset. Empty until they are materialized; --from exports fill it. |
legacyPath |
The file’s public path, as content references it. Must start with /; . / .. segments and backslashes are rejected (the import reads <source><legacyPath>). |
reviewNotes |
Draft checklist. The import refuses entries that still have notes; notes are never imported. |
Types and the validator live in @tgmc/media (SiteMediaEntry, validateSiteManifest, serializeSiteManifest). The validator is strict: unknown keys, a path that does not match kind / name / ext, an ext whose type does not belong to kind (image + .pdf), duplicate ids, names or legacy paths are structural errors; metadata policy issues are reported separately so a draft can still be written.
Review workflow
npm run build:libs
npm run media:site-manifest -- --draft --review-out tmp/site-media-review.md
--draft reads every file under the source (--source <dir>, default data/media-source/ when it exists, else core/web/public; folders starting with . or _ are skipped, non-media files such as the HTML labs are listed under skipped, and files the overrides exclude under excluded). For each file it:
- Detects the real format from the bytes (a
.pngthat is really an animated GIF becomes.gif). - Pre-fills the title (gallery item title, then the SVG
<title>, then the filename), alt (the longest content alt that fits) and description (the longest caption that fits, else the SVG<desc>), from every content JSON file undercore/web/content/(exceptmedia.jsonitself, and--out) and quoted paths incore/web/{app,shared,server}. - Sanitizes the bytes (sanitizer), then records the sha256, dimensions, duration and LQIP.
- Adds notes:
check:(an owner decision: generated title, several content alts, a borrowed gallery title, a changed extension, a renamed collision, a generated-media credit),unused:(nothing references the file),duplicate:(same sanitized bytes as another file) andinvalid:(fails the metadata policy).
--review-out writes a Markdown table with each entry’s legacy and new path, title, alt, description, credit and review notes, so every field the owner signs off on is visible in one place.
The owner edits media.json directly: fix titles, alt text, descriptions and credits, delete each note once resolved, then rerun --draft. A rerun keeps each existing entry’s id, name, editorial fields, variants and the owner’s remaining check: notes, and recomputes the bytes, dimensions, LQIP and the automatic unused: / duplicate: / invalid: notes. kind and ext always follow the sniffed bytes: when a source changes format (say the animated GIF named .png is replaced by a real PNG), the entry moves to the new extension (and kind code), its variants are reset, a name already taken in the new kind gets -2, and a check: format changed: … note asks for review. Its summary lists changed (sha256 differs from the committed manifest) and dropped (no longer in the source).
PDFs embed the title, credit (Author) and description (Subject) in the sanitized file, so editing a PDF’s title changes its sha256: rerun --draft before importing.
Overrides
Decisions a rerun must not undo live in core/web/site-media.overrides.json (committed; outside content/ so it is never scanned as content; --overrides <file> points elsewhere):
{
"exclude": { "/i/portfolio/social-card.png": "why it is not imported" },
"entries": {
"/d/Resume2026.pdf": { "name": "Tamara Mack-resume-2026" },
"/v/portfolio/generated/vimg-tesseract-framework.mp4": { "credit": "Tamara Mack (AI-assisted)" }
}
}
exclude— legacyPath → reason. The file stays on disk but gets no entry (summaryexcluded, notdropped), and stops causingduplicate:notes.entries.<legacyPath>.name— wins over the drafted and the previous name; the id stays the UUIDv5 of the legacyPath. Lowercase words joined by-; a name another file already uses is an error.entries.<legacyPath>.credit— replaces the credit and clears thecheck: generated media; confirm the creditnote. For PDFs it is also written as the Author.
Unknown keys are errors; overrides for paths that are not in the source are listed under staleOverrides. Titles, alt text and descriptions are edited in media.json itself (a rerun keeps them).
npm run media:site-manifest -- --from <endpoint> exports the manifest back from a catalog (assets tagged site), including ready variants. Endpoints are media:transfer’s sqlite:<dir> or aws:<table>@<bucket> with --region, --dynamodb-endpoint, --s3-endpoint, --path-style. postgres: is refused (the site CLIs have no --blobs); to seed a Postgres catalog, import into sqlite: and media:transfer from there.
Rendering: metadata only (part 2a)
Content and code keep referencing site media by its public path, exactly as before ("src": "/i/portfolio/manhattan-2150-keyframe.png"); UiImage and Nuxt Image (IPX, sizes → srcset) are unchanged. The manifest’s path (m/pf/…) is only the catalog key the optional import writes; the site never requests it. The manifest adds metadata:
useSiteMedia()(app/composables/useSiteMedia.ts) andresolveSiteMedia(pathOrId)(#shared/site-media, pure and SSR-safe) return{ id, kind, url, alt, title, width, height, aspectCss, missing }for a public path or a manifest id.urlis always the public path. An unknown path comes back unchanged withmissing: true(dev builds warn once); an unknown id gets a transparent 1x1 GIF.- Client map. The browser never loads
media.json.core/web/shared/site-media-map.jsonholds onlyid,path(the public path),kind,ext,title,alt,widthandheightper entry: no review notes, hashes, descriptions, credits or LQIPs (content already carries its LQIPs and aspect ratios fromenrich-image-meta).npm run media:site-manifest -- --draftrewrites it with the manifest;npm run media:site-mapregenerates it alone.scripts/site-media-client-map.test.js(CI) fails when it is out of step withmedia.json, andcore/web/tests/site-media.spec.tsfails if client code importsmedia.json. - Where the metadata shows today. The manifest alt and title surface only in
og:image:alt/twitter:image:altof the default social image. On the page, content’s ownalt(and components’ computed alt, such as the about portrait) wins;UiImageand the gallery components do not read the manifest;AppCaseStudyMediareads only a raster’s dimensions, for its width ladder (Responsive sizes and format). - Default social image. Without a page
image, or when the page image is an SVG or a video (crawlers do not render those; five of the six case studies lead with an SVG diagram),usePortfolioSeouses themanhattan-2150-keyframefile (siteSocialImage(siteUrl, pageImage)). A raster page image is used as given, absolute on the site URL, without the default’s width, height, type or alt. The default:og:image/twitter:image= site URL +/i/portfolio/manhattan-2150-keyframe.png(absolute), withog:image:width1672,og:image:height941,og:image:typeimage/pngand the manifest alt asog:image:alt/twitter:image:alt. The file is tracked inpublic/, so every build, the tamaramack.github.io copy included, serves it. (/i/portfolio/social-card.png, the old default, has the same bytes and is excluded from the manifest.)
Content guard
core/web/tests/site-media-guard.spec.ts scans core/web/content (JSON, Markdown, YAML), core/web/app (Vue, TS, SCSS), core/web/assets (SCSS), core/web/shared and core/web/server (TS), the Nuxt layers web extends (packages/nuxt-layer-base app / scss / src and packages/nuxt-layer-ui app / src, plus both nuxt.config.ts) and core/web/nuxt.config.ts (not media.json or the client map). Every /i/…, /v/… or /d/… path it finds, after a quote, bracket, =, ,, :, } (as in `${base}/i/x.png`) or whitespace, must be a manifest legacyPath, so every site file on the page has reviewed metadata. A self-test pins what the pattern catches and that an unknown path is flagged.
Allowlist (permanent):
| Path | Why |
|---|---|
/i/tesseract/…, /i/portfolio/tesseract/… |
Intentional case-study paths (owner, #279) |
/d/htm/adv_wire_tess.html, /d/htm/wire_tess.html |
HTML labs (pages, not media), served from public/d/htm/ |
A new site image: add the file under public/, rerun npm run media:site-manifest -- --draft, review its title and alt in media.json, then reference its public path.
Import
The import is optional tooling: it copies the site’s media into a catalog (for example to try admin features against real files). The site never reads site media from the catalog, so no environment needs it, and it is not a deploy prerequisite.
# rehearsal against a scratch catalog (imports entries that still have notes)
npm run media:site-import -- --to sqlite:./data/site-media-rehearsal --allow-unreviewed
# production, after the review
npm run media:site-import -- --to aws:<table>@<bucket> --dry-run
npm run media:site-import -- --to aws:<table>@<bucket>
For each entry the import checks that <source><legacyPath> exists and is media, then (importSiteMedia in @tgmc/media):
- Refuses entries with
reviewNotes(unless--allow-unreviewed) or metadata policy failures (refusedin the report). - Skips entries the target already has with the same id, path and manifest
sha256(and its object), before the file is sanitized, so a rerun after a sharp / svgo / ffmpeg upgrade stays idempotent and needs no ffmpeg when every video is already imported. - Sanitizes the rest exactly as the draft did (a sanitizer error, such as no ffmpeg for an MP4, fails that entry only).
- Fails entries whose sanitized bytes do not hash to the manifest
sha256(the manifest is stale, or the tool versions changed: rerun--draftand review the diff). - Copies the rest through
transferMedia, so it inherits the transfer’s safety: the name is held on the target, objects are written create-only and re-hashed there, an existing asset with the same id, sha256 and path is skipped (reruns are safe), and anything else at that id, name or key is a conflict, never overwritten. Rows keep the manifest id, name and path;metacarriestags: ['site'],filename, the editorial fields, dimensions, LQIP andlegacyPath. Each written asset gets anasset.site_importedaudit event.
It prints a JSON report (copied, skipped, conflicts, conflictReasons, failed, refused) and exits 1 when anything was refused, conflicted or failed, 2 on bad arguments. A dry run opens a sqlite: target read-only and writes nothing.
The import is create-only, not a sync. Once an entry is imported, editing its title, alt text, description or credit in media.json and re-importing does not update the catalog: the entry is skipped (same id, path and sha256), or for a PDF, whose sanitized bytes embed the title and credit, reported as a conflict. Admin’s Details and Rename… can edit the imported copies, but they change only the catalog; the site keeps serving public/{i,v,d} with the metadata in media.json. --from exports the catalog back into media.json when the two should be brought in step.
Production import runbook
Only if a production catalog should hold the site’s media; nothing on the site depends on it.
- Run it on the machine and OS that produced the committed draft (Windows today), with the same ffmpeg (
ffmpeg -version, or pinFFMPEG_PATH) and the samenode_modules— sanitized bytes, and so every sha256, depend on them. npm run build:libs, thennpm run media:site-import -- --to aws:<table>@<bucket> --dry-run. Expectfailed: [],conflicts: []andrefused: [](anyrefusedentry still has review notes).- Only then run the same command without
--dry-run, and keep the JSON report.
Tooling notes
- ffmpeg. MP4 remuxing runs ffmpeg as a separate process, resolved by
resolveFfmpegPath(@tgmc/image/sanitize):FFMPEG_PATH, thenffmpegonPATH, then the optionalffmpeg-staticpackage (rootoptionalDependencies;allowScriptslets its install script download the binary; its ownFFMPEG_BINvariable overrides the binary it reports). With none of them, sanitizing an MP4 fails with a message saying so; other formats don’t need ffmpeg. Licence: the ffmpeg-static binary is GPL-3.0-or-later; it is only executed by local scripts, never linked, bundled intocore/web/ Nitro / Lambda, or redistributed. - Determinism. The sanitized sha256 depends on the sharp / svgo / pdf-lib / ffmpeg versions (and can depend on the platform): for example
vimg-tesseract-framework.mp4remuxes to different bytes under ffmpeg 6.1 (ffmpeg-static) and 8.1. After upgrading any of them, rerun--draft; the import fails loudly rather than storing bytes that differ from the manifest (entries already imported are skipped first). - Code.
scripts/site-media-{cli,client-map,draft,content,review}.jshave no workspace imports and are tested undernode --testin CI (scripts/site-media-*.test.js);scripts/site-media-{manifest,import,io}.jswire in@tgmc/mediaand@tgmc/imageand neednpm run build:libs.
Resized images on the CDN
On AWS the Lambda serves no public/ files (serveStatic: false) and so cannot resize them either. A site-root path in the HTML went API Gateway → Lambda, and server/middleware/cdn.ts answered with a 302 to CloudFront: about 0.16 s per image before the download, and 1.8–2.6 s for the case-study SVG diagrams. Resized images (/_ipx/…) were worse: nothing generated them, so CloudFront returned 403. With a CDN on an aws_lambda build (NUXT_APP_CDN_URL at build time, which CD sets), site media now goes to the CDN directly:
| Media | URL in the HTML | Comes from |
|---|---|---|
Rasters (UiImage → NuxtImg) |
<cdn>/_ipx/w_<ladder width>/<path> |
public/_ipx/, written at build time |
Rasters asked for as WebP (format="webp") |
<cdn>/_ipx/w_<ladder width>&f_webp/<path>.webp |
public/_ipx/, written at build time |
SVG diagrams (UiSvgImg), videos and posters |
<cdn>/<path> (usePublicAssetUrl) |
public/ as is |
- Width ladder (
shared/ipx-variants.ts).IPX_VARIANT_WIDTHSis the one list both sides use. ThecdnIpxprovider (app/providers/cdn-ipx.ts) snaps the widthNuxtImgasks for up to the smallest rung that covers it and drops the height, so the source aspect ratio is kept andUiImagecrops in CSS (object-fit: cover). The URL is the same on server and client; absolute, protocol-relative anddata:sources pass through. - Formats (
IPX_VARIANT_FORMATS, today['webp']). Aformatmodifier in that list links the converted variant,w_<width>&f_webp/<path>.webp; any other format (or the source’s own) links the same-format one. The.webpextension is there because the S3 sync sets each object’sContent-Typefrom its extension (scripts/sam-aws-helpers.mjs), and it keepsa.jpganda.pngfrom sharing a key. - Build step (
config-properties/ipx-variants.ts, run from thenitro:build:public-assetshook innuxt.config.ts). Every raster incontent/media.json(bylegacyPath) is written at every rung with sharp into Nitro’spublic/_ipx/, keeping its format and never enlarged, and once more as WebP when it is not WebP already. The usual S3 sync uploads them withContent-Type: image/webpfor the.webpfiles and the shortCache-Control(public, max-age=3600, must-revalidate) of every unversioned public file. A source path with no file inpublic/is logged and gets no variant (its URL answers 403/404, as before). Today: 8 rasters × 7 widths = 56 same-format files, plus 5 non-WebP rasters × 7 widths = 35 WebP files (91 files, about 31.5 MB; the WebP set is 2.6 MB). The animated GIF (/i/tesseract/blue-8-cell-simple.png, sniffedext: gif) is not a raster to the build step and gets no_ipxvariant. - A raster outside the manifest gets no variants. Add it to
content/media.json(review workflow) before using it inUiImage. - Public files.
usePublicAssetUrl()(@tgmc/nuxt-layer-ui) prefixesruntimeConfig.app.cdnURLto site-root paths. Nuxt itself rewrites only literal template paths, never runtime:srcvalues orNuxtImgsources (research note). URLs with a scheme, protocol-relative,data:andblob:URLs pass through, and so does everything when no CDN is set. No folder is special-cased and the path text never changes. - Other builds (dev, node-server, no CDN) keep the stock ipx provider and its
/_ipxhandler. The CDN middleware still 302s static paths, which catches old cached HTML and any call site that is not converted. - docker:test. The
cdnservice (nginx,127.0.0.1:4301) stands in for CloudFront and servespublic/,_ipx/included. Build withNUXT_APP_CDN_URL=http://localhost:4301to get the AWS behaviour (docker/README.md). - Why not prerender the variants or resize on the Lambda? Tried and dropped on 2026-10-19: the Lambda’s ipx has no source files, a CloudFront failover to it is a circular dependency in
infra/sam/template.yaml(cfn-lintE3004), and Nitro hung on the ipx routes during prerender while the build still exited 0. Details in the research note.
Responsive sizes and format
UiImage has two modes.
- Default (NuxtImg).
sizesis Nuxt Image’s syntax (mobile-first:key:sizeapplies from thekeypx width up, values invworpx, nocalc()), and NuxtImg builds thesizesattribute and its srcset from it: each value × the densities (1×, 2×).format(webp…) is forwarded. Every existing caller uses this mode, unchanged. widths. With a list of candidate file widths,UiImagerenders a plain<img>:sizesis a nativesizesstring, passed through as is, and the srcset is aw-descriptor ladder built with the Nuxt Image URL builder ($img) in the requestedformat, each candidate cropped towidth/height’s ratio when both are set. A native string can use em media conditions and rem /calc()lengths, which NuxtImg’s syntax cannot (its media are px, so they drift from the theme’s em breakpoints when the reader’s default font size is not 16 px). Stopwidthsat the source’s width: nothing is upscaled, so a larger descriptor would overstate the file. In developmentUiImagewarns whenwidthscomes withoutsizes(the browser would assume 100vw).
$img comes from @nuxt/image’s image: { inject: true }, set on both image configs in core/web/nuxt.config.ts; the layer does not depend on @nuxt/image. Without it (an app without inject, such as core/admin today) widths is ignored and NuxtImg renders the image with its own srcset; the native sizes is then not passed on, since NuxtImg’s syntax cannot read it. Loading (lazy by default), decoding and the fade-in behave the same in both modes: the plain <img> fades in on load, and, like NuxtImg, an image that finished before hydration is marked loaded on mount unless the server-side onerror marker says it failed.
The /about portrait (app/pages/about.vue, values in shared/about-portrait.ts) is the first widths user. Its box is the sidebar’s content width (pages/about.scss and the theme’s split layout): the sidebar column (14 / 16 / 18rem from 48em / 90em / 120em) minus its padding (2 × 1.1rem) and border (2 × 1 px), and below 48em the viewport minus the page pad and the same padding. From 120em the root font is 125%, so those rems count × 1.25. In sizes, em and rem are the reader’s default font size, as in media queries, so the slot follows their text size like the layout does:
(min-width: 120em) calc(19.75rem - 2px), (min-width: 90em) calc(13.8rem - 2px),
(min-width: 48em) calc(11.8rem - 2px), (min-width: 30em) calc(100vw - 4.7rem - 2px),
calc(100vw - 4.2rem - 2px)
tests/about-page.spec.ts evaluates the string against boxes measured on a production build at a 16 px and a 20 px default. widths is [320, 480, 640, 960, 1024] (1024 is the source) and the format is WebP. The portrait stays lazy with no fetchpriority or preload: the owner’s decision is that it is not the page’s priority. Measured on .output/local (3 cold runs each; the 20 px default set through Chromium’s Page.setFontSizes):
| Viewport | Before (JPEG, px sizes) |
After (WebP, native sizes) |
|---|---|---|
| 375 × 812, DPR 3 | 960 px JPEG, 93.8 KB; LCP (portrait) 2.0–2.5 s | 960 px WebP, 55.0 KB; LCP (portrait) 1.2–1.5 s |
| 375 × 812, DPR 2 | 960 px JPEG | 640 px WebP, 30.0 KB; LCP (portrait) 1.3 s |
| 1280 × 800, DPR 1 | 480 px JPEG, 30.5 KB (LCP is the h1) | 320 px WebP, 10.7 KB (LCP is the h1) |
| 800 × 900, 20 px default | 704 px box; a px sizes would ask for 187 px |
960 px WebP, 55.0 KB (not upscaled) |
| 1280 × 800, 20 px default | 234 px box | 320 px WebP, 10.7 KB |
| 375 × 812, DPR 3, 20 px def. | 289 px box | 960 px WebP, 55.0 KB |
Case studies (/work/[slug], app/components/AppCaseStudyMedia.vue, values in shared/case-study-media.ts) are the second widths user. The page passes a native sizes to AppCaseStudyMedia: CASE_STUDY_HERO_SIZES for the hero and caseStudyArtifactSizes(count) for the Artifacts cells. For a raster in content/media.json, caseStudyRasterLadder(src) turns that into widths (each IPX_VARIANT_WIDTHS rung below the source, then the source width, at most the largest rung), the source’s own width / height (so no candidate is cropped to another ratio; the frame already has the file’s aspectCss) and format="webp" unless the source is WebP. SVG diagrams, video, a call without sizes and a raster outside the manifest render as before: the manifest is the list the CDN build writes variants for, so an unlisted raster (today the intentional /i/portfolio/tesseract/… paths) keeps the default NuxtImg srcset rather than linking variants that do not exist. Loading is unchanged: the hero stays eager with no fetchpriority or preload, the Artifacts stay lazy.
The boxes come from pages/work/case-study.scss, layouts/site.scss and the theme’s prose / split layout. The body column is --prose-max (42rem) once there is room; before that it is the viewport minus the site padding (0.5rem below 48em, 0.75rem to 67.5em), the page pad (0.5rem below 30em, 0.75rem to 48em, then clamp(0.75rem, 0.5rem + 2vw, 1.5rem)) and, from 48em, the 14rem page nav and its 2rem gap. From 120em the root font is 125%, so 42rem counts as 52.5rem. An Artifacts cell is the section’s content box (body − 2 × 1.5rem padding − 2 × 1 px border), halved with the 1 px gap once both columns can be 16rem; a lone artifact spans the grid (auto-fit drops the empty column), hence the separate single-cell string:
hero: (min-width: 120em) 52.5rem, (min-width: 62.5em) 42rem, (min-width: 50em) calc(100vw - 20.5rem),
(min-width: 48em) calc(96vw - 18.5rem), (min-width: 44.5em) 42rem,
(min-width: 30em) calc(100vw - 2.5rem), calc(100vw - 2rem)
artifact: (min-width: 120em) calc(24.375rem - 1.5px), (min-width: 62.5em) calc(19.5rem - 1.5px),
(min-width: 55.75em) calc(50vw - 11.75rem - 1.5px), (min-width: 50em) calc(100vw - 23.5rem - 2px),
(min-width: 48em) calc(96vw - 21.5rem - 2px), (min-width: 44.5em) calc(19.5rem - 1.5px),
(min-width: 37.75em) calc(50vw - 2.75rem - 1.5px), (min-width: 30em) calc(100vw - 5.5rem - 2px),
calc(100vw - 5rem - 2px)
single: the artifact string without the halving (39rem / 48.75rem - 2px at the wide end)
tests/case-study-media-sizes.spec.ts evaluates the three strings against boxes measured on a production build at 320–2560 px and a 16 px and a 20 px default, and checks that every candidate of every case-study raster is a variant the CDN build writes (cdnIpx snaps the source width up to the next rung, whose file is the source size, never enlarged). tests/case-study-media-component.spec.ts covers the rendering (raster, WebP source, unlisted raster, SVG, loading). Measured on .output/local (the innovation-prototyping hero, manhattan-2150-keyframe.png, 1672 × 941; 3 cold runs each):
| Viewport | Hero before (1× / 2× PNG) | Hero after (WebP, native sizes) |
Artifacts on the page, before → after |
|---|---|---|---|
| 375 × 812, DPR 3 | 2880 px asked, 1672 px PNG, 3,467 KB | 1280 px WebP, 127 KB (343 px box) | 4,329 KB → 375 KB |
| 375 × 812, DPR 2 | 2880 px asked, 1672 px PNG, 3,467 KB | 960 px WebP, 76 KB | 4,329 KB → 194 KB |
| 1280 × 800, DPR 1 | 1440 px PNG, 2,610 KB (672 px box) | 960 px WebP, 76 KB | 1,557 KB → 58 KB |
| 800 × 900, 20 px default | 1440 px PNG, 2,610 KB (750 px box) | 960 px WebP, 76 KB | 1,557 KB → 118 KB |
The LCP element of that page is text (the lead paragraph or the h1, 0.38–0.50 s before and after): the hero fades in from opacity: 0, which Chromium does not count. On data-visualization (one WebP artifact) at a 1280 × 800 viewport the LCP is the artifact; its file went from 109 KB (960 px) to 57 KB (640 px) and the LCP stayed within run-to-run noise (1.3–1.6 s, dominated by the local ipx resizing each cold request). Screenshots at DPR 3 show the hero sharp. Before, the local ipx also cropped every Artifacts candidate to 16:9 (width="960" height="540"), including the 1:1 vimg-crystal-volume.webp; the ladder now keeps the source ratio, as the CDN variants always did.
WebP needs no JPEG fallback in the browsers the site supports (Safari 14+). AVIF would be about 44% smaller again (960 px: 30.9 KB) but needs a <picture> with a fallback, so it is a TODO. The local ipx handler answers max-age=60 (its default), which only applies to local / development builds. On AWS the variants are S3 objects with the one-hour revalidated cache (the repo policy for unversioned files). Neither is changed.
Media slots and placeholders
Pages that had no imagery get media slots: named places for a picture or video, listed in core/web/content/media-slots.json and read through #shared/media-slots. Until the real asset exists, a slot renders a labelled placeholder, so the layout is final before the art is.
{
"version": 1,
"slots": {
"case-study.walkthrough": {
"kind": "video",
"src": null,
"poster": null,
"alt": "Placeholder: screen-recorded walkthrough of this case study",
"ratio": "16 / 9",
"caption": "Walkthrough video coming soon."
}
}
}
- Storage and seeding. Slots live in the data store, next to the posts:
MediaSlotStore(core/web/server/db/media-slot-store.ts,getMediaSlotStore/createMediaSlotStore, the sameDATA_BACKENDresolution as the post store) keeps one record per tenant and slot id:{ tenant, id, kind, ratio, assetId, src, alt, decorative, caption, captions, poster, lqip, dominantColor, updatedAt }. A record’sassetId(a media library asset) wins oversrc, then the placeholder. SQLite and Postgres use themedia_slotstable (migrations/003_media_slots.sql, primary key(tenant, id)); DynamoDB uses items in the Posts table (id: 'SLOT#pf#<slotId>',entityType: 'mediaSlot', see data stores).media-slots.jsonis the seed and the defaults:seedRecordsFromJsonturns each JSON slot into aportfoliorecord (assetId: null,decorative: false, missing optional fieldsnull), andlistMediaSlots(store)inserts every seed id the store lacks (insertIfAbsent, which never overwrites) before it lists. So the first read seeds an empty store, a slot added to the JSON later appears on the next read, and a slot edited in the store keeps its edit. There is no seed script; every backend seeds lazily. Editing the JSON after a slot is seeded does not change the stored record. The store contract (core/web/tests/server/db/media-slot-store.spec.ts) runs on all three backends. - Precedence and slot views.
core/web/server/utils/media-slot-views.tsturns each record into aMediaSlotView(#shared/media-refs: the slot’s fields plusid,placeholder,unavailable,decorative,srcset,width,height,assetId).toSlotView(record, ref)applies the precedence with fall-through: a resolvedassetIdwins and givessrc,srcset,width,height,lqip,dominantColorandposter, with the record’saltunless it is blank (then the asset’s alt); anassetIdthat does not resolve, or resolves to an asset the slot’s kind cannot render (animageorsvgslot takesimageandsvgassets, avideoslot onlyvideo), falls through to the record’ssrc; with nosrceither the view isunavailable(the labelled fallback), not the “not made yet” placeholder.placeholderissrc === null && !unavailable. An acceptedimageorsvgasset gives the view its ownkind, so an svg asset in an image slot (or as a blog cover) renders throughUiSvgImg, a directimg, never NuxtImg / IPX; otherwisekindcomes from the record.ratio,caption,captionsanddecorativealways come from the record.getMediaSlotViews()lists the records (listMediaSlots) and resolves every slot’s asset in oneresolveMediaRefscall. The record list is cached per process for 60 s (MEDIA_REF_TTL_MS; on DynamoDB a list is a full Posts-table scan, too heavy for every render), andclearMediaSlotCache()drops it (plan 4’s slot writes call it); other instances see a slot edit within 60 s. A store that fails (or cannot be created) falls back to the JSON seed, logsmedia.slots_store_unavailableand caches nothing, so the page still answers 200. - The route.
GET /api/media-slotsanswers{ slots: Record<slotId, MediaSlotView> }withCache-Control: public, max-age=0, must-revalidate, neverimmutable(library media changes without a deploy).useMediaSlots()fetches it once per page: every slot sharesuseAsyncData('media-slots')withdedupe: 'defer', and its handler joins the request already in flight for the app (Nuxt can run the handler once per caller), so a page with several slots makes one request. After hydration it reuses the server’s payload, and a client navigation from one slot page to another reuses the loaded views (the shared key). The views arenullwhen the route fails or answers anything withoutslots. AnAppMediaSlotgiven aview(the blog cover) does not calluseMediaSlots()at all, so a blog post makes no/api/media-slotsrequest for its cover (decided at setup). - Editing through the API. The authenticated slot routes (admin principal only; 401 without a token, 403
admin_onlyfor a tenant token; every answerCache-Control: no-store; Web write endpoints) edit theportfolioslots. The code iscore/web/server/utils/media-slot-write.ts(saveMediaSlot,resetMediaSlot), with the routes undercore/web/server/api/media-slots/.GET /api/media-slots/recordsanswers{ slots: Array<{ record, view, needsMedia, seed }> }: every stored record (seeding the missing ones first, likelistMediaSlots), itstoSlotViewview (oneresolveMediaRefscall for the list),needsMedia(the view is a placeholder orunavailable) and its JSON seed record (nullwhen the slot has none).GET /api/media-slots(the public views) is unchanged; Nitro serves both.PUT /api/media-slots/:idtakes{ assetId, src, alt, decorative, caption, captions }and answers the saved record. It is a full replace: a field left out is saved as empty (null, or''/false), not kept.kindandratiostay as the record (or, for a slot not stored yet, the seed) has them; an id with neither is 404Media slot not found.- Validation (422
{ code: 'VALIDATION', fieldErrors: { <field>: [message] } }, nothing written):kind, if sent, must match the slot’s; anassetIdmust be an asset of tenantportfoliowhose kind the slot accepts (ACCEPTED_ASSET_KINDS: image or svg for image and svg slots, video for video slots), elseassetId: 'Pick an image from the portfolio library'(an SVG,a video), and with no media library a save that names anassetIdis refused the same way.src,altandcaptionsfollow thevalidateMediaSlotsrules:srcis root-relative or https;altdescribes the picture, and may be empty only whendecorative;captionsare for video slots only, with a root-relative or https.vttsrc, a language tagsrclangand alabel(reported ascaptions,captions.src,captions.srclang,captions.label).caption,assetIdandsrcare trimmed, and''becomesnull;altis trimmed. Input hardening, checked before any lookup: anassetIdoutside[A-Za-z0-9_-]{1,64}is a 422 onassetId, andsrcis at most 2048 characters,alt,captionand eachcaptionsfield at most 300. - Reset to seed.
POST /api/media-slots/:id/resetreplaces the stored record with the slot’sseedRecordsFromJson()entry and answers it; an id with no seed is 404. This is how amedia-slots.jsonedit reaches a slot that is already stored. - A save or reset writes its usage (
slotUsagePage:pending, the store write, thenlivethroughevent.waitUntil; a clearedassetIdwriteslive []; Usage list writes) and then callsclearMediaSlotCache(), so this process’s next views read the new record. Other processes see it when their cached list expires (MEDIA_REF_TTL_MS).
- JSON fallback.
resolveMediaSlot(id, fallbackId)(#shared/media-slots) still readsmedia-slots.jsonand returns the same view shape (no asset). It is the fallback when the route fails, and the only source in the static tamaramack.github.io export, which has no server routes. - Fields.
kindisimage,svgorvideo;srcisnull(placeholder) or a root-relative /https://URL;altdescribes the picture;ratiois a CSSaspect-ratio(16 / 9); optionalcaption,posterandcaptions(video),lqipanddominantColor(raster).captionsis{ "src": "/v/<name>.en.vtt", "srclang": "en", "label": "English" }: a root-relative or https WebVTT file, a language tag and a track name, video slots only.validateMediaSlotsenforces all of these;core/web/tests/media-slots.spec.tschecks the manifest and that every staticslot-id/fallback-idused in a.vuefile exists, andcore/web/tests/media-slot-component.spec.tsmountsAppMediaSlotonce per kind against a stub manifest, plus fetched, given, decorative and unavailable views;core/web/tests/server/utils/media-slot-views.spec.tscovers the precedence, the record cache, the store fallback and the route’s cache header. - Rendering.
AppMediaSlot(propsslotId,fallbackId,view,sizes,eager) takes its slot from theviewprop, else the fetched views (useMediaSlots()) byslotIdthenfallbackId, else the JSON slot (resolveMediaSlot). It renders it throughAppMediaFile(kind,src,srcset,unavailable,alt,ratio,width,height,poster,captions,lqip,dominantColor,sizes,eager), inside afigure.media-slot[data-slot]with the optional<figcaption>. With nosrcthe art is not made yet and it shows theAppPlaceholderMedia“Placeholder” tag; otherwise it isUiImage(raster, with LQIP / dominant colour),UiSvgImg(svg) or a native<video controls playsinline>with a<track kind="captions" default>whencaptionsis set. If the file then fails to load, or the view isunavailable, the samefigureshows the labelled “unavailable” fallback, named by the slot’salt. Adecorativeslot renders its media withalt="".sizesis Nuxt Image syntax (defaultxs:100vw md:100vw lg:1440px) for a JSON slot, which goes through NuxtImg. A view with asrcset(a library asset) renders a plainimg, so it gets a nativesizes: the caller’s when it has no Nuxt screen tokens (xs:,md:…), else100vw. Video stays native, likeAppCaseStudyMediaandGalleryExhibit: the repo has no shared video component (@tgmc/media-playeris a controller class used only by the/media-playerdemo). The old.media-slot__videostyles moved to.media-file__videoand are archived intheme/core/scss/_archive/2026-10-22-media-fallbacks/. - Placeholder rules. The placeholder is a
div(it sits inside the slot’sfigure) holding an inline SVG drawn only with theme roles (--theme-surface-variant-color,--theme-border-strong-color,--theme-link-color), so it follows every theme and colour mode. Its visible “Placeholder” label is aUiTag(severity="secondary", positioned in the corner) hidden from assistive tech; the placeholder is exposed asrole="img"with the slot’s realaltas its accessible name, and reserves the slot’saspect-ratio, so swapping in the real asset causes no layout shift. Video slots add a play glyph. Placeholder alt text starts withPlaceholder:so screen-reader users hear the same thing sighted users see. - Swapping in the real asset. Once a slot is seeded, the live site reads its stored record, so a slot is changed in the store: edit it in Admin → Slots (admin § Slots: choose a library asset, set a static path, alt and captions, or Reset to seed), which uses Editing through the API above; editing
media-slots.jsonthen changes only the static github.io export, which reads the JSON, until the slot is reset to its seed (Reset to seed). The JSON seeds new slot ids and feeds that export. A JSONsrc(and, for video,poster) is a public/i/…or/v/…file that is an entry incontent/media.json(the content guard fails on any other/i|v|d/path; site media gets no/m/URLs, owner decision 2026-10-17), or anhttps://URL. Updatealtto describe the real picture (drop thePlaceholder:prefix) and keepratiomatching the asset. A video with speech needs captions (WCAG 1.2.2): add the.vttnext to it and setcaptions; a cross-originhttpstrack must be served with CORS headers. No page change is needed. - Per-item overrides. Pages that repeat a slot per item pass a specific id with a generic fallback:
blog.cover.<slug>falls back toblog.cover,case-study.hero.<slug>tocase-study.hero,case-study.walkthrough.<slug>tocase-study.walkthrough. Add"blog.cover.my-post": {…}to give one post its own cover;resolveMediaSlotthrows for an unknown id with no known fallback. - Where slots appear. Under the page hero on Work (
work.hero), Process (process.hero), AI Lab (ai-lab.hero), Blog (blog.hero) and Product (product.hero); under each blog post’s header (blog.cover.<slug>); on case studies as the hero when the study has no media of its own (case-study.hero.<slug>), and in a Walkthrough section after Artifacts (case-study.walkthrough.<slug>). Code and Docs have no hero imagery (they are working / reading surfaces), and About keeps its real portrait.
Fallbacks when media is missing
When a file is missing or fails to load in a media slot or on a case study, the page shows a labelled stand-in instead, built by AppMediaFallback (core/web/app/components/AppMediaFallback.vue; props kind, alt, ratio default 16 / 9, poster). Its root is always its own [data-media-fallback="<kind>"] element. Its poster / placeholder box (.media-fallback__box) keeps ratio, unless a caller frames the root with its own aspect-ratio; the box then fills that frame.
- Coverage. Media slots (
AppMediaSlot→AppMediaFile) and case-study media (AppCaseStudyMedia) get the labelled fallback. Other pages that callUiImage/UiSvgImgdirectly (AppWorkCard,AppOrbitStage,GalleryExhibitimages, the About portrait) pass no#fallbackyet: a failed file there is an empty frame named byalt(hidden when decorative), never a broken-image icon. The gallery video (GalleryExhibit’s raw<video>) has no fallback yet. A document or model link is not probed, so it falls back only when its reference is unresolved. Follow-ups are in the TODO. - Copy.
#shared/media-fallbackholdsMEDIA_UNAVAILABLE_LABEL(the visible label per kind:Image unavailable,Video unavailable,Audio unavailable,3D model unavailable,Unavailablefor documents; svg reads as an image),mediaFallbackName(kind, alt)(the accessible name<label>: <alt>, the label alone for a blank alt,<alt> (unavailable)for documents) andmediaRatio(width, height, fallback)(a CSSaspect-ratiofrom two positive numbers, else the fallback). - Per kind. Image, svg, and video / model without a usable poster render
AppPlaceholderMediawith the kind’s label. Video / model with apostershow it (img alt="") in arole="img"box named bymediaFallbackName, with the label tag; if the poster fails too, orposterchanges, it falls back to the placeholder or retries. Audio is a plain text row (no player, nothing focusable) and a document is plain text marked unavailable (no link). Long names wrap (overflow-wrap: anywhere). - Blank alt. Only a decorative image or svg (blank
alt) keeps a hidden fallback (aria-hidden, no name). Every other kind is named by its label alone.AppMediaFilereplaces a failedUiImage/UiSvgImgwholesale withAppMediaFallback, which names itself; thefallbackLabelprop and#fallbackslot on the kit components serve other callers, where the failed root carries the name and the fallback is presentational. The roots setdisplay: block; inline-size: 100%, so they size themselves insideUiSvgImg’s inline failedspanthere. -
AppPlaceholderMedia. Props are nowalt,ratio,kind(any media kind) andlabel(defaultPlaceholder, shown in the tag). A blankaltmakes it decorative. AppMediaFile. One renderer for every kind (core/web/app/components/AppMediaFile.vue; propskind,src,alt,ratio,poster,captions,sizes,widths,width,height,format,lqip,dominantColor,eager,unavailable; root[data-media-kind="<kind>"]). Image →UiImage, svg →UiSvgImg(both get the kind’sfallbackLabel), video → nativevideo(controls,playsinline, the file in asource, the captionstrack) in a ratio box, audio → nativeaudio(preload="metadata"), document → a link withaltas its text, or the file name for a blankalt(never probed: no request on render), model → its poster throughUiImage(or a placeholder labelled3D model) with anOpen the 3D model: <alt>link below (Open the 3D modelfor a blankalt).src: nullis thePlaceholderart (audio / document, with no box to hold, get their fallback row);unavailable(the file could not be resolved) or any failed load rendersAppMediaFallback. A failure is anerrorfromUiImage/UiSvgImg/ thevideoor itssource/ theaudio; a newsrcclears it. A model’s poster failing falls to the placeholder and keeps the link. A video’s frame is never empty at rest: it usespreload="none"only while a working poster covers the frame (a missing video file is then noticed when the reader presses play). A video without a poster usespreload="metadata", so the first frame paints and a missing file errors at rest, which shows the fallback. A video whose poster fails gets the same treatment. A brokenposterfires no event on thevideo, so a hiddenimgprobes it; on failure theposterattribute is dropped,preloadbecomesmetadata, and the fallback is not offered the broken poster. Every kind’s box, the image’s included, uses one ratio:ratio, elsemediaRatio(width, height). A failure therefore does not shift the layout.-
useMediaFailure(src, element?)(core/web/app/composables/useMediaFailure.ts) holds that state for one file:failed(a ref),onError(bind as@error="onError"), cleared when thesrcgetter changes. Given anelementgetter (the renderedvideo/audio, or animgsuch as the poster probe), it also catches a file that failed before hydration. On mount, and only when the component was set up while hydrating, the element counts as failed in two cases. Avideo/audiofails when itserroris set or itsnetworkStateisNETWORK_NO_SOURCE(3). Animgfails when it carries thedata-errormarker that its server-renderedonerrorleaves; bindimgSsrErrorAttrsfrom the same module for that. Not after client navigation, where browsers reportNETWORK_NO_SOURCEbriefly on insert; theerrorevent covers that case.useVideoPoster(poster)in the same module holds a video’s poster rule for both components:posterProbe(the probeimgref),posterFailed,onPosterError,posterShownandpreload(noneonly while a working poster covers the frame, elsemetadata). - Media slots.
AppMediaSlotpasses the slot’s fields toAppMediaFile, so a slot with asrcthat fails to load (a raster, svg or video file) shows the fallback for its kind inside the samefigure, keeping thefigcaption:Image unavailable: <alt>for a raster or svg, and for a video the slot’sposter(or the placeholder) with no player. This is distinct from a slot whosesrcisnull: that is the “Placeholder” (art not made yet), keeps the slot’s ownaltas its name and is unchanged. “Unavailable” always means a file that should exist could not be shown. - Case-study media.
AppCaseStudyMedia(/work/[slug]hero and artifacts) keeps its own markup (thecase-study-mediaroot carrying the page’s scope, the WebPwladder, diagrams’data-media-kind) and usesuseMediaFailurefor the same rules: a raster (UiImage) or SVG / diagram (UiSvgImg) that fails, or a video whosesourcefails or that failed before hydration, becomesAppMediaFallback.case-study-media(kindimage,svgorvideo;altfrom the item; ratioitem.aspectCss, else the WebP ladder’s source size, elsemediaRatio(width, height): the ratioUiImagereserved; whilepages/work/case-study.scssframes a video’s fallback ([data-media-fallback='video'], hero and grid) at the--media-ratioit gives the player (9:16 on phones), its box filling that frame, so a failure does not shift the layout; the video’sposter). Its video follows the never-empty-frame rule above:preload="none"only while a working poster covers the frame, elsemetadata. The poster probe sits in thevideo’s fallback content, so the component keeps one root; it must stay eager, because a lazy image in non-rendered content may never load in some engines. A newitem.srcretries.
Tests:
core/web/tests/media-fallback.spec.ts: the helpers;core/web/tests/media-fallback-component.spec.ts:AppMediaFallbackper kind;core/web/tests/media-file-component.spec.ts:AppMediaFileanduseMediaFailure;core/web/tests/use-video-poster.spec.ts:useVideoPoster;core/web/tests/media-slot-component.spec.ts: slots, including the failed-file cases;core/web/tests/case-study-media-component.spec.ts: case-study media;core/web-e2e/src/e2e/media-fallback.cy.ts(real browser, files blocked with 404s): the case-study hero SVG and the lazy artifact image fall back with their names and no broken image or page-level overflow at phone, tablet and desktop; a video whose poster 404s ends withpreload="metadata"and noposter(the probe inside<video>loads); a failed hero video’s fallback keeps the 9:16 player frame on a phone.
Library media on public pages
A page can reference a library asset by id (never by URL or key). The server resolves the id at render time.
Resolution and cache
core/web/server/utils/media-refs.ts resolves ids for a render: resolveMediaRefs(ids) answers a map with every id, null when the id does not resolve. createMediaRefResolver is the same resolver with its library, storage and clock injected (tests).
- What an id resolves to. A
ResolvedMediaRef(#shared/media-refs): kind, mime,src,srcset,alt,decorative,width,height,lqip,dominantColor,poster. Every URL is the public media base (mediaPublicBaseUrl()) + key +?v=<sha8>.- An image’s
srcsetlists its ready640/1280/1920variants by width (webp first; never thetthumbnail). Itssrcis the largest of them, else the original. - An image always has a
srcset. With no ready variants it is the original:<src> <width>wwhen the meta has a width, else the bare<src>. SoUiImagealways takes its plain-imgbranch for library media. It never goes through NuxtImg / IPX, which would rewrite the versioned URL to a/_ipx/…path that it refuses (403). An image without variants is served at its original size. - Other kinds have no
srcset;srcis the original. altismeta.alt(else''),decorativeismeta.decorative === true. Size, LQIP and dominant colour come from the asset’s meta when set.posteris the original URL of the image asset named bymeta.posterId(a video’s poster), when that asset resolves.
- An image’s
- Not resolved:
null. An unknown id, a malformed id (not[A-Za-z0-9_-]{1,64}, never looked up) and another tenant’s asset all resolve tonull, which renders the kind’s fallback. Onlyportfolioassets are public. - Cache: 60 s per process. Each resolution is kept in Nitro’s in-memory
media-refsstorage, keyedportfolio:<id>, forMEDIA_REF_TTL_MS(60 000 ms), anulltoo, so a deleted id doesn’t hit the catalog on every render. The memory driver has no TTL of its own, so each entry carries itsexpiresAt. - Clearing is per process. The
@tgmc/media-nuxtroutes that change an asset (delete, rename, meta edit, re-process) emit a change after they succeed.server/plugins/media-refs-cache.tslistens and clears that asset’s entry, so the instance that handled the change renders it at once (a clear that fails is logged asmedia.refs_clear_failed; the entry then expires within the TTL). A resolve already in flight when the entry is cleared does not cache what it read. - Other instances: within 60 s. Another Lambda instance (or the admin’s own process, when it changed the asset) never hears the change; its entry expires within the TTL. So a deleted or renamed asset can show its old URL for up to 60 s on other instances: a renamed asset’s old URL is a 404 there, which renders the fallback. A poster’s own change likewise reaches its video’s cached entry only when the TTL ends.
- Catalog down. When the library cannot be read, every id the call had to look up resolves to
null(placeholders, never a 500), the call logsmedia.refs_unavailableonce and nothing is cached, so the next render tries again.
Tests: core/web/tests/server/utils/media-refs.spec.ts (a real library on in-memory SQLite) and packages/media-nuxt/tests/media-asset-events.spec.ts (the event and the four emitting routes).
Usage list writes
A post or slot write keeps the library’s usage list (which published pages use each asset) up to date, so a delete can’t silently take media off a page. The code is core/web/server/utils/media-usage-sync.ts. The posts service (createBlogPostFromBody, updateBlogPostFromBody, deleteBlogPostById) runs it when it is given a sync, and without one it writes no usage.
- Pages. A post is two usage pages, both labelled with its title and linking
/blog/<slug>:post(the asset ids in the body,extractAssetRefIds, which deliberately over-counts) andpost-cover(coverAssetId). A slot is oneslotpage labelledMedia slot <id>, linkingslotPageUrl(id). Only published posts record rows. A slot counts as soon as it is saved. The tenant isportfolio. - Pending before visible. A write that makes or keeps a post published first writes
pendingrows: the previous ids and the next ids together. The delete check treatspendingas in use. A published create picks its post id before the write (BlogPostStore.createtakes an optional server-onlyid), so its rows name the post before it exists. - The 2 s window. The pending write never fails or slows a publish beyond 2000 ms. On a timeout or error the publish goes ahead and the server logs
media.usage_pending_failed. Until the rebuild repairs the list, the post’s new assets can be deleted without a warning. That gap is the documented window. A pending write that times out keeps running, and the live write waits for it, so a late pending write normally lands before the live rows. That wait is bounded byPENDING_SETTLE_MS(10 s): a pending write still unsettled then is logged asmedia.usage_write_failedwithreason: 'pending_stuck', and the live rows are written anyway. If the stuck write lands later it can briefly mark the rowspendingagain, which only makes a delete more careful; the rebuild repairs it. - Live after, in the background. After the write, a background task (
event.waitUntil, else fire-and-forget) writesliverows: the post’s ids, or[]when it is unpublished or deleted. Each page is retried after 1 s and 4 s, then logged asmedia.usage_write_failed. If the store write throws after a pending write, the task puts back the previous rows (their ids, or[]). An id with no asset in the tenant (unknown, or another tenant’s) gets no row and is logged asmedia.usage_missing. - On AWS Lambda the live write is awaited (≤ 5 s). Nitro 2.13’s
aws-lambdaruntime has no platformwaitUntil: it would return the response and Lambda would freeze the environment with the live write, its retries and the settle wait still pending.core/web/server/plugins/media-usage-wait.tstherefore awaits the request’sevent.waitUntilwork inbeforeResponse, only when the Nitro preset isaws_lambda(a no-op onnode-server, where the process keeps running), bounded to 5000 ms in total. A publish on Lambda normally takes a few hundred ms longer; in the worst case about 2 s (pending) plus 5 s (live). When the bound cuts the wait it logsmedia.usage_wait_timeout, and the cut work may never finish: its rows staypending. KeepMEDIA_USAGE_REBUILD_ENABLED=1ontestandproduction(cicd) as the backstop that settles them. - Rebuild input.
buildUsageRebuildRequest(posts, slots)lists every published post and everyportfolioslot with an asset, forMediaLibrary.rebuildUsage; a slot of another tenant is left out, since the request names one tenant.POST /api/media-usage/rebuild(admin principal only,no-store, Web write endpoints) runs it throughrebuildMediaUsage(core/web/server/utils/media-slot-write.ts): every post (listAll; the builder keeps the published ones) and the storedportfolioslots, thenMediaLibrary.rebuildUsage. It answersRebuildUsageResult({ added, removed, countersRepaired }), or 503Media library unavailablewhen the library cannot open. - One sync per write. A sync holds per-write state (the pages its
beforeWritenamed), so every handler builds a fresh one; it is never shared between requests. - Who writes today. The web’s authenticated post routes (
POST /api/blog/posts,PUTandDELETE /api/blog/posts/:id, Web write endpoints) build a sync on the web’s media library, its background work handed toevent.waitUntil. The admin’s blog and slot routes build one on its own library in local media mode; in forward mode (MEDIA_API_URL) they forward the write to these web routes, which record the usage (admin § Forward mode). The web’s slot routes (PUT /api/media-slots/:id,POST /api/media-slots/:id/reset) build one the same way.
Tests: core/web/tests/server/utils/media-usage-sync.spec.ts, core/web/tests/server/api/posts/posts-service.spec.ts (usage sync), core/web/tests/server/api/blog-posts-routes.spec.ts (the web routes and their auth table), core/web/tests/server/api/media-slots-admin-routes.spec.ts and core/web/tests/server/utils/media-slot-write.spec.ts (slot writes and the rebuild), core/admin/tests/admin-blog-usage.spec.ts, core/admin/tests/admin-blog-forward.spec.ts and core/admin/tests/admin-slots-routes.spec.ts (forward mode sends the writes to these routes), core/web/tests/server/plugins/media-usage-wait.spec.ts (the Lambda wait), and the store contract (create keeps a given id).
Blog covers and embeds
A post’s cover and the media in its body come from the library. GET /api/posts/:slug resolves them on the server (core/web/server/utils/blog-post-media.ts) and answers { ...post, html, cover, segments } with Cache-Control: public, max-age=0, must-revalidate. The cover id and the body’s block ids resolve in one resolveMediaRefs call, next to getMediaSlotViews(). Neither throws: with the catalog down the cover falls back and every media segment has ref: null, and the post still answers 200. html (the whole body as sanitized html) stays for the github.io export and older clients; in it a block reference renders as the unavailable text, like an inline one.
- Syntax.
or::media{asset=<id> alt="…"}, for any kind (the kind comes from the asset). Ids match[A-Za-z0-9_-]{1,64}. A missing alt falls back to the asset’s alt. - Block only. A reference renders as media only when it stands alone on its line, outside a code fence (
splitBodyMedia). Anasset:image inside running text is rendered as the textImage unavailable: <alt>in aspan.blog-media-unavailable:renderBlogMarkdownturns anyimgwhosesrcis missing or not http(s) / root-relative into that escaped text, never animgwithoutsrc. An inline reference still counts as usage, so a delete can’t take it away silently. The same rule turns a relative image src () intoImage unavailable: xtext: a post body uses library references or root-relative / https URLs. - Segments.
renderPostSegments(markdown, refs)answers the body in order:{ type: 'html', html }for each markdown run (throughrenderBlogMarkdown) and{ type: 'media', assetId, alt, ref }for each block (altis the written alt, else the asset’s;refisnullwhen the id does not resolve, for example another tenant’s asset). - Cover precedence, with fall-through.
resolvePostCover(post, slots, refs):coverAssetId, then slotblog.cover.<slug>, then slotblog.cover, then the placeholder. A source that does not resolve falls through to the next: an unknown or another tenant’s asset, an asset of a kind the image cover cannot render (it takesimageandsvg, like an image slot), or a slot that is itself a placeholder or unavailable. The cover isunavailable(the labelled fallback) only when an asset id was set and nothing after it resolved either; otherwise it is theblog.coverplaceholder. When the post’s asset wins, the view’s id isblog.cover.<slug>and itsaltiscoverAlt, else the asset’s alt, else the slot’s; it is decorative only when the asset is and the post sets nocoverAlt. A slot that wins keeps its own alt (it shows a different picture); an unavailable cover is named bycoverAlt, else the slot’s alt. - The page.
app/pages/blog/[slug].vuerendersAppMediaSlot(:view="post.cover", eager)and onearticle.blog-bodywhose children are the segments: each html chunk in adisplay: contentswrapper (v-html), each block throughAppMediaFilewith the ref’s fields,unavailable: ref === nullandkind: ref?.kind ?? 'image'. Body media get the prose column’s nativesizes,(min-width: 42em) 42rem, 100vw(--prose-max), so the browser does not pick a 100vw candidate from thesrcset. The cover sits above the prose column, in the page shell; with asrcsetit getsAppMediaSlot’s native100vw, and an svg cover renders throughUiSvgImgwith its direct/m/…svg?v=URL. An answer withoutcover/segmentsrenders the slot by id andhtml. - Writing references. In the admin blog editor, Insert media picks a library asset of any kind and writes its block reference on its own line at the caret, with a blank line before and after (
bodyMediaReferenceinshared/media-refs.ts, the parser’s inverse; its alt drops[ ] ( ) { } \so a reference counts exactly one asset); Choose cover setscoverAssetIdfrom an image or SVG (see admin § Blog editor). Inserted mid-line, the block splits that paragraph in two; inserted inside a code fence, it renders as code, not media, but still counts as usage (extractAssetRefIdsover-counts on purpose). - Covers from the portfolio tenant only. The site renders
portfolioassets only, so the picker lists that tenant, and a post create or update whosecoverAssetIdnames an asset of another tenant is a 422 oncoverAssetId, “Pick an image from the portfolio library” (coverTenantChecksinserver/api/posts/service.ts; the web routes and the admin’s local mode both run it). A cover id with no asset at all still saves: the page shows the fallback and the post is flagged Needs media. With the library unavailable, or a lookup that fails for another reason (logged asmedia.cover_check_failed), the write is not checked. - Captions gap: warned, not blocked. A library video or audio embedded in a body renders a native
video/audiowith no captionstrackor transcript yet: aResolvedMediaRefhas no captions field (slots do). Insert media warns “No captions yet: this video will play without captions.” (or “this audio”) and still inserts (owner, 2026-10-23). Until captions support for library video and audio lands (asset meta or a captions asset), only embed time-based media that has no speech, or link a transcript in the post text (WCAG 1.2.1 / 1.2.2).
Tests: core/web/tests/server/utils/blog-post-media.spec.ts (precedence, segments, the route), core/web/tests/server/utils/render-blog-markdown.spec.ts (inline images), core/web/tests/server/utils/media-refs.spec.ts (the srcset without variants), core/web/tests/blog-post-page-component.spec.ts (the page with a cover, segments and a fallback; a library image without variants renders a plain img with its direct URL, never /_ipx/; an svg cover renders a direct img; body and cover sizes are native).
Related: @tgmc/media, @tgmc/image sanitizer, promote media to production.