@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Steve Tsala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,374 @@
1
- # Temporary Holding Version
1
+ # @softistx/alxia-media
2
2
 
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.
3
+ > Moved from `@alxia/media`: see the [migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md).
4
+
5
+ Media through the API, for [alxia](https://www.npmjs.com/package/@softistx/alxia):
6
+ the browser asks your server for a file and your server streams it from a
7
+ **private bucket**. No presigned URL, no public bucket hostname, no CORS rule
8
+ on the storage. You declare *kinds* of file (who may read, who may write, which
9
+ types, how big, how often) and mount the routes once.
10
+
11
+ - `defineMediaKind`: per kind, the authorization, the content types, the size
12
+ limit and the throttle;
13
+ - `mediaRoutes`: `PUT` (a streamed body in, a **key** out), `GET` (Range,
14
+ ETag and 304), optional `DELETE`;
15
+ - key validation, typed refusals, and the response headers a private file
16
+ needs;
17
+ - `@softistx/alxia-media/image`, opt-in: `withImageRendition` makes PNG (or WebP)
18
+ squares of each uploaded picture, served at `/media/<kind>/<key>/<size>`.
19
+
20
+ Keys are returned, never URLs: your records keep the key, and a page builds
21
+ `/media/<kind>/<key>` on its own origin.
22
+
23
+ ```sh
24
+ bun add @softistx/alxia-media @softistx/alxia @softistx/s3
25
+ bun add -d typescript
26
+ ```
27
+
28
+ `@softistx/s3` is a peer: it is the bucket (`open` for streamed reads with
29
+ `Range`, `put` with a declared size for streamed writes). `@softistx/image`
30
+ is an **optional** peer (`^0.5.0 || ^0.6.0`), needed only for `@softistx/alxia-media/image`
31
+ (`bun add @softistx/image`, on **Bun 1.4.1 or later**, where `Bun.Image`
32
+ exists); `@softistx/alxia-media` alone never loads it.
33
+
34
+ `@softistx/s3` and `@softistx/image` are public on npmjs: no scope entry or token is needed.
35
+
36
+ ## Usage
37
+
38
+ ```ts
39
+ import { alxia } from '@softistx/alxia';
40
+ import { defineMediaKind, mediaRoutes } from '@softistx/alxia-media';
41
+ import { bindBucket, defineBucket } from '@softistx/s3';
42
+
43
+ const bucket = bindBucket(
44
+ defineBucket({ bucket: 'media', key: (p: { key: string }) => p.key }),
45
+ { accessKeyId: 'id', secretAccessKey: 'secret', endpoint: 'http://s3:9000' },
46
+ );
47
+
48
+ interface Viewer {
49
+ readonly viewer: { id: string; canUpload: boolean } | null;
50
+ }
51
+
52
+ const documents = defineMediaKind<Viewer>({
53
+ name: 'documents',
54
+ accept: ['application/pdf', 'image/png', 'image/jpeg'],
55
+ maxBytes: 10 * 1024 * 1024,
56
+ authorizeWrite: ({ viewer }) => viewer?.canUpload === true,
57
+ authorizeRead: ({ viewer }) => viewer !== null,
58
+ });
59
+
60
+ const app = alxia()
61
+ .derive(({ request }) => ({ viewer: readViewer(request) })) // your authentication
62
+ .plugin(mediaRoutes([documents], { bucket }));
63
+
64
+ declare function readViewer(request: Request): Viewer['viewer'];
65
+ ```
66
+
67
+ ```ts no-check
68
+ // PUT /media/documents (Content-Type: application/pdf, the file as the body)
69
+ // 200 { "key": "0f8fad5b-d9cb-469f-a165-70867728950e", "contentType": "application/pdf", "size": 48213 }
70
+
71
+ // GET /media/documents/0f8fad5b-d9cb-469f-a165-70867728950e
72
+ // 200, 206 with Range, 304 with If-None-Match, 404 for anything else
73
+ ```
74
+
75
+ Mount `mediaRoutes` **after** the middlewares that authenticate: the kinds'
76
+ callbacks read the context they add (`defineMediaKind<Viewer>` names what
77
+ they read, and `plugin` refuses an app that does not give it).
78
+
79
+ ## The routes
80
+
81
+ | route | does |
82
+ | --- | --- |
83
+ | `PUT <prefix>/<kind>` | stores the raw body under a fresh key; answers `{ key, contentType, size }` |
84
+ | `GET <prefix>/<kind>/<key>` | streams the file: `Range`, `ETag`, `If-None-Match`, `If-Range` |
85
+ | `GET <prefix>/<kind>/<key>/<size>` | a named rendition, for a kind that lists `sizes` |
86
+ | `DELETE <prefix>/<kind>/<key>` | for a kind with `authorizeDelete`: removes the file and every rendition listed in `sizes`; `204`, also when nothing was there |
87
+
88
+ `prefix` is `/media` by default. A file lives in the bucket at
89
+ `<kind>/<key>` (`<kind>/<key>/<size>` for a rendition, `<size>.<ext>` with `keyExtension`).
90
+
91
+ ## A kind
92
+
93
+ | option | |
94
+ | --- | --- |
95
+ | `name` | a URL segment and the bucket folder: lower-case words and digits joined by hyphens, starting with a letter |
96
+ | `accept` | the content types an upload may have, exact (`image/png`), no partial wildcard (`image/*`). `'*'` alone takes any type, for a general file manager: a type with a known signature is sniffed, any other is stored as declared (`application/octet-stream` when the upload declares none), and a file whose type is not one this package can sniff (PNG, JPEG, GIF, WebP, AVIF, PDF, MP3, AAC, Ogg, WAV, MP4, QuickTime, WebM) or exactly `text/plain` is served `application/octet-stream` with `Content-Disposition: attachment` (`image/svg+xml` and every `+xml` type are downloads). It takes `sizes` (the app writes them, see the guide's "Sizes your own worker writes") but no `renditions`. A body with no `Content-Length` is held in memory up to `maxBytes` (see [memory and deadlines](./docs/guide.md#uploads-memory-and-deadlines)): send `Content-Length`, above all with a large `maxBytes`. With `'*'`, `sniff: true` behaves as `'known'` and `sniff: false` checks none |
97
+ | `maxBytes` | the most bytes an upload may have: a safe integer, 1 or more |
98
+ | `authorizeWrite(ctx)` | may the caller upload; `false` is a 403, or answer a refusal of your own (`{ code, status }`, see Refusals) |
99
+ | `authorizeRead(ctx, key)` | may the caller read this key; `false` is a **404**, the answer for a file that is not there, or a refusal of your own. Or `public: true` for a kind anyone may read |
100
+ | `authorizeDelete(ctx, key)` | optional; declaring it mounts `DELETE`; `false` is a 403; `{ code: 'in_use', status: 409 }` refuses with that code and status |
101
+ | `throttle(ctx)` | optional, called after `authorizeWrite` and before a byte is read: `true`/nothing lets it through, `false` is a 429, a number is a 429 with that `Retry-After` |
102
+ | `quota(ctx, { declared, type })` | optional, called after the type and the declared-length checks and before a byte is read: `declared` is the request's `Content-Length` (`undefined` when it sent none), `ctx.request` the request. `true` lets it through, `false` is a 403, `{ code: 'quota_exceeded', status: 402 }` refuses with that code and status. A `quota` that throws is a `500` |
103
+ | `sizes` | optional names of the sizes stored beside the file, served at `GET <kind>/<key>/<size>`: made by `renditions` at upload, or written by your own code (a worker) at `mediaPlace(kind, prefix)(key, size)`, on any kind, `accept: '*'` included. A size not written yet is a 404 |
104
+ | `renditions` | optional `{ types, make }`: what each upload is made into, stored under its `sizes` before the `PUT` answers. `withImageRendition` gives one. Its optional `keyExtension` (a file extension) ends every rendition key in it, for a bucket that stores `<size>.webp`; `withImageRendition({ keyExtension: true })` takes the format's |
105
+ | `keepOriginal` | `true` by default. `false` stores the renditions alone: the upload is held in memory (up to `maxBytes`), made into its sizes and never written, so its EXIF/GPS never reaches the bucket; `GET <kind>/<key>` is then a 404. Needs `renditions`. A list of accepted types (`['application/pdf']`) keeps the original of those types only: images and PDFs in one kind, the PDF's bytes stored, the images' not |
106
+ | `renditionTypes` | optional: the accepted types `renditions` is made from. Default: every accepted type, or, with a `keepOriginal` list, the types the list leaves out. Every accepted type must be kept or listed here |
107
+ | `attachment` | optional: `true` or a list of accepted types served with `Content-Disposition: attachment` (a download, never shown inline), the file and its sizes. Default: off, a PDF stays `inline` |
108
+ | `cacheControl` | optional `Cache-Control` of the kind's 200, 206 and 304 answers; default `private, max-age=31536000, immutable` (`public, …` for a public kind). `'private, no-cache'` makes the browser revalidate on every use, so `authorizeRead` runs each time and the `ETag` answers a cheap `304`. Refusals stay `no-store` |
109
+ | `sniff` | `true` by default: the first bytes must be those of the declared type, and a type with no known signature is refused at declaration. `'known'` checks the types that have a signature and takes the others in `accept` as declared (a kind mixing PDF and docx). `false` checks none |
110
+
111
+ `defineMediaKind` throws where it is declared on a bad name, an empty
112
+ `accept` (`accept: '*'` is the one wildcard allowed, `image/*` still throws), a `maxBytes` that is not a safe integer of 1 or more, a
113
+ type this package cannot sniff (without `sniff: 'known'` or `sniff: false`), a `sizes` entry that
114
+ is not a name, or a private kind with no `authorizeRead` (give it, or
115
+ `public: true`). The types refuse the last one too, and `public: true`
116
+ together with `authorizeRead`. It throws on `renditions` too: `accept: '*' takes no renditions` (its `sizes` alone are fine),
117
+ `renditions needs sizes, the names of what it makes`, `renditions lists no
118
+ content type`, and `renditions type … is not an exact content type`.
119
+
120
+ A callback that **throws** is not a refusal: its error goes to the app's error
121
+ handling (a `500` by default), as any handler's would. `authorizeWrite` and
122
+ `throttle` and `quota` run before a byte of the body is read, so nothing is stored.
123
+
124
+ ## What an upload checks, in order
125
+
126
+ 1. `authorizeWrite`: 403.
127
+ 2. `throttle`: 429.
128
+ 3. The `Content-Type` is in `accept`: 415. With `accept: '*'` any well-formed type passes, and no `Content-Type` is stored as `application/octet-stream`.
129
+ 4. The declared `Content-Length` is within `maxBytes`: 413, before the body is read. A declared `Content-Length: 0` is refused 400 (`empty_body`) here, before `quota`, and one that is not a number is `size_mismatch`.
130
+ 5. `quota`, given that declared length: 403, or the refusal of your own. Still before the body is read.
131
+ 6. The body is not empty: 400 (a body with no declared length that turns out empty; a declared `Content-Length: 0` was refused at step 4).
132
+ 7. The first bytes are the type's (PNG, JPEG, GIF, WebP, AVIF, PDF, MP3, AAC (`audio/aac`, ADTS), Ogg, WAV, MP4 audio (`audio/mp4`), MP4 video, QuickTime (`video/quicktime`, brand `qt `), WebM): 415. With `sniff: 'known'` a type outside this list is not checked; with `sniff: false` none is.
133
+ 8. For a kind with `renditions`, once the file is stored: its renditions are
134
+ made and stored. A picture that cannot be made into them is 422 (or 415),
135
+ and the file is removed.
136
+
137
+ A body that **declares its length** streams straight into the bucket, never
138
+ held in memory. One that does not (chunked) is held up to `maxBytes` and
139
+ refused 413 as soon as it outgrows it, because the bucket needs the length
140
+ before the first byte: the memory it costs is `maxBytes` × the chunked uploads
141
+ in flight, so a server in front should send `Content-Length`. A body that ends
142
+ short or runs long is refused and nothing is stored. The upload's idle
143
+ deadline (`writeTimeoutMs`, 60 s) starts over after each chunk, so a slow
144
+ upload that keeps moving is never cut; a client that sends nothing for that
145
+ long is refused `408 stalled`.
146
+
147
+ ## What a read answers
148
+
149
+ | request | answer |
150
+ | --- | --- |
151
+ | a key that is not a UUID, a refused reader, a missing object | `404` (identical) |
152
+ | `If-None-Match` with the file's ETag (or `*`) | `304`, no body |
153
+ | `Range: bytes=0-99`, `bytes=100-`, `bytes=-500` | `206` with `Content-Range` |
154
+ | a range starting past the end | `416` with `Content-Range: bytes */<size>` |
155
+ | several ranges, another unit, a malformed `Range` | `200`, the whole file |
156
+ | `If-Range` that is not the file's ETag | `200`, the whole file |
157
+
158
+ Headers on every file: `Cache-Control: private, max-age=31536000, immutable`
159
+ (`public, …` for a public kind: the key is fresh per upload, so what is under
160
+ it never changes), `ETag`, `Accept-Ranges: bytes`, `X-Content-Type-Options:
161
+ nosniff`, `Cross-Origin-Resource-Policy: same-origin` (`cross-origin` for a
162
+ public kind), `Content-Security-Policy: sandbox; default-src 'none'`, and
163
+ `Content-Disposition: inline` for a PDF. A stored type the kind does not accept
164
+ is served as `application/octet-stream` with `attachment`. A kind with
165
+ `accept: '*'` serves only the types it can sniff and `text/plain`, by exact name,
166
+ as stored; every other type is that download.
167
+
168
+ If an earlier middleware sets `Cache-Control: no-store` on every response,
169
+ exempt the media prefix: `no-store` would defeat the year of caching.
170
+
171
+ A year of `immutable` caching has a cost: a `DELETE`, or a reader who loses
172
+ the permission, does not reach a client that already cached the file. That
173
+ browser keeps serving it from its cache until the entry expires or is evicted.
174
+ For content a reader can lose access to, set `cacheControl: 'private, no-cache'`
175
+ on the kind: the browser revalidates on every use, `authorizeRead` runs each
176
+ time, and a `304` costs no body. See the [guide](https://github.com/softistx/alxia/blob/develop/packages/media/docs/guide.md#caching-deletes-and-lost-permissions).
177
+
178
+ ## Refusals
179
+
180
+ Every refusal has a code and a status, and the same typed `MediaRefusal`:
181
+
182
+ | code | status |
183
+ | --- | --- |
184
+ | `unauthenticated` | 401: no viewer; answered by a guard, never by default (see below) |
185
+ | `not_found` | 404 |
186
+ | `forbidden` | 403 |
187
+ | `unsupported_type` | 415 (`accept` in the body lists the types) |
188
+ | `too_large` | 413 (`limit` in the body) |
189
+ | `empty_body`, `size_mismatch`, `interrupted` | 400 |
190
+ | `stalled` | 408: the client sent nothing for `writeTimeoutMs` |
191
+ | `range_not_satisfiable` | 416 (the size is in `Content-Range: bytes */<size>`, not in the body) |
192
+ | `throttled` | 429 (`Retry-After`, and `retryAfter` in the body, when the throttle gave seconds) |
193
+ | `unprocessable` | 422: the renditions could not be made (`reason` in the body: `decode`, `dimensions`, `pixels`; `min` for `dimensions`) |
194
+ | `invalid_crop` | 400: the crop of an image kind with `crop` is not three whole numbers or does not fit the picture |
195
+ | `unavailable` | 503: the bucket did not answer |
196
+
197
+ **Refusals of your own.** `authorizeWrite`, `authorizeRead` and
198
+ `authorizeDelete` may answer a `MediaDenial` instead of `false`: a snake_case
199
+ `code`, a `status` from 400 to 599 and optional `params` that the body carries
200
+ beside the code. `authorizeDelete: async (ctx, key) => (await inUse(key)) ?
201
+ { code: 'in_use', status: 409, params: { count: 3 } } : true` answers
202
+ `409 { error: 'in_use', count: 3 }` and removes nothing. `params` cannot rename
203
+ `error`, `type`, `status`, `title`, `detail` or `instance`. A malformed denial
204
+ is the app's bug, a `500`. For a code of this table, `status` may be left
205
+ out: a guard that sees no viewer answers `{ code: 'unauthenticated' }` and the
206
+ route answers `401 { error: 'unauthenticated' }` (`403` stays what `false`
207
+ means, `404` for a read). The `refusal` option sees it like any other
208
+ (`refusal.code`, `refusal.status`, `refusal.details.params`).
209
+
210
+ `@softistx/alxia-react-router/media` answers in the same shape. Besides these, it has
211
+ codes of its own, which only a BFF relay gives: `unauthenticated` (401),
212
+ `forbidden` (403, a cross-site request), `method_not_allowed` (405),
213
+ `length_required` (411), `proxy_misconfigured` (500) and `unavailable` (502 or
214
+ 504, the API did not answer). `forbidden` and `unavailable` are also API codes,
215
+ with the status above.
216
+
217
+ The body is `{ error: <code> }` plus the extras above, or an RFC 9457 problem
218
+ under `alxia({ errors: 'problem' })`. Every refusal is sent with
219
+ `Cache-Control: no-store`. Answer in your own format with the `refusal`
220
+ option; `MEDIA_REFUSAL_STATUS` maps each code to its status, and
221
+ `isMediaRefusal(error)` tells a refusal from any other error, whichever copy
222
+ of the package threw it:
223
+
224
+ ```ts
225
+ import { alxia } from '@softistx/alxia';
226
+ import { isMediaRefusal, MEDIA_REFUSAL_STATUS, mediaRoutes } from '@softistx/alxia-media';
227
+ import type { MediaBucket } from '@softistx/alxia-media';
228
+
229
+ declare const bucket: MediaBucket;
230
+
231
+ alxia().plugin(
232
+ mediaRoutes([], {
233
+ bucket,
234
+ refusal: (refusal, ctx) =>
235
+ // a 503 keeps the default body; the rest in the app's format
236
+ refusal.status === MEDIA_REFUSAL_STATUS.unavailable
237
+ ? undefined
238
+ : ctx.reply(refusal.status, { errors: [{ code: `media.${refusal.code}` }] }),
239
+ }),
240
+ );
241
+
242
+ export function describeFailure(error: unknown): string {
243
+ return isMediaRefusal(error) ? `media refused: ${error.code}` : 'unexpected';
244
+ }
245
+ ```
246
+
247
+ ## Sizes your own code writes
248
+
249
+ `sizes` with no `renditions` are names only: nothing makes them at upload. A
250
+ worker stores each object, and `GET <kind>/<key>/<size>` serves it with the
251
+ original's `authorizeRead` and `cacheControl`, and the stored object's own
252
+ `Content-Type` and `ETag`. Not written yet, or not declared: `404`. A `DELETE` of
253
+ the original removes its declared sizes too.
254
+
255
+ ```ts
256
+ const files = defineMediaKind({
257
+ name: 'files',
258
+ accept: '*',
259
+ sizes: ['thumb', 'preview'],
260
+ maxBytes: 95 * 1024 * 1024,
261
+ authorizeWrite: ({ viewer }) => viewer !== null,
262
+ authorizeRead: ({ viewer }) => viewer !== null,
263
+ });
264
+
265
+ // in a worker, once the preview is made
266
+ await bucket.put({ key: mediaPlace('files', prefix)(key, 'thumb') }, webp, {
267
+ type: 'image/webp',
268
+ });
269
+ ```
270
+
271
+ ## Images: `@softistx/alxia-media/image`
272
+
273
+ It needs Bun 1.4.1 or later (`Bun.Image`) and the optional peer
274
+ `@softistx/image`, from npmjs.
275
+ Importing the subpath without the peer fails at startup with
276
+ `@softistx/alxia-media/image needs @softistx/image, …`; a bundled server carries the
277
+ peer in its bundle.
278
+
279
+ `withImageRendition({ sizes })` gives a kind square renditions of every
280
+ picture it takes, made **at upload**: once the original is stored,
281
+ `@softistx/image` decodes it (first bytes checked, EXIF rotation applied, the
282
+ centred square of its short side, every piece of metadata stripped), resizes
283
+ it to each size and stores it as a PNG at `<kind>/<key>/<size>` (`<size>.png` with `keyExtension`), before the
284
+ `PUT` answers. A `GET` only streams what was stored, with the same `Range`,
285
+ `ETag` and `304` as the file, each size its own `ETag`. The original stays as
286
+ uploaded.
287
+
288
+ ```ts
289
+ import { defineMediaKind } from '@softistx/alxia-media';
290
+ import { withImageRendition } from '@softistx/alxia-media/image';
291
+
292
+ export const logos = defineMediaKind({
293
+ name: 'logos',
294
+ accept: ['image/png', 'image/jpeg', 'image/webp'],
295
+ maxBytes: 2 * 1024 * 1024,
296
+ authorizeWrite: () => true,
297
+ authorizeRead: () => true,
298
+ ...withImageRendition({ sizes: [256, 64] }),
299
+ });
300
+ // GET /media/logos/<key>/64: a 64 px PNG square; /media/logos/<key>/32: 404
301
+ ```
302
+
303
+ | option | default | |
304
+ | --- | --- | --- |
305
+ | `sizes` | required unless `full` is set | the square sides, in pixels (1 to 4096, unique); each size is named by its number |
306
+ | `format` | `'png'` | `'png'` or `'webp'` |
307
+ | `minSide` | the largest size | the smallest side a picture may have: nothing is enlarged |
308
+ | `maxPixels` | `25000000` | the most pixels a picture may claim |
309
+ | `quality` | `80` | the WebP quality of the resize; with `format: 'png'` it is a `TypeError` at declaration |
310
+ | `concurrency` | `2` | how many pictures are decoded at once |
311
+ | `full` | none | `{ fit: 'inside', maxSide }`: the whole picture, aspect ratio kept, longer side at most `maxSide` (1 to 8192), never enlarged, metadata stripped; served at `/<key>/full`. `sizes` may then be left out |
312
+ | `fit` | `'cover'` | `'cover'` is the centred square; `'inside'` keeps the whole picture, aspect ratio kept, inside a `size` x `size` box and never enlarged (no `crop` with it) |
313
+ | `enlarge` | `true` | `false` makes a size at the picture's own side when it is smaller (a 20 px picture gives a 20 px thumbnail for `256`), never blown up; `minSide` still refuses a picture that is too small |
314
+ | `crop` | none | `'query'` reads the square from the upload's `?x=&y=&size=`; a function of the request returns `{ x, y, size }` (or `undefined` for the centred default). A crop that does not fit is `400 invalid_crop` |
315
+
316
+ `crop: 'query'` behind `@softistx/alxia-react-router/media` needs that proxy to
317
+ forward the query: `forwardQuery: ['x', 'y', 'size']`, or the crop never
318
+ reaches the API and the centred default is made.
319
+
320
+ A picture that cannot be decoded, or is smaller than `minSide`, is
321
+ `422 unprocessable` (`reason`: `decode`, `dimensions` with `min`, `pixels`); a format
322
+ `@softistx/image` does not decode (GIF, AVIF, HEIC on Linux) is
323
+ `415 unsupported_type`. Nothing stays stored then. Keep `accept` to PNG,
324
+ JPEG and WebP. See the [guide](https://github.com/softistx/alxia/blob/develop/packages/media/docs/guide.md#images).
325
+
326
+ ## Options of `mediaRoutes`
327
+
328
+ | option | default | |
329
+ | --- | --- | --- |
330
+ | `bucket` | required | a bound `@softistx/s3` bucket whose key is the `key` it is given |
331
+ | `prefix` | `/media` | where the routes are mounted |
332
+ | `readTimeoutMs` | `10000` | how long the bucket may take to start answering a read |
333
+ | `writeTimeoutMs` | `60000` | the idle deadline of an upload, restarted at each chunk: a client that stalls is `408 stalled` |
334
+ | `refusal` | none | answers a refusal in your format; return `undefined` for the default |
335
+ | `keyPrefix(ctx, kind)` | none | folders every object of the request lives under (`tenants/<id>`): writes, reads and deletes use `<prefix>/<kind>/<key>[/<size>]`, so a request reaches only its own prefix. It may throw a `MediaRefusal`. Segments are letters, digits and `. _ = -`, else a `TypeError` (500) |
336
+ | `uploaded(uploaded, ctx)` | none | shapes the `200` body of an upload from `{ key, contentType, size, kind, sizes, renditions }` (`renditions`: `{ size, contentType, width?, height? }` per stored size, the pixel size of each picture made by `@softistx/alxia-media/image`); if it throws, what was stored is removed |
337
+
338
+ ## Exports
339
+
340
+ | export | |
341
+ | --- | --- |
342
+ | `defineMediaKind`, `mediaRoutes` | a kind, and the routes of some kinds |
343
+ | `newMediaKey`, `isMediaKey`, `mediaObjectKey`, `mediaPlace`, `isMediaKindName`, `MediaKey`, `MediaPlace` | keys, and whether a string is a valid kind name |
344
+ | `MediaRefusal`, `isMediaRefusal`, `MEDIA_REFUSAL_STATUS` | the refusal class, its guard across package copies, and the status of each code |
345
+ | `MEDIA_SIGNATURES` | the content types this package sniffs, each with its signature check |
346
+ | `MediaKindInput`, `MediaKind`, `MediaContext`, `ThrottleDecision`, `MediaUploadIntent` | what `defineMediaKind` takes and gives, what the callbacks read, what `throttle` answers, what `quota` is given (`declared`, `type`) |
347
+ | `MediaRoutesOptions`, `MediaBucket`, `MediaUpload`, `MediaUploaded` | the options of `mediaRoutes`, the bucket it takes, what a `PUT` answers, what the `uploaded` hook is given |
348
+ | `MediaDenial`, `MediaVerdict` | the refusal an `authorize*` callback may answer (`{ code, status?, params? }`), and `boolean \| MediaDenial` |
349
+ | `MediaRefusalCode`, `MediaRefusalDetails`, `MediaRefusalStatus` | a refusal's code, its extras, its status |
350
+ | `MediaRenditions`, `MediaRendition` (optional `width`/`height`), `MediaStoredRendition`, `MediaFile` | a kind's `renditions`, one rendition it makes, the stored file it is given |
351
+
352
+ | subpath | exports |
353
+ | --- | --- |
354
+ | `@softistx/alxia-media/image` | `withImageRendition`, and the types `ImageRenditionOptions`, `ImageRendition`, `ImageCrop`, `ImageFull` (needs the optional peer `@softistx/image`) |
355
+
356
+ ## Keys
357
+
358
+ `newMediaKey()` makes one (a lower-case UUID), `isMediaKey(value)` checks one,
359
+ `mediaObjectKey(kind, key, size?)` is its bucket key **when no `keyPrefix` is
360
+ set** (and no `keyExtension`: it never adds one). With a prefix, the object lives at `<prefix>/<kind>/<key>[/<size>]`
361
+ (`<size>.<ext>` with `keyExtension`):
362
+ `mediaPlace(kind, prefix, extension?)(key, size?)` computes it, with the prefix your
363
+ hook returns for that request. A key is the only thing a record keeps.
364
+
365
+ ## Testing
366
+
367
+ The package's own specs run against a real S3 API: SeaweedFS, started by
368
+ `@softistx/s3/testing`, with no Docker. See the
369
+ [guide](https://github.com/softistx/alxia/blob/develop/packages/media/docs/guide.md#testing).
370
+
371
+ ## Documentation
372
+
373
+ [Guide](https://github.com/softistx/alxia/blob/develop/packages/media/docs/guide.md), [troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/media/docs/troubleshooting.md),
374
+ [roadmap](https://github.com/softistx/alxia/blob/develop/packages/media/docs/roadmap.md).
package/dist/body.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ /** Reading an upload's body: an idle deadline on each read, and no copy of what is held. */
2
+ /** The bytes of `chunks` as one array. */
3
+ export declare function joined(chunks: readonly Uint8Array[], length: number): Uint8Array;
4
+ /** Reads chunks until `bytes` are held, or the body ends. */
5
+ export declare function readHead(reader: ReadableStreamDefaultReader<Uint8Array>, bytes: number, idleMs: number): Promise<{
6
+ chunks: Uint8Array<ArrayBufferLike>[];
7
+ length: number;
8
+ done: boolean;
9
+ }>;
10
+ /**
11
+ * The chunks already read, then the rest of the body, as one stream.
12
+ * `stalled()` says whether it was cancelled while it waited on the client:
13
+ * the bucket's idle deadline then fell on the client's side, not its own.
14
+ */
15
+ export declare function resumed(chunks: readonly Uint8Array[], reader?: ReadableStreamDefaultReader<Uint8Array>): {
16
+ readonly body: ReadableStream<Uint8Array>;
17
+ stalled(): boolean;
18
+ };
19
+ /** Reads the rest of a body of unknown length, up to `limit` bytes in all. */
20
+ export declare function collected(held: readonly Uint8Array[], heldLength: number, reader: ReadableStreamDefaultReader<Uint8Array>, limit: number, idleMs: number): Promise<{
21
+ chunks: Uint8Array<ArrayBufferLike>[];
22
+ length: number;
23
+ }>;
24
+ //# sourceMappingURL=body.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"body.d.ts","sourceRoot":"","sources":["../src/body.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAI5F,0CAA0C;AAC1C,wBAAgB,MAAM,CACrB,MAAM,EAAE,SAAS,UAAU,EAAE,EAC7B,MAAM,EAAE,MAAM,GACZ,UAAU,CAQZ;AAqBD,6DAA6D;AAC7D,wBAAsB,QAAQ,CAC7B,MAAM,EAAE,2BAA2B,CAAC,UAAU,CAAC,EAC/C,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM;;;;GAcd;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CACtB,MAAM,EAAE,SAAS,UAAU,EAAE,EAC7B,MAAM,CAAC,EAAE,2BAA2B,CAAC,UAAU,CAAC,GAC9C;IAAE,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,CAAC;IAAC,OAAO,IAAI,OAAO,CAAA;CAAE,CA+BnE;AAED,8EAA8E;AAC9E,wBAAsB,SAAS,CAC9B,IAAI,EAAE,SAAS,UAAU,EAAE,EAC3B,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,2BAA2B,CAAC,UAAU,CAAC,EAC/C,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM;;;GAed"}
@@ -0,0 +1,21 @@
1
+ /** What the routes need of a bucket, and how its failures become refusals. */
2
+ import { type BoundBucket } from '@softistx/s3';
3
+ import type { MediaKind } from './kind';
4
+ import { MediaRefusal } from './refusal';
5
+ /**
6
+ * The bucket the files live in: an `@softistx/s3` store bound with a key
7
+ * made of the `key` it is given. It stays private: nothing here signs a URL.
8
+ *
9
+ * ```ts
10
+ * const bucket = bindBucket(
11
+ * defineBucket({ bucket: 'media', key: (p: { key: string }) => p.key }),
12
+ * options,
13
+ * );
14
+ * ```
15
+ */
16
+ export type MediaBucket = Pick<BoundBucket<{
17
+ readonly key: string;
18
+ }>, 'open' | 'put' | 'delete'>;
19
+ /** A failure of the bucket, as the refusal it is; anything else comes back as it is. */
20
+ export declare function refusalOfFailure(error: unknown, kind: MediaKind<never>): MediaRefusal | undefined;
21
+ //# sourceMappingURL=bucket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bucket.d.ts","sourceRoot":"","sources":["../src/bucket.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAE9E,OAAO,EAAE,KAAK,WAAW,EAAgC,MAAM,cAAc,CAAC;AAC9E,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAkB,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzD;;;;;;;;;;GAUG;AACH,MAAM,MAAM,WAAW,GAAG,IAAI,CAC7B,WAAW,CAAC;IAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAAC,EACrC,MAAM,GAAG,KAAK,GAAG,QAAQ,CACzB,CAAC;AAEF,wFAAwF;AACxF,wBAAgB,gBAAgB,CAC/B,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,GACpB,YAAY,GAAG,SAAS,CA0B1B"}
@@ -0,0 +1,11 @@
1
+ /** The checks an upload passes before a byte of its body is read. */
2
+ import type { MediaContext, MediaKind } from './kind';
3
+ /**
4
+ * The permission, throttle, type, declared length and quota checks, in that order,
5
+ * before a byte of the body is read.
6
+ */
7
+ export declare function admitted(ctx: MediaContext<object>, kind: MediaKind<object>): Promise<{
8
+ type: string;
9
+ declared: number | undefined;
10
+ }>;
11
+ //# sourceMappingURL=checks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checks.d.ts","sourceRoot":"","sources":["../src/checks.ts"],"names":[],"mappings":"AAAA,qEAAqE;AAErE,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAKtD;;;GAGG;AACH,wBAAsB,QAAQ,CAC7B,GAAG,EAAE,YAAY,CAAC,MAAM,CAAC,EACzB,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC,GACrB,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC,CAuCzD"}
@@ -0,0 +1,106 @@
1
+ // src/refusal.ts
2
+ import {
3
+ errorFormat,
4
+ problem,
5
+ problemOf
6
+ } from "@softistx/alxia";
7
+ var MEDIA_REFUSAL_STATUS2 = {
8
+ unauthenticated: 401,
9
+ not_found: 404,
10
+ forbidden: 403,
11
+ unsupported_type: 415,
12
+ too_large: 413,
13
+ empty_body: 400,
14
+ size_mismatch: 400,
15
+ interrupted: 400,
16
+ stalled: 408,
17
+ range_not_satisfiable: 416,
18
+ throttled: 429,
19
+ unprocessable: 422,
20
+ invalid_crop: 400,
21
+ unavailable: 503
22
+ };
23
+ var DENIAL_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
24
+ function isDenial(value) {
25
+ return typeof value === "object" && value !== null && "code" in value;
26
+ }
27
+ function validStatus(denial) {
28
+ if (denial.status === undefined)
29
+ return Object.hasOwn(MEDIA_REFUSAL_STATUS2, denial.code);
30
+ return Number.isInteger(denial.status) && denial.status >= 400 && denial.status <= 599;
31
+ }
32
+ function refusalOfVerdict(verdict, otherwise) {
33
+ if (verdict === true)
34
+ return;
35
+ if (verdict === false)
36
+ return otherwise;
37
+ if (!isDenial(verdict) || typeof verdict.code !== "string" || !DENIAL_CODE.test(verdict.code) || !validStatus(verdict)) {
38
+ throw new TypeError("@softistx/alxia-media: an authorize callback answers true, false or { code, status } (snake_case code, status 400 to 599)");
39
+ }
40
+ return new MediaRefusal2(verdict.code, {
41
+ ...verdict.status !== undefined && { status: verdict.status },
42
+ ...verdict.params !== undefined && { params: verdict.params }
43
+ });
44
+ }
45
+
46
+ class MediaRefusal2 extends Error {
47
+ name = "MediaRefusal";
48
+ code;
49
+ status;
50
+ details;
51
+ constructor(code, details = {}, options) {
52
+ super(`media: ${code}`, options);
53
+ this.code = code;
54
+ const given = details.status;
55
+ const valid = given !== undefined && Number.isInteger(given) && given >= 400 && given <= 599;
56
+ this.status = valid ? given : (Object.hasOwn(MEDIA_REFUSAL_STATUS2, code) ? MEDIA_REFUSAL_STATUS2[code] : undefined) ?? 500;
57
+ this.details = details;
58
+ }
59
+ }
60
+ function isMediaRefusal2(error) {
61
+ return error instanceof MediaRefusal2 || error instanceof Error && error.name === "MediaRefusal" && "code" in error;
62
+ }
63
+ var RESERVED = new Set([
64
+ "error",
65
+ "type",
66
+ "status",
67
+ "title",
68
+ "detail",
69
+ "instance"
70
+ ]);
71
+ var reservedFree = (params) => Object.fromEntries(Object.entries(params ?? {}).filter(([name]) => !RESERVED.has(name)));
72
+ function refusalReply(ctx, refusal) {
73
+ const { code, details } = refusal;
74
+ const status = refusal.status;
75
+ const headers = {};
76
+ if (details.retryAfter !== undefined) {
77
+ headers["retry-after"] = String(Math.max(1, Math.ceil(details.retryAfter)));
78
+ }
79
+ if (code === "range_not_satisfiable" && details.size !== undefined) {
80
+ headers["content-range"] = `bytes */${details.size}`;
81
+ }
82
+ headers["cache-control"] = "no-store";
83
+ const extensions = {
84
+ ...reservedFree(details.params),
85
+ ...details.limit !== undefined && { limit: details.limit },
86
+ ...details.retryAfter !== undefined && {
87
+ retryAfter: Math.max(1, Math.ceil(details.retryAfter))
88
+ },
89
+ ...details.accept !== undefined && { accept: details.accept },
90
+ ...details.reason !== undefined && { reason: details.reason },
91
+ ...details.min !== undefined && { min: details.min }
92
+ };
93
+ if (errorFormat(ctx) === "problem") {
94
+ return problem(problemOf(ctx, {
95
+ status,
96
+ type: `urn:alxia:media:${code.replaceAll("_", "-")}`,
97
+ ...extensions
98
+ }), { headers });
99
+ }
100
+ return ctx.reply(status, { error: code, ...extensions }, { headers });
101
+ }
102
+
103
+ export { MEDIA_REFUSAL_STATUS2, refusalOfVerdict, MediaRefusal2, isMediaRefusal2, refusalReply };
104
+
105
+ //# debugId=7EB12796E2EC3CCD64756E2164756E21
106
+ //# sourceMappingURL=index-8s779ve6.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/refusal.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * The typed refusals of the media routes: one code per way a request is\n * turned away, each with its status. A read refused by `authorizeRead` is\n * `not_found`, as an object that is not there is: the two are not told apart.\n * A guard that sees no viewer answers `{ code: 'unauthenticated' }` (a 401)\n * instead of `false`.\n */\n\nimport {\n\ttype AnyReply,\n\ttype BaseContext,\n\ttype ClientErrorStatus,\n\terrorFormat,\n\tproblem,\n\tproblemOf,\n\ttype ServerErrorStatus,\n} from '@softistx/alxia';\n\n/** Why a media request was refused. */\nexport type MediaRefusalCode =\n\t| 'unauthenticated'\n\t| 'not_found'\n\t| 'forbidden'\n\t| 'unsupported_type'\n\t| 'too_large'\n\t| 'empty_body'\n\t| 'size_mismatch'\n\t| 'interrupted'\n\t| 'stalled'\n\t| 'range_not_satisfiable'\n\t| 'throttled'\n\t| 'unprocessable'\n\t| 'invalid_crop'\n\t| 'unavailable';\n\n/** The status each code answers with. */\nexport const MEDIA_REFUSAL_STATUS = {\n\tunauthenticated: 401,\n\tnot_found: 404,\n\tforbidden: 403,\n\tunsupported_type: 415,\n\ttoo_large: 413,\n\tempty_body: 400,\n\tsize_mismatch: 400,\n\tinterrupted: 400,\n\tstalled: 408,\n\trange_not_satisfiable: 416,\n\tthrottled: 429,\n\tunprocessable: 422,\n\tinvalid_crop: 400,\n\tunavailable: 503,\n} as const satisfies Record<MediaRefusalCode, number>;\n\nexport type MediaRefusalStatus =\n\t(typeof MEDIA_REFUSAL_STATUS)[MediaRefusalCode];\n\n/** What a refusal may carry beside its code. */\nexport interface MediaRefusalDetails {\n\t/** `too_large`: the most bytes the kind takes. */\n\treadonly limit?: number;\n\t/** `throttled`: seconds to wait. */\n\treadonly retryAfter?: number;\n\t/** `range_not_satisfiable`: the whole object's size, when known. */\n\treadonly size?: number;\n\t/** `unsupported_type`: the types the kind accepts. */\n\treadonly accept?: readonly string[];\n\t/** `unprocessable`: what about the file its renditions could not be made from (`decode`, `dimensions`, `pixels`). */\n\treadonly reason?: string;\n\t/** `unprocessable` with the reason `dimensions`: the smallest side, in pixels, a picture may have. */\n\treadonly min?: number;\n\t/**\n\t * Parameters the app words the refusal from, answered beside the code\n\t * (`{ error: 'in_use', count: 3 }`). A name the answer already uses\n\t * (`error`, `type`, `status`, `title`, `detail`, `instance`) is dropped.\n\t */\n\treadonly params?: Readonly<Record<string, unknown>>;\n\t/** A refusal of the app's own code (see `MediaDenial`): its status. */\n\treadonly status?: number;\n}\n\n/**\n * What a kind's `authorize*` callbacks may answer instead of `false`: a\n * refusal of the app's own, with its code and its status (`{ code: 'in_use',\n * status: 409 }`), answered as any other refusal is.\n */\nexport interface MediaDenial {\n\t/** Snake case: lower-case words and digits joined by underscores. */\n\treadonly code: string;\n\t/**\n\t * An HTTP error status, 400 to 599. Left out, it is the status of a code\n\t * the package has (`{ code: 'unauthenticated' }` is a 401); a code of\n\t * your own needs it.\n\t */\n\treadonly status?: number;\n\treadonly params?: Readonly<Record<string, unknown>>;\n}\n\n/** What an `authorize*` callback answers: allowed or not, or a refusal of its own. */\nexport type MediaVerdict = boolean | MediaDenial;\n\nconst DENIAL_CODE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;\n\n/** Whether `value` is the denial shape (and not a boolean). */\nfunction isDenial(value: unknown): value is MediaDenial {\n\treturn typeof value === 'object' && value !== null && 'code' in value;\n}\n\n/** Whether a denial has a status 400 to 599, or none and a code with a status of its own. */\nfunction validStatus(denial: MediaDenial): boolean {\n\tif (denial.status === undefined)\n\t\treturn Object.hasOwn(MEDIA_REFUSAL_STATUS, denial.code);\n\treturn (\n\t\tNumber.isInteger(denial.status) &&\n\t\tdenial.status >= 400 &&\n\t\tdenial.status <= 599\n\t);\n}\n\n/**\n * The refusal an `authorize*` answer comes to: none for `true`, `otherwise`\n * for `false`, the denial's own for a `MediaDenial`. A denial with a bad code\n * or status is the app's bug (a 500), not a refusal.\n */\nexport function refusalOfVerdict(\n\tverdict: unknown,\n\totherwise: MediaRefusal,\n): MediaRefusal | undefined {\n\tif (verdict === true) return undefined;\n\tif (verdict === false) return otherwise;\n\tif (\n\t\t!isDenial(verdict) ||\n\t\ttypeof verdict.code !== 'string' ||\n\t\t!DENIAL_CODE.test(verdict.code) ||\n\t\t!validStatus(verdict)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t'@softistx/alxia-media: an authorize callback answers true, false or { code, status } (snake_case code, status 400 to 599)',\n\t\t);\n\t}\n\treturn new MediaRefusal(verdict.code, {\n\t\t...(verdict.status !== undefined && { status: verdict.status }),\n\t\t...(verdict.params !== undefined && { params: verdict.params }),\n\t});\n}\n\n/** A request turned away. Thrown inside the routes, answered by them. */\nexport class MediaRefusal extends Error {\n\toverride readonly name = 'MediaRefusal';\n\treadonly code: MediaRefusalCode | (string & {});\n\treadonly status: number;\n\treadonly details: MediaRefusalDetails;\n\n\tconstructor(\n\t\tcode: MediaRefusalCode | (string & {}),\n\t\tdetails: MediaRefusalDetails = {},\n\t\toptions?: { cause?: unknown },\n\t) {\n\t\tsuper(`media: ${code}`, options);\n\t\tthis.code = code;\n\t\tconst given = details.status;\n\t\t// A refusal never answers below 400 or above 599: a `status` out of\n\t\t// range is ignored, and a code of the app's own without one is a 500.\n\t\tconst valid =\n\t\t\tgiven !== undefined &&\n\t\t\tNumber.isInteger(given) &&\n\t\t\tgiven >= 400 &&\n\t\t\tgiven <= 599;\n\t\tthis.status = valid\n\t\t\t? given\n\t\t\t: ((Object.hasOwn(MEDIA_REFUSAL_STATUS, code)\n\t\t\t\t\t? (MEDIA_REFUSAL_STATUS as Record<string, number>)[code]\n\t\t\t\t\t: undefined) ?? 500);\n\t\tthis.details = details;\n\t}\n}\n\n/** Whether `error` is a `MediaRefusal`, whichever copy of the package threw it. */\nexport function isMediaRefusal(error: unknown): error is MediaRefusal {\n\treturn (\n\t\terror instanceof MediaRefusal ||\n\t\t(error instanceof Error && error.name === 'MediaRefusal' && 'code' in error)\n\t);\n}\n\nconst RESERVED = new Set([\n\t'error',\n\t'type',\n\t'status',\n\t'title',\n\t'detail',\n\t'instance',\n]);\n\nconst reservedFree = (params: MediaRefusalDetails['params']) =>\n\tObject.fromEntries(\n\t\tObject.entries(params ?? {}).filter(([name]) => !RESERVED.has(name)),\n\t);\n\n/** The reply a refusal is answered with, unless the `refusal` option answers it. */\nexport function refusalReply(\n\tctx: BaseContext,\n\trefusal: MediaRefusal,\n): AnyReply {\n\tconst { code, details } = refusal;\n\t// A denial's status is checked 400 to 599 where it is read.\n\tconst status = refusal.status as ClientErrorStatus | ServerErrorStatus;\n\tconst headers: Record<string, string> = {};\n\tif (details.retryAfter !== undefined) {\n\t\theaders['retry-after'] = String(Math.max(1, Math.ceil(details.retryAfter)));\n\t}\n\tif (code === 'range_not_satisfiable' && details.size !== undefined) {\n\t\theaders['content-range'] = `bytes */${details.size}`;\n\t}\n\t// Whatever the app's other headers say, a refusal is not kept.\n\theaders['cache-control'] = 'no-store';\n\tconst extensions = {\n\t\t...reservedFree(details.params),\n\t\t...(details.limit !== undefined && { limit: details.limit }),\n\t\t...(details.retryAfter !== undefined && {\n\t\t\tretryAfter: Math.max(1, Math.ceil(details.retryAfter)),\n\t\t}),\n\t\t...(details.accept !== undefined && { accept: details.accept }),\n\t\t...(details.reason !== undefined && { reason: details.reason }),\n\t\t...(details.min !== undefined && { min: details.min }),\n\t};\n\tif (errorFormat(ctx) === 'problem') {\n\t\treturn problem(\n\t\t\tproblemOf(ctx, {\n\t\t\t\tstatus,\n\t\t\t\ttype: `urn:alxia:media:${code.replaceAll('_', '-')}`,\n\t\t\t\t...extensions,\n\t\t\t}),\n\t\t\t{ headers },\n\t\t);\n\t}\n\treturn ctx.reply(status, { error: code, ...extensions }, { headers });\n}\n"
6
+ ],
7
+ "mappings": "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",
8
+ "debugId": "7EB12796E2EC3CCD64756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,19 @@
1
+ /** The headers of a served file. */
2
+ import type { OpenedObject } from '@softistx/s3';
3
+ import type { MediaKind } from './kind';
4
+ /**
5
+ * The type a file is served as: the one stored if the kind accepts it (or,
6
+ * for a size, if its `renditions` make it; a size the app wrote, with no `renditions`, keeps its stored type when it is inline-safe), else, for an object stored without a type,
7
+ * the kind's only type, else bytes.
8
+ */
9
+ export declare function servedType(kind: MediaKind<never>, stored: string | undefined, sized?: boolean): {
10
+ type: string;
11
+ known: boolean;
12
+ };
13
+ /**
14
+ * The headers every answer about a file carries: how long it is kept, that
15
+ * the browser must not guess its type, who may embed it, and a CSP that
16
+ * leaves a document opened directly no script and no network.
17
+ */
18
+ export declare function mediaHeaders(kind: MediaKind<never>, opened: Pick<OpenedObject, 'eTag' | 'lastModified' | 'contentType'>, sized?: boolean): Headers;
19
+ //# sourceMappingURL=headers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"headers.d.ts","sourceRoot":"","sources":["../src/headers.ts"],"names":[],"mappings":"AAAA,oCAAoC;AAEpC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAoBxC;;;;GAIG;AACH,wBAAgB,UAAU,CACzB,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,EACtB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,KAAK,UAAQ,GACX;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CA8BlC;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAC3B,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,EACtB,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,GAAG,cAAc,GAAG,aAAa,CAAC,EACnE,KAAK,UAAQ,GACX,OAAO,CA4BT"}
@@ -0,0 +1,2 @@
1
+ export { type ImageCrop, type ImageFull, type ImageRendition, type ImageRenditionOptions, withImageRendition, } from './rendition';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/image/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,KAAK,qBAAqB,EAC1B,kBAAkB,GAClB,MAAM,aAAa,CAAC"}