@softistx/alxia-media 0.0.0-stage → 0.12.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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +373 -2
  3. package/dist/body.d.ts +24 -0
  4. package/dist/body.d.ts.map +1 -0
  5. package/dist/bucket.d.ts +21 -0
  6. package/dist/bucket.d.ts.map +1 -0
  7. package/dist/checks.d.ts +11 -0
  8. package/dist/checks.d.ts.map +1 -0
  9. package/dist/chunks/index-8s779ve6.js +106 -0
  10. package/dist/chunks/index-8s779ve6.js.map +10 -0
  11. package/dist/headers.d.ts +19 -0
  12. package/dist/headers.d.ts.map +1 -0
  13. package/dist/image/index.d.ts +2 -0
  14. package/dist/image/index.d.ts.map +1 -0
  15. package/dist/image/index.js +199 -0
  16. package/dist/image/index.js.map +11 -0
  17. package/dist/image/peer.d.ts +14 -0
  18. package/dist/image/peer.d.ts.map +1 -0
  19. package/dist/image/rendition.d.ts +109 -0
  20. package/dist/image/rendition.d.ts.map +1 -0
  21. package/dist/index.d.ts +9 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +825 -0
  24. package/dist/index.js.map +22 -0
  25. package/dist/key.d.ts +40 -0
  26. package/dist/key.d.ts.map +1 -0
  27. package/dist/kind-callbacks.d.ts +28 -0
  28. package/dist/kind-callbacks.d.ts.map +1 -0
  29. package/dist/kind-check.d.ts +20 -0
  30. package/dist/kind-check.d.ts.map +1 -0
  31. package/dist/kind.d.ts +173 -0
  32. package/dist/kind.d.ts.map +1 -0
  33. package/dist/range.d.ts +17 -0
  34. package/dist/range.d.ts.map +1 -0
  35. package/dist/read.d.ts +11 -0
  36. package/dist/read.d.ts.map +1 -0
  37. package/dist/refusal.d.ts +90 -0
  38. package/dist/refusal.d.ts.map +1 -0
  39. package/dist/rendition.d.ts +94 -0
  40. package/dist/rendition.d.ts.map +1 -0
  41. package/dist/routes.d.ts +62 -0
  42. package/dist/routes.d.ts.map +1 -0
  43. package/dist/sniff.d.ts +16 -0
  44. package/dist/sniff.d.ts.map +1 -0
  45. package/dist/write.d.ts +42 -0
  46. package/dist/write.d.ts.map +1 -0
  47. package/docs/README.md +11 -0
  48. package/docs/guide.md +902 -0
  49. package/docs/roadmap.md +73 -0
  50. package/docs/troubleshooting.md +563 -0
  51. package/package.json +65 -5
package/docs/guide.md ADDED
@@ -0,0 +1,902 @@
1
+ # Guide
2
+
3
+ ## The idea
4
+
5
+ A browser never talks to the bucket. It asks your server, and your server
6
+ streams the object back:
7
+
8
+ ```
9
+ browser -> your server (@softistx/alxia-media routes) -> private bucket
10
+ ```
11
+
12
+ That removes a whole class of setup: no presigned URL to sign per read, no
13
+ public hostname for storage, no CORS rule on the bucket, no `img-src` for
14
+ another origin in your CSP. The cost is that file bytes cross your server,
15
+ which `@softistx/alxia-media` keeps cheap by streaming them in both directions.
16
+
17
+ A file is identified by its **key**, a UUID the upload answers. A record keeps
18
+ the key, never a URL.
19
+
20
+ ## Mounting the routes
21
+
22
+ ```ts
23
+ import { alxia } from '@softistx/alxia';
24
+ import { defineMediaKind, mediaRoutes } from '@softistx/alxia-media';
25
+ import { bindBucket, defineBucket } from '@softistx/s3';
26
+
27
+ interface Session {
28
+ readonly session: { userId: string; roles: readonly string[] } | null;
29
+ }
30
+
31
+ const bucket = bindBucket(
32
+ defineBucket({ bucket: 'media', key: (p: { key: string }) => p.key }),
33
+ { accessKeyId: 'id', secretAccessKey: 'secret', endpoint: 'http://s3:9000' },
34
+ );
35
+
36
+ const questionFiles = defineMediaKind<Session>({
37
+ name: 'question-files',
38
+ accept: ['image/png', 'image/jpeg', 'image/webp', 'audio/mpeg', 'application/pdf'],
39
+ maxBytes: 10 * 1024 * 1024,
40
+ authorizeWrite: ({ session }) => session?.roles.includes('editor') === true,
41
+ authorizeRead: ({ session }) => session !== null,
42
+ });
43
+
44
+ export const app = alxia()
45
+ .derive(({ request }) => ({ session: readSession(request) }))
46
+ .plugin(mediaRoutes([questionFiles], { bucket }));
47
+
48
+ declare function readSession(request: Request): Session['session'];
49
+ ```
50
+
51
+ The bucket is bound with a `key` function that returns the `key` it is given:
52
+ the routes choose the layout (`<kind>/<key>`) and pass their own deadlines.
53
+
54
+ **Authenticate before you mount.** `mediaRoutes` reads nothing about the
55
+ caller: `authorizeRead` and `authorizeWrite` receive the context your earlier
56
+ middlewares built. **API keys must be refused by your own
57
+ middleware before the routes are mounted**: the routes do not look at how the
58
+ caller authenticated, so a key that your middleware lets through is a caller
59
+ the callbacks will see. Do the same for any other credential you do not want
60
+ to serve media to.
61
+
62
+ ## Who may read
63
+
64
+ `authorizeRead(ctx, key)` decides per key, so the rule can depend on the
65
+ record that carries it:
66
+
67
+ ```ts
68
+ import { defineMediaKind } from '@softistx/alxia-media';
69
+
70
+ declare function isInPublishedQuiz(key: string): Promise<boolean>;
71
+ declare function isInViewersAttempt(userId: string, key: string): Promise<boolean>;
72
+
73
+ interface Viewer {
74
+ readonly viewer: { id: string; canEdit: boolean } | null;
75
+ }
76
+
77
+ export const questionMedia = defineMediaKind<Viewer>({
78
+ name: 'question-media',
79
+ accept: ['image/png'],
80
+ maxBytes: 1024 * 1024,
81
+ authorizeWrite: ({ viewer }) => viewer?.canEdit === true,
82
+ authorizeRead: async ({ viewer }, key) => {
83
+ if (viewer === null) return false;
84
+ if (viewer.canEdit) return true;
85
+ return (await isInPublishedQuiz(key)) || (await isInViewersAttempt(viewer.id, key));
86
+ },
87
+ });
88
+ ```
89
+
90
+ A refusal and a missing object both answer `404` with the same body, so a
91
+ caller cannot tell a key that exists from one that does not. `authorizeRead`
92
+ runs only for a key that is a well-formed UUID; anything else is a 404 before
93
+ your code is called.
94
+
95
+ A **public** kind (`public: true`) has no `authorizeRead` and is served with
96
+ `Cache-Control: public` and `Cross-Origin-Resource-Policy: cross-origin`.
97
+ Choose it deliberately: anyone who learns a key can read the file.
98
+
99
+ ## Who may write, and how often
100
+
101
+ `authorizeWrite` is the permission. `throttle` is the budget, and it runs
102
+ **after** the permission, so a caller who may not upload spends none of it, and
103
+ **before** a byte of the body is read:
104
+
105
+ ```ts
106
+ import { defineMediaKind } from '@softistx/alxia-media';
107
+
108
+ const uploads = new Map<string, { count: number; resetAt: number }>();
109
+
110
+ function spend(userId: string, limit: number, windowMs: number): number | true {
111
+ const now = Date.now();
112
+ const entry = uploads.get(userId);
113
+ if (entry === undefined || entry.resetAt <= now) {
114
+ uploads.set(userId, { count: 1, resetAt: now + windowMs });
115
+ return true;
116
+ }
117
+ entry.count += 1;
118
+ return entry.count <= limit ? true : Math.ceil((entry.resetAt - now) / 1000);
119
+ }
120
+
121
+ export const avatars = defineMediaKind<{ user: { id: string } }>({
122
+ name: 'avatars',
123
+ accept: ['image/png', 'image/jpeg'],
124
+ maxBytes: 512 * 1024,
125
+ authorizeWrite: () => true,
126
+ authorizeRead: () => true,
127
+ // true lets it through; a number refuses with that Retry-After
128
+ throttle: ({ user }) => spend(user.id, 10, 60_000),
129
+ });
130
+ ```
131
+
132
+ Use your shared limiter (`@softistx/alxia-redis` for several processes) the same way:
133
+ the callback returns `true`, `false` or the seconds to wait.
134
+
135
+ A callback that **throws** (a database that is down inside `authorizeRead`,
136
+ say) is not a refusal: the error goes to the app's error handling, a `500` by
137
+ default, like any handler's. `authorizeWrite` and `throttle` run before a byte
138
+ of the body is read, so a throw there stores nothing. Return `false` for a
139
+ caller you mean to refuse.
140
+
141
+ ### A storage quota, before the body
142
+
143
+ `throttle` counts uploads; it does not know how big this one is. `quota` is
144
+ given the **declared `Content-Length`** and the request's context, after the
145
+ permission, the throttle, the type and the `maxBytes` checks, and before a byte
146
+ of the body is read, so an upload over the account's storage is refused with
147
+ nothing stored and nothing to delete afterwards:
148
+
149
+ ```ts
150
+ import { defineMediaKind } from '@softistx/alxia-media';
151
+
152
+ declare function usedBytes(tenantId: string): Promise<number>;
153
+ const LIMIT = 5 * 1024 * 1024 * 1024;
154
+
155
+ export const files = defineMediaKind<{ tenant: { id: string } }>({
156
+ name: 'files',
157
+ accept: ['application/pdf'],
158
+ maxBytes: 50 * 1024 * 1024,
159
+ authorizeWrite: () => true,
160
+ authorizeRead: () => true,
161
+ quota: async ({ tenant }, { declared }) => {
162
+ // A body with no declared length is held in memory up to maxBytes,
163
+ // so count the worst case rather than nothing.
164
+ const needed = declared ?? 50 * 1024 * 1024;
165
+ if ((await usedBytes(tenant.id)) + needed <= LIMIT) return true;
166
+ return { code: 'quota_exceeded', status: 402 };
167
+ },
168
+ });
169
+ ```
170
+
171
+ `true` lets the upload through, `false` is a 403, and a `{ code, status }`
172
+ refusal is answered as it says. The request itself is `ctx.request` when you
173
+ need a header of your own. The declared length is the client's claim: the body
174
+ is still refused if it is longer or shorter, so the claim can only make the
175
+ check stricter than the truth, never let a larger file through.
176
+
177
+ ## Uploads: memory and deadlines
178
+
179
+ A body that declares its `Content-Length` streams into the bucket: whatever
180
+ its size, the server holds a chunk or two. A **chunked** body (no
181
+ `Content-Length`) is held in memory until it ends, up to the kind's
182
+ `maxBytes`, because the bucket needs the length before the first byte. The
183
+ chunks are handed to the bucket as they are, never copied into one buffer, so
184
+ one such upload costs about `maxBytes`; the worst case is `maxBytes` × the
185
+ chunked uploads in flight at once. Size `maxBytes` with that in mind, and have
186
+ a server in front of the API (a page server, a BFF) send `Content-Length`.
187
+
188
+ `writeTimeoutMs` (60 s by default) is an **idle** deadline on the body: each
189
+ read of the client's next chunk gets that long, and it starts over after each
190
+ one, for a chunked body as for a declared one. A client that sends nothing for
191
+ that long is refused `408 stalled`: the reader is cancelled and nothing is
192
+ stored. A slow upload that keeps moving is never cut. The bucket's own waits
193
+ (taking the bytes, answering after the last one) have the same deadline, and a
194
+ bucket that stalls is `503 unavailable`.
195
+
196
+ ## Deleting
197
+
198
+ A kind with `authorizeDelete` gets `DELETE <prefix>/<kind>/<key>`. It removes
199
+ the file and every rendition in `sizes`, and answers `204` whether or not
200
+ anything was there. The route does not know which records carry a key; decide
201
+ that in `authorizeDelete` (refuse while a record still carries it), or sweep
202
+ unreferenced keys yourself.
203
+
204
+ Refusing with `false` is a `403` (a `404` for a read). A guard that sees no
205
+ viewer says so with `{ code: 'unauthenticated' }`: `401 { error:
206
+ 'unauthenticated' }`, with no `status` to give, since the package knows it. An
207
+ app that answers 401 without a viewer, then 404 for an unknown tenant, then 403
208
+ writes `authorizeRead: ({ viewer }) => viewer ? check(viewer) : { code:
209
+ 'unauthenticated' }`. Nothing changes for a guard that answers `true` or
210
+ `false`. To tell the caller why, answer a refusal of
211
+ your own, with its code, status and the numbers the page words it from:
212
+
213
+ ```ts
214
+ import { defineMediaKind } from '@softistx/alxia-media';
215
+
216
+ declare function countReferences(key: string): Promise<number>;
217
+
218
+ export const attachments = defineMediaKind({
219
+ name: 'attachments',
220
+ accept: ['application/pdf'],
221
+ maxBytes: 5 * 1024 * 1024,
222
+ authorizeWrite: () => true,
223
+ public: true,
224
+ authorizeDelete: async (_ctx, key) => {
225
+ const count = await countReferences(key);
226
+ return count === 0 || { code: 'in_use', status: 409, params: { count } };
227
+ },
228
+ });
229
+ // DELETE /media/attachments/<key> -> 409 { "error": "in_use", "count": 2 }, nothing removed
230
+ ```
231
+
232
+ `authorizeWrite` and `authorizeRead` take the same answer (a quota's `402`, a
233
+ file archived `410`). `params` is added to the body beside the code; under
234
+ `errors: 'problem'` it becomes the problem's extension members. The `refusal`
235
+ option receives it as `refusal.details.params`.
236
+
237
+ ## One folder per tenant
238
+
239
+ `keyPrefix(ctx, kind)` puts every object of a request under folders of its
240
+ own, and reads and deletes look only there:
241
+
242
+ ```ts
243
+ import { alxia } from '@softistx/alxia';
244
+ import { defineMediaKind, MediaRefusal, mediaRoutes } from '@softistx/alxia-media';
245
+ import type { MediaBucket } from '@softistx/alxia-media';
246
+
247
+ declare const bucket: MediaBucket;
248
+ declare function tenantOf(request: Request): string | undefined;
249
+
250
+ const files = defineMediaKind({
251
+ name: 'files',
252
+ accept: ['application/pdf'],
253
+ maxBytes: 1024 * 1024,
254
+ authorizeWrite: () => true,
255
+ authorizeRead: () => true,
256
+ });
257
+
258
+ export const app = alxia().plugin(
259
+ mediaRoutes([files], {
260
+ bucket,
261
+ keyPrefix: ({ request }, kind) => {
262
+ const tenant = tenantOf(request);
263
+ if (tenant === undefined) throw new MediaRefusal('forbidden');
264
+ return `tenants/${tenant}`;
265
+ },
266
+ }),
267
+ );
268
+ // PUT stores tenants/<id>/files/<key>; another tenant's GET of that key is a 404
269
+ ```
270
+
271
+ To place a key by hand (a migration script), `mediaPlace` checks the prefix too:
272
+
273
+ ```ts
274
+ import { mediaPlace } from '@softistx/alxia-media';
275
+
276
+ const place = mediaPlace('files', 'tenants/acme');
277
+ place('0b1c2d3e-0000-4000-8000-000000000000', 'thumb'); // tenants/acme/files/<key>/thumb
278
+ ```
279
+
280
+ The prefix is resolved first, once per request, so a tenant that guesses
281
+ another's key finds nothing: the key alone never names an object. Segments
282
+ are letters, digits and `. _ = -` joined by `/`; anything else (`..`, an empty
283
+ segment, a leading `/`) is the app's bug and throws a `TypeError`, a `500`,
284
+ since silently changing a prefix could move an object into another tenant's
285
+ folder. Existing objects are not moved when you add a prefix: keys written
286
+ before it are under `<kind>/<key>` and are not found. With a prefix,
287
+ `mediaObjectKey(kind, key)` is no longer the bucket key; use
288
+ `mediaPlace(kind, prefix, extension?)(key, size?)` (both exported; `extension` is the kind's
289
+ `renditions.keyExtension`, which `mediaObjectKey` never adds) in a migration script.
290
+
291
+ **Caching.** Keys are immutable and a public kind is served `public,
292
+ max-age=31536000, immutable`. If the prefix comes from something that is not
293
+ in the URL (a header, the host), a shared cache (CDN, proxy) would store one
294
+ tenant's answer and give it to another. Make such a kind private
295
+ (`authorizeRead`, served `private`), or have the cache vary on that header
296
+ (`Vary: X-Tenant`), or put the tenant in the URL (`prefix: '/media/<tenant>'`
297
+ per mount). A prefix derived from the path or the session cookie needs
298
+ nothing.
299
+
300
+ Behind `@softistx/alxia-react-router/media`, `crop: 'query'` needs
301
+ `forwardQuery: ['x', 'y', 'size']` on the proxy.
302
+
303
+ ## Shaping the upload's answer
304
+
305
+ `uploaded(uploaded, ctx)` returns the `200` body, from the stored upload:
306
+
307
+ ```ts
308
+ import { alxia } from '@softistx/alxia';
309
+ import { mediaRoutes } from '@softistx/alxia-media';
310
+ import type { MediaBucket } from '@softistx/alxia-media';
311
+
312
+ declare const bucket: MediaBucket;
313
+
314
+ export const app = alxia().plugin(
315
+ mediaRoutes([], {
316
+ bucket,
317
+ uploaded: ({ key, sizes }) => ({ key, version: 1, sizes }),
318
+ }),
319
+ );
320
+ // PUT /media/avatars -> { "key": "…", "version": 1, "sizes": ["256", "64"] }
321
+ ```
322
+
323
+ `sizes` are the renditions actually stored. `renditions` lists the same ones
324
+ with their `contentType` and, for a picture made by `@softistx/alxia-media/image`, its
325
+ `width` and `height` in pixels, so you can store them beside the key without
326
+ reading the stored file:
327
+
328
+ ```ts
329
+ import { alxia } from '@softistx/alxia';
330
+ import { mediaRoutes } from '@softistx/alxia-media';
331
+ import type { MediaBucket } from '@softistx/alxia-media';
332
+
333
+ declare const bucket: MediaBucket;
334
+
335
+ export const app = alxia().plugin(
336
+ mediaRoutes([], {
337
+ bucket,
338
+ uploaded: ({ key, renditions }) => ({ key, renditions }),
339
+ }),
340
+ );
341
+ // -> { "key": "…", "renditions": [{ "size": "full", "contentType": "image/webp", "width": 2560, "height": 1440 }] }
342
+ ```
343
+
344
+ A `make` of your own sets `width` and `height` on the `MediaRendition` it
345
+ returns to have them here; left out, they are absent. If the hook throws, the file and
346
+ its renditions are removed before the error is answered.
347
+
348
+ ## From a browser
349
+
350
+ ```ts no-check
351
+ const response = await fetch('/media/question-files', {
352
+ method: 'PUT',
353
+ headers: { 'content-type': file.type },
354
+ body: file, // a File streams; its length is declared
355
+ });
356
+ const { key } = await response.json(); // keep the key, not a URL
357
+
358
+ // later
359
+ <img src={`/media/question-files/${key}`} alt="" />
360
+ <audio controls src={`/media/question-files/${key}`} />
361
+ ```
362
+
363
+ Audio and video need `Range` (Safari asks for `bytes=0-1` first); the routes
364
+ answer `206` and `Accept-Ranges: bytes`. The path is on your own origin, so a
365
+ CSP of `img-src 'self'` is enough.
366
+
367
+ ### PDFs and the `sandbox` policy
368
+
369
+ Every file is sent with `Content-Security-Policy: sandbox; default-src 'none'`,
370
+ so a file opened on its own can run nothing on your origin. Chromium's built-in
371
+ PDF viewer may refuse to render a PDF served with `sandbox` (a blank page or a
372
+ download, in a tab or an `<iframe>`), where Firefox and Safari show it. The
373
+ header stays: it is what makes a stored file harmless. Check how your PDFs open
374
+ in Chromium; when they do not, render them in the page with a PDF library
375
+ (pdf.js) from the bytes `fetch` returns, or offer them as a download.
376
+
377
+ To make a type a download whatever the browser would do with it, set
378
+ `attachment` on the kind: `attachment: ['application/pdf']` (or `true` for
379
+ every type) adds `Content-Disposition: attachment` to its files and sizes, and
380
+ an image in the same kind still shows inline.
381
+
382
+ ### Caching, deletes and lost permissions
383
+
384
+ A private file is sent with `Cache-Control: private, max-age=31536000,
385
+ immutable`: the key is fresh per upload, so what is under it never changes,
386
+ and a browser may keep it a year without asking again. The cost: a `DELETE`,
387
+ or a reader who loses the permission, does not reach a client that already
388
+ cached the file. That browser keeps showing it from its cache. Only clients
389
+ that have not fetched it yet see the `404`. Treat a file as readable, for
390
+ whoever already fetched it, until that cache entry is gone; a file that must
391
+ stop being readable on every device at once is not one a delete can recall.
392
+
393
+ For per-user content a reader can lose access to (a file readable only while
394
+ its quiz is published, or while a role holds), give the kind its own
395
+ `cacheControl`. The browser's cache is keyed by URL, not by user, so a year
396
+ of caching outlives the permission:
397
+
398
+ ```ts
399
+ const material = defineMediaKind({
400
+ name: 'material',
401
+ accept: ['application/pdf'],
402
+ maxBytes: 5_000_000,
403
+ authorizeRead: (ctx, key) => canStillRead(ctx, key),
404
+ cacheControl: 'private, no-cache', // revalidate on every use
405
+ });
406
+ ```
407
+
408
+ `no-cache` lets the browser keep the file but ask before each use. The
409
+ request reaches the route, `authorizeRead` runs first, and a client that
410
+ sends `If-None-Match` with the file's `ETag` gets a `304` with no body (the
411
+ header is on 200, 206 and 304 answers alike). A reader who lost access gets
412
+ the `404`, so the stale copy is no longer shown. Refusals stay `no-store`.
413
+
414
+ ## Behind a proxy or another server
415
+
416
+ When another server (a page server, say) sits between the browser and the API,
417
+ it must stream, not buffer, and pass these through:
418
+
419
+ - request: `Range`, `If-None-Match`, `If-Range`, `Content-Type`,
420
+ `Content-Length` (for an upload), the body as a stream;
421
+ - response: the status (`200`, `206`, `304`, `416`), `Content-Type`,
422
+ `Content-Length`, `Content-Range`, `ETag`, `Cache-Control`, `Accept-Ranges`.
423
+
424
+ It can also refuse an upload whose declared length is over the kind's limit
425
+ before it reaches the API. Have it send `Content-Length` with an upload: a
426
+ chunked body is held in the API's memory (see
427
+ [memory and deadlines](#uploads-memory-and-deadlines)).
428
+
429
+ If an app-wide middleware sets `Cache-Control: no-store`, exempt the media
430
+ prefix. The routes set their own `Cache-Control` per response; a refusal is
431
+ `no-store`.
432
+
433
+ ## Keys already in a bucket
434
+
435
+ An object stored at `<kind>/<uuid>` is served as it is: name the kind after the
436
+ existing folder and keep the existing UUIDs as keys. The object's stored
437
+ `Content-Type` is what is served, when the kind accepts it (a kind with
438
+ `accept: '*'` serves it only when it is a type this package can sniff, or
439
+ `text/plain`; see "Any content type"). A kind with a single
440
+ accepted type serves objects stored without a type (or as a generic
441
+ `application/octet-stream`, what a bucket gives an object put with none) as
442
+ that type; an object stored as any other type it does not accept is a download.
443
+
444
+ ## Images
445
+
446
+ `@softistx/alxia-media/image` turns a kind into an image kind: every picture it takes
447
+ is made into square renditions at upload, served at
448
+ `<prefix>/<kind>/<key>/<size>`. It needs **Bun 1.4.1 or later**, where
449
+ `Bun.Image` exists, and its optional peer `@softistx/image`. That peer is public on npmjs. Install it:
450
+
451
+ ```sh
452
+ bun add @softistx/image
453
+ ```
454
+
455
+ The subpath imports the peer by a literal specifier when it is imported, so
456
+ an app that bundles its server (`bun build`) carries `@softistx/image` in the
457
+ bundle, and an app without it fails at startup, not at the first upload.
458
+
459
+ `@softistx/alxia-media/image` is import-only: it loads the peer with a top-level
460
+ `await`, so `require('@softistx/alxia-media/image')` throws. Use `import`.
461
+
462
+ ```ts
463
+ import { defineMediaKind } from '@softistx/alxia-media';
464
+ import { withImageRendition } from '@softistx/alxia-media/image';
465
+
466
+ interface Viewer {
467
+ readonly viewer: { id: string; canUpload: boolean } | null;
468
+ }
469
+
470
+ export const avatars = defineMediaKind<Viewer>({
471
+ name: 'avatars',
472
+ accept: ['image/png', 'image/jpeg', 'image/webp'],
473
+ maxBytes: 5 * 1024 * 1024,
474
+ authorizeWrite: ({ viewer }) => viewer?.canUpload === true,
475
+ authorizeRead: ({ viewer }) => viewer !== null,
476
+ ...withImageRendition({ sizes: [256, 64] }),
477
+ });
478
+ ```
479
+
480
+ `withImageRendition` gives the kind its `sizes` (`['256', '64']`) and its
481
+ `renditions`. A page shows `/media/avatars/<key>/64` in a list and
482
+ `/media/avatars/<key>/256` on a profile; `/media/avatars/<key>` is the picture
483
+ as it was uploaded.
484
+
485
+ ### Made at upload, not on read
486
+
487
+ The `PUT` stores the original, reads it back, has `@softistx/image` decode it,
488
+ and stores each size before it answers. A `GET` of a size streams a stored
489
+ object, exactly as the file is streamed, so:
490
+
491
+ - reading costs no decoding: a page with fifty thumbnails makes the server
492
+ resize nothing, and nobody can make it resize by asking for sizes;
493
+ - each size is its own object, with its own `ETag`, `304` and `Range`;
494
+ - a picture that cannot be made into its sizes is refused to the person who
495
+ uploads it (`422`), not served as a `404` to everyone after.
496
+
497
+ The cost is the upload's time (a decode and one resize per size) and the
498
+ storage of each size. A size added later exists only for pictures uploaded
499
+ after: older keys answer `404` at it until the app makes their renditions.
500
+
501
+ ### What a rendition is
502
+
503
+ The centred square of the picture's short side, after the JPEG's EXIF
504
+ rotation, resized to the size, with every piece of metadata (EXIF, GPS, ICC,
505
+ XMP) removed. `format: 'png'` (the default) stores a PNG, for a PDF renderer
506
+ or a printer that draws only PNG and JPEG; `format: 'webp'` a smaller WebP for
507
+ a page. `@softistx/image` encodes the PNG itself (`quality` is the WebP's: giving it
508
+ with `format: 'png'` is a `TypeError` at declaration). Colour is not converted to sRGB.
509
+
510
+ By default nothing is enlarged: a picture whose short side is under
511
+ `minSide` (the largest size by default) is refused `422 unprocessable` with
512
+ `reason: 'dimensions'`. A smaller `minSide` accepts it, and then every size
513
+ above its short side is scaled up and comes out soft.
514
+
515
+ ```ts
516
+ import { withImageRendition } from '@softistx/alxia-media/image';
517
+
518
+ export const thumbnails = withImageRendition({
519
+ sizes: [512, 128],
520
+ format: 'webp',
521
+ minSide: 128, // a 300 px picture is taken; its 512 px size is scaled up, soft
522
+ quality: 85, // the WebP quality, 1 to 100 (WebP only)
523
+ maxPixels: 12_000_000, // refuse a picture claiming more: 422, reason 'pixels'
524
+ });
525
+ ```
526
+
527
+ ### Small pictures and whole pictures in a size
528
+
529
+ A size is a centred square of the short side, enlarged when the picture is
530
+ smaller than the size (a `minSide` below the size lets such a picture in).
531
+ Two options change that:
532
+
533
+ ```ts
534
+ withImageRendition({ sizes: [256], minSide: 16, enlarge: false });
535
+ // a 20x20 picture: the 256 size is 20x20, not blown up
536
+ withImageRendition({ sizes: [256], fit: 'inside' });
537
+ // the whole picture, aspect ratio kept, inside 256x256, never enlarged
538
+ ```
539
+
540
+ `enlarge: false` keeps the square crop and caps its side at the picture's;
541
+ `fit: 'inside'` drops the crop for the whole picture and takes no `crop`.
542
+
543
+ ### Keeping the file extension on rendition keys
544
+
545
+ Renditions are stored at `<kind>/<key>/<size>`, with no extension. A bucket
546
+ that already holds `<kind>/<key>/256.webp` is adopted without copying a single
547
+ object by turning on `keyExtension`:
548
+
549
+ ```ts
550
+ import { defineMediaKind } from '@softistx/alxia-media';
551
+ import { withImageRendition } from '@softistx/alxia-media/image';
552
+
553
+ export const avatar = defineMediaKind({
554
+ name: 'avatar',
555
+ accept: ['image/jpeg', 'image/png'],
556
+ maxBytes: 2 * 1024 * 1024,
557
+ public: true,
558
+ authorizeWrite: () => true,
559
+ authorizeDelete: () => true,
560
+ ...withImageRendition({ sizes: [256], format: 'webp', keyExtension: true }),
561
+ });
562
+ // PUT stores <prefix>/avatar/<key>/256.webp
563
+ // GET /media/avatar/<key>/256 reads <prefix>/avatar/<key>/256.webp
564
+ // DELETE removes <prefix>/avatar/<key>/256.webp
565
+ ```
566
+
567
+ The extension is the rendition's format (`webp` or `png`). The URL still ends
568
+ in `/256`, and the original (`<kind>/<key>`, with `keepOriginal`) keeps its
569
+ key. The option is off by default; turning it on or off later moves every
570
+ rendition key, so objects stored the other way answer `404`. With your own
571
+ `renditions`, set `keyExtension: 'webp'` (lower-case letters and digits, no
572
+ dot); `mediaPlace(kind, prefix, 'webp')` builds the same keys in your code.
573
+
574
+ ### The whole picture
575
+
576
+ Squares lose the edges of a screenshot or a document. `full` adds the whole
577
+ picture, its aspect ratio kept, its longer side at most `maxSide` pixels. It
578
+ is never enlarged: a picture already within `maxSide` keeps its size. EXIF
579
+ rotation is applied and every metadata (GPS included) is stripped, and it is
580
+ stored in `format` under the size `full`. A kind with `full` only has
581
+ `sizes: ['full']`; beside squares it lists `['256', 'full']`.
582
+
583
+ ```ts
584
+ import { withImageRendition } from '@softistx/alxia-media/image';
585
+
586
+ // a 2880x1800 PNG with GPS EXIF -> GET /media/shots/<key>/full: a 2560x1600
587
+ // WebP with no metadata
588
+ export const shots = withImageRendition({
589
+ format: 'webp',
590
+ full: { fit: 'inside', maxSide: 2560 },
591
+ });
592
+ // beside squares: withImageRendition({ sizes: [256], full: { fit: 'inside', maxSide: 1600 } })
593
+ ```
594
+
595
+ `crop` and `minSide` apply to the squares only; `full` is made from the whole
596
+ picture. A `maxSide` that is not a whole number from 1 to 8192, or a `fit`
597
+ other than `'inside'`, is a `TypeError` at declaration.
598
+
599
+ ### Cropping at upload
600
+
601
+ By default the square is the centre of the short side. `crop: 'query'` lets
602
+ the caller choose it: the upload's `?x=&y=&size=` (pixels of the picture as a
603
+ person sees it, after EXIF rotation) are the square's corner and side. None of
604
+ the three means the centred default. A function of the request does the same
605
+ from anything else:
606
+
607
+ ```ts
608
+ import { withImageRendition } from '@softistx/alxia-media/image';
609
+
610
+ export const fromQuery = withImageRendition({ sizes: [256, 64], crop: 'query' });
611
+ // PUT /media/avatars?x=10&y=20&size=300
612
+
613
+ export const fromHeader = withImageRendition({
614
+ sizes: [256, 64],
615
+ crop: (request) => {
616
+ const [x, y, size] = (request.headers.get('x-crop') ?? '').split(',').map(Number);
617
+ return size === undefined ? undefined : { x: x ?? 0, y: y ?? 0, size };
618
+ },
619
+ });
620
+ ```
621
+
622
+ A crop that is missing a value, is not whole numbers of 0 or more, or does not
623
+ fit the picture is refused `400 invalid_crop`, and nothing stays stored. Without
624
+ `crop` a query is ignored.
625
+
626
+ ### Renditions only
627
+
628
+ `keepOriginal: false` on the kind stores the sizes and never the upload: the
629
+ body is held in memory (up to `maxBytes`), made into its renditions and
630
+ dropped, so the original's EXIF and GPS data never reach the bucket.
631
+ `GET /media/<kind>/<key>` is a `404`; only the sizes are served. Combine it
632
+ with `withImageRendition`:
633
+
634
+ ```ts
635
+ import { defineMediaKind } from '@softistx/alxia-media';
636
+ import { withImageRendition } from '@softistx/alxia-media/image';
637
+
638
+ export const avatars = defineMediaKind({
639
+ name: 'avatars',
640
+ accept: ['image/png', 'image/jpeg'],
641
+ maxBytes: 4 * 1024 * 1024,
642
+ authorizeWrite: () => true,
643
+ public: true,
644
+ keepOriginal: false,
645
+ ...withImageRendition({ sizes: [256, 64], crop: 'query' }),
646
+ });
647
+ ```
648
+
649
+ Memory is the whole upload at once, as a picture's decode already needs;
650
+ bound it with `maxBytes`. Without `renditions` the kind throws at
651
+ declaration, since nothing would be stored.
652
+
653
+ #### One kind for pictures and PDFs
654
+
655
+ A list of types keeps the original of those types only. Pictures are made
656
+ into their sizes and dropped; the PDF is stored as it is, and no size is made
657
+ of it:
658
+
659
+ ```ts
660
+ export const attachments = defineMediaKind({
661
+ name: 'attachments',
662
+ accept: ['image/png', 'image/jpeg', 'image/webp', 'application/pdf'],
663
+ maxBytes: 8 * 1024 * 1024,
664
+ authorizeWrite: () => true,
665
+ public: true,
666
+ keepOriginal: ['application/pdf'],
667
+ attachment: ['application/pdf'], // the PDF is always a download
668
+ ...withImageRendition({ sizes: [256], enlarge: false }),
669
+ });
670
+ ```
671
+
672
+ `renditions` is run on the accepted types the list leaves out; list
673
+ `renditionTypes` to run it on others too. Every accepted type must be kept or
674
+ rendered, or `defineMediaKind` throws, since an upload of it would store
675
+ nothing.
676
+
677
+ ### Refusals
678
+
679
+ | what | answer |
680
+ | --- | --- |
681
+ | the bytes are not a picture it decodes, or are damaged | `422 unprocessable`, `reason: 'decode'` |
682
+ | smaller than `minSide` | `422 unprocessable`, `reason: 'dimensions'`, `min` (the smallest side, in pixels) |
683
+ | a `crop` that does not fit the picture | `400 invalid_crop` |
684
+ | more pixels than `maxPixels` | `422 unprocessable`, `reason: 'pixels'` |
685
+ | a GIF, an AVIF, a HEIC on Linux | `415 unsupported_type` |
686
+
687
+ In every case the original and any size already stored are removed, so the
688
+ key is never seen. Keep `accept` to `image/png`, `image/jpeg` and `image/webp`.
689
+
690
+ ### Memory
691
+
692
+ A picture is held in memory while it is decoded: up to `maxBytes`, plus about
693
+ four bytes per pixel. `concurrency` (2 by default) is how many decode at once
694
+ per kind; lower `maxPixels` to bound the worst case. See `@softistx/image`'s
695
+ own documentation for measured figures.
696
+
697
+ ### Renditions of your own
698
+
699
+ `renditions` is a plain kind option: `{ types, make }`, where `make` is given
700
+ the stored file (`{ key, contentType, bytes, request }`, `request` being the
701
+ upload's: read a crop or the caller from it) and returns
702
+ `{ size, contentType, bytes }` for sizes the kind lists, in types `types`
703
+ lists. A `MediaRefusal` it throws answers the upload; any other error is a
704
+ `500`. Either way the file is removed. A refusal may carry `params` and `min`
705
+ (`new MediaRefusal('unprocessable', { reason: 'dimensions', min: 256 })`),
706
+ answered beside the code.
707
+
708
+ ```ts
709
+ import { defineMediaKind, MediaRefusal } from '@softistx/alxia-media';
710
+
711
+ export const transcripts = defineMediaKind({
712
+ name: 'transcripts',
713
+ accept: ['application/pdf'],
714
+ maxBytes: 10 * 1024 * 1024,
715
+ authorizeWrite: () => true,
716
+ authorizeRead: () => true,
717
+ sizes: ['text'],
718
+ renditions: {
719
+ types: ['text/plain'],
720
+ make: async ({ bytes }) => {
721
+ const text = await extractText(bytes);
722
+ if (text === '') throw new MediaRefusal('unprocessable', { reason: 'empty' });
723
+ return [{ size: 'text', contentType: 'text/plain', bytes: new TextEncoder().encode(text) }];
724
+ },
725
+ },
726
+ });
727
+
728
+ declare function extractText(pdf: Uint8Array): Promise<string>;
729
+ ```
730
+
731
+ ## Keys and refusals in your own code
732
+
733
+ The package exports what your code needs to handle keys and refusals without
734
+ parsing a response:
735
+
736
+ ```ts
737
+ import {
738
+ isMediaKey,
739
+ isMediaRefusal,
740
+ MEDIA_REFUSAL_STATUS,
741
+ newMediaKey,
742
+ } from '@softistx/alxia-media';
743
+
744
+ const key = newMediaKey(); // a lower-case UUID: what a record keeps
745
+ isMediaKey(key); // true; a path segment that is not a key is a 404 before your code runs
746
+
747
+ function statusOf(error: unknown): number | undefined {
748
+ // whichever copy of the package threw it
749
+ return isMediaRefusal(error) ? MEDIA_REFUSAL_STATUS[error.code] : undefined;
750
+ }
751
+ ```
752
+
753
+ A kind that takes both sniffable types and types with no signature (the office
754
+ formats docx, xlsx, pptx, odt, ods, odp are zip containers this package does
755
+ not recognise) sets `sniff: 'known'`: the PDF is still refused when its first
756
+ bytes are an HTML page, and the office file is stored as declared.
757
+
758
+ ```ts
759
+ const documents = defineMediaKind({
760
+ name: 'documents',
761
+ accept: [
762
+ 'application/pdf',
763
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
764
+ ],
765
+ sniff: 'known',
766
+ maxBytes: 10 * 1024 * 1024,
767
+ authorizeWrite: () => true,
768
+ public: true,
769
+ });
770
+ ```
771
+
772
+ ### Any content type
773
+
774
+ A general-purpose file manager sets `accept: '*'`: any well-formed type is
775
+ stored (none declared is stored as `application/octet-stream`), a type with a
776
+ known signature is still checked against its first bytes (`sniff: false`
777
+ checks none), and any other is stored as declared. On the way out only the
778
+ types this package can sniff (raster images, audio, video, PDF) and
779
+ `text/plain` are served in the page, by exact name; everything else, HTML, SVG
780
+ and every `+xml` type included, is `application/octet-stream` with
781
+ `Content-Disposition: attachment`, under the same `nosniff` and sandbox CSP.
782
+ Such a kind takes no `renditions`, but it can declare `sizes` that your own code writes (next section). A body with no `Content-Length`
783
+ is held in memory up to `maxBytes`: see "Uploads: memory and deadlines", and
784
+ send the length.
785
+
786
+ ```ts
787
+ const files = defineMediaKind({
788
+ name: 'files',
789
+ accept: '*',
790
+ maxBytes: 95 * 1024 * 1024,
791
+ authorizeWrite: ({ viewer }) => viewer !== null,
792
+ authorizeRead: ({ viewer }) => viewer !== null,
793
+ });
794
+ ```
795
+
796
+ A type taken unverified is only as safe as its serving headers (`nosniff`,
797
+ sandbox CSP, `Content-Disposition`); keep such a kind to files you do not
798
+ render inline.
799
+
800
+ `MEDIA_SIGNATURES` is the list of content types the `sniff` check knows, each
801
+ with its signature test: read it to see what a kind may `accept` with `sniff`
802
+ on (a type not in it needs `sniff: 'known'` or `sniff: false`). `MediaKindInput` types the object
803
+ `defineMediaKind` takes, `MediaRoutesOptions` the options of `mediaRoutes`,
804
+ `MediaBucket` the bucket it takes (which your own tests can fake), and
805
+ `MediaContext` what the callbacks receive.
806
+
807
+ **Kinds that need different context.** `mediaRoutes([a, b], …)` infers one
808
+ `Requires` from the array: two kinds whose `Requires` differ do not compile in
809
+ one call. Mount one `mediaRoutes` call per `Requires` (each can use the same
810
+ `bucket` and a different `prefix`, or the same prefix and different kinds).
811
+
812
+
813
+ ### Sizes your own worker writes
814
+
815
+ Previews of a file whose type the package cannot make (a PDF's first page, a
816
+ video poster) are made by your own code, after the upload. Declare the names
817
+ alone, on any kind, `accept: '*'` included, with no `renditions`:
818
+
819
+ ```ts
820
+ import { defineMediaKind, mediaPlace } from '@softistx/alxia-media';
821
+
822
+ const files = defineMediaKind({
823
+ name: 'files',
824
+ accept: '*',
825
+ sizes: ['thumb', 'preview'],
826
+ maxBytes: 95 * 1024 * 1024,
827
+ authorizeWrite: ({ viewer }) => viewer !== null,
828
+ authorizeRead: ({ viewer }) => viewer !== null,
829
+ authorizeDelete: ({ viewer }) => viewer !== null,
830
+ });
831
+
832
+ // a background worker, once it has made the picture
833
+ const place = mediaPlace('files', prefix); // the `keyPrefix` of mediaRoutes, '' without one
834
+ await bucket.put({ key: place(key, 'thumb') }, thumbWebp, { type: 'image/webp' });
835
+ ```
836
+
837
+ `GET <prefix>/files/<key>/thumb` then streams that object:
838
+
839
+ - `authorizeRead` and `cacheControl` are the original's;
840
+ - `Content-Type` and `ETag` are the stored object's (a type the package serves
841
+ inline, such as `image/webp`; any other is a download);
842
+ - a declared size nobody wrote yet, and a size not declared, are `404`;
843
+ - `DELETE` of the original deletes the declared sizes too.
844
+
845
+ A key is fresh per upload, so a size is written once. If a worker rewrites one,
846
+ give the kind `cacheControl: 'private, no-cache'`: the default year of
847
+ `immutable` caching would keep the old bytes in browsers.
848
+
849
+ ## Testing
850
+
851
+ `@softistx/s3/testing` starts SeaweedFS with no Docker. Specs then see real
852
+ signatures, real `Range` handling and real refusals:
853
+
854
+ ```ts
855
+ import { afterAll, beforeAll, expect, test } from 'bun:test';
856
+ import { alxia } from '@softistx/alxia';
857
+ import { defineMediaKind, mediaRoutes } from '@softistx/alxia-media';
858
+ import { bindBucket, defineBucket } from '@softistx/s3';
859
+ import { startTestS3, type TestS3 } from '@softistx/s3/testing';
860
+
861
+ let s3: TestS3;
862
+
863
+ beforeAll(async () => {
864
+ s3 = await startTestS3();
865
+ await s3.createBucket('media-test');
866
+ }, 120_000);
867
+ afterAll(() => s3.stop());
868
+
869
+ test('an upload comes back by its key', async () => {
870
+ const bucket = bindBucket(
871
+ defineBucket({ bucket: 'media-test', key: (p: { key: string }) => p.key }),
872
+ s3.options,
873
+ );
874
+ const notes = defineMediaKind({
875
+ name: 'notes',
876
+ accept: ['application/pdf'],
877
+ maxBytes: 1024,
878
+ authorizeWrite: () => true,
879
+ authorizeRead: () => true,
880
+ });
881
+ const app = alxia().plugin(mediaRoutes([notes], { bucket }));
882
+
883
+ const body = new TextEncoder().encode('%PDF-1.7 hello');
884
+ const put = await app.request('/media/notes', {
885
+ method: 'PUT',
886
+ body,
887
+ // a server sets it from the wire; an in-process Request has none
888
+ headers: { 'content-type': 'application/pdf', 'content-length': String(body.length) },
889
+ });
890
+ const { key } = (await put.json()) as { key: string };
891
+
892
+ const get = await app.request(`/media/notes/${key}`);
893
+ expect(await get.text()).toBe('%PDF-1.7 hello');
894
+ });
895
+ ```
896
+
897
+ The first run downloads the SeaweedFS binary once (give `beforeAll` a long
898
+ timeout); cache `~/.cache/nxgt/seaweedfs` in CI.
899
+
900
+ A body built in a spec has no `Content-Length` unless you set it: without it
901
+ the upload takes the chunked path (held in memory up to `maxBytes`), not the
902
+ streamed one.