@kerf-js/media 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ravonus
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11
+ Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,489 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://github.com/Ravonus/kerf">
3
+ <img src="https://raw.githubusercontent.com/Ravonus/kerf/main/site/public/logo.svg" width="88" height="88" alt="Kerf">
4
+ </a>
5
+ </p>
2
6
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
7
+ <h1 align="center">@kerf-js/media</h1>
8
+
9
+ <p align="center">
10
+ <strong>Images that arrive at their size: AVIF plus a fallback, a width ladder, a placeholder, and quality measured per image.</strong><br>
11
+ One plugin encodes <code>?media</code> imports at build time, serves uploads at run time, and checks every <code>&lt;img&gt;</code> and <code>&lt;video&gt;</code> you write.
12
+ </p>
13
+
14
+ <p align="center">
15
+ <a href="https://www.npmjs.com/package/@kerf-js/media"><img src="https://img.shields.io/npm/v/@kerf-js/media?color=145c3c&label=npm" alt="npm version"></a>
16
+ <a href="https://github.com/Ravonus/kerf/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-145c3c" alt="MIT license"></a>
17
+ <a href="https://github.com/Ravonus/kerf/actions"><img src="https://img.shields.io/github/actions/workflow/status/Ravonus/kerf/quality.yml?branch=main&label=checks" alt="checks"></a>
18
+ </p>
19
+
20
+ <p align="center">
21
+ <a href="#quick-start">Quick start</a> ·
22
+ <a href="https://github.com/Ravonus/kerf/tree/main/docs">Docs</a> ·
23
+ <a href="https://github.com/Ravonus/kerf/tree/main/examples">Examples</a> ·
24
+ <a href="https://github.com/Ravonus/kerf/blob/main/CHANGELOG.md">Changelog</a> ·
25
+ <a href="https://github.com/Ravonus/kerf">GitHub</a>
26
+ </p>
27
+
28
+ > [!IMPORTANT]
29
+ > **Early release (0.1.x).** APIs can change between minor versions. Pin the version and read the
30
+ > [changelog](https://github.com/Ravonus/kerf/blob/main/CHANGELOG.md) before you upgrade.
31
+
32
+ Kerf's `<Media>` component (from `@kerf-js/core/media`) renders a record: intrinsic width and height, the files to pick
33
+ from, a placeholder. This plugin is what makes those records. Without it, a `?media` import reads the size from the
34
+ file header and serves the original. With it, the build resizes and re-encodes every image with
35
+ [sharp](https://sharp.pixelplumbing.com/), cleans SVGs with [SVGO](https://svgo.dev/), and the server does the same for
36
+ files your users upload. It also adds the `M` diagnostics to `kerf check`, so a raw `<img>` without a size or an
37
+ `alt` is caught before it ships.
38
+
39
+ ## Highlights
40
+
41
+ - **AVIF first, a compatible fallback last.** Efficient formats (`avif` by default, `webp` on request) go in front of a
42
+ fallback that follows the source: JPEG for photos, lossless PNG for graphics and anything with alpha.
43
+ - **Quality measured, not guessed.** With the `ssimulacra2` tool on `PATH`, each format is binary-searched (at most 5
44
+ encodes) to the lowest quality that scores at or above the target, 80 by default. Without it, fixed qualities are
45
+ used and the record says `quality: 'fixed'`.
46
+ - **A width ladder.** 320, 640, 960, 1280, 1920 and 2560 px by default, capped at the source's own width, so the browser
47
+ picks the smallest file that is sharp enough.
48
+ - **Placeholders.** A dominant colour and a 16 px WebP data URL, so the box is filled before the image paints.
49
+ - **Uploads on the same path.** `ctx.media.ingest(file)` stores the original under a hash of its bytes and returns the
50
+ same record shape; each size is encoded once, on first request, and cached for a year.
51
+ - **Unsafe SVGs refused.** An SVG with `<script>`, `<foreignObject>`, `on*=` handlers, an external `href`, `url()` or
52
+ `@import` is neither optimised nor stored (M012).
53
+ - **Video, audio and GIFs** when [`@kerf-js/media-ffmpeg`](https://www.npmjs.com/package/@kerf-js/media-ffmpeg) <sup>[source](https://github.com/Ravonus/kerf/tree/main/packages/media-ffmpeg)</sup>
54
+ is also installed: an AV1/H.264 ladder with a poster, Opus and AAC, and GIFs turned into video when that saves 15%.
55
+ - **Cached by content.** Build output is keyed by the bytes, the options, the encoder versions and a format version
56
+ under `.kerf/cache/media`, so restarts and rebuilds don't re-encode.
57
+
58
+ ## Contents
59
+
60
+ - [Install](#install)
61
+ - [Quick start](#quick-start)
62
+ - [How it plugs into Kerf](#how-it-plugs-into-kerf)
63
+ - [Options](#options)
64
+ - [Images at build time](#images-at-build-time)
65
+ - [Uploads and the media route](#uploads-and-the-media-route)
66
+ - [Video, audio and animated GIFs](#video-audio-and-animated-gifs)
67
+ - [The `encoder` modes](#the-encoder-modes)
68
+ - [Diagnostics](#diagnostics)
69
+ - [API reference](#api-reference)
70
+ - [Recipes](#recipes)
71
+ - [Limits](#limits)
72
+ - [Troubleshooting](#troubleshooting)
73
+ - [Related packages](#related-packages)
74
+
75
+ ## Install
76
+
77
+ ```bash
78
+ # npm
79
+ npm install @kerf-js/media
80
+
81
+ # pnpm
82
+ pnpm add @kerf-js/media
83
+
84
+ # bun
85
+ bun add @kerf-js/media
86
+ ```
87
+
88
+ Or let the `kerf` CLI install it and add it to `kerf.config.ts` in one step:
89
+
90
+ ```bash
91
+ npx kerf add media
92
+ ```
93
+
94
+ The `landing` template (`--template landing`) already has it in its dependencies and its `kerf.config.ts`; the other templates and a
95
+ plain new app don't.
96
+
97
+ `kerf add media` installs the package and writes this into `kerf.config.ts` (the package has no `/plugin` entry, so
98
+ the import is from the main entry, by its named export):
99
+
100
+ ```ts
101
+ import { media } from '@kerf-js/media'
102
+ ```
103
+
104
+ **What it needs**
105
+
106
+ | Need | Why |
107
+ | --- | --- |
108
+ | Node 24 or later | `engines` in package.json |
109
+ | `sharp` (a dependency of this package) | Every raster encode. For the media route, the **app** needs `sharp` in its own dependencies so the built server can load it; a build without it warns with M017. |
110
+ | `ssimulacra2` on `PATH` (optional) | The quality search. It's the SSIMULACRA2 tool from libjxl. Without it, fixed qualities are used. |
111
+ | A disk that outlives deploys (for uploads) | The media route stores files in `.kerf/media`, or `KERF_MEDIA_DIR`. |
112
+ | `@kerf-js/media-ffmpeg` and ffmpeg (optional) | Video, audio, and GIF-to-video. |
113
+
114
+ ## Quick start
115
+
116
+ ```ts
117
+ // kerf.config.ts
118
+ import { defineConfig } from '@kerf-js/core/config'
119
+ import { media } from '@kerf-js/media'
120
+
121
+ export default defineConfig({
122
+ plugins: [media()],
123
+ })
124
+ ```
125
+
126
+ ```tsx
127
+ // src/routes/index.tsx
128
+ import { Media } from '@kerf-js/core/media'
129
+ import hero from '../../assets/hero.jpg?media'
130
+
131
+ export default function Home() {
132
+ return (
133
+ <Media
134
+ src={hero}
135
+ alt="A lighthouse at dusk, its beam crossing low cloud"
136
+ priority
137
+ width="1/2"
138
+ />
139
+ )
140
+ }
141
+ ```
142
+
143
+ `hero` is a record, not a URL: `width`, `height`, `sources` (an AVIF `srcset` and a JPEG one), `dominant` and
144
+ `placeholder`. `<Media>` renders it with its final box size, the placeholder behind it, and `srcset`/`sizes` from
145
+ `width`. `priority` loads the one hero image eagerly; everything else is lazy.
146
+
147
+ ## How it plugs into Kerf
148
+
149
+ `media()` is a plugin (namespace `M`) that provides two slots and a check hook:
150
+
151
+ | Slot / hook | Side | Module | What it does |
152
+ | --- | --- | --- | --- |
153
+ | `media.build@1` | build | `src/build.mjs` → `createMediaBuild` | `@kerf-js/core/vite` calls it for each `?media` import (and `?media&audio=…`). |
154
+ | `media.server@1` | server | `@kerf-js/media/server` → `createMediaServer` | `@kerf-js/start` uses it for `ctx.media.ingest` and the `/_kerf/m/…` route. |
155
+ | `check` | `kerf check` | `src/check.mjs` → `checkMedia` | Runs over `**/*.{tsx,jsx}` and reports M001–M013 and M016. |
156
+ | `media.encode@1` (consumer) | build, server | provided by `@kerf-js/media-ffmpeg` | Video, audio and animated GIFs. Without a provider, a video import is P101. |
157
+
158
+ It declares these permissions: read media files (`png`, `jpg`, `gif`, `webp`, `avif`, `svg` and common video/audio
159
+ extensions), the `KERF_MEDIA_DIR` environment variable, spawning `ssimulacra2`, and a native addon (sharp). It also
160
+ contributes agent notes and a catalog entry for `<Media>`.
161
+
162
+ Options are validated when the config loads. An unknown key or a bad value is **P115**, with the option's path (for
163
+ example `formats.0` or `quality.target`).
164
+
165
+ ## Options
166
+
167
+ All options are optional. `media()` with none is the configuration the defaults below describe.
168
+
169
+ | Option | Type | Default | What it does |
170
+ | --- | --- | --- | --- |
171
+ | `formats` | `('avif' \| 'webp')[]` | `['avif']` | Efficient formats placed before the fallback. The fallback follows the source and isn't listed here. |
172
+ | `widths` | `number[]` | `[320, 640, 960, 1280, 1920, 2560]` | The width ladder, sorted for you. The largest also caps the output width. |
173
+ | `quality.target` | `number` (1–100) | `80` | The SSIMULACRA2 score each format is searched to. 80 is about visually lossless at normal viewing. |
174
+ | `quality.scorer` | `string` | `'ssimulacra2'` | The scorer command, or `'none'` to use fixed qualities. |
175
+ | `placeholder` | `boolean` · `'inline'` · `'file'` | `true` | Adds `dominant` (a `#rrggbb` colour) and `placeholder`, a 16 px WebP. `true` or `'inline'`: a `data:` URL. `'file'`: its own hashed file, for a CSP without `data:` in `img-src`. `false`: neither. |
176
+ | `gifLimit` | `number` (bytes) | `262144` (256 KB) | A GIF over this is M004, at build and in `kerf check`. |
177
+ | `encoder` | `'off' \| 'compatible' \| 'server'` | `'off'` | See [The `encoder` modes](#the-encoder-modes). |
178
+ | `swap` | `'intent' \| 'idle' \| 'never'` | `'intent'` | When the compatible copy swaps in. Only valid with `encoder: 'compatible'`. |
179
+ | `video.codecs` | `('av1' \| 'vp9' \| 'hevc')[]` | `['av1']` | Efficient video codecs next to H.264, which is always there. |
180
+ | `video.widths` | `number[]` | `[640, 960, 1280, 1920]` | The video ladder. |
181
+ | `gif.toVideo` | `'auto' \| 'never'` | `'auto'` | `'never'` keeps animated GIFs as GIFs. |
182
+ | `gif.keepUnder` | `number` (bytes) | `8192` | A GIF under this stays a GIF. |
183
+ | `server.dir` | `string` | `'.kerf/media'` | The upload store, relative to the app. `KERF_MEDIA_DIR` overrides it. |
184
+ | `server.maxBytes` | `number` | `20971520` (20 MB) | The largest upload `ingest` accepts (M018 above it). |
185
+
186
+ Fixed qualities, used when no scorer runs: AVIF 50, WebP 75, JPEG 78. PNG is lossless at compression level 9.
187
+
188
+ ## Images at build time
189
+
190
+ For each `?media` import the build provider:
191
+
192
+ 1. Reads the image with sharp and applies EXIF orientation, so a portrait shot stored sideways comes out upright with
193
+ its width and height swapped.
194
+ 2. Builds the ladder: every configured width below the source's width, plus the source width capped at the largest
195
+ rung. A 1000 px image with the default ladder gets 320, 640, 960 and 1000.
196
+ 3. Picks formats: the configured efficient formats, then the fallback. JPEG, AVIF, HEIF, TIFF and opaque WebP sources
197
+ count as photos (JPEG fallback); everything else, and WebP with alpha, is a graphic (PNG fallback).
198
+ `?media&photo` encodes an opaque lossless source of photographic pixels (a painted or rendered PNG) as a photo.
199
+ 4. Searches quality once per format at the largest rung, between AVIF 20–90 or WebP/JPEG 40–95.
200
+ 5. Encodes every format at every width and names each file `<stem>-<width>-<hash>.<ext>`.
201
+ 6. Adds the placeholder and dominant colour.
202
+
203
+ The record looks like this:
204
+
205
+ ```ts
206
+ {
207
+ // 'graphic' for PNG-like sources, 'vector' for SVG
208
+ kind: 'photo',
209
+ src: 'hero-1280-3f9c0a1b.jpg', // the largest fallback file
210
+ width: 1280, height: 853,
211
+ type: 'image/jpeg',
212
+ sources: [
213
+ { type: 'image/avif', srcset: 'hero-320-….avif 320w, …' },
214
+ { type: 'image/jpeg', srcset: 'hero-320-….jpg 320w, …' },
215
+ ],
216
+ name: 'hero.jpg',
217
+ quality: 'ssimulacra2', // or 'fixed'
218
+ qualities: { avif: 52, jpeg: 81 },
219
+ dominant: '#6b7f5a',
220
+ placeholder: 'data:image/webp;base64,…',
221
+ }
222
+ ```
223
+
224
+ **SVG** is checked for unsafe content (M012), must have `width`/`height` or a `viewBox` (M001 otherwise), and goes
225
+ through SVGO with `multipass`. It ships as one file with `kind: 'vector'`.
226
+
227
+ **Animated GIFs** ship as they are unless a `media.encode` provider can turn them into something smaller (see below).
228
+ A GIF over `gifLimit` that stays a GIF is M004.
229
+
230
+ ## Uploads and the media route
231
+
232
+ `createMediaServer(options).at(root, encode)` is the store `@kerf-js/start` gives your server functions as `ctx.media`:
233
+
234
+ ```ts
235
+ // src/server/photos.ts
236
+ import { mutation } from '@kerf-js/start'
237
+ import { z } from '@kerf-js/start/media'
238
+
239
+ export const uploadPhoto = mutation({
240
+ input: z.object({
241
+ photo: z
242
+ .file()
243
+ .max(8 * 1024 * 1024)
244
+ .mime(['image/jpeg', 'image/png', 'image/webp']),
245
+ alt: z.string().trim().min(1).max(200),
246
+ }),
247
+ auth: 'user',
248
+ run: async ({ input, ctx }) => {
249
+ const image = await ctx.media.ingest(input.photo)
250
+ // store `image` (a MediaAsset) in a JSON column, render it with
251
+ // <Media src={image} alt={…} />
252
+ return image
253
+ },
254
+ })
255
+ ```
256
+
257
+ What `ingest(bytes, { name })` does:
258
+
259
+ - Refuses files over `server.maxBytes` with **M018**.
260
+ - Hashes the bytes (SHA-256, first 32 hex digits). The same bytes are stored once; a second upload returns the stored
261
+ record with its own `name`.
262
+ - Sniffs video and audio from the first bytes, not the file name. Those need `@kerf-js/media-ffmpeg`, or they are
263
+ M018 naming the fix.
264
+ - Refuses an unsafe SVG with **M012**, and anything sharp can't read with **M018**.
265
+ - Writes `source` and `meta.json` into `<dir>/<hash>/` (`meta.json` last, through a rename, so it only exists when the
266
+ original is whole) and returns a record whose URLs are `/_kerf/m/<hash>/<width>.auto`.
267
+
268
+ Nothing is resized at upload. The route `/_kerf/m/<hash>/<width>.<format>` encodes a size on its first request, writes
269
+ it next to the original, and reads it from disk afterwards. Concurrent requests for the same size share one encode.
270
+
271
+ | Rule | Detail |
272
+ | --- | --- |
273
+ | Formats | `auto` picks the first of `formats` the `Accept` header names with `q > 0`, in the config's order; a wildcard promises nothing, so it falls back to JPEG or PNG. `avif`, `webp`, `jpg` and `png` can be asked for directly when configured or the fallback. |
274
+ | Widths | Only widths on the record's ladder. Anything else, or a malformed hash, is a 404. |
275
+ | Headers | `cache-control: public, max-age=31536000, immutable`, an `ETag`, `x-content-type-options: nosniff`, `vary: Accept` when negotiated, and a `sandbox` content security policy for SVG. |
276
+ | Quality | Fixed qualities: no SSIMULACRA2 search at run time. |
277
+
278
+ ## Video, audio and animated GIFs
279
+
280
+ These need a `media.encode@1` provider. Add [`@kerf-js/media-ffmpeg`](https://www.npmjs.com/package/@kerf-js/media-ffmpeg) <sup>[source](https://github.com/Ravonus/kerf/tree/main/packages/media-ffmpeg)</sup>
281
+ next to `media()`:
282
+
283
+ ```ts
284
+ import { defineConfig } from '@kerf-js/core/config'
285
+ import { media } from '@kerf-js/media'
286
+ import { mediaFfmpeg } from '@kerf-js/media-ffmpeg'
287
+
288
+ export default defineConfig({
289
+ plugins: [
290
+ media({ video: { codecs: ['av1', 'vp9'] } }),
291
+ mediaFfmpeg(),
292
+ ],
293
+ })
294
+ ```
295
+
296
+ **Video** (`.mp4`, `.m4v`, `.mov`, `.webm`, `.mkv`, `.ogv`):
297
+
298
+ - An H.264 ladder is always built, plus each configured efficient codec. An efficient set ships only if it is at least
299
+ 15% smaller than the H.264 one; winners go first, H.264 last.
300
+ - With a scorer, a CRF search (at most 4 encodes) at the top width samples five frames: the mean SSIMULACRA2 score must
301
+ reach the target and the worst frame must reach the target minus 5.
302
+ - An H.264 `yuv420p` source already at the top width, with AAC or no audio, is remuxed at that rung instead of
303
+ re-encoded.
304
+ - A WebP poster frame is taken at `min(1 s, duration / 10)`, with the placeholder from the same frame.
305
+ - HDR or over-8-bit sources come out 8-bit SDR, with **M015**.
306
+
307
+ **Audio** (`.mp3`, `.wav`, `.flac`, `.ogg`, `.oga`, `.opus`, `.m4a`, `.aac`): Opus and AAC. A source already in that
308
+ codec and under its bitrate (96 kbps Opus, 128 kbps AAC) is remuxed, not re-encoded.
309
+
310
+ **Animated GIFs** become video when that is a real saving. A GIF stays a GIF when it is under `gif.keepUnder`, has
311
+ fewer than 4 frames, when nothing comes out at least 15% smaller, or with `gif.toVideo: 'never'`. A GIF with
312
+ transparency becomes an animated WebP instead (H.264 has no alpha), when that is 15% smaller.
313
+
314
+ **Muxing a sound into a loop:** `import loop from './loop.gif?media&audio=./beat.opus'` loops the GIF for the length of
315
+ the sound.
316
+
317
+ Uploaded video and audio use fixed CRFs and a queue: `ingest` returns the record at once, and the sizes encode one at a
318
+ time. Until a size exists, its URL serves the original with `cache-control: no-store` if browsers can play it, and
319
+ otherwise waits for that encode. A restart loses nothing: the first request for a missing size encodes it.
320
+
321
+ ## The `encoder` modes
322
+
323
+ | Mode | What happens |
324
+ | --- | --- |
325
+ | `'off'` (default) | Everything is encoded at build time; the files ship with the build. |
326
+ | `'compatible'` | The page shows the efficient file, and a compatible copy swaps in so a saved file opens anywhere. For images the copy is the fallback ladder that already exists, so it adds 0 KB. For video it is the H.264 top rung; for a GIF turned video, the original GIF. **M014** (info) says what each asset adds. `swap` picks when: `'intent'` (right-click, long-press or drag), `'idle'`, or `'never'`. |
327
+ | `'server'` | Image `?media` imports are not encoded at build time. The build stores each original in the media store and the record points at `/_kerf/m/…`, so the server encodes sizes on first request. Video and audio are still built. Needs a running server and a store that reaches it. |
328
+
329
+ ## Diagnostics
330
+
331
+ `kerf docs M001` (or any code) prints the full entry. The `by` column says who reports it.
332
+
333
+ | Code | Severity | Reported by | Catches |
334
+ | --- | --- | --- | --- |
335
+ | M001 | error | `kerf check`, build | A raw `<img>`/`<video>` with no `width`/`height` or `aspect-ratio` outside a `<Boundary>`; an SVG with no size. The check inserts the file's size for an imported file. |
336
+ | M002 | error | `kerf check` | An image rendered through `?url` or a string path to a project file. The fix rewrites the import to `?media`. |
337
+ | M003 | warning | `kerf check` | A raw `<img>` whose file is wider than its `width` × 2 × 1.25. |
338
+ | M004 | warning | `kerf check`, build | A GIF over `gifLimit` rendered raw, or shipped as a GIF. |
339
+ | M005 | error | `kerf check` | `<video autoplay>` without `muted` (autofix). |
340
+ | M006 | warning | `kerf check` | `<video>` without `poster`. |
341
+ | M007 | error | `kerf check` | Missing `alt`, `<Media alt="">` without `decorative`, or `alt` equal to the file name. |
342
+ | M008 | warning | `kerf check` | A route's first media is `loading="lazy"`, or `priority` media is lazy (autofix for the second). |
343
+ | M009 | warning | `kerf check` | More than 2 `priority` media in one route (autofix). |
344
+ | M010 | warning | `kerf check` | A `priority` `<Media>` with no `width` or `sizes`. |
345
+ | M011 | warning | `kerf check` | `<video autoplay loop>` without `controls`, or a GIF in a raw `<img>` (WCAG 2.2.2). |
346
+ | M012 | error | `kerf check`, build, `ingest` | An SVG with active content or external references. |
347
+ | M013 | warning | `kerf check` | A `public/` file referenced by string. |
348
+ | M014 | info | build | What `encoder: 'compatible'` adds. |
349
+ | M015 | warning | build | An HDR or over-8-bit video that comes out 8-bit SDR. |
350
+ | M016 | warning | `kerf check` | `<Media src>` given a string. |
351
+ | M017 | error | `@kerf-js/start` | `ctx.media` or a `/_kerf/m/` URL with no `media.server` provider, or `sharp` missing from the app's dependencies. |
352
+ | M018 | error | `ingest`, build | An upload that isn't a readable image or is over `maxBytes` (422); a video with no video track; a video upload with no encoder. |
353
+ | M019 | error/warning | `@kerf-js/media-ffmpeg` | ffmpeg missing, not the pinned binary, or without an encoder. |
354
+
355
+ ## API reference
356
+
357
+ | Export | Entry | What it is |
358
+ | --- | --- | --- |
359
+ | `media(options?)` | `@kerf-js/media` | The plugin for `kerf.config.ts`. Typed by `MediaOptions`. |
360
+ | `MediaOptions` | `@kerf-js/media` (type) | The options in the table above. |
361
+ | `createMediaBuild(options?)` | `@kerf-js/media/build` | The `media.build@1` provider: `{ build(source, ctx) }` returns `{ asset, files, diagnostics? }`. |
362
+ | `findScorer(name)` | `@kerf-js/media/build` | The scorer command if it runs, else `null`. Cached per process. |
363
+ | `DEFAULTS`, `FIXED`, `MIME`, `encoders`, `hex`, `isPhoto` | `@kerf-js/media/build` | Shared defaults, fixed qualities, content types, the sharp encoder calls and helpers. |
364
+ | `createMediaServer(options?)` | `@kerf-js/media/server` | The `media.server@1` provider: `.at(root, encode)` returns `{ ingest, serve, settled }`. |
365
+ | `negotiate(accept, formats, fallback)` | `@kerf-js/media/server` | Picks the format for `auto` from an `Accept` header. |
366
+
367
+ <details>
368
+ <summary><code>createMediaBuild().build(source, ctx)</code></summary>
369
+
370
+ `source` is `{ file, bytes, audio? }`: the absolute path, the bytes, and an optional audio file to mux in. `ctx` is
371
+ `{ cacheDir, root, encode }`, where `encode` maps `media.encode` keys (`video/h264`, `audio/opus`, …) to providers.
372
+ Core's Vite plugin passes `.kerf/cache/media` as `cacheDir`. The result's `files` are `{ name, bytes }` for the build to
373
+ emit; a diagnostic with `severity: 'error'` fails that import.
374
+
375
+ </details>
376
+
377
+ <details>
378
+ <summary><code>createMediaServer().at(root, encode)</code></summary>
379
+
380
+ - `ingest(bytes, { name? })`: stores an original and returns a `MediaAsset`. Throws an `Error` with `code` set to
381
+ `M012` or `M018` when it refuses.
382
+ - `serve({ hash, width, format, accept })`: returns `{ bytes, type, width, format, negotiated, temporary? }`, or `null`
383
+ for a 404.
384
+ - `settled()`: resolves when queued video and audio encodes are done (used by tests).
385
+
386
+ The store is `KERF_MEDIA_DIR` when set, else `server.dir` resolved against `root`.
387
+
388
+ </details>
389
+
390
+ ## Recipes
391
+
392
+ **WebP as well as AVIF, and a smaller ladder**
393
+
394
+ ```ts
395
+ media({ formats: ['avif', 'webp'], widths: [480, 960, 1440] })
396
+ ```
397
+
398
+ **Fixed qualities on a CI machine without the scorer, on purpose**
399
+
400
+ ```ts
401
+ media({ quality: { scorer: 'none' } })
402
+ ```
403
+
404
+ **A strict CSP: the placeholder as a file**
405
+
406
+ ```ts
407
+ media({ placeholder: 'file' })
408
+ ```
409
+
410
+ The default placeholder is a `data:` URL, which `img-src 'self'` blocks.
411
+ With `'file'` each image and video poster gets a `name-placeholder-<hash>.webp`
412
+ of a few hundred bytes next to its ladder, and the record points at it.
413
+ Uploads through the media route still inline theirs.
414
+
415
+ **Uploads on a mounted volume**
416
+
417
+ ```bash
418
+ KERF_MEDIA_DIR=/data/media node .output/server/index.mjs
419
+ ```
420
+
421
+ On `kerf deploy` targets with a volume, uploads go to `.data/media` through `KERF_MEDIA_DIR`.
422
+
423
+ **A raw `<img>` that the check flags, and the fix**
424
+
425
+ ```tsx
426
+ // M001, M002: no size, and the file bypasses the optimiser
427
+ import logo from './logo.png?url'
428
+ export const Logo = () => <img src={logo} alt="Acme" />
429
+ ```
430
+
431
+ ```tsx
432
+ import { Media } from '@kerf-js/core/media'
433
+ import logo from './logo.png?media'
434
+ export const Logo = () => (
435
+ <Media
436
+ src={logo}
437
+ alt="Acme"
438
+ width="120px"
439
+ />
440
+ )
441
+ ```
442
+
443
+ ## Limits
444
+
445
+ - Image input is PNG, JPEG, GIF, WebP, AVIF and SVG (what `ingest` names when it refuses a file). Efficient output
446
+ formats are AVIF and WebP only.
447
+ - The quality search runs at build time only. Uploaded images use fixed qualities.
448
+ - The upload store is a directory on the server's disk. Function hosts without a persistent disk can't keep uploads
449
+ (`kerf check` reports E003 for a deploy target). `cdn.images` (Cloudinary) is checked but not wired yet (E014).
450
+ - Video, audio and GIF-to-video need ffmpeg through `@kerf-js/media-ffmpeg`. Without it a video `?media` import
451
+ fails with P101 and a video upload with M018.
452
+ - The build cache under `.kerf/cache/media` grows with every distinct input; delete it to reclaim space.
453
+
454
+ ## Troubleshooting
455
+
456
+ | Symptom | Cause and fix |
457
+ | --- | --- |
458
+ | `quality: 'fixed'` on every record | `ssimulacra2` isn't on `PATH`. Install libjxl's tool, or set `quality.scorer` to its path. |
459
+ | `P115` when the config loads | A bad option. The message names the path, such as `formats.0` (`jxl` isn't supported) or `quality.target` (must be 1–100). `swap` without `encoder: 'compatible'` is also P115. |
460
+ | `M017` in the server log | No `media()` in `plugins`, or the app doesn't list `sharp` in its own dependencies. |
461
+ | `M018` on upload | Over `server.maxBytes` (20 MB by default), not an image sharp can read, or a video with no encoder installed. |
462
+ | `P101 … needs media.encode` | A video or audio `?media` import with no `mediaFfmpeg()` in `plugins`. |
463
+ | CSP reports a blocked `data:image/webp` | The inline placeholder. Set `placeholder: 'file'`, or add `data:` to `img-src`. |
464
+ | Uploaded images vanish after a deploy | The store isn't on persistent storage. Point `KERF_MEDIA_DIR` at a volume. |
465
+
466
+ ## Related packages
467
+
468
+ | Package | What it is |
469
+ | --- | --- |
470
+ | [`@kerf-js/core`](https://www.npmjs.com/package/@kerf-js/core) | `<Media>`, `timeline()` and the `?media` import (`@kerf-js/core/media`). |
471
+ | [`@kerf-js/start`](https://www.npmjs.com/package/@kerf-js/start) | `ctx.media`, `z.media()` and the `/_kerf/m/` route. |
472
+ | [`@kerf-js/media-ffmpeg`](https://www.npmjs.com/package/@kerf-js/media-ffmpeg) | The `media.encode@1` provider: video and audio through ffmpeg. |
473
+ | [`@kerf-js/cli`](https://www.npmjs.com/package/@kerf-js/cli) | `kerf add media`, `kerf check` and `kerf docs M001`. |
474
+ | [`@kerf-js/text`](https://www.npmjs.com/package/@kerf-js/text) | The other asset plugin: fonts and text measurement. |
475
+
476
+ ## Contributing
477
+
478
+ See [CONTRIBUTING.md](https://github.com/Ravonus/kerf/blob/main/CONTRIBUTING.md). From the repository root:
479
+
480
+ ```bash
481
+ pnpm --filter @kerf-js/media test
482
+ ```
483
+
484
+ The video tests skip where ffmpeg isn't on `PATH`. `test/save.headful.mjs` is the `encoder: 'compatible'` save-as gate in headed
485
+ browsers; it needs Linux, Xvfb and `xdotool`, and its header says how to run it.
486
+
487
+ ## License
488
+
489
+ [MIT](https://github.com/Ravonus/kerf/blob/main/LICENSE)
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@kerf-js/media",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "@kerf-js/media: the media.build@1 provider (sharp + SVGO: AVIF plus a compatible fallback, an SSIMULACRA2 quality search, width ladders, placeholders), the media.server@1 route provider, and M001–M018",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Ravonus/kerf.git",
9
+ "directory": "packages/media"
10
+ },
11
+ "homepage": "https://github.com/Ravonus/kerf/tree/main/packages/media#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/Ravonus/kerf/issues"
14
+ },
15
+ "type": "module",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./src/index.d.ts",
19
+ "default": "./src/index.mjs"
20
+ },
21
+ "./build": "./src/build.mjs",
22
+ "./server": "./src/server.mjs"
23
+ },
24
+ "dependencies": {
25
+ "sharp": "0.35.5",
26
+ "svgo": "4.1.0"
27
+ },
28
+ "peerDependencies": {
29
+ "@kerf-js/core": "^0.1.0"
30
+ },
31
+ "engines": {
32
+ "node": ">=24"
33
+ },
34
+ "keywords": [
35
+ "kerf"
36
+ ],
37
+ "files": [
38
+ "src",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public"
44
+ }
6
45
  }