Skip to the content.

@tgmc/media

Node / Nitro / Lambda media catalog library for TGMC portfolio apps.

Package README: packages/media/README.md.

Role

Concern Owner
Asset inventory (image / svg / audio / video / model / document) This package
Child recipes + materialize This package
Image pixel transforms @tgmc/image (composed)
SVG / audio / video / model / document transforms Placeholders (TransformerNotImplementedError) until later
Local catalog / jobs / audit SQLite adapter
Local blobs FsBlobStore (filesystem, behaves like the S3 bucket)
AWS DynamoDB / S3 / Lambda @tgmc/media-aws + @tgmc/media-nuxt /api/media/*
PostgreSQL catalog / jobs / audit @tgmc/media-postgres
Admin grid / multi-upload UI @tgmc/admin /admin/media + /api/admin/media/*
Nuxt / Next host adapters @tgmc/media-client + @tgmc/media-nuxt

Requirements: docs/plans/2026-09-22-001-feat-media-library-sdk-plan.md · Admin UI: docs/plans/2026-09-22-003-feat-admin-media-ui-plan.md · Hosts: docs/plans/2026-09-22-004-feat-media-host-adapters-plan.md.

API surface

import { createMediaLibrary } from '@tgmc/media';

const { library, close } = createMediaLibrary({
  dbPath: './data/media.sqlite',
  blobDir: './data/media-blobs',
});

// A host's local mode: `<root>/media.sqlite` + `<root>/blobs` (`localMediaBlobDir(root)`), on-ingest recipes in the request.
// const { library, close } = createLocalMediaLibrary({ root: './.data/media', sanitize });

await library.ingest({
  kind: 'image',
  data: './a.png',
  mime: 'image/png',
  meta: { tags: ['hero', 'logo'] },
});
await library.addAssetTags(assetId, ['brand']);
await library.listAssets({ tag: 'hero' });
await library.materializeChild(assetId, null, null, { variant: '640' }); // catalog variant
await library.materializeChild(assetId, 'square', {
  kind: 'image',
  ops: [{ type: 'resize', ops: { width: 800, height: 800 } }],
  format: 'webp',
}); // custom recipe
await library.deleteAsset(assetId); // hard cascade; frees the name once the objects are gone; MediaInUseError (409 in_use) while a published page uses it
await library.deleteAsset(assetId, { force: true }); // admin: deletes an in-use asset, removes its usage rows, audits asset.force_deleted
await library.getAssetUsage(assetId); // the published pages that use it
await library.replacePageUsage(
  { tenant: 'portfolio', pageType: 'post', pageId },
  { assetIds, pageLabel, url, state: 'live' }
);
await library.rebuildUsage({ tenant: 'portfolio', pageTypes: ['post'], pages }); // full rebuild of those page types
close();

Scoped library

HTTP hosts never hand MediaLibrary to a route. scopeMediaLibrary(library, principal, { writesFrozen }) (src/scoped-library.ts) wraps it for one caller (MediaPrincipal: { type: 'admin' } or { type: 'tenant', tenant, tokenId, scopes }); @tgmc/media-nuxt builds it per request (media-nuxt § Auth).

Keys, names and variants

The key is the URL. The same string is the CDN path, the MinIO/S3 key, the host-dev URL and the storage key (no leading slash on keys):

m/{tenant}/{kind}/{name}.{ext}              original
m/{tenant}/{kind}/{name}@{variant}.{ext}    processed variant
Part Values
tenant pf portfolio (default), ha example-organization (TENANT_CODES)
kind i image, s svg, v video, a audio, d document, o model (KIND_CODES)
name lowercase kebab-case; the whole filename (name.ext) is at most 36 characters
variant t (320 px), 640, 1280, 1920, or c-{8 hex} for a custom recipe; p (poster) is reserved

@tgmc/media exports originalKey, variantKey, parseMediaKey (paths.ts), normalizeMediaFilename (meta-policy.ts), slugMediaFilename (filename.ts) and the variant helpers (variants.ts). MediaAsset carries tenant, name and path; MediaChild carries variant and path. The asset id stays an internal DB key and never appears in a URL.

Filenames

slugMediaFilename is mechanical: basename only, accents stripped, lowercase kebab-case ASCII, extension at most 8 alphanumerics, truncated so name.ext is at most 36 characters, untitled when nothing is left. The SQLite migration backfill uses it so existing names never change.

normalizeMediaFilename is the policy name every ingest uses (ingest, reserveName, registerRemoteAsset): it first drops generator prefixes (vimg, mj, midjourney, dall-e, firefly, sora, chatgpt), camera prefixes (IMG_, DSC_, PXL_ …), UUIDs, long hex tokens, digit runs of 10 or more and single-letter middle initials, then slugs the rest (falling back to the plain slug when nothing is left). Tamara G Mack_Resume_2026.pdf → Tamara Mack-resume-2026.pdf; vimg-tesseract-framework.mp4 → tesseract-framework.mp4.

IngestInput takes optional filename and tenant; without a filename the name comes from the file path (when data is a path), else {kind}-{first 8 of the sha256}.{ext}. Only an explicit mime is checked against the extension; without one the extension decides the mime, and an extensionless name takes the extension of the resolved mime.

Metadata policy

validateMediaMeta(kind, meta, { computed? }) → { ok, issues, meta } (assertMediaMeta throws RecipeValidationError instead). Rules (MEDIA_META_LIMITS): title required, 3–80 characters; alt at most 150 and required for image and svg (and video with a posterId); description at most 300; credit at most 80, defaulting to DEFAULT_MEDIA_CREDIT (Tamara Mack). Text fields must be human text, not identifiers: UUIDs, long hex, camera names, generator prefixes (vimg; mj only before _ / - or alone, since MJ is also initials), vendor job ids and filenames are rejected. width / height / durationSec are computed fields and are rejected unless computed: true (the site import sets it).

MediaLibrary checks the policy on ingest (before anything is reserved or written) and registerRemoteAsset. It is on by default: every admin and /api/media upload must carry a title and, for images and SVG, alt text or decorative: true. A failure is a MediaMetaValidationError, which mediaErrorToHttp sends as 400 data: { code: 'invalid_meta', issues: [{ field, code, message }] } (@tgmc/media-client throws MediaInvalidMetaError with the issues). enforceMetaPolicy: false (createMediaLibrary({ enforceMetaPolicy: false })) is the explicit opt-out for bulk tools that import files without editorial metadata: the bin/media.mjs CLI uses it. transferMedia copies rows with insertAsset and never runs the policy; the site import checks its manifest instead.

Edits. updateAssetMeta(id, patch, { validate: true }) is a person’s edit, used by both PATCH routes (admin and /api/media, whose { meta?, tags? } body becomes the patch; tags replace). The patch is merged over the stored meta and checked with validateMediaMetaEdit(kind, current, patch): width / height / durationSec in the patch are rejected (only the on-ingest recipes measure them), and the editorial rules run on the merged meta only when the patch touches an editorial field (EDITORIAL_META_FIELDS), so a tags-only edit of an older asset without a title still saves. A blank text field clears it; a blank credit falls back to the default. The stored meta is the normalized result. Internal writers (the on-ingest recipes) leave validate off.

Variants

Materialize job state for rejected inputs

A source the image guards refuse (ImageInputError: over MAX_BYTES, an edge over MAX_EDGE_PX, or undecodable bytes) is a terminal failure, like a bad recipe: runMaterializeJob marks the job failed (lastError holds the message), marks the child failed (a live ready child keeps serving its old object), writes the child.materialize_failed audit event, and then rethrows the ImageInputError. HTTP hosts therefore answer 413 / 422 through mediaErrorToHttp with the real message, and the SQS worker (mediaWorkerHandler) acks it instead of redelivering (a redelivery of a failed job returns early anyway). Nothing is left queued, so the next “Create variant” for the same variant and format is accepted and fails the same way (422), never 409. Other terminal failures (RecipeValidationError, missing transformer) still return { child, job } with status failed. Retryable adapter errors still re-queue the job. On-ingest recipes (below) report a variant refused this way as failed, not retryable.

On-ingest recipes

runOnIngestRecipes(library, assetId, options?) (on-ingest.ts) is what every new asset gets automatically. It is idempotent, so re-running it (a redelivered S3 event, “Re-run processing”) changes nothing that is already done.

  1. Meta, read from the original through library.readOriginal(asset) (a stat check against the ingest size cap first). Images get width, height, lqip and dominantColor (@tgmc/image); SVG gets width / height from the attributes or the viewBox (readSvgDimensions); a PDF document gets pageCount when the optional pdf-lib package is installed (options.pdfPageCount injects a reader). Only changed keys are written, so editorial meta stays.
  2. Variants (onIngestVariants): images get the catalog t, 640, 1280 and 1920 (webp), never wider than the original (t always). SVG, video, audio, models and documents get none; a video poster stays a separate image asset linked through meta.posterId.

A ready variant is skipped, a failed one is made again, and one with an active job is left alone. A variant whose materialize fails ends as a failed child; one that hit an adapter fault (a thrown error) is also marked failed (failMaterializeDispatch, so it is not left queued with nothing to redeliver it) and reported retryable. The other variants still run. An original that cannot be read (missing object, storage fault) returns retryable with nothing written. An original that cannot be decoded, or is over the size cap, records meta.processingError and makes no variant; a later successful run clears it. The function never throws for a recipe failure, only MediaNotFoundError for a missing (or concurrently deleted) asset.

MediaLibrary takes hooks.onIngested (also through createMediaLibrary({ hooks }) and createAwsMediaLibrary({ onIngested })). It runs after ingest and registerRemoteAsset; an error is audited (asset.on_ingest_failed) and never fails the ingest, and the returned asset is re-read so it carries the new meta. onIngestRecipesHook is the hook that runs the recipes. onIngestStatus(asset, children, jobs, now?) gives each step’s status (queued / running / ready / failed, with the error) for the admin drawer. A step still waiting after ON_INGEST_STALL_MS (15 minutes, above the AWS worker’s give-up point of three 360 s receives) reads not-started (no child yet, counted from the asset’s createdAt) or stalled (its queued job, or its running job’s startedAt, is that old). The admin stops polling those and offers Re-run processing; scripts/media-smoke.js fails on them at once. Which runner calls the recipes depends on the host: see media-nuxt § On-ingest processing.

Concurrent runners. The S3 trigger, a duplicated S3 event and Re-run processing can run the recipes for the same asset at the same time; each variant still ends with exactly one child:

Name reservation

A name (the key without its extension) is unique per (tenant, kind), whatever the extension. hero.png and hero.jpg cannot coexist: a variant key drops the original’s extension (m/pf/i/hero@640.webp), so two originals sharing a name would overwrite each other’s variants and deleting one would delete the other’s. SQLite enforces it with UNIQUE(tenant, kind, name); DynamoDB with a NAME# item (see media-aws); Postgres with the same unique constraint plus a per-name advisory lock (see media-postgres).

Rename

library.renameAsset(id, { filename }) (rename-asset.ts) moves an asset to a new name within its (tenant, kind). The filename is normalized like an upload’s; the extension may be left out but cannot change (400). A taken name is a MediaNameConflictError (409 name_conflict with a suggestion), an asset with an active job is a MediaConflictError (409), an unknown asset 404. Both hosts expose it as POST …/assets/:id/rename with { filename } (@tgmc/media-client renameAsset), answering the asset with its new publicUrl / previewUrl.

  1. Hold the new name (holdName, 30 minutes), so no upload or other rename can take it meanwhile, and record the plan as an asset.rename_started audit event.
  2. Copy the original and every stored variant to the new keys, create-only (the same object headers, with the new Content-Disposition filename). The copy is server-side when the blob store has the optional BlobStore.copy (S3 CopyObject, copyFile with COPYFILE_EXCL on FsBlobStore), else a read and a create-only put. An object already at a new key is adopted only when its bytes are identical (an interrupted earlier run; SHA-256 streamed through digestSha256 where the store has it); anything else is a 409. A missing original is a 409; a missing variant is skipped.
  3. Switch the catalog in one store transaction (CatalogStore.renameAsset): the asset’s name / path and meta.filename, every child path, the new name claimed and the old one held for this asset until the cleanup releases it. The transaction refuses (409) while a job is queued or running with a fresh lease, or when the asset’s children changed since the plan (SQLite and Postgres compare the stored children; DynamoDB requires an unchanged childRev, which every child write bumps). SQLite and Postgres do it in one SQL transaction; DynamoDB in one TransactWriteItems (asset, children, both NAME# items). asset.renamed is audited.
  4. Delete the old keys and release the old name, call hooks.afterRename({ oldPaths, newPaths }) (createAwsMediaLibrary wires it to a CloudFront invalidation of the old paths when ASSETS_DISTRIBUTION_ID is set) and audit asset.rename_cleaned. A failing purge is audited as asset.invalidation_failed (paths, error) and never holds the rename open or blocks the next one. The old name is re-held for the asset first; if someone else holds it (only possible after a release), the keys are theirs and are left alone.

Child writes (variants, materialize jobs) carry the asset path they were planned for. A job whose asset moved meanwhile deletes the key it wrote (unless the old name already belongs to another asset) and redoes the variant under the new key (bounded retries; an asset that keeps moving is a retryable on-ingest failure, not “asset deleted”). A metadata edit (updateAssetMeta) writes only meta and updatedAt (one DynamoDB UpdateItem), so an edit read before a rename never restores the old name or path.

Old /m/ URLs stop working. There are no redirects: catalog media is new and admin-owned, so whoever renames updates the pages that use it. Site media (/i, /v, /d) is not in the catalog and never moves (site media).

Crash safety. Old keys are only deleted after the switch, and every step can be re-run. Re-running the same rename before the switch adopts the identical copies already written. A failure before the switch deletes every copy under the new name (the asset still holds it, so they are its own, including those of a concurrent rename to the same name that failed too; only foreign bytes a copy refused to overwrite stay), releases the new name and audits asset.rename_abandoned, unless another unfinished rename of the same asset targets the same key (it may have adopted those copies; holds are re-entrant per asset), in which case it only audits (skipped: 'another rename uses the new keys'); a store error that arrives after the switch committed (a lost response) carries on. Nothing after the switch fails the rename: a failed cleanup is audited as asset.rename_cleanup_failed, and the old name stays held for the asset. Cleanup checks every planned move before deleting anything: when a new key is missing while its old key still exists, the old keys are kept, the missing copies are written again (create-only) and the cleanup fails, so the next resume finishes it. A variant missing on both sides (skipped by the copy) does not block it. library.resumeRename(id) finishes it from the asset.rename_started event that has no asset.rename_cleaned / asset.rename_abandoned; the next rename of the asset runs it first (409 while it still fails), and GET /api/media/assets/:id and the admin’s local detail read run it on every read. It also abandons a rename that died before its switch: once its 30-minute hold on the new name has lapsed, the copies are deleted and the name released (asset.rename_abandoned, reason: 'never switched'); while the asset still holds the name the rename may still be copying, and when another asset holds it by now only the event is closed. The abandon holds the name under its own holder id (<assetId>#abandon), not the asset id, so it cannot re-enter the hold of a new rename of the same asset that took the name between its read and its hold, and that rename gets a 409 while the abandon runs. deleteAssetCascade returns the keys of the rows it deleted, read in the same transaction (DynamoDB: the asset delete is conditioned on the path it read and retried when a rename moved it, up to five attempts, then a 409), so a rename that switched while the asset was being deleted cannot leave its new keys behind. deleteAsset also removes what an unfinished rename left on either side (copies of one that never switched, old keys of one that never cleaned up) unless that name now belongs to another asset, and releases its holds (its own and a leftover <assetId>#abandon hold).

Metadata edits (PATCH …/assets/:id, validateMediaMetaEdit) accept only the editorial fields and tags: width / height / durationSec are computed, any other key (filename, facets, …) is invalid (400 invalid_meta). The admin labels an asset by its current key, not meta.filename.

Upload sanitizing

MediaLibraryDeps.sanitize (createMediaLibrary({ sanitize }), createAwsMediaLibrary({ sanitize })) turns on sanitizing of uploads (sanitize-upload.ts). It is off when unset: the CLI, transferMedia and the site import never sanitize. The sanitizer is injected, so this package imports only @tgmc/image/sanitize-core and never reaches svgo, pdf-lib or ffmpeg (tests/sanitize-boundary.spec.ts fails on a static import of @tgmc/image/sanitize or /sanitize-web, svgo, pdf-lib or ffmpeg-static).

Host Sanitizer Formats
Web server (@tgmc/media-nuxt, any mode) createWebUploadSanitizer() from @tgmc/image/sanitize-web (sharp + svgo) rasters, SVG
Admin server (core/admin) createFullUploadSanitizer({ ffmpegPath: resolveFfmpegPath() }) from @tgmc/image/sanitize rasters, SVG, PDF, MP4
MediaWorker Lambda none (it never registers uploads) —

S3 object headers

BlobStore.put(key, data, { contentType, cacheControl, contentDisposition, createOnly }). createOnly refuses to replace an existing object: it throws MediaBlobExistsError, sent as If-None-Match: * on S3 (where 412 and 409 map to that error) and published through an exclusive link on FsBlobStore. MediaLibrary passes the asset mime, public, max-age=31536000, immutable and inline; filename="<name>.<ext>" (objectHeaders(contentType, key), also used by transferMedia). S3BlobStore sets them as object metadata; FsBlobStore keeps them in its sidecar (below). Presigned browser uploads sign the full PRESIGN_REQUIRED_HEADERS set (Content-Type, If-None-Match, Cache-Control, Content-Disposition; see media-aws), so those objects carry the same cache and download headers as server-side puts.

Versioned public URLs

The one-year immutable cache is kept, but a key can get new bytes: a catalog variant is re-materialized in place, an upload is re-encoded at complete, and a name is reused after a delete or rename. So every public media URL carries the object’s content version, ?v=<first 8 hex of its SHA-256>, built in one place: mediaPublicObjectUrl(base, key, version) in src/public-url.ts (browser-safe, no imports; also exported as @tgmc/media/public-url). The version of an original is its sha256 (mediaAssetObject); of a variant, its meta.sha256, which runMaterializeJob records for every ready child (mediaChildObject); a variant materialized before that falls back to an 8-hex digest of its updatedAt (mediaObjectVersion), which every re-materialize bumps. mediaPreviewObject(asset, children) is mediaPreviewKey plus the previewed object’s version. New bytes get a new URL, so neither CloudFront (whose m/* cache key includes v, see infra) nor a browser serves a stale copy; the stores ignore the query (S3, MinIO and the local /m/** stand-in serve the key). The CDN purges (afterReplace, afterDelete, afterRename) still run and invalidate every cached version of the key (/key*), including links that kept an old v. mediaAssetUrls(base, asset, children) gives both an asset’s publicUrl and previewUrl, and withMediaAssetUrlsList(library, assets, base) does it for a list page (only image / svg rows read their children). Users: @tgmc/media-nuxt (publicUrl / previewUrl, Asset URLs), the admin’s local mode (both through those two helpers), and sitePublicMediaUrl(key, runtimeConfig, sha256) in core/web/shared/media-public.ts (import-free copy, pinned to the same result by tests/media-public.spec.ts).

Filesystem blob store

FsBlobStore(root) is the local stand-in for the S3 bucket, so host dev and DATA_BACKEND=sqlite|postgres behave like AWS:

SQLite migration

openMediaDatabase(dbPath, { blobDir }) migrates older databases in place and idempotently: it adds tenant, name, path (assets) and variant, path (children), backfills names from meta.filename (else {kind}-{id8}, de-duplicated with numeric suffixes), marks old children as custom, renames later assets that collide on (tenant, kind, name) across extensions with -2, -3 (their variants are re-keyed; when two assets shared a variant key, the one object at that key cannot be attributed, so both children are marked failed and need re-materializing), creates the unique (tenant, kind, name) index (replacing the old path index and media_path_reservations table with media_name_reservations; a colliding row whose key cannot be parsed aborts the migration with an error naming the row), then moves blobs on disk from the legacy blob_key to the new path. blob_key stays as a legacy column. A missing file keeps its row pending for the next run; an existing destination marks the row done. Moved blobs have no sidecar; FsBlobStore derives their metadata. Take a copy of data/ first.

Kind vs tags / meta

Field Role
kind Exclusive processing pipeline (image / svg / audio / video / model / document)
meta.tags Many editorial labels (hero, lottie, project names) — normalized lowercase kebab
meta facets Pipeline hints without new kinds: animated, hdr, panorama, designSource, motionFormat (ASSET_META_KEYS)

List with ?tag= (admin + /api/media). PATCH …/assets/:id with { tags } or { meta } to update (a validated edit, see Metadata policy).

Usage list and delete safeguards

A usage record says that a published page uses an asset: MediaUsageRecord is { tenant, pageType, pageId, assetId, pageLabel, url, state, updatedAt }. state is live (the page is published with the asset) or pending (written ahead of a publish that may not land; a rebuild removes it once it is older than PENDING_USAGE_GRACE_MS, 15 minutes). A page is one of four MediaPageTypes (MEDIA_PAGE_TYPES): post, post-cover, slot, site. Drafts never count.

The UsageStore port (ports/index.ts; adapters implement it next to their catalog store):

DeleteAssetCascadeOptions.usage is 'refuse' (default) or 'ignore'. With 'refuse' the cascade reads the asset’s usage rows inside its atomic step and, if any exist, throws MediaInUseError(assetId, pages) (pages ordered like listUsageForAsset, pending rows included) and changes nothing. With 'ignore' it deletes the asset and leaves the rows for removeAssetUsage. parseForceQuery(value) is the shared parser for a ?force= query (undefined/'0' is false, '1' is true, anything else 'invalid').

mediaErrorToHttp sends MediaInUseError as 409 in_use (checked before the generic conflict branch):

{
  "statusCode": 409,
  "statusMessage": "Asset a-1 is used by 1 published page",
  "data": {
    "code": "in_use",
    "pages": [
      { "pageType": "post", "pageId": "p-1", "pageLabel": "Harbor notes", "url": "/blog/harbor-notes", "state": "live" }
    ]
  }
}

Library methods. MediaLibrary takes the store as deps.usage (createMediaLibrary passes the SQLite one); each usage method throws Error('MediaLibrary has no usage store') without it.

Delete sequence (deleteAsset(id, { force? }), delete-asset.ts):

  1. The running-job check (409 while a materialize job runs).
  2. Pre-check: without force, the usage store’s listUsageForAsset; any row (live or pending) is a MediaInUseError with the pages, and nothing is deleted or audited.
  3. asset.delete_started is recorded, then the atomic check: the cascade runs with usage: 'refuse' and reads the rows again inside its atomic step, so a page published between the pre-check and the cascade still refuses it. That refusal changes nothing, is audited as asset.delete_refused ({ pages }) and rethrown. The event closes the delete: resumeDelete treats it like asset.deleted and never finishes a refused delete, even if the asset’s rows disappear some other way later.
  4. From here the delete runs as before (name hold, objects, asset.deleted).

Force ({ force: true }, the admin’s override): it needs the usage store (else it is refused before anything changes). It reads the pages and records asset.delete_started with force: true and those pages, then runs the cascade with usage: 'ignore'. With 'ignore' the cascade returns the usage rows it read inside its atomic step (DeleteAssetCascadeResult.usage, on the returned key array). After the cascade no usage write adds a row for the gone asset (it reports the id in missing), but a page write or a rebuild can still remove one. So the delete audits asset.force_deleted ({ tenant, pages }, pages ordered by pageType, then pageId) with the union of the rows the cascade read and the rows listed again now. A page published between the pre-read and the cascade is named too. Only then does it remove the rows (removeAssetUsage) and finish as above. The audit comes before the remove, so a crash in between loses no page from the record. A failure after the cascade (including either of those steps) is asset.delete_failed like any other step. Repeating deleteAsset for the gone id (with or without force; the audit trail says whether it was forced) resumes it. For an open asset.delete_started with force: true, resumeDelete appends asset.force_deleted only when none follows it (with the union of delete_started.pages and the rows listed now), and always calls removeAssetUsage (idempotent), before finishing the objects (asset.deleted, resumed: true). The resume never re-runs the cascade, so the rows a forced delete leaves behind (which make a plain cascade of the gone id refuse) cannot stall it. The one residual gap, for an adapter that returns .usage (every adapter passing the usage contract does): only after a crash between the cascade and the asset.force_deleted audit can a page go unnamed, and only one that was both published after the pre-read and then republished or rebuilt in that window. If recording asset.delete_refused itself fails, the caller still gets the MediaInUseError (409), not the audit error.

The admin offers a forced delete only from a refusal (plan 4, admin § Used by, refusal and Delete anyway): Delete anyway appears only after Delete… found pages, so a forced delete from the admin always has pages and asset.force_deleted names them. The library itself still accepts force on an unused asset (it audits force_deleted with pages: [] and returns forced: true); only a direct API caller can do that.

The admin server passes all of this through in both its modes (deleteMediaAsset(event, id, { force }), getMediaAssetUsage, rename usedBy; admin § Admin API), and @tgmc/media-client turns a 409 in_use into MediaInUseError (media-client).

A usage write for an asset whose delete has not finished finds no asset row and reports the id in missing. Rename never reads or changes usage: rows key on the asset id, so a renamed asset keeps its pages. The library delete itself is immediate; the 8-second Undo is the admin’s client-side delay before it sends the delete, unchanged.

SQLite (SqliteUsageStore, in createSqliteMediaStores as usage and passed to MediaLibrary by createMediaLibrary): the media_usage table in the catalog database, keyed by (asset_id, tenant, page_type, page_id), with an index on (tenant, page_type, page_id) for page reads. SCHEMA creates it with CREATE TABLE IF NOT EXISTS, so existing databases gain it on their next open. Each method is one transaction. A row is written only while the asset exists in the page’s tenant (INSERT … SELECT … WHERE EXISTS on media_assets); an id that finds no asset lands in missing and a row left behind by a forced delete is dropped the same way. SqliteCatalogStore.deleteAssetCascade reads the rows in its own transaction before the first delete, so a usage write and a delete never both succeed. rebuildUsage runs as one transaction: rows of the listed types that pages does not list are deleted, listed rows are inserted or rewritten as live (an old listed row whose asset is gone is deleted and counted in removed), and a row written less than PENDING_USAGE_GRACE_MS before now is neither deleted nor rewritten. countersRepaired is always 0 (SQL keeps no counters).

Postgres (PostgresUsageStore, @tgmc/media-postgres): the same table and rules, with row locks instead of SQLite’s single writer: a per-page advisory lock, FOR KEY SHARE on each asset a write adds or keeps (against the cascade’s FOR UPDATE), and the cascade reading the rows after its row lock. See media-postgres § Concurrency.

DynamoDB (DynamoUsageStore, @tgmc/media-aws): rows under the asset, a mirror per page, a per-asset counter that changes in the same transaction as every row, and a page head whose revision every chunk checks and bumps. The cascade’s ConditionCheck on the counter (index 2 of its transaction) is the atomic check; a forced cascade’s check is “counter unchanged since read”, so its .usage rows are the rows at the delete. A counter above zero with no rows is refused as a conflict naming the rebuild, and rebuildUsage repairs counters (countersRepaired). Writes go in chunks of 20 assets (the 100-item transaction limit): each chunk commits only against the state it planned from; writers of a multi-chunk page may alternate chunks, and the last to finish wins. See media-aws § Keys and DynamoDB layout.

Times, every adapter. Each usage store passes updatedAt (replacePageUsage) and now (rebuildUsage) through normalizeUsageTime(value, field) before its transaction: stored as UTC ISO with milliseconds (rows are compared and ordered as strings), and a value that is not a time throws a plain Error naming the field, before anything changes.

Catalog contract tests

tests/contract/catalog-contract.ts is one suite for every CatalogStore / JobStore / AuditStore adapter: describeCatalogContract(label, harness) with a harness that opens fresh stores (open()), releases them (close(stores)) and, optionally, shared resources (dispose()); an undefined harness skips the suite. It pins the SQLite adapter’s behaviour: round-trips (numbers, nested meta, timestamps), list order and paging, tenant / kind / tag filters, conflict errors (MEDIA_CONFLICT, MediaNameConflictError across extensions), name holds (extend, consume, expiry, release, one winner under concurrency), the two-phase discard (markNameDiscarding / releaseDiscardedName and the reservation-required insert; tests/contract/name-discard-contract.ts, which the DynamoDB adapter also runs through describeNameDiscardContract), child writes guarded by their asset, finalize outcomes, job transitions (one concurrent claim wins) and audit order. Errors are matched by name / code, because an adapter package throws the classes of its own built @tgmc/media.

A new adapter adds one spec with its harness.

tests/contract/usage-contract.ts does the same for UsageStore and the usage refusal of deleteAssetCascade: describeUsageContract(label, harness), where open() returns { catalog, usage } over the same data with no usage rows at all and no assets with the case’s ids: a fresh database / schema / table per case, or the shared one truncated before each case (rebuildUsage works on a whole tenant and page type, so rows left by an earlier case would be removed and counted). It covers row writes and reads, the difference a replace writes, missing and other-tenant assets, the refusal (live and pending rows, page order, nothing changed), usage: 'ignore' plus removeAssetUsage, time normalization and invalid times, and rebuildUsage (listed types and tenant only, old pending rows removed, old rows of gone assets dropped, rows younger than the grace period never removed or rewritten). Its race case — a usage write racing deleteAssetCascade either refuses the delete or records the asset missing, never both — must pass both branches on a backend with concurrent writers; rounds alternate which call starts first, and the test never asserts which one won. SQLite (tests/sqlite-contract.spec.ts) runs it always; with one synchronous writer the start order decides the branch there. Postgres (packages/media-postgres/tests/postgres-contract.spec.ts, when MEDIA_PG_TEST_URL is set) runs it unchanged, with a fresh schema per case; there the cascade usually takes the row lock first whatever the start order, so that package adds lock tests that hold each side open to force both orders (media-postgres § Tests). DynamoDB (@tgmc/media-aws) runs it unchanged on the in-memory DocumentClient (tests/dynamo-usage.spec.ts) and, when DYNAMODB_TEST_ENDPOINT is set, on DynamoDB Local with a fresh table per case (tests/dynamo-local.contract.spec.ts); there too the cascade commits first when left alone, so that file adds two cases that hold each side at its transaction (media-aws § Keys and DynamoDB layout).

Transfer between backends

transferMedia copies a catalog and its objects from one backend to another through the ports only (no AWS import in this package). It seeds production from a local catalog and pulls backups the other way. Operators use the npm run media:transfer CLI (runbook).

import { createSqliteMediaStores, transferMedia, type MediaEndpoint } from '@tgmc/media';
import { S3BlobStore, createDynamoMediaStores } from '@tgmc/media-aws';

const local = createSqliteMediaStores({
  dbPath: './data/admin-media/media.sqlite',
  blobDir: './data/admin-media/blobs',
});
const dynamo = createDynamoMediaStores({ tableName: 'portfolio-prod-Media', region: 'us-west-2' });
const target: MediaEndpoint = {
  catalog: dynamo.catalog,
  audit: dynamo.audit,
  blobs: new S3BlobStore({ bucket: 'portfolio-prod-assets-<account>', region: 'us-west-2' }),
};
const report = await transferMedia({ source: local, target, dryRun: true });
local.close();

Site media manifest and import

The site’s own media is described by a reviewed manifest (core/web/content/media.json) and imported with fixed ids. Workflow and CLIs: site media.

CLI

npm run build --workspace=@tgmc/media
node packages/media/bin/media.mjs smoke --db /tmp/m.sqlite --blob-dir /tmp/m-blobs

bin/media.mjs is the only executable entry (it owns process.exit). src/cli.ts exports runCli(argv) → exit code and must stay free of import-time side effects: it is bundled into server builds via the package entry, where a “run if main” guard fired and exited the admin server (solution; guarded by tests/cli-import.spec.ts).

Boundaries