@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
@@ -0,0 +1,23 @@
1
+ import type { ImageFormat } from '../set/options.js';
2
+ import type { ImageStore, StoredImage } from './types.js';
3
+ /**
4
+ * Stores the image a request uploads, under a fresh id.
5
+ *
6
+ * - The request's `content-type` must be `image/*` (any case, parameters
7
+ * ignored); otherwise `ImageError` `UNSUPPORTED_TYPE` / `format`, before the
8
+ * body is read. The bytes themselves are still judged by their magic bytes.
9
+ * - The body is streamed into `store.replace`, so a body over the set's byte
10
+ * limit is an `ImageError` `TOO_LARGE` / `bytes` and is cancelled at the
11
+ * chunk that crosses it.
12
+ * - The optional crop comes from `?x=&y=&size=` (see `cropFromQuery`); a
13
+ * bad one is `INVALID_CROP`.
14
+ *
15
+ * `owner` is the store's params without `imageId`; the id is
16
+ * `crypto.randomUUID()` and is returned, to be saved beside `version`.
17
+ */
18
+ export declare function uploadImage<P extends {
19
+ imageId: string;
20
+ }, F extends ImageFormat = ImageFormat>(store: Pick<ImageStore<P, F>, 'replace'>, owner: Omit<P, 'imageId'>, request: Request): Promise<{
21
+ id: string;
22
+ } & StoredImage<F>>;
23
+ //# sourceMappingURL=upload-image.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload-image.d.ts","sourceRoot":"","sources":["../../src/s3/upload-image.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAEvD;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,WAAW,CAChC,CAAC,SAAS;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,EAC7B,CAAC,SAAS,WAAW,GAAG,WAAW,EAEnC,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,SAAS,CAAC,EACxC,KAAK,EAAE,IAAI,CAAC,CAAC,EAAE,SAAS,CAAC,EACzB,OAAO,EAAE,OAAO,GACd,OAAO,CAAC;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,CAkB1C"}
@@ -0,0 +1,25 @@
1
+ import { type ImageFormat, type ImageSetOptions } from './options.js';
2
+ import type { ImageSet } from './types.js';
3
+ /**
4
+ * An image set: what to make of an upload, defined once.
5
+ *
6
+ * ```ts
7
+ * const avatars = defineImageSet({ sizes: [256, 64] });
8
+ * const { variants } = await avatars.process(await request.blob());
9
+ * ```
10
+ *
11
+ * The set's type follows `options.format`: `defineImageSet()` is an
12
+ * `ImageSet<'webp'>`, `defineImageSet({ format: 'png' })` an `ImageSet<'png'>`.
13
+ *
14
+ * Throws a `TypeError` on a Bun older than 1.4.1, where `Bun.Image` is missing.
15
+ * Invalid options throw a `TypeError` here, naming the option.
16
+ */
17
+ export declare function defineImageSet(options?: ImageSetOptions & {
18
+ format?: 'webp';
19
+ }): ImageSet<'webp'>;
20
+ export declare function defineImageSet<F extends ImageFormat>(options: ImageSetOptions & {
21
+ format: F;
22
+ }): ImageSet<F>;
23
+ /** Options whose format is only known as `ImageFormat`: a set of either. */
24
+ export declare function defineImageSet(options?: ImageSetOptions): ImageSet;
25
+ //# sourceMappingURL=define-image-set.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"define-image-set.d.ts","sourceRoot":"","sources":["../../src/set/define-image-set.ts"],"names":[],"mappings":"AAEA,OAAO,EAEN,KAAK,WAAW,EAChB,KAAK,eAAe,EAEpB,MAAM,WAAW,CAAC;AAEnB,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAExC;;;;;;;;;;;;;GAaG;AACH,wBAAgB,cAAc,CAC7B,OAAO,CAAC,EAAE,eAAe,GAAG;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAC7C,QAAQ,CAAC,MAAM,CAAC,CAAC;AACpB,wBAAgB,cAAc,CAAC,CAAC,SAAS,WAAW,EACnD,OAAO,EAAE,eAAe,GAAG;IAAE,MAAM,EAAE,CAAC,CAAA;CAAE,GACtC,QAAQ,CAAC,CAAC,CAAC,CAAC;AACf,4EAA4E;AAC5E,wBAAgB,cAAc,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,QAAQ,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * A FIFO semaphore: `limit(task)` runs the task once fewer than `max` tasks
3
+ * are running, tasks starting in the order they were submitted. A task that
4
+ * throws frees its place, and its error is the caller's.
5
+ */
6
+ export declare function createLimit(max: number): <T>(task: () => Promise<T>) => Promise<T>;
7
+ //# sourceMappingURL=limit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limit.d.ts","sourceRoot":"","sources":["../../src/set/limit.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,WAAW,CAC1B,GAAG,EAAE,MAAM,GACT,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAoB3C"}
@@ -0,0 +1,104 @@
1
+ /** The variants' format. */
2
+ export type ImageFormat = 'webp' | 'png';
3
+ /** The content type of each format: the one place the two are paired. */
4
+ export declare const CONTENT_TYPES: Readonly<{
5
+ readonly webp: "image/webp";
6
+ readonly png: "image/png";
7
+ }>;
8
+ /** A variant's content type, following its set's format `F`. */
9
+ export type ImageContentType<F extends ImageFormat = ImageFormat> = (typeof CONTENT_TYPES)[F];
10
+ /** The content type of a format: `image/webp` or `image/png`. */
11
+ export declare function contentTypeOf<F extends ImageFormat>(format: F): ImageContentType<F>;
12
+ /** The options a WebP set takes beside the common ones. */
13
+ type WebpOutput = {
14
+ /** The variants' format. Default `'webp'`. */
15
+ format?: 'webp';
16
+ /** Lossless WebP. Default `false`, lossy at `quality`. */
17
+ lossless?: boolean;
18
+ /**
19
+ * The WebP quality, 1 to 100. Default 80. With `lossless`, it trades
20
+ * encoding time for size instead of losing detail.
21
+ */
22
+ quality?: number;
23
+ };
24
+ /**
25
+ * A PNG set: each size encoded once to PNG from the decoded upload. `quality`
26
+ * and `lossless` are WebP's, so they are refused here.
27
+ */
28
+ type PngOutput = {
29
+ format: 'png';
30
+ lossless?: never;
31
+ quality?: never;
32
+ };
33
+ /** What `defineImageSet` takes; every field has a default. */
34
+ export type ImageSetOptions = (WebpOutput | PngOutput) & {
35
+ /**
36
+ * The square sides to produce, in pixels: a non-empty list of unique whole
37
+ * numbers from 1 to 4096. Default `[256, 64]`.
38
+ */
39
+ sizes?: readonly number[];
40
+ /**
41
+ * The upload's byte limit, a whole number of 1 or more. Default 5 MiB,
42
+ * which admits most 12 MP photos but refuses most 48 MP phone JPEGs (about
43
+ * 11 MB). Raise it with `maxPixels`: `maxBytes: 12 * 1024 * 1024`.
44
+ */
45
+ maxBytes?: number;
46
+ /**
47
+ * The most pixels (width × height) an upload may claim, a whole number of
48
+ * 1 or more. Default 25 000 000, which covers a 24 MP phone's output. A
49
+ * 48 MP image is admitted only by raising this, and its JPEG (about 11 MB)
50
+ * is refused by the default `maxBytes` first: raise both.
51
+ *
52
+ * **Memory.** One call peaks at about Bun's decode of the source (4 bytes
53
+ * per pixel) + the intermediate PNG + the crop square, about
54
+ * 4 × (2 × the largest size)² bytes. A centred crop with the default sizes
55
+ * is cheap (17 to 18 MB measured, at 12 to 49 MP). The expensive path is a
56
+ * small caller `crop` on a big image, or large `sizes`. Measured on
57
+ * Bun 1.4.3, photo-like JPEGs, one call: a 256 px crop on 25 MP grows the
58
+ * process by about 150 MB (2.7 s), on 36 MP about 210 MB (4 s), on 49 MP
59
+ * about 280 MB (5.4 s); `sizes: [4096]` on 49 MP about 0.9 to 1.3 GB (9 s) and `[2048]` about
60
+ * 460 to 530 MB (3 s).
61
+ *
62
+ * **Bun 1.4.3 holds on to each `png()` output** (about the size of that
63
+ * PNG per call) until a later collection, so sequential worst-case calls
64
+ * climb before the memory falls back: 70 calls with a small crop climbed to
65
+ * about 720 MB at 25 MP and to over 1.6 GB at 36 MP. Lowering `maxPixels`
66
+ * is the lever that shrinks both.
67
+ */
68
+ maxPixels?: number;
69
+ /**
70
+ * The smallest side an upload, or a crop of it, may have. Default: the
71
+ * largest of `sizes`, so no variant is ever enlarged.
72
+ */
73
+ minSide?: number;
74
+ /**
75
+ * How many `process` calls of this set decode at once, a whole number from
76
+ * 1 to 64. Default 2. The others wait their turn, in order, after their
77
+ * bytes are read and their format sniffed. It limits the calls in flight,
78
+ * **not the memory**: Bun holds each `png()` output until a later
79
+ * collection (see `maxPixels`), so memory can pass `concurrency` × one
80
+ * call's peak. Measured on Bun 1.4.3, photo-like JPEG, 36 MP with a 256 px
81
+ * crop, 4 calls at once grew the process by about 770 MB with `concurrency`
82
+ * 4, 510 MB with 2 and 330 MB with 1.
83
+ *
84
+ * **The wait queue is not bounded**, and each waiting call holds its
85
+ * upload's bytes (up to `maxBytes`). A server that can receive more uploads
86
+ * than it decodes should cap them before they reach `process`.
87
+ */
88
+ concurrency?: number;
89
+ };
90
+ /** The options with every default applied. */
91
+ export type ResolvedOptions = {
92
+ readonly sizes: readonly number[];
93
+ readonly maxBytes: number;
94
+ readonly maxPixels: number;
95
+ readonly minSide: number;
96
+ readonly quality: number;
97
+ readonly concurrency: number;
98
+ readonly format: ImageFormat;
99
+ readonly lossless: boolean;
100
+ };
101
+ /** The options with their defaults, or a `TypeError` naming the bad one. */
102
+ export declare function resolveOptions(options?: ImageSetOptions): ResolvedOptions;
103
+ export {};
104
+ //# sourceMappingURL=options.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../../src/set/options.ts"],"names":[],"mappings":"AAEA,4BAA4B;AAC5B,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,KAAK,CAAC;AAEzC,yEAAyE;AACzE,eAAO,MAAM,aAAa;;;EAGf,CAAC;AAEZ,gEAAgE;AAChE,MAAM,MAAM,gBAAgB,CAAC,CAAC,SAAS,WAAW,GAAG,WAAW,IAC/D,CAAC,OAAO,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC;AAE3B,iEAAiE;AACjE,wBAAgB,aAAa,CAAC,CAAC,SAAS,WAAW,EAClD,MAAM,EAAE,CAAC,GACP,gBAAgB,CAAC,CAAC,CAAC,CAErB;AAED,2DAA2D;AAC3D,KAAK,UAAU,GAAG;IACjB,8CAA8C;IAC9C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,0DAA0D;IAC1D,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF;;;GAGG;AACH,KAAK,SAAS,GAAG;IAChB,MAAM,EAAE,KAAK,CAAC;IACd,QAAQ,CAAC,EAAE,KAAK,CAAC;IACjB,OAAO,CAAC,EAAE,KAAK,CAAC;CAChB,CAAC;AAEF,8DAA8D;AAC9D,MAAM,MAAM,eAAe,GAAG,CAAC,UAAU,GAAG,SAAS,CAAC,GAAG;IACxD;;;OAGG;IACH,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;;;;;;;;;;OAaG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,8CAA8C;AAC9C,MAAM,MAAM,eAAe,GAAG;IAC7B,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;CAC3B,CAAC;AA0DF,4EAA4E;AAC5E,wBAAgB,cAAc,CAAC,OAAO,GAAE,eAAoB,GAAG,eAAe,CAmB7E"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Throws a clear `TypeError` when the runtime has no `Bun.Image` (Bun older
3
+ * than 1.4.1, or not Bun at all). Takes the `Bun` global as an argument so it
4
+ * can be tested without touching the real one.
5
+ */
6
+ export declare function assertBunImage(bun: unknown): void;
7
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/set/runtime.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAUjD"}
@@ -0,0 +1,60 @@
1
+ import type { ImageInput } from '../input/read-input.js';
2
+ import type { SniffedFormat } from '../input/sniff.js';
3
+ import type { ImageContentType, ImageFormat } from './options.js';
4
+ export type { ImageContentType } from './options.js';
5
+ /**
6
+ * A square to keep, in pixels of the **auto-oriented** image: the picture as
7
+ * a person sees it, after EXIF rotation. `(x, y)` is its top-left corner.
8
+ *
9
+ * Only a JPEG's EXIF orientation is applied (measured on Bun 1.4.3): the
10
+ * orientation of a PNG (`eXIf`) or of a WebP (`EXIF`) is ignored, so for those
11
+ * the frame is the stored one.
12
+ */
13
+ export type CropBox = {
14
+ x: number;
15
+ y: number;
16
+ size: number;
17
+ };
18
+ export type ProcessOptions = {
19
+ /** The square to keep. Default: the centred square of the short side. */
20
+ crop?: CropBox;
21
+ };
22
+ /** One output: a square WebP, or PNG with `format: 'png'`. */
23
+ export type ImageVariant<F extends ImageFormat = ImageFormat> = {
24
+ /** The side asked for in `sizes`; `width` and `height` equal it. */
25
+ size: number;
26
+ width: number;
27
+ height: number;
28
+ /** The set's `contentType`. */
29
+ contentType: ImageContentType<F>;
30
+ bytes: Uint8Array;
31
+ };
32
+ export type ProcessedImage<F extends ImageFormat = ImageFormat> = {
33
+ /** The upload as read: its format and its oriented size. */
34
+ source: {
35
+ format: SniffedFormat;
36
+ width: number;
37
+ height: number;
38
+ };
39
+ /** One per size, in the order of `sizes`. */
40
+ variants: ImageVariant<F>[];
41
+ };
42
+ /**
43
+ * An image set; `F` is its format, inferred by `defineImageSet` from
44
+ * `options.format` (`'webp'` when absent). `ImageSet` alone takes any set.
45
+ */
46
+ export type ImageSet<F extends ImageFormat = ImageFormat> = {
47
+ /** The sides this set produces, in the order of `process`'s variants. */
48
+ readonly sizes: readonly number[];
49
+ /** The variants' format, also the extension to put in a key. */
50
+ readonly format: F;
51
+ /** The variants' content type: `image/webp` or `image/png`. */
52
+ readonly contentType: ImageContentType<F>;
53
+ /**
54
+ * Checks, crops, resizes and re-encodes an upload to the set's format, with every
55
+ * metadata stripped. Refusals are `ImageError`; a `crop` that is not
56
+ * whole numbers or does not fit the image is an `ImageError` (`INVALID_CROP`).
57
+ */
58
+ process(input: ImageInput, options?: ProcessOptions): Promise<ProcessedImage<F>>;
59
+ };
60
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/set/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAE/D,YAAY,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAElD;;;;;;;GAOG;AACH,MAAM,MAAM,OAAO,GAAG;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAE7D,MAAM,MAAM,cAAc,GAAG;IAC5B,yEAAyE;IACzE,IAAI,CAAC,EAAE,OAAO,CAAC;CACf,CAAC;AAEF,8DAA8D;AAC9D,MAAM,MAAM,YAAY,CAAC,CAAC,SAAS,WAAW,GAAG,WAAW,IAAI;IAC/D,oEAAoE;IACpE,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,+BAA+B;IAC/B,WAAW,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;IACjC,KAAK,EAAE,UAAU,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,cAAc,CAAC,CAAC,SAAS,WAAW,GAAG,WAAW,IAAI;IACjE,4DAA4D;IAC5D,MAAM,EAAE;QAAE,MAAM,EAAE,aAAa,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IACjE,6CAA6C;IAC7C,QAAQ,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC;CAC5B,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,QAAQ,CAAC,CAAC,SAAS,WAAW,GAAG,WAAW,IAAI;IAC3D,yEAAyE;IACzE,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,gEAAgE;IAChE,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;IACnB,+DAA+D;IAC/D,QAAQ,CAAC,WAAW,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;IAC1C;;;;OAIG;IACH,OAAO,CACN,KAAK,EAAE,UAAU,EACjB,OAAO,CAAC,EAAE,cAAc,GACtB,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC;CAC9B,CAAC"}
@@ -0,0 +1,3 @@
1
+ /** Whether the value is a whole number from `min` (default 0) to `max` (default: no limit). */
2
+ export declare function isWhole(value: unknown, min?: number, max?: number): value is number;
3
+ //# sourceMappingURL=whole.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"whole.d.ts","sourceRoot":"","sources":["../../src/set/whole.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,wBAAgB,OAAO,CACtB,KAAK,EAAE,OAAO,EACd,GAAG,SAAI,EACP,GAAG,SAA2B,GAC5B,KAAK,IAAI,MAAM,CAOjB"}
package/docs/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # `@softistx/image` documentation
2
+
3
+ Avatar and photo uploads on Bun's own `Bun.Image`. Start with the
4
+ [README](../README.md); these pages hold the detail.
5
+
6
+ | Page | Read it when |
7
+ | --- | --- |
8
+ | [Processing](guide/processing.md) | you turn an upload into WebP or PNG squares: inputs, the output format, limits, the crop (`cropFromQuery`), memory, HEIC |
9
+ | [Rendering](guide/rendering.md) | you need one picture of any ratio, a rectangle crop, or JPEG: `renderImage` |
10
+ | [Thumbnail of a PDF](guide/pdf.md) | you need a preview of page 1 of a PDF: `renderPdfFirstPage` from `@softistx/image/pdf` |
11
+ | [Storing](guide/storing.md) | you keep the variants in a `@softistx/s3` bucket and serve them; `uploadImage` for an HTTP route |
12
+ | [Troubleshooting](troubleshooting.md) | you have an error message and want its cause |
13
+ | [Roadmap](roadmap.md) | you want to know what is next |
@@ -0,0 +1,60 @@
1
+ # Thumbnail of a PDF
2
+
3
+ `renderPdfFirstPage` from `@softistx/image/pdf` draws page 1 of a PDF as one
4
+ picture (WebP, JPEG or PNG), with the same inputs, limits and `ImageError`
5
+ refusals as [`renderImage`](rendering.md). The page is drawn by
6
+ [pdf.js](https://github.com/mozilla/pdf.js) on a
7
+ [`@napi-rs/canvas`](https://github.com/Brooooooklyn/canvas) (prebuilt binaries,
8
+ no system binary), then encoded by `Bun.Image`, like every other picture of this
9
+ package.
10
+
11
+ ## Install the two optional peers
12
+
13
+ Only the `/pdf` subpath needs them; the root entry and `/s3` never import them.
14
+
15
+ ```sh
16
+ bun add pdfjs-dist @napi-rs/canvas
17
+ ```
18
+
19
+ ## Render
20
+
21
+ ```ts
22
+ import { renderPdfFirstPage } from '@softistx/image/pdf';
23
+
24
+ const pdf = await Bun.file('document.pdf').arrayBuffer();
25
+ const { bytes, width, height, contentType, source } = await renderPdfFirstPage(pdf, {
26
+ width: 256,
27
+ format: 'webp',
28
+ });
29
+ // 256 x 362 for an A4 portrait page; source: { format: 'pdf', pages: 12, width: 595, height: 842 }
30
+ ```
31
+
32
+ - `width` (1 to 8192) is the output width. A PDF is vector, so the page is drawn
33
+ at that width, never stretched from a smaller picture, and the height follows
34
+ the page's ratio (rotation applied).
35
+ - `height` is optional and caps the output: a tall page is scaled down to fit
36
+ `width` x `height` and the output is then narrower than `width`.
37
+ - The page is drawn on a **white** background, so a JPEG has no black corners.
38
+ - `format`, `quality` (1 to 100, default 80; a `TypeError` with `png`),
39
+ `maxBytes` (default 5 MiB), `maxPixels` (default 25 000 000, checked on the
40
+ output size before the page is drawn) and `signal` work as in `renderImage`.
41
+ - `source` gives the page count and the size of page 1 in points (1/72 inch).
42
+
43
+ ## Refusals
44
+
45
+ | `code` | `reason` | When |
46
+ | --- | --- | --- |
47
+ | `UNSUPPORTED_TYPE` | `format` | no `%PDF-` header in the first 1024 bytes |
48
+ | `TOO_LARGE` | `bytes`, `pixels` | the file is over `maxBytes`, or the page would render over `maxPixels` (or 8192 on a side) |
49
+ | `UNDECODABLE` | `decode` | the PDF is damaged, password-protected, has no page, or page 1 fails to draw; `error.cause` is pdf.js's error |
50
+
51
+ A missing peer is a plain `Error` naming the two packages (see
52
+ [troubleshooting](../troubleshooting.md#softistximagepdf-needs-the-optional-peers-pdfjs-dist-and-napi-rscanvas)).
53
+
54
+ ## What to know
55
+
56
+ - Only page 1 is drawn. Fonts that a PDF does not embed use pdf.js's bundled
57
+ standard fonts, not the system's.
58
+ - A PDF is untrusted input: system fonts are not read. A hostile file can still be slow to draw, so pass a `signal` with a
59
+ timeout (`AbortSignal.timeout(10_000)`) when the upload is not yours.
60
+ - Calls draw two at a time, like `renderImage`.
@@ -0,0 +1,313 @@
1
+ # Processing an upload
2
+
3
+ How `defineImageSet(...).process(input, { crop })` turns an upload into square
4
+ WebP variants, and what it refuses. For storing the result, see
5
+ [storing](storing.md).
6
+
7
+ ```ts
8
+ import { defineImageSet } from '@softistx/image';
9
+
10
+ const avatars = defineImageSet({ sizes: [256, 64] });
11
+ const { source, variants } = await avatars.process(await request.blob());
12
+
13
+ console.log(source); // { format: 'jpeg', width: 3024, height: 4032 }
14
+ for (const v of variants) console.log(v.size, v.contentType, v.bytes.byteLength);
15
+ ```
16
+
17
+ ```ts
18
+ type ImageInput =
19
+ | Uint8Array
20
+ | ArrayBuffer
21
+ | Blob
22
+ | ReadableStream<Uint8Array>;
23
+
24
+ type ImageSet = {
25
+ readonly sizes: readonly number[];
26
+ process(input: ImageInput, options?: ProcessOptions): Promise<ProcessedImage>;
27
+ };
28
+
29
+ type ProcessedImage = {
30
+ source: { format: 'jpeg' | 'png' | 'webp' | 'heic'; width: number; height: number };
31
+ variants: ImageVariant[]; // one per size, in the order of `sizes`
32
+ };
33
+ ```
34
+
35
+ ## Inputs
36
+
37
+ | Input | How its size is checked |
38
+ | --- | --- |
39
+ | `Uint8Array`, `ArrayBuffer`, `Blob` | against `maxBytes` before anything is read; a `Blob` is checked again once read, since its size is only a claim |
40
+ | `ReadableStream<Uint8Array>`, a `Blob` whose `size` is not a number (Bun's `S3File`) | chunk by chunk; the stream is cancelled at the chunk that crosses `maxBytes`, so no more than the limit plus one chunk is held |
41
+
42
+ ```ts
43
+ const { variants } = await avatars.process(request.body as ReadableStream<Uint8Array>);
44
+ ```
45
+
46
+ Anything else is a `TypeError`:
47
+ `image input must be a Uint8Array, an ArrayBuffer, a Blob or a ReadableStream of Uint8Array`.
48
+ A stream chunk that is not a `Uint8Array` is a `TypeError` too
49
+ (`a stream chunk must be a Uint8Array`).
50
+
51
+ The format is judged by the **first bytes**, never by a file name or a declared
52
+ content type. JPEG, PNG, WebP and HEIC are accepted; anything else, AVIF
53
+ included, is `UNSUPPORTED_TYPE` with reason `format`. `format` also covers a
54
+ format this machine cannot decode, other than HEIC.
55
+
56
+ An AVIF file relabelled with HEIF brands (`mif1` and no `avif` brand) passes
57
+ the sniff as HEIC. Where the machine decodes it (macOS), it is re-encoded to
58
+ WebP like any other image; elsewhere it is `heic-unavailable`. Known and
59
+ harmless: nothing but the pixels leaves the pipeline.
60
+
61
+ ## Options
62
+
63
+ | Option | Type | Default | Effect |
64
+ | --- | --- | --- | --- |
65
+ | `sizes` | `readonly number[]` | `[256, 64]` | the square sides to produce, unique whole numbers from 1 to 4096 |
66
+ | `maxBytes` | `number` | `5 * 1024 * 1024` | byte limit; over it is `TOO_LARGE` (`bytes`). Admits most 12 MP photos; a 48 MP phone JPEG (about 11 MB) is refused until you raise it |
67
+ | `maxPixels` | `number` | `25_000_000` | width x height limit, which covers a 24 MP phone; over it is `TOO_LARGE` (`pixels`). It sets the worst-case memory (see below) |
68
+ | `minSide` | `number` | the largest of `sizes` | the smallest side of the image, or of the crop; under it is `TOO_SMALL` |
69
+ | `format` | `'webp' \| 'png'` | `'webp'` | the variants' format (see [Output format](#output-format)) |
70
+ | `lossless` | `boolean` | `false` | lossless WebP; WebP only |
71
+ | `quality` | `number` | `80` | WebP quality, 1 to 100; WebP only |
72
+ | `concurrency` | `number` | `2` | uploads that decode at once, 1 to 64; not a hard memory ceiling (see below) |
73
+
74
+ To accept 48 MP phones, raise both limits, and plan the memory below:
75
+
76
+ ```ts
77
+ defineImageSet({ maxPixels: 50_000_000, maxBytes: 16 * 1024 * 1024 });
78
+ ```
79
+
80
+ A bad option throws a `TypeError` when the set is defined:
81
+
82
+ | Message |
83
+ | --- |
84
+ | `sizes must be a non-empty array of whole numbers` |
85
+ | `sizes[] must be a whole number of 1 to 4096, got <value>` |
86
+ | `sizes must be unique, got [<sizes>]` |
87
+ | `<option> must be a whole number of <min> or more, got <value>` (`maxBytes`, `maxPixels`, `minSide`) |
88
+ | `<option> must be a whole number of <min> to <max>, got <value>` (`quality`, `concurrency`) |
89
+ | `format must be 'webp' or 'png', got <value>` |
90
+ | `lossless must be a boolean, got <value>` |
91
+ | `lossless applies to WebP only: a PNG is always lossless` |
92
+ | `quality applies to WebP only: a PNG is always lossless` |
93
+
94
+ ```ts
95
+ defineImageSet({ quality: 0 }); // TypeError: quality must be a whole number of 1 to 100, got 0
96
+ ```
97
+
98
+ `minSide` applies to the short side of the image, or to `crop.size` when a crop
99
+ is given. It is checked **after** the crop's shape and fit: a crop that does
100
+ not fit the image is `INVALID_CROP` whatever its size, and a crop that fits but
101
+ is under `minSide` is `TOO_SMALL`.
102
+
103
+ ## The crop
104
+
105
+ Without a crop, the centred square of the short side is kept. With one, give
106
+ `{ x, y, size }` in pixels of the **oriented** picture: the one a person sees
107
+ after EXIF rotation. A phone photo stored sideways with an orientation tag is
108
+ cropped as the upright picture.
109
+
110
+ **Orientation is applied for a JPEG only** (measured on Bun 1.4.3): the
111
+ orientation of a PNG (`eXIf` chunk) or of a WebP (`EXIF` chunk) is ignored, so
112
+ for those the picture is cropped as stored.
113
+
114
+ In an HTTP route, `cropFromQuery(new URL(request.url).searchParams)` reads the
115
+ crop from `?x=&y=&size=`: `undefined` when none is present, otherwise a crop
116
+ whose missing, blank or non-numeric values are `NaN`, refused here as
117
+ `INVALID_CROP`.
118
+
119
+ ```ts
120
+ const { source } = await avatars.process(bytes); // oriented size
121
+ const side = Math.min(source.width, source.height);
122
+
123
+ await avatars.process(bytes, { crop: { x: 0, y: 0, size: side } });
124
+ ```
125
+
126
+ ```ts
127
+ type CropBox = { x: number; y: number; size: number };
128
+ ```
129
+
130
+ | Crop | Result |
131
+ | --- | --- |
132
+ | not three whole numbers of 0 or more | `ImageError` `INVALID_CROP`: `a crop is { x, y, size }, three whole numbers of 0 or more` |
133
+ | outside the image | `ImageError` `INVALID_CROP`: `a <size>px crop at (<x>, <y>) does not fit the <w>x<h> image` |
134
+ | `size` under `minSide` | `ImageError` `TOO_SMALL`: `the crop is <size>px, under the <minSide>px minimum` |
135
+
136
+ `INVALID_CROP` (reason `crop`) is an `ImageError` because the crop usually comes
137
+ from a request: a handler answers a 4xx for it, like any other refusal. The
138
+ internal check on the pixels the package crops (see
139
+ [troubleshooting](../troubleshooting.md#a-wxh-region-at-x-y-does-not-fit-a-wxh-image))
140
+ stays a `RangeError`: it is a bug guard, not a request value.
141
+
142
+ ## Refusals
143
+
144
+ ```ts
145
+ import { defineImageSet, ImageError } from '@softistx/image';
146
+
147
+ try {
148
+ await avatars.process(bytes);
149
+ } catch (error) {
150
+ if (!(error instanceof ImageError)) throw error;
151
+ switch (error.reason) {
152
+ case 'bytes':
153
+ case 'pixels':
154
+ return respond(413);
155
+ case 'format':
156
+ case 'heic-unavailable':
157
+ return respond(415);
158
+ case 'decode':
159
+ case 'dimensions':
160
+ return respond(422);
161
+ case 'crop':
162
+ return respond(400);
163
+ }
164
+ }
165
+ ```
166
+
167
+ | `code` | `reason` | Message |
168
+ | --- | --- | --- |
169
+ | `TOO_LARGE` | `bytes` | `the upload is over <maxBytes> bytes` |
170
+ | `TOO_LARGE` | `pixels` | `the image has too many pixels`, or `the PNG has <w>x<h> pixels, over the <maxPixels> limit` |
171
+ | `UNSUPPORTED_TYPE` | `format` | `the upload is not a JPEG, PNG, WebP or HEIC`, or `this machine cannot decode <format>` |
172
+ | `UNSUPPORTED_TYPE` | `heic-unavailable` | `this machine cannot decode HEIC (Linux cannot)` |
173
+ | `UNDECODABLE` | `decode` | `the <format> image cannot be decoded`, or `the PNG cannot be read: <why>` |
174
+ | `INVALID_CROP` | `crop` | `a crop is { x, y, size }, three whole numbers of 0 or more`, or `a <size>px crop at (<x>, <y>) does not fit the <w>x<h> image` |
175
+ | `TOO_SMALL` | `dimensions` | `the image is <w>x<h>, under <minSide>px on its short side`, or the crop message above |
176
+
177
+ When Bun refuses the image, its own error is `error.cause`. An error that
178
+ Bun's refusal codes do not cover (a bug, an out-of-memory) is rethrown
179
+ untouched, never taken for a bad upload.
180
+
181
+ ## HEIC
182
+
183
+ HEIC decodes where Bun's `Bun.Image` can decode it: **macOS and Windows**. On
184
+ Linux a HEIC is refused as `UNSUPPORTED_TYPE` with reason `heic-unavailable`.
185
+ If your server runs on Linux and users upload from iPhones, ask the client to
186
+ convert, or answer that refusal with a message that says so.
187
+
188
+ ## The pipeline, and why `maxPixels` is checked twice
189
+
190
+ `Bun.Image` has no crop, so the package crops on pixels it decodes itself:
191
+
192
+ 1. read the bytes (`maxBytes`) and sniff the format;
193
+ 2. read the oriented size with `Bun.Image(...).metadata()` under `maxPixels`
194
+ (first check, on what the upload **claims**);
195
+ 3. check the crop and `minSide`;
196
+ 4. shrink the image once, to a PNG at Bun's default level, only as far as the
197
+ largest size needs;
198
+ 5. read that PNG with the package's own reader **while it inflates**, which
199
+ checks `maxPixels` again (second check, on what the PNG **holds**), keeps
200
+ two rows at a time and copies only the square's columns, then stops after
201
+ the square's last row;
202
+ 6. resize the square to each size and encode it to the set's format: WebP
203
+ (`quality`, or `lossless`) or PNG, once per size.
204
+
205
+ The second check exists because the reader in step 5 is ours, not Bun's: it
206
+ does not trust a header that step 4 produced. It also refuses inflated data
207
+ longer than the header promises, as far as it reads: it stops after the
208
+ square, so data past the last row it needs is never looked at.
209
+
210
+ The PNG of step 4 is **not** uncompressed: it is at Bun's default level, which
211
+ gives the smallest PNG, and so the least memory held (see below). On a 36 MP
212
+ photo (Bun 1.4.3, photo-like JPEG) the default level gave a 45 MB PNG and level 0 a 146 MB one, and the
213
+ process grew by about that much per call.
214
+
215
+ ## Memory and `concurrency`
216
+
217
+ **One call peaks at about** Bun's decode of the source (4 bytes per pixel) +
218
+ the intermediate PNG of step 4 + the crop square, about
219
+ `4 x (2 x the largest size)^2` bytes. Our reader adds two rows and the crop
220
+ and nothing that grows with the image. Measured on Bun 1.4.3, on photo-like
221
+ JPEGs (a gradient with sensor-like noise, never a flat test pattern), the
222
+ growth of the process's RSS for one call, each in a fresh process:
223
+
224
+ | Source | Centred crop, `[256, 64]` | 256 px crop, `[256, 64]` | Time of the 256 px crop |
225
+ | --- | --- | --- | --- |
226
+ | 12 MP (4000x3000) | 17 MB | 78 MB | 1.3 s |
227
+ | 25 MP | 17 MB | 148 MB | 2.7 s |
228
+ | 36 MP | 17 MB | 207 MB | 4.0 s |
229
+ | 49 MP | 18 MB | 276 MB | 5.4 s |
230
+
231
+ | 49 MP, centred crop | Peak | Time |
232
+ | --- | --- | --- |
233
+ | `sizes: [1024]` | 105 MB | 0.7 s |
234
+ | `sizes: [2048]` | 460 to 530 MB | 3 s |
235
+ | `sizes: [4096]` | 0.9 to 1.3 GB | 9 s |
236
+
237
+ A **centred crop with small sizes is cheap**: the shrink makes a small image
238
+ first. The **expensive path** is a small `crop` on a huge image (the shrink
239
+ cannot go below the source) or large `sizes` (the crop square is
240
+ `(2 x the largest size)^2` pixels).
241
+
242
+ **Bun 1.4.3 holds on to every `png()` output** until a later collection, about
243
+ the PNG's size per call, and gives it back only in bursts. Sequential calls
244
+ with a small crop therefore climb before the memory falls: 70 calls on 25 MP
245
+ photos climbed to 716 MB (falling back to about 140 MB several times); 70 calls
246
+ on 36 MP photos climbed past 1.6 GB. JPEG encoding does not do this, and the
247
+ default centred crop stays flat. That is why the default `maxPixels` is
248
+ 25 million, and why the default PNG level is kept: it makes the smallest PNG.
249
+ These figures were measured with the default WebP output. A `format: 'png'`
250
+ set also keeps one `png()` output per size, on top of the shrink's; that has
251
+ not been measured yet.
252
+
253
+ **`concurrency` is not a hard ceiling** for the same reason. It limits how many
254
+ calls decode at once, and four 36 MP calls with a 256 px crop (Bun 1.4.3, photo-like JPEG) grew the process by
255
+ 330 MB at `concurrency` 1, 510 MB at 2 and 770 MB at 4 (the last two in 4.3 to
256
+ 8.2 s, against 16 s at 1). Budget about the one-call peak per slot, plus what
257
+ Bun still holds from earlier calls.
258
+
259
+ The limit is per set, so two sets add up. The calls beyond `concurrency` wait in
260
+ order after their bytes are read and sniffed. **The wait queue is not
261
+ bounded**, and each waiting call holds its upload's bytes (up to `maxBytes`):
262
+ a server that can receive more uploads than it decodes should cap them before
263
+ they reach `process`.
264
+
265
+ ```ts
266
+ // a small server: one decode at a time, a lower pixel ceiling
267
+ const avatars = defineImageSet({ concurrency: 1, maxPixels: 16_000_000 });
268
+ ```
269
+
270
+ The crop PNG is encoded on zlib's thread pool, so a large crop does not stop the
271
+ event loop: with `sizes: [4096]` on 36 MP the longest stall fell from 1.1 s to
272
+ 0.3 s. That costs memory: the async encode adds memory at the peak, because the
273
+ deflate input and output are held together; the figures above, measured on the
274
+ async build, include it. The spread is run to run.
275
+
276
+ ## Output format
277
+
278
+ A set makes WebP by default: lossy at `quality` 80, the smallest file for a
279
+ photo. Two other outputs exist, chosen per set:
280
+
281
+ - **`format: 'png'`** for a consumer that does not read WebP (a PDF renderer,
282
+ an older mail client). Each size is encoded to PNG **once**, from the decoded
283
+ upload: it is never a WebP decoded again, so it carries no WebP artefact and
284
+ costs one encode per size. A PNG is several times the size of a lossy WebP
285
+ of a photo, so the bucket's `maxSize` must allow for the largest PNG variant.
286
+ - **`lossless: true`** for a WebP that keeps every pixel of the resized square
287
+ (a logo, a drawing, a screenshot). `quality` is passed along and, in
288
+ lossless mode, trades encoding time for size instead of losing detail.
289
+
290
+ ```ts
291
+ import { defineImageSet } from '@softistx/image';
292
+
293
+ const forPdf = defineImageSet({ sizes: [512, 128], format: 'png' });
294
+ forPdf.format; // 'png': the extension to put in a key
295
+ forPdf.contentType; // 'image/png'
296
+ const { variants } = await forPdf.process(await request.blob());
297
+ // variants[0].contentType === 'image/png'
298
+
299
+ const logos = defineImageSet({ sizes: [256], lossless: true }); // image/webp
300
+ ```
301
+
302
+ `quality` and `lossless` are WebP options: either beside `format: 'png'` is a
303
+ `TypeError` (and a type error), rather than a setting silently ignored.
304
+
305
+ ## Metadata and colour
306
+
307
+ Every variant is a fresh WebP or PNG: ICC profile, EXIF (GPS included), XMP and every
308
+ other metadata are gone.
309
+
310
+ **The pixels are not converted to sRGB.** The ICC profile is dropped and this
311
+ package does not convert the pixels to sRGB, so a Display P3 or Adobe RGB photo
312
+ may look a little flatter. If colour accuracy matters, convert to
313
+ sRGB before the upload reaches this package.