@tgmc/image
Node / Nitro / Lambda image library for TGMC portfolio apps.
Package README: packages/image/README.md.
Role
| Concern | Owner |
|---|---|
| Raster brightness / contrast / saturation / grayscale / chroma-key | sharp in this package |
| CSS color parse, HSL/hex, dominant polish | @tgmc/theme Color / Color.enhance |
| Cache keys | @tgmc/utilities sha256Hex |
| Aspect ratio meta (SSR + client) | @tgmc/utilities/universal aspectRatio |
LQIP data: URLs |
Local helpers in this package (toLqipDataUrl) — not utilities yet |
| Overlay ink vs dominant swatch | @tgmc/theme pickContrastingInk (UI) |
Sass theme-* color-fns |
Vue SCSS only — never imported into this Node package |
CDN upload, invalidation, and asset inventory belong to @tgmc/media + @tgmc/media-aws. This package returns relative paths and ImageAsset metadata and is composed by @tgmc/media for image child materialize.
Env gate: Nitro /api/image/* handlers call assertImageApiEnabled() and only run when raw SYS_ENV is exactly local, development, or legacy remote. Empty, missing, typo, test, and production return 404 (fail-closed — does not use normalizeSysEnv, which defaults unknown values to local).
API surface
import { ingestImage, transformImage, ImageAsset, enhancePixels, applyTransparency, resizeImage } from '@tgmc/image';
ingestImage(input, options?)→ImageAssetwith thumb (optional disk write), LQIP data URL, polished dominant color, dimensionstransformImage(input, ops[], options?)→{ buffer, contentType, meta }-
Ops: colormonotransparencyresizecropformat normalizeTransformOp(raw, { allowFormat? })validates one untrusted op and returns a clean copy: unknown and absent fields dropped, edges clamped toMAX_EDGE_PX, crop offsets rounded and floored at 0,formatquality clamped; color factors outsideCOLOR_OP_MIN–COLOR_OP_MAXand missing numbers throwTransformOpError(stable messages).core/web’s/api/image(formatops refused) and@tgmc/media’sparseRecipe(formatallowed) both use it.- Rejected inputs throw
ImageInputError(reason:'bytes'overMAX_BYTES,'dimensions'overMAX_EDGE_PX,'unreadable'not decodable), thrown byassertSafeImageInput,assertWithinByteLimitandtransformImage. The message texts are stable (core/webmatches them). Hosts treat it as a client error:@tgmc/media’smediaErrorToHttpmaps it to 413 (bytes) or 422.
Sanitize media before it is stored
@tgmc/image/sanitize (a separate subpath, not re-exported from the package entry, so svgo, pdf-lib and the ffmpeg call never reach the Nitro / Lambda bundle by accident; guarded by tests/entry-boundary.spec.ts) strips third-party identifiers before bytes are hashed and stored. Output is deterministic for the same input, options and tool versions. @tgmc/image/sanitize-web is the svgo-only slice for the web server: rasters (sharp) and SVG (svgo), never pdf-lib or ffmpeg (also guarded by the entry-boundary test).
svgo, pdf-lib and ffmpeg-static are optional peerDependencies (svgo and pdf-lib are also devDependencies for the package tests; the root package.json provides all three to the scripts, ffmpeg-static as an optional dependency). The MediaWorker Lambda that scripts/sam-build.mjs stages from @tgmc/media-aws → @tgmc/media → @tgmc/image runtime dependencies therefore never installs them; the entry-boundary test also checks the package.json. The web app needs svgo at run time, so @tgmc/media-nuxt and @tgmc/web declare it as a dependency and Nitro traces it into the server output.
import {
probeMedia,
resolveFfmpegPath,
sanitizeFormatForFilename,
sanitizeMedia,
sniffSanitizeFormat,
} from '@tgmc/image/sanitize';
const format = sniffSanitizeFormat(bytes) ?? sanitizeFormatForFilename(filename);
const ffmpegPath = format === 'mp4' ? (resolveFfmpegPath() ?? undefined) : undefined;
const clean = await sanitizeMedia(bytes, { format, document: { title, author, subject }, ffmpegPath });
const { width, height, durationSec } = await probeMedia(clean, format);
resolveFfmpegPath() returns FFMPEG_PATH, else ffmpeg when it runs from PATH, else the optional ffmpeg-static binary (loaded with createRequire at call time; its FFMPEG_BIN variable overrides that binary), else null; sanitizeMedia for an MP4 without one throws FFMPEG_NOT_FOUND, which says how to provide it. ffmpeg (GPL-3.0-or-later as shipped by ffmpeg-static) runs as a separate process and is never bundled or redistributed.
| Format | What it does |
|---|---|
| JPEG / PNG / WebP / AVIF / GIF | sharp re-encode with EXIF orientation applied; EXIF, XMP, IPTC and PNG text / C2PA chunks dropped; the ICC profile is kept; GIF / WebP animation kept. JPEG / WebP / AVIF are lossy re-encodes (q92 4:4:4 / q90 / q70); PNG stays lossless. |
| SVG | svgo: doctype, XML declaration, comments, <metadata> and editor namespaces (Inkscape, Sodipodi, Figma data-*) removed; ids nothing references removed; <title> / <desc> kept. Also removes <script>, every on* attribute (any case or prefix), <foreignObject>, elements in a non-SVG namespace, xml:base, href and on* animations (<set> / <animate> targeting them), processing instructions at any depth, any href / xlink:href that is not #fragment or a png / jpeg / gif / webp / avif data: URL, and any <style> element or style / presentation attribute whose CSS (escapes decoded) has an @import, image-set() or a url() that is not #fragment or such a data: URL. |
pdf-lib: the Info dictionary is replaced by the given Title / Author / Subject only (Title required; a source Author / Subject with no replacement is removed), XMP /Metadata, /PieceInfo and unreachable objects removed, the trailer /ID dropped. Active content is removed too: /OpenAction, /AA, embedded files (/EF, the EmbeddedFiles name tree), the JavaScript name tree, AcroForm /XFA, unsafe /A and /Next actions (JavaScript, Launch, SubmitForm, ImportData, GoToR, GoToE, Rendition, RichMediaExecute, Sound, Movie, and URI actions to javascript: / data: / file:), and FileAttachment / RichMedia / Screen / Movie / Sound / 3D annotations. Every dictionary in the file is checked, indirect references (/S, /Subtype, /URI, /Next, /Annots) are resolved, and an unsafe action also loses its own /S, /JS and /URI however it is reached. Input over MAX_PDF_SANITIZE_BYTES (10 MiB) is refused before parsing (ImageInputError, reason bytes): pdf-lib parses every object in JS, so an object-dense file just under the cap (~60k objects) still takes ~10 s, with the event loop blocked for at most ~0.5 s at a time. The save writes 2000 objects per event-loop turn (pdf-lib’s default of 50 spent most of the time waiting between turns). |
|
| MP4 | ffmpeg remux (-c copy, no re-encode; -map 0:V skips attached cover pictures) with global and stream metadata, chapters and data streams dropped, bit-exact flags and +faststart. ffmpeg may read only local files as MOV / MP4 (-protocol_whitelist file -format_whitelist mov,mp4 -f mov, mp4RemuxArgs) and is killed after 120 s (MP4_SANITIZE_TIMEOUT_MS; timeoutMs option). Needs ffmpegPath (resolveFfmpegPath()). |
sniffSanitizeFormat(bytes) trusts magic bytes over the extension (a .png that is really a GIF stays animated). scanForIdentifiers(bytes, format) lists leftover metadata structures and IDENTIFIER_DENYLIST tokens (C2PA, XMP document ids, Adobe, Midjourney, DALL, openai, Figma, Inkscape, Sodipodi) in the metadata-bearing bytes; the tests assert it is empty after sanitizing. Known gap: the x264 encoder string inside the H.264 bitstream (SEI) survives a remux, because removing it means re-encoding.
Upload sanitizers. @tgmc/image/sanitize-core holds the pieces that need only sharp: sanitizeRaster, sniffSanitizeFormat / sanitizeFormatForFilename, scanForIdentifiers, findSvgActiveContent, sniffMarkup and createRasterUploadSanitizer() (JPEG / PNG / WebP / AVIF / GIF). findSvgActiveContent(bytes) scans the whole SVG text (numeric character references decoded) for what svgo would remove: doctype, processing instructions, <script>, <foreignObject>, event handlers, on* / href animations, xml:base, javascript: (tabs and newlines ignored) or external hrefs, unsafe CSS, with any XML prefix (a.b:script); and for markup that is not plain UTF-8: invalid UTF-8, a declared encoding other than UTF-8, a UTF-16 BOM or a C0 control character other than tab / LF / CR (SVG_ENCODING_PROBLEMS). It is the post-check after svgo, not a replacement for it: @tgmc/media refuses an SVG svgo leaves active, and one that is not plain UTF-8. sniffMarkup(bytes) says whether bytes start like SVG, HTML or other XML ('svg' | 'html' | 'xml' | null), so @tgmc/media can refuse markup posing as another type. It is safe for the web Nitro and the MediaWorker Lambda. @tgmc/image/sanitize-web adds createWebUploadSanitizer() (rasters and SVG) and sanitizeSvg (async: it imports svgo on its first call, not at module load, because the web Nitro bundle loads every static import at boot and svgo alone takes ~150 ms of a ~690 ms cold start; guarded by tests/sanitize-svg-lazy.spec.ts); @tgmc/image/sanitize adds createFullUploadSanitizer({ ffmpegPath }) for every format (SVG, PDF with the asset title, MP4). All three return an UploadSanitizer (supports(format), sanitize(bytes, { format, title? })), which @tgmc/media takes as MediaLibraryDeps.sanitize (media § Upload sanitizing).
Callers: the site media manifest and import (site media), the admin server (full sanitizer) and the web server (web sanitizer: rasters and SVG) for uploads.
Web wiring (core/web)
GET /api/image/transform?src=…&w=…&format=webp&quality=80&ops=[…]— on-demand variants- Query
format/qualityown the encode; nestedtype:"format"ops are rejected (400) -
Response headers: Content-Type,Cache-Control,X-Image-Cache(HITMISS), X-Image-Width/X-Image-Height - Disk cache under
.cache/image/with atomic writes +.meta.jsonsidecars for HIT dims
- Query
POST /api/image/ingest{ src, thumbLongEdge?, lqipLongEdge?, enhanceDominant? }— returns delivery DTO (thumbSrc,lqip,dominantColor, dims); thumb underpublic/i/_derived/UiImage— LQIP / dominant placeholder +NuxtImgfade-in (gallery + work cards + case-study detail rasters);sizes,widthsandformatpick a right-sized WebP candidate (site media § Responsive sizes and format)
Does not replace @nuxt/image / IPX for ordinary static assets.
Content LQIP metadata
Gallery exhibits and case-study media store optional lqip / dominantColor / aspectCss in Nuxt Content JSON (SSR-safe; no runtime sharp in test/prod).
Regenerate after adding rasters under core/web/public/i/:
npm run build --workspace=@tgmc/image
npm run content:enrich-images
# preview: npm run content:enrich-images -- --dry-run
Script: scripts/enrich-image-meta.mjs (dedupes by file path; also enriches video poster fields). Run it on a workstation and commit the JSON: GitHub Actions never run it (cicd.md § No media work in GitHub Actions). CD only copies the committed files under public/i, which stay there for good (owner decision 2026-10-17); the script stays in use.
Build / test
npx nx run @tgmc/image:build
npx nx run @tgmc/image:test