@softistx/image 0.0.0-stage → 0.6.2

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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +551 -2
  3. package/dist/chunks/index-b71y3faz.js +20 -0
  4. package/dist/chunks/index-b71y3faz.js.map +10 -0
  5. package/dist/chunks/index-pj79f6q4.js +732 -0
  6. package/dist/chunks/index-pj79f6q4.js.map +23 -0
  7. package/dist/chunks/index-wfsrqqk2.js +16 -0
  8. package/dist/chunks/index-wfsrqqk2.js.map +10 -0
  9. package/dist/crop/crop-png.d.ts +39 -0
  10. package/dist/crop/crop-png.d.ts.map +1 -0
  11. package/dist/crop/from-query.d.ts +11 -0
  12. package/dist/crop/from-query.d.ts.map +1 -0
  13. package/dist/crop/png-chunks.d.ts +29 -0
  14. package/dist/crop/png-chunks.d.ts.map +1 -0
  15. package/dist/crop/png.d.ts +24 -0
  16. package/dist/crop/png.d.ts.map +1 -0
  17. package/dist/crop/row-assembler.d.ts +17 -0
  18. package/dist/crop/row-assembler.d.ts.map +1 -0
  19. package/dist/crop/unfilter.d.ts +10 -0
  20. package/dist/crop/unfilter.d.ts.map +1 -0
  21. package/dist/errors/image-error.d.ts +49 -0
  22. package/dist/errors/image-error.d.ts.map +1 -0
  23. package/dist/index.d.ts +10 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +42 -0
  26. package/dist/index.js.map +11 -0
  27. package/dist/input/read-input.d.ts +10 -0
  28. package/dist/input/read-input.d.ts.map +1 -0
  29. package/dist/input/sniff.d.ts +9 -0
  30. package/dist/input/sniff.d.ts.map +1 -0
  31. package/dist/pdf/index.d.ts +3 -0
  32. package/dist/pdf/index.d.ts.map +1 -0
  33. package/dist/pdf/index.js +166 -0
  34. package/dist/pdf/index.js.map +10 -0
  35. package/dist/pdf/render-pdf-page.d.ts +56 -0
  36. package/dist/pdf/render-pdf-page.d.ts.map +1 -0
  37. package/dist/process/bun-errors.d.ts +8 -0
  38. package/dist/process/bun-errors.d.ts.map +1 -0
  39. package/dist/process/geometry.d.ts +49 -0
  40. package/dist/process/geometry.d.ts.map +1 -0
  41. package/dist/process/process.d.ts +23 -0
  42. package/dist/process/process.d.ts.map +1 -0
  43. package/dist/render/render-image.d.ts +61 -0
  44. package/dist/render/render-image.d.ts.map +1 -0
  45. package/dist/s3/bind-image-store.d.ts +27 -0
  46. package/dist/s3/bind-image-store.d.ts.map +1 -0
  47. package/dist/s3/index.d.ts +4 -0
  48. package/dist/s3/index.d.ts.map +1 -0
  49. package/dist/s3/index.js +73 -0
  50. package/dist/s3/index.js.map +11 -0
  51. package/dist/s3/types.d.ts +61 -0
  52. package/dist/s3/types.d.ts.map +1 -0
  53. package/dist/s3/upload-image.d.ts +23 -0
  54. package/dist/s3/upload-image.d.ts.map +1 -0
  55. package/dist/set/define-image-set.d.ts +25 -0
  56. package/dist/set/define-image-set.d.ts.map +1 -0
  57. package/dist/set/limit.d.ts +7 -0
  58. package/dist/set/limit.d.ts.map +1 -0
  59. package/dist/set/options.d.ts +104 -0
  60. package/dist/set/options.d.ts.map +1 -0
  61. package/dist/set/runtime.d.ts +7 -0
  62. package/dist/set/runtime.d.ts.map +1 -0
  63. package/dist/set/types.d.ts +60 -0
  64. package/dist/set/types.d.ts.map +1 -0
  65. package/dist/set/whole.d.ts +3 -0
  66. package/dist/set/whole.d.ts.map +1 -0
  67. package/docs/README.md +13 -0
  68. package/docs/guide/pdf.md +60 -0
  69. package/docs/guide/processing.md +313 -0
  70. package/docs/guide/rendering.md +88 -0
  71. package/docs/guide/storing.md +219 -0
  72. package/docs/roadmap.md +71 -0
  73. package/docs/troubleshooting.md +724 -0
  74. package/package.json +90 -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,552 @@
1
- # Temporary Holding Version
1
+ # @softistx/image
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
+ Avatar and photo uploads on **Bun's own `Bun.Image`**: an upload is checked by
4
+ its first bytes, cropped to a square, resized and re-encoded to WebP (or PNG), with
5
+ every piece of metadata stripped. `renderImage` makes one picture of any ratio, from a rectangle, as JPEG too. Refusals are thrown before anything is
6
+ stored, and `@softistx/image/s3` stores the result in a `@softistx/s3` bucket.
7
+
8
+ ```ts
9
+ import { defineImageSet } from '@softistx/image';
10
+
11
+ const avatars = defineImageSet();
12
+ const { variants } = await avatars.process(await request.blob());
13
+ // variants: a 256 px and a 64 px square, as image/webp
14
+ ```
15
+
16
+ > **0.x.** The API is still settling.
17
+
18
+ ## Install
19
+
20
+ `@softistx/image` is public on npm, with no registry setting and no token. It moved from
21
+ `@nxgt/image` (npm), which gets no new version: replace the name in your imports
22
+ and `package.json`.
23
+
24
+ ```sh
25
+ bun add @softistx/image typescript @types/bun@^1.4.1
26
+ bun add @softistx/s3 # optional: only for @softistx/image/s3
27
+ bun add pdfjs-dist @napi-rs/canvas # optional: only for @softistx/image/pdf
28
+ ```
29
+
30
+ - **Bun 1.4.1 or later, and Bun only.** `Bun.Image` landed in 1.4.1; this
31
+ package does not run on Node. It has no required dependency: the image
32
+ work is Bun's own. HEIC decodes on macOS and Windows and is refused on Linux.
33
+ - `typescript` `^6.0.3 || ^7.0.0`: required peer.
34
+ - `@types/bun` `^1.4.1`: needed to typecheck the shipped declarations.
35
+ - `@softistx/s3`: **optional** peer, needed only for the `/s3` subpath. The root
36
+ entry never imports it.
37
+ - `pdfjs-dist` `^6.5.0` and `@napi-rs/canvas` `^1.1.0`: **optional** peers, needed
38
+ only for the `/pdf` subpath (a thumbnail of a PDF). Prebuilt binaries, no
39
+ system binary; the root entry never imports them.
40
+
41
+ ## Subpaths
42
+
43
+ | Subpath | Exports |
44
+ | --- | --- |
45
+ | `@softistx/image` | `defineImageSet`, `renderImage`, `cropFromQuery`, `ImageError`, and the types `RenderOptions`, `RenderedImage`, `RenderFormat`, `CropRect`, `ImageSet`, `ImageSetOptions`, `ImageFormat`, `ImageContentType`, `ProcessOptions`, `CropBox`, `ProcessedImage`, `ImageVariant`, `ImageInput`, `ImageErrorCode`, `ImageErrorReason` |
46
+ | `@softistx/image/pdf` | `renderPdfFirstPage`, and the types `PdfRenderOptions`, `PdfRenderedImage`, `PdfInput` (needs `pdfjs-dist` and `@napi-rs/canvas`) |
47
+ | `@softistx/image/s3` | `bindImageStore`, `uploadImage`, and the types `ImageStore`, `StoredImage`, `StoredVariant` (needs `@softistx/s3`) |
48
+
49
+ ## Process an upload
50
+
51
+ `defineImageSet` fixes what to make of an upload; `process` does it. The input
52
+ is a `Uint8Array`, an `ArrayBuffer`, a `Blob` or a `ReadableStream<Uint8Array>`.
53
+
54
+ ```ts
55
+ import { defineImageSet, ImageError, type ImageErrorCode } from '@softistx/image';
56
+ import { Hono } from 'hono'; // hono is only the example router
57
+
58
+ const avatars = defineImageSet({ sizes: [256, 64] });
59
+ const app = new Hono();
60
+
61
+ app.post('/avatar', async (c) => {
62
+ const form = await c.req.formData();
63
+ const file = form.get('file');
64
+ if (!(file instanceof Blob)) return c.json({ error: 'no file' }, 400);
65
+ try {
66
+ const { source, variants } = await avatars.process(file);
67
+ return c.json({
68
+ format: source.format,
69
+ sizes: variants.map((v) => [v.size, v.bytes.byteLength]),
70
+ });
71
+ } catch (error) {
72
+ if (error instanceof ImageError) {
73
+ // a 4xx for every refusal: the upload or the crop is the caller's
74
+ const statuses = {
75
+ TOO_LARGE: 413,
76
+ UNSUPPORTED_TYPE: 415,
77
+ UNDECODABLE: 422,
78
+ TOO_SMALL: 422,
79
+ INVALID_CROP: 400,
80
+ } as const satisfies Record<ImageErrorCode, number>;
81
+ return c.json(
82
+ { error: error.code, reason: error.reason },
83
+ statuses[error.code],
84
+ );
85
+ }
86
+ throw error; // anything else is a 500
87
+ }
88
+ });
89
+ ```
90
+
91
+ The result is `{ source, variants }`: `source` is the upload's format
92
+ (`'jpeg' | 'png' | 'webp' | 'heic'`) and its size after EXIF rotation, and
93
+ `variants` holds one square per size, in the order of `sizes`, each
94
+ with `size`, `width`, `height`, `contentType` (`image/webp`, or `image/png` with
95
+ `format: 'png'`) and `bytes`.
96
+
97
+ Any other input type is a `TypeError`.
98
+
99
+ ## Store the variants
100
+
101
+ `bindImageStore` stores every size in a `@softistx/s3` bucket whose key takes a
102
+ `size` beside its other params. Put a **fresh id per upload** in the key.
103
+
104
+ ```ts
105
+ import { randomUUID } from 'node:crypto';
106
+ import { defineImageSet } from '@softistx/image';
107
+ import { bindImageStore } from '@softistx/image/s3';
108
+ import { bindBucket, defineBucket } from '@softistx/s3';
109
+
110
+ const avatarBucket = defineBucket({
111
+ bucket: 'avatars',
112
+ key: (p: { imageId: string; size: number }) =>
113
+ `avatars/${p.imageId}/${p.size}.webp`,
114
+ });
115
+
116
+ const avatars = bindImageStore(
117
+ defineImageSet(),
118
+ bindBucket(avatarBucket, {
119
+ endpoint: 'https://s3.example.com', // your own, from the environment
120
+ accessKeyId: 'access-key',
121
+ secretAccessKey: 'secret-key',
122
+ }),
123
+ );
124
+
125
+ const imageId = randomUUID();
126
+ const { version } = await avatars.replace({ imageId }, await request.blob());
127
+ // save imageId and version on the user, then remove the former image:
128
+ // await avatars.remove({ imageId: formerImageId });
129
+ const url = avatars.presignGet({ imageId }, 64, { expiresIn: 300 });
130
+ ```
131
+
132
+ Objects are never public. The bucket must accept the set's `contentType`
133
+ (`image/webp` by default) and a `maxSize` of at
134
+ least the largest variant, and must be bound **without a public default `acl`**
135
+ (Bun would send it on every put). See [storing](docs/guide/storing.md) for why the key
136
+ carries a fresh id, how to serve images, and what a failed put leaves behind.
137
+
138
+ ## Options
139
+
140
+ Every option is optional. A bad one throws a `TypeError` naming it when the
141
+ set is defined.
142
+
143
+ | Option | Type | Default | Effect |
144
+ | --- | --- | --- | --- |
145
+ | `sizes` | `number[]` | `[256, 64]` | the square sides to produce: unique whole numbers, 1 to 4096 |
146
+ | `maxBytes` | `number` | 5 MiB | the upload's byte limit. Most 12 MP photos fit; a 48 MP phone JPEG is about 11 MB and is refused unless you raise it |
147
+ | `maxPixels` | `number` | `25_000_000` | the most pixels (width x height) an upload may claim; covers 24 MP phone output. Raising it raises the worst-case memory (see [Traps](#traps)) |
148
+ | `minSide` | `number` | the largest of `sizes` | the smallest side the upload, or its crop, may have, so nothing is enlarged |
149
+ | `format` | `'webp' \| 'png'` | `'webp'` | the variants' format; the set's `format` and `contentType` say it, for the key's extension and the bucket's `contentType`. A PNG is several times the size of a WebP: check the bucket's `maxSize` |
150
+ | `lossless` | `boolean` | `false` | lossless WebP (WebP only: a PNG is always lossless) |
151
+ | `quality` | `number` | `80` | the WebP quality, 1 to 100 (WebP only) |
152
+ | `concurrency` | `number` | `2` | how many uploads decode at once, 1 to 64. Not a hard memory ceiling: Bun keeps each PNG it encodes until a later collection (see [Traps](#traps)) |
153
+
154
+ ```ts
155
+ import { defineImageSet } from '@softistx/image';
156
+
157
+ const photos = defineImageSet({
158
+ sizes: [1024, 256],
159
+ maxBytes: 10 * 1024 * 1024,
160
+ maxPixels: 40_000_000, // 36 MP and 40 MP phones: about 4 B/px at the peak
161
+ quality: 85,
162
+ concurrency: 1,
163
+ });
164
+ ```
165
+
166
+ ## Crop
167
+
168
+ The default is the centred square of the short side. Pass `crop: { x, y, size }`
169
+ to keep another one, in pixels of the picture **as a person sees it, after EXIF
170
+ rotation**: `(x, y)` is its top-left corner.
171
+
172
+ ```ts
173
+ import { defineImageSet } from '@softistx/image';
174
+
175
+ const avatars = defineImageSet();
176
+ const { variants } = await avatars.process(await request.blob(), {
177
+ crop: { x: 120, y: 40, size: 600 },
178
+ });
179
+ ```
180
+
181
+ A crop that is not three whole numbers of 0 or more, or is not an object, or does not fit the image,
182
+ is an `ImageError` with the code `INVALID_CROP`, so a handler answers a 4xx. A crop that fits but is under `minSide` is refused as `TOO_SMALL`.
183
+ Orientation is applied for a JPEG only; a PNG or WebP orientation tag is ignored.
184
+
185
+ ## Render one picture
186
+
187
+ `defineImageSet` makes squares. For one picture of any ratio, optionally a
188
+ rectangle of the upload, and as **JPEG**, WebP or PNG, call `renderImage`. It
189
+ takes the same input types and applies the same checks as a set: the first-bytes
190
+ sniffing, `maxBytes` and `maxPixels`, EXIF orientation, every metadata
191
+ stripped, and at most two decodes at a time.
192
+
193
+ ```ts
194
+ import { renderImage } from '@softistx/image';
195
+
196
+ const { bytes, width, height, contentType } = await renderImage(
197
+ await request.blob(),
198
+ {
199
+ crop: { x: 0, y: 120, width: 1600, height: 900 }, // the upright picture, in pixels
200
+ width: 800,
201
+ height: 450,
202
+ format: 'jpeg', // image/jpeg
203
+ quality: 85,
204
+ },
205
+ );
206
+ ```
207
+
208
+ The crop is resized to exactly `width` x `height` (`fit: 'fill'`: give it the
209
+ crop's ratio) and **never enlarged**: a crop smaller than `width` x `height` on
210
+ either side is `TOO_SMALL`, so a caller clamps its target to the crop. Without
211
+ `crop` the whole upright picture is used. A crop that is not four whole numbers
212
+ (`x`, `y` of 0 or more, `width`, `height` of 1 or more) or does not fit the
213
+ picture is `INVALID_CROP`. `signal` aborts the call with its reason.
214
+
215
+ ## Thumbnail of a PDF
216
+
217
+ `renderPdfFirstPage` draws page 1 of a PDF as JPEG, WebP or PNG, with the same
218
+ inputs, limits and refusals as `renderImage`. Install the optional peers first:
219
+ `bun add pdfjs-dist @napi-rs/canvas`.
220
+
221
+ ```ts
222
+ import { renderPdfFirstPage } from '@softistx/image/pdf';
223
+
224
+ const { bytes, width, height, contentType, source } = await renderPdfFirstPage(
225
+ await request.blob(),
226
+ { width: 256, format: 'webp' }, // height follows the page's ratio
227
+ );
228
+ // source: { format: 'pdf', pages, width, height } (the page, in points)
229
+ ```
230
+
231
+ The page is drawn on white at `width` (a vector page is never stretched);
232
+ `height` is an optional cap. Bytes without a `%PDF-` header are
233
+ `UNSUPPORTED_TYPE`, a damaged or password-protected PDF is `UNDECODABLE`. See
234
+ [Thumbnail of a PDF](docs/guide/pdf.md).
235
+
236
+ ## Output and metadata
237
+
238
+ Every variant is a WebP square by default. `format: 'png'` makes PNG squares
239
+ instead, each encoded once from the decoded upload (never through WebP), for a
240
+ consumer that does not read WebP, such as a PDF renderer; `lossless: true` makes
241
+ lossless WebP. `quality` and `lossless` are WebP's: either one beside
242
+ `format: 'png'` is a `TypeError`.
243
+
244
+ ```ts
245
+ import { defineImageSet } from '@softistx/image';
246
+
247
+ const forPdf = defineImageSet({ sizes: [512], format: 'png' });
248
+ const [logo] = (await forPdf.process(bytes)).variants;
249
+ await Bun.write(`logo-512.${forPdf.format}`, logo.bytes); // image/png
250
+
251
+ const exact = defineImageSet({ lossless: true }); // image/webp, lossless
252
+ ```
253
+
254
+ The ICC profile, EXIF (GPS included), XMP and
255
+ every other metadata are removed, so a photo's location never reaches a stored
256
+ file.
257
+
258
+ ```ts
259
+ import { defineImageSet } from '@softistx/image';
260
+
261
+ const [large, small] = (await defineImageSet().process(bytes)).variants;
262
+ await Bun.write('avatar-256.webp', large.bytes);
263
+ await Bun.write('avatar-64.webp', small.bytes);
264
+ ```
265
+
266
+ **Colour is not converted.** The ICC profile is dropped and this package does
267
+ not convert the pixels to sRGB, so a Display P3 or Adobe RGB photo may look a
268
+ little flatter.
269
+
270
+ ## API
271
+
272
+ ### `defineImageSet(options?)`
273
+
274
+ `(options?: ImageSetOptions) => ImageSet`. Fixes what to make of an upload and
275
+ checks the options once, when it is defined (see [Options](#options)). It
276
+ touches nothing and holds no connection.
277
+
278
+ ### `ImageSet`
279
+
280
+ | Member | |
281
+ | --- | --- |
282
+ | `sizes` | `readonly number[]`, the sides it produces, in the order of the variants |
283
+ | `format` | `'webp' \| 'png'`, the variants' format, also the extension to put in a key |
284
+ | `contentType` | `'image/webp' \| 'image/png'`, the variants' content type |
285
+ | `process(input, { crop }?)` | `Promise<ProcessedImage>`: checks, crops, resizes and re-encodes `input` to the set's format, every metadata stripped |
286
+
287
+ ```ts
288
+ type ImageInput = Uint8Array | ArrayBuffer | Blob | ReadableStream<Uint8Array>;
289
+ type CropBox = { x: number; y: number; size: number };
290
+ type ProcessOptions = { crop?: CropBox };
291
+
292
+ type ImageFormat = 'webp' | 'png';
293
+ // 'image/webp' for 'webp', 'image/png' for 'png'; both without an argument
294
+ type ImageContentType<F extends ImageFormat = ImageFormat> = /* ... */;
295
+
296
+ // F is the set's format: defineImageSet() is an ImageSet<'webp'>,
297
+ // defineImageSet({ format: 'png' }) an ImageSet<'png'>
298
+ type ProcessedImage<F extends ImageFormat = ImageFormat> = {
299
+ source: { format: 'jpeg' | 'png' | 'webp' | 'heic'; width: number; height: number };
300
+ variants: ImageVariant<F>[]; // one per size, in the order of `sizes`
301
+ };
302
+ type ImageVariant<F extends ImageFormat = ImageFormat> = {
303
+ size: number;
304
+ width: number;
305
+ height: number;
306
+ contentType: ImageContentType<F>; // the set's
307
+ bytes: Uint8Array;
308
+ };
309
+ ```
310
+
311
+ ### `renderImage(input, options)`
312
+
313
+ `<F extends 'jpeg' | 'webp' | 'png'>(input: ImageInput, options: RenderOptions<F>) => Promise<RenderedImage<F>>`.
314
+ See [Render one picture](#render-one-picture).
315
+
316
+ ```ts
317
+ type CropRect = { x: number; y: number; width: number; height: number };
318
+ type RenderOptions<F extends RenderFormat = RenderFormat> = {
319
+ crop?: CropRect; // upright picture; default: all of it
320
+ width: number; // 1 to 8192
321
+ height: number; // 1 to 8192
322
+ format: F; // 'jpeg' | 'webp' | 'png'
323
+ quality?: number; // 1 to 100, default 80; a TypeError with 'png'
324
+ maxBytes?: number; // default 5 MiB
325
+ maxPixels?: number; // default 25 000 000
326
+ signal?: AbortSignal;
327
+ };
328
+ type RenderedImage<F extends RenderFormat = RenderFormat> = {
329
+ source: { format: 'jpeg' | 'png' | 'webp' | 'heic'; width: number; height: number };
330
+ bytes: Uint8Array;
331
+ width: number;
332
+ height: number;
333
+ contentType: 'image/jpeg' | 'image/webp' | 'image/png'; // follows F
334
+ };
335
+ ```
336
+
337
+ ### `renderPdfFirstPage(input, options)` (`@softistx/image/pdf`)
338
+
339
+ `<F extends 'jpeg' | 'webp' | 'png'>(input: ImageInput, options: PdfRenderOptions<F>) => Promise<PdfRenderedImage<F>>`.
340
+ See [Thumbnail of a PDF](#thumbnail-of-a-pdf).
341
+
342
+ ```ts
343
+ type PdfRenderOptions<F extends RenderFormat = RenderFormat> = {
344
+ width: number; // 1 to 8192
345
+ height?: number; // 1 to 8192, a cap; default: the page's ratio
346
+ format: F;
347
+ quality?: number; // 1 to 100, default 80; a TypeError with 'png'
348
+ maxBytes?: number; // default 5 MiB
349
+ maxPixels?: number; // default 25 000 000
350
+ signal?: AbortSignal;
351
+ };
352
+ type PdfRenderedImage<F extends RenderFormat = RenderFormat> = {
353
+ source: { format: 'pdf'; pages: number; width: number; height: number }; // page 1, in points
354
+ bytes: Uint8Array;
355
+ width: number;
356
+ height: number;
357
+ contentType: 'image/jpeg' | 'image/webp' | 'image/png'; // follows F
358
+ };
359
+ ```
360
+
361
+ ### `ImageError`
362
+
363
+ `class ImageError extends Error`, with `code: ImageErrorCode` and
364
+ `reason: ImageErrorReason` (see [Errors](#errors)). `extends Error`, not
365
+ `TypeError`, so a handler's `TypeError` branch never catches it.
366
+
367
+ ```ts
368
+ type ImageErrorCode =
369
+ | 'TOO_LARGE'
370
+ | 'UNSUPPORTED_TYPE'
371
+ | 'UNDECODABLE'
372
+ | 'TOO_SMALL'
373
+ | 'INVALID_CROP';
374
+ type ImageErrorReason =
375
+ | 'bytes'
376
+ | 'pixels'
377
+ | 'format'
378
+ | 'heic-unavailable'
379
+ | 'decode'
380
+ | 'dimensions'
381
+ | 'crop';
382
+ ```
383
+
384
+ ### `cropFromQuery(params)`
385
+
386
+ `(params: URLSearchParams) => CropBox | undefined`. Reads the optional square
387
+ crop of an upload route from `?x=&y=&size=`: `undefined` when none of the three
388
+ is present, otherwise a crop where a missing, blank or non-numeric value is
389
+ `NaN`. Nothing is validated here: the set refuses it as `INVALID_CROP`.
390
+
391
+ ```ts
392
+ import { cropFromQuery } from '@softistx/image';
393
+
394
+ const crop = cropFromQuery(new URL(request.url).searchParams);
395
+ const processed = await set.process(await request.blob(), { crop });
396
+ ```
397
+
398
+ ### `uploadImage(store, owner, request)` (`@softistx/image/s3`)
399
+
400
+ `<P extends { imageId: string }>(store, owner: Omit<P, 'imageId'>, request: Request) => Promise<{ id, version, variants }>`.
401
+ Refuses a request whose `content-type` is not `image/*` with
402
+ `UNSUPPORTED_TYPE`, then streams the body into `store.replace` under a fresh
403
+ `crypto.randomUUID()` id, with the crop of `cropFromQuery`. A body over the
404
+ byte limit is `TOO_LARGE`; a bad crop is `INVALID_CROP`. Save `id` and
405
+ `version`, then remove the former image.
406
+
407
+ ```ts
408
+ import { uploadImage } from '@softistx/image/s3';
409
+
410
+ // PUT /images/item?x=0&y=0&size=300
411
+ const { id, version } = await uploadImage(avatars, { userId }, request);
412
+ ```
413
+
414
+ ### `bindImageStore(set, bucket)` (`@softistx/image/s3`)
415
+
416
+ `<P extends { size: number }>(set: ImageSet, bucket: BoundBucket<P>) => ImageStore<Omit<P, 'size'>>`.
417
+ The bucket's key takes a `size` number beside its other params; the store's
418
+ methods take the params without it.
419
+
420
+ | `ImageStore<P>` | |
421
+ | --- | --- |
422
+ | `replace(params, input, { crop }?)` | `Promise<StoredImage>`: processes the upload, puts every size with the set's `contentType`, returns `{ version, variants }`. A refused upload writes nothing; a failed put deletes only the keys whose put succeeded |
423
+ | `remove(params)` | `Promise<void>`: deletes every size; a missing object is fine |
424
+ | `presignGet(params, size, options?)` | a signed URL for one size (`options` is `@softistx/s3`'s `PresignGetOptions`). A `size` outside the set is a `RangeError` |
425
+ | `bytes(params, size)` | `Promise<Uint8Array \| undefined>` |
426
+ | `keyFor(params, size)` | the key of one size. A `size` outside the set is a `RangeError` |
427
+
428
+ ```ts
429
+ type StoredImage<F extends ImageFormat = ImageFormat> = { version: string; variants: StoredVariant<F>[] };
430
+ type StoredVariant<F extends ImageFormat = ImageFormat> = {
431
+ size: number;
432
+ key: string;
433
+ width: number;
434
+ height: number;
435
+ contentType: ImageContentType<F>; // the set's
436
+ byteLength: number;
437
+ };
438
+ ```
439
+
440
+ `version` is 16 hex characters of the SHA-256 over the variants' bytes: the
441
+ same picture processed again gives the same version, so it can be a
442
+ cache-busting query.
443
+
444
+ ## Errors
445
+
446
+ A refusal is an `ImageError` whose `code` and `reason` tell a caller which
447
+ check failed. Every one is thrown before anything is stored.
448
+
449
+ | `code` | `reason` | When |
450
+ | --- | --- | --- |
451
+ | `TOO_LARGE` | `bytes`, `pixels` | the upload is over `maxBytes`, or claims more than `maxPixels` |
452
+ | `UNSUPPORTED_TYPE` | `format`, `heic-unavailable` | the first bytes are not a JPEG, PNG, WebP or HEIC (a PDF for `renderPdfFirstPage`), a HEIC on a machine that cannot decode one (Linux), or a format this machine cannot decode |
453
+ | `UNDECODABLE` | `decode` | the format is right and the content is damaged or unsupported (for a PDF: damaged, password-protected or without a page) |
454
+ | `TOO_SMALL` | `dimensions` | the short side, or the crop, is under `minSide`; for `renderImage`, the crop (or picture) is smaller than `width` x `height` on either side |
455
+ | `INVALID_CROP` | `crop` | the `crop` is not three whole numbers of 0 or more (`{ x, y, width, height }` for `renderImage`), or does not fit the image |
456
+
457
+ ```ts
458
+ import { defineImageSet, ImageError } from '@softistx/image';
459
+
460
+ try {
461
+ await defineImageSet().process(bytes);
462
+ } catch (error) {
463
+ if (error instanceof ImageError) {
464
+ console.log(error.code, error.reason, error.cause); // cause: Bun's error, when there is one
465
+ }
466
+ }
467
+ ```
468
+
469
+ Other errors (an S3 failure, an out-of-memory) are not turned into an
470
+ `ImageError`. A bad **option** or a wrong **input type** is a `TypeError`, and a
471
+ `size` the store does not have is a `RangeError`: all three are the caller's
472
+ code, not the upload.
473
+
474
+ The exact messages of the other errors, each explained in
475
+ [troubleshooting](docs/troubleshooting.md):
476
+
477
+ - `TypeError`: [`image input must be a Uint8Array, an ArrayBuffer, a Blob or a ReadableStream of Uint8Array`](docs/troubleshooting.md#image-input-must-be-a-uint8array-an-arraybuffer-a-blob-or-a-readablestream-of-uint8array)
478
+ - `TypeError`: [`a stream chunk must be a Uint8Array`](docs/troubleshooting.md#a-stream-chunk-must-be-a-uint8array)
479
+ - `TypeError` from an option: [`<option> must be a whole number of <min> or more, got <value>`, `<option> must be a whole number of <min> to <max>, got <value>`, `sizes must be a non-empty array of whole numbers`, `sizes must be unique, got [<sizes>]`](docs/troubleshooting.md#input-and-options)
480
+ - `ImageError` `INVALID_CROP`: [`a crop is { x, y, size }, three whole numbers of 0 or more`](docs/troubleshooting.md#a-crop-is--x-y-size--three-whole-numbers-of-0-or-more)
481
+ - `TypeError` from `renderImage`: [`format must be 'jpeg', 'webp' or 'png', got <value>`, `quality applies to JPEG and WebP only: a PNG is always lossless`](docs/troubleshooting.md#renderimage)
482
+ - `ImageError` `INVALID_CROP` from `renderImage`: [`a crop is { x, y, width, height }, whole numbers: ...`, `a <w>x<h> crop at (<x>, <y>) does not fit the <w>x<h> image`](docs/troubleshooting.md#renderimage)
483
+ - `ImageError` `TOO_SMALL` from `renderImage`: [`the crop is <w>x<h>, under the <w>x<h> asked for`](docs/troubleshooting.md#renderimage)
484
+ - `ImageError` `INVALID_CROP`: [`a <size>px crop at (<x>, <y>) does not fit the <w>x<h> image`](docs/troubleshooting.md#a-sizepx-crop-at-x-y-does-not-fit-the-wxh-image)
485
+ - `RangeError`: [`<call>: size <n> is not one of the set's sizes (<sizes>)`](docs/troubleshooting.md#call-size-n-is-not-one-of-the-sets-sizes-sizes)
486
+ - `TypeError` on an old Bun: [`@softistx/image needs Bun 1.4.1 or later, where Bun.Image exists`](docs/troubleshooting.md#softistximage-needs-bun-141-or-later-where-bunimage-exists)
487
+
488
+ ## What does not compile
489
+
490
+ Each is a `@ts-expect-error` case in `test/types/process.ts` or
491
+ `test/types/s3.ts`.
492
+
493
+ - An input that is a string (a path) or a number, and a `crop` without `x`,
494
+ `y` and `size` or given as a width and a height.
495
+ - `sizes` that is a number or a list of strings, an option the set does not
496
+ have, and a `process` option other than `crop`.
497
+ - An `ImageError` built with a `code` or a `reason` that is not in the lists.
498
+ - A bucket whose key has no `size`, a `size` that is a string or optional, or
499
+ that is passed inside the params.
500
+ - Params missing `imageId` (or whatever the key names) on `replace`, `remove`
501
+ or `keyFor`, a `replace` of a number, and a `remove` with a non-string id.
502
+ - A `format` other than `'webp'` or `'png'`, `lossless` or `quality` beside
503
+ `format: 'png'`, and a `lossless` that is not a boolean; a png set's
504
+ `contentType` (and its variants') is `'image/png'`, so assigning it to
505
+ `'image/webp'` does not compile.
506
+
507
+ ## Traps
508
+
509
+ - **Bun 1.4.3 holds on to every `png()` output.** The pipeline encodes one PNG
510
+ per call (the shrunk image), and Bun keeps it until a later collection, about
511
+ its size per call, giving memory back only in bursts. Measured on photo-like
512
+ JPEGs: 70 sequential calls with a 256 px crop climbed to about 720 MB at
513
+ 25 MP and past 1.6 GB at 36 MP, then fell back. A centred crop with the
514
+ default sizes stays flat (about 17 MB). The expensive path is a small `crop`
515
+ on a huge image, or large `sizes`: one call peaks at about Bun's decode of the
516
+ source (4 bytes per pixel) + the intermediate PNG + the crop square
517
+ (about `4 x (2 x the largest size)^2` bytes). `concurrency` limits the calls
518
+ in flight, **not** this retention, so it is not a hard memory ceiling; lower
519
+ `maxPixels` to shrink both. These figures were measured with the default
520
+ WebP output. A `format: 'png'` set also keeps one `png()` output per size,
521
+ on top of the shrink's; not yet measured. See [processing](docs/guide/processing.md#memory-and-concurrency).
522
+ - **A PNG variant is several times the size of a WebP one.** A `format: 'png'`
523
+ set stores much larger objects for a photo, so the bucket's `maxSize` must
524
+ allow for the largest PNG variant, or every put is refused.
525
+ - **The default `maxBytes` refuses large phone photos.** `maxPixels` (25 MP)
526
+ admits a 24 MP photo, but 5 MiB refuses many JPEGs above about 12 MP, and a 48 MP one
527
+ (about 11 MB) always. Raise `maxBytes` with `maxPixels`.
528
+ - **There is no `acl` option, and a public default `acl` applies.** The store
529
+ passes only `type` on a put, so an `acl` given to `bindBucket` is sent on
530
+ every object. Bind the bucket without one.
531
+ - **HEIC is refused on Linux** (`UNSUPPORTED_TYPE`, `heic-unavailable`); it
532
+ decodes on macOS and Windows only.
533
+ - **Fixed params plus `remove(former)` delete the new image.** With a key that
534
+ does not change, `replace` writes under the same keys the former image used,
535
+ so removing "the former" removes what you just stored. Use a fresh id per
536
+ upload and remove the former id's set afterwards.
537
+ - **Orientation is applied for a JPEG only.** The orientation tag of a PNG or a
538
+ WebP is ignored, so a `crop` is in the stored frame for those.
539
+ - **The wait queue behind `concurrency` is unbounded**, and each waiting call
540
+ holds its upload's bytes (up to `maxBytes`). Cap uploads before `process`.
541
+ - **A bad `crop` is an `ImageError`** (`INVALID_CROP`), not a `RangeError`:
542
+ answer it with a 4xx like the other refusals.
543
+
544
+ ## Documentation
545
+
546
+ - [docs/README.md](docs/README.md): the index of the guides.
547
+ - [Processing](docs/guide/processing.md): inputs, limits, the crop, memory, HEIC.
548
+ - [Rendering](docs/guide/rendering.md): `renderImage`, rectangle crops, JPEG, never enlarging.
549
+ - [Thumbnail of a PDF](docs/guide/pdf.md): `renderPdfFirstPage`, the optional peers, refusals.
550
+ - [Storing](docs/guide/storing.md): bucket keys, the fresh-id recipe, serving.
551
+ - [docs/troubleshooting.md](docs/troubleshooting.md): the messages a consumer sees, and their fixes.
552
+ - [docs/roadmap.md](docs/roadmap.md): what is next.
@@ -0,0 +1,20 @@
1
+ // src/crop/from-query.ts
2
+ var NAMES = ["x", "y", "size"];
3
+ function numberOf(params, name) {
4
+ const value = params.get(name);
5
+ return value === null || value.trim() === "" ? Number.NaN : Number(value);
6
+ }
7
+ function cropFromQuery2(params) {
8
+ if (NAMES.every((name) => !params.has(name)))
9
+ return;
10
+ return {
11
+ x: numberOf(params, "x"),
12
+ y: numberOf(params, "y"),
13
+ size: numberOf(params, "size")
14
+ };
15
+ }
16
+
17
+ export { cropFromQuery2 };
18
+
19
+ //# debugId=B9B3280435ADC2BD64756E2164756E21
20
+ //# sourceMappingURL=index-b71y3faz.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/crop/from-query.ts"],
4
+ "sourcesContent": [
5
+ "import type { CropBox } from '../set/types';\n\nconst NAMES = ['x', 'y', 'size'] as const;\n\nfunction numberOf(params: URLSearchParams, name: (typeof NAMES)[number]) {\n\tconst value = params.get(name);\n\treturn value === null || value.trim() === '' ? Number.NaN : Number(value);\n}\n\n/**\n * The square crop an upload route reads from `?x=&y=&size=`.\n *\n * - None of the three present: `undefined`, the default centred crop.\n * - Otherwise a `CropBox`, where a missing, blank or non-numeric value is\n * `NaN`. Nothing is validated here: the set refuses it as `INVALID_CROP`,\n * a refusal to answer with a 4xx.\n */\nexport function cropFromQuery(params: URLSearchParams): CropBox | undefined {\n\tif (NAMES.every((name) => !params.has(name))) return undefined;\n\treturn {\n\t\tx: numberOf(params, 'x'),\n\t\ty: numberOf(params, 'y'),\n\t\tsize: numberOf(params, 'size'),\n\t};\n}\n"
6
+ ],
7
+ "mappings": ";AAEA,IAAM,QAAQ,CAAC,KAAK,KAAK,MAAM;AAE/B,SAAS,QAAQ,CAAC,QAAyB,MAA8B;AAAA,EACxE,MAAM,QAAQ,OAAO,IAAI,IAAI;AAAA,EAC7B,OAAO,UAAU,QAAQ,MAAM,KAAK,MAAM,KAAK,OAAO,MAAM,OAAO,KAAK;AAAA;AAWlE,SAAS,cAAa,CAAC,QAA8C;AAAA,EAC3E,IAAI,MAAM,MAAM,CAAC,SAAS,CAAC,OAAO,IAAI,IAAI,CAAC;AAAA,IAAG;AAAA,EAC9C,OAAO;AAAA,IACN,GAAG,SAAS,QAAQ,GAAG;AAAA,IACvB,GAAG,SAAS,QAAQ,GAAG;AAAA,IACvB,MAAM,SAAS,QAAQ,MAAM;AAAA,EAC9B;AAAA;",
8
+ "debugId": "B9B3280435ADC2BD64756E2164756E21",
9
+ "names": []
10
+ }