@softistx/image 0.0.0-stage → 0.6.1

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,732 @@
1
+ import {
2
+ ImageError2
3
+ } from "./index-wfsrqqk2.js";
4
+
5
+ // src/crop/png.ts
6
+ import { promisify } from "node:util";
7
+ import { deflate } from "node:zlib";
8
+ var deflateAsync = promisify(deflate);
9
+ var PNG_SIGNATURE = [
10
+ 137,
11
+ 80,
12
+ 78,
13
+ 71,
14
+ 13,
15
+ 10,
16
+ 26,
17
+ 10
18
+ ];
19
+ function chunk(type, data) {
20
+ const out = new Uint8Array(12 + data.length);
21
+ const view = new DataView(out.buffer);
22
+ view.setUint32(0, data.length);
23
+ for (let i = 0;i < 4; i++)
24
+ out[4 + i] = type.charCodeAt(i);
25
+ out.set(data, 8);
26
+ view.setUint32(8 + data.length, Bun.hash.crc32(out.subarray(4, 8 + data.length)) >>> 0);
27
+ return out;
28
+ }
29
+ async function encodePng(image) {
30
+ const { width, height, channels, pixels } = image;
31
+ const stride = width * channels;
32
+ const raw = new Uint8Array((stride + 1) * height);
33
+ for (let y = 0;y < height; y++) {
34
+ raw.set(pixels.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
35
+ }
36
+ const header = new Uint8Array(13);
37
+ const view = new DataView(header.buffer);
38
+ view.setUint32(0, width);
39
+ view.setUint32(4, height);
40
+ header[8] = 8;
41
+ header[9] = channels === 4 ? 6 : 2;
42
+ const parts = [
43
+ new Uint8Array(PNG_SIGNATURE),
44
+ chunk("IHDR", header),
45
+ chunk("IDAT", await deflateAsync(raw, { level: 1 })),
46
+ chunk("IEND", new Uint8Array(0))
47
+ ];
48
+ const out = new Uint8Array(parts.reduce((n, part) => n + part.length, 0));
49
+ let at = 0;
50
+ for (const part of parts) {
51
+ out.set(part, at);
52
+ at += part.length;
53
+ }
54
+ return out;
55
+ }
56
+
57
+ // src/crop/png-chunks.ts
58
+ function refuse(why) {
59
+ return new ImageError2("UNDECODABLE", "decode", `the PNG cannot be read: ${why}`);
60
+ }
61
+ function chunkAt(bytes, at) {
62
+ if (at + 12 > bytes.length)
63
+ throw refuse("no IEND chunk");
64
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
65
+ const length = view.getUint32(at);
66
+ if (at + 12 + length > bytes.length)
67
+ throw refuse("a chunk is cut short");
68
+ return {
69
+ type: String.fromCharCode(...bytes.subarray(at + 4, at + 8)),
70
+ data: bytes.subarray(at + 8, at + 8 + length),
71
+ next: at + 12 + length
72
+ };
73
+ }
74
+ function readHeader(bytes, maxPixels) {
75
+ if (!PNG_SIGNATURE.every((value, i) => bytes[i] === value)) {
76
+ throw refuse("no PNG signature");
77
+ }
78
+ const first = chunkAt(bytes, 8);
79
+ if (first.type !== "IHDR" || first.data.length !== 13) {
80
+ throw refuse("no IHDR chunk");
81
+ }
82
+ const header = first.data;
83
+ const view = new DataView(header.buffer, header.byteOffset, 13);
84
+ const width = view.getUint32(0);
85
+ const height = view.getUint32(4);
86
+ if (width < 1 || height < 1 || width > 2147483647 || height > 2147483647) {
87
+ throw refuse("the size is not valid");
88
+ }
89
+ if (maxPixels !== undefined && width * height > maxPixels) {
90
+ throw new ImageError2("TOO_LARGE", "pixels", `the PNG has ${width}x${height} pixels, over the ${maxPixels} limit`);
91
+ }
92
+ if (header[8] !== 8)
93
+ throw refuse("only 8-bit samples are read");
94
+ if (header[12] !== 0)
95
+ throw refuse("an interlaced PNG is not read");
96
+ const samples = { 0: 1, 2: 3, 4: 2, 6: 4 }[header[9]];
97
+ if (samples === undefined) {
98
+ throw refuse("this colour type (a palette, for one) is not read");
99
+ }
100
+ return { width, height, samples };
101
+ }
102
+ function idatStream(bytes, onCancel) {
103
+ let at = 8;
104
+ let sawData = false;
105
+ return new ReadableStream({
106
+ pull(controller) {
107
+ try {
108
+ for (;; ) {
109
+ const found = chunkAt(bytes, at);
110
+ at = found.next;
111
+ if (found.type === "IDAT") {
112
+ sawData = true;
113
+ controller.enqueue(found.data);
114
+ return;
115
+ }
116
+ if (found.type === "IEND") {
117
+ if (!sawData)
118
+ throw refuse("no IDAT chunk");
119
+ controller.close();
120
+ return;
121
+ }
122
+ }
123
+ } catch (error) {
124
+ controller.error(error);
125
+ }
126
+ },
127
+ cancel() {
128
+ onCancel?.();
129
+ }
130
+ });
131
+ }
132
+
133
+ // src/crop/unfilter.ts
134
+ function unfilterRow(type, row, previous, offset, stride, bpp) {
135
+ const end = offset + stride;
136
+ switch (type) {
137
+ case 0:
138
+ return true;
139
+ case 1:
140
+ for (let i = offset + bpp;i < end; i++) {
141
+ row[i] = row[i] + row[i - bpp] & 255;
142
+ }
143
+ return true;
144
+ case 2:
145
+ for (let i = offset;i < end; i++) {
146
+ row[i] = row[i] + previous[i] & 255;
147
+ }
148
+ return true;
149
+ case 3:
150
+ for (let i = offset;i < end; i++) {
151
+ const left = i - bpp >= offset ? row[i - bpp] : 0;
152
+ row[i] = row[i] + (left + previous[i] >> 1) & 255;
153
+ }
154
+ return true;
155
+ case 4:
156
+ for (let i = offset;i < end; i++) {
157
+ const has = i - bpp >= offset;
158
+ const left = has ? row[i - bpp] : 0;
159
+ const upLeft = has ? previous[i - bpp] : 0;
160
+ row[i] = row[i] + paeth(left, previous[i], upLeft) & 255;
161
+ }
162
+ return true;
163
+ default:
164
+ return false;
165
+ }
166
+ }
167
+ function paeth(a, b, c) {
168
+ const p = a + b - c;
169
+ const pa = Math.abs(p - a);
170
+ const pb = Math.abs(p - b);
171
+ const pc = Math.abs(p - c);
172
+ if (pa <= pb && pa <= pc)
173
+ return a;
174
+ return pb <= pc ? b : c;
175
+ }
176
+
177
+ // src/crop/row-assembler.ts
178
+ function createRowAssembler(stride, height, bpp, onRow) {
179
+ let previous = new Uint8Array(stride + 1);
180
+ let current = new Uint8Array(stride + 1);
181
+ let filled = 0;
182
+ let y = 0;
183
+ return {
184
+ get rows() {
185
+ return y;
186
+ },
187
+ feed(part) {
188
+ let at = 0;
189
+ while (at < part.length) {
190
+ if (y >= height) {
191
+ throw refuse("the pixel data is longer than the header says");
192
+ }
193
+ const take = Math.min(part.length - at, stride + 1 - filled);
194
+ current.set(part.subarray(at, at + take), filled);
195
+ filled += take;
196
+ at += take;
197
+ if (filled < stride + 1)
198
+ continue;
199
+ if (!unfilterRow(current[0], current, previous, 1, stride, bpp)) {
200
+ throw refuse("a row has an unknown filter");
201
+ }
202
+ const more = onRow(current, y);
203
+ [previous, current] = [current, previous];
204
+ filled = 0;
205
+ y++;
206
+ if (!more)
207
+ return false;
208
+ }
209
+ return true;
210
+ }
211
+ };
212
+ }
213
+
214
+ // src/crop/crop-png.ts
215
+ function checkRegion(region, header) {
216
+ const { x, y, width, height } = region;
217
+ if (![x, y, width, height].every(Number.isInteger) || x < 0 || y < 0 || width < 1 || height < 1 || x + width > header.width || y + height > header.height) {
218
+ throw new RangeError(`a ${width}x${height} region at (${x}, ${y}) does not fit a ${header.width}x${header.height} image`);
219
+ }
220
+ }
221
+ function copyColumns(row, region, samples, out, outRow) {
222
+ const from = 1 + region.x * samples;
223
+ if (samples >= 3) {
224
+ out.set(row.subarray(from, from + region.width * samples), outRow);
225
+ return;
226
+ }
227
+ const channels = samples === 1 ? 3 : 4;
228
+ for (let i = 0;i < region.width; i++) {
229
+ const grey = row[from + i * samples];
230
+ const at = outRow + i * channels;
231
+ out[at] = grey;
232
+ out[at + 1] = grey;
233
+ out[at + 2] = grey;
234
+ if (channels === 4)
235
+ out[at + 3] = row[from + i * samples + 1];
236
+ }
237
+ }
238
+ async function cropPng(bytes, region, maxPixels, onCancel) {
239
+ const header = readHeader(bytes, maxPixels);
240
+ const wanted = typeof region === "function" ? region(header) : region;
241
+ checkRegion(wanted, header);
242
+ const { width, height, samples } = header;
243
+ const channels = samples === 1 || samples === 3 ? 3 : 4;
244
+ const lastRow = wanted.y + wanted.height - 1;
245
+ const out = new Uint8Array(wanted.width * wanted.height * channels);
246
+ const rows = createRowAssembler(width * samples, height, samples, (row, y) => {
247
+ if (y >= wanted.y) {
248
+ const outRow = (y - wanted.y) * wanted.width * channels;
249
+ copyColumns(row, wanted, samples, out, outRow);
250
+ }
251
+ return y < lastRow || lastRow === height - 1;
252
+ });
253
+ const inflate = new DecompressionStream("deflate");
254
+ const reader = idatStream(bytes, onCancel).pipeThrough(inflate).getReader();
255
+ try {
256
+ for (;; ) {
257
+ let part;
258
+ try {
259
+ part = await reader.read();
260
+ } catch (error) {
261
+ if (error instanceof ImageError2)
262
+ throw error;
263
+ throw refuse("the pixel data is not valid zlib");
264
+ }
265
+ if (part.done) {
266
+ if (rows.rows < height) {
267
+ throw refuse("the pixel data is shorter than the header says");
268
+ }
269
+ break;
270
+ }
271
+ if (!rows.feed(part.value))
272
+ break;
273
+ }
274
+ return {
275
+ width: wanted.width,
276
+ height: wanted.height,
277
+ channels,
278
+ pixels: out
279
+ };
280
+ } finally {
281
+ await reader.cancel().catch(() => {
282
+ return;
283
+ });
284
+ }
285
+ }
286
+
287
+ // src/input/read-input.ts
288
+ function tooLarge(maxBytes) {
289
+ return new ImageError2("TOO_LARGE", "bytes", `the upload is over ${maxBytes} bytes`);
290
+ }
291
+ async function readStream(stream, maxBytes) {
292
+ const reader = stream.getReader();
293
+ const chunks = [];
294
+ let total = 0;
295
+ try {
296
+ for (;; ) {
297
+ const { done, value } = await reader.read();
298
+ if (done)
299
+ break;
300
+ if (!(value instanceof Uint8Array)) {
301
+ await reader.cancel().catch(() => {
302
+ return;
303
+ });
304
+ throw new TypeError("a stream chunk must be a Uint8Array");
305
+ }
306
+ total += value.byteLength;
307
+ if (total > maxBytes) {
308
+ await reader.cancel().catch(() => {
309
+ return;
310
+ });
311
+ throw tooLarge(maxBytes);
312
+ }
313
+ chunks.push(value);
314
+ }
315
+ } finally {
316
+ reader.releaseLock();
317
+ }
318
+ const bytes = new Uint8Array(total);
319
+ let at = 0;
320
+ for (const chunk of chunks) {
321
+ bytes.set(chunk, at);
322
+ at += chunk.byteLength;
323
+ }
324
+ return bytes;
325
+ }
326
+ async function readInput(input, maxBytes) {
327
+ if (input instanceof Uint8Array) {
328
+ if (input.byteLength > maxBytes)
329
+ throw tooLarge(maxBytes);
330
+ return input;
331
+ }
332
+ if (input instanceof ArrayBuffer) {
333
+ if (input.byteLength > maxBytes)
334
+ throw tooLarge(maxBytes);
335
+ return new Uint8Array(input);
336
+ }
337
+ if (input instanceof Blob) {
338
+ if (!Number.isFinite(input.size))
339
+ return readStream(input.stream(), maxBytes);
340
+ if (!(input.size <= maxBytes))
341
+ throw tooLarge(maxBytes);
342
+ const buffer = await input.arrayBuffer();
343
+ if (buffer.byteLength > maxBytes)
344
+ throw tooLarge(maxBytes);
345
+ return new Uint8Array(buffer);
346
+ }
347
+ if (input instanceof ReadableStream)
348
+ return readStream(input, maxBytes);
349
+ throw new TypeError("image input must be a Uint8Array, an ArrayBuffer, a Blob or a ReadableStream of Uint8Array");
350
+ }
351
+
352
+ // src/input/sniff.ts
353
+ var HEIC_BRANDS = new Set(["heic", "heix", "hevc", "hevx", "mif1", "msf1"]);
354
+ var AVIF_BRANDS = new Set(["avif", "avis"]);
355
+ function startsWith(bytes, signature, at = 0) {
356
+ return bytes.length >= at + signature.length && signature.every((value, i) => bytes[at + i] === value);
357
+ }
358
+ function ascii(bytes, at, length) {
359
+ return String.fromCharCode(...bytes.subarray(at, at + length));
360
+ }
361
+ function brandsOf(bytes) {
362
+ if (bytes.length < 12 || ascii(bytes, 4, 4) !== "ftyp")
363
+ return [];
364
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
365
+ const end = Math.min(bytes.length, Math.max(view.getUint32(0), 16));
366
+ const brands = [ascii(bytes, 8, 4)];
367
+ for (let at = 16;at + 4 <= end; at += 4)
368
+ brands.push(ascii(bytes, at, 4));
369
+ return brands;
370
+ }
371
+ function sniffFormat(bytes) {
372
+ if (startsWith(bytes, [255, 216, 255]))
373
+ return "jpeg";
374
+ if (startsWith(bytes, PNG_SIGNATURE))
375
+ return "png";
376
+ if (bytes.length >= 12 && ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 4) === "WEBP") {
377
+ return "webp";
378
+ }
379
+ const brands = brandsOf(bytes);
380
+ if (brands.some((brand) => AVIF_BRANDS.has(brand)))
381
+ return;
382
+ if (brands.some((brand) => HEIC_BRANDS.has(brand)))
383
+ return "heic";
384
+ return;
385
+ }
386
+
387
+ // src/set/whole.ts
388
+ function isWhole(value, min = 0, max = Number.POSITIVE_INFINITY) {
389
+ return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
390
+ }
391
+
392
+ // src/process/geometry.ts
393
+ function shrinkScale(cropSide, largestSize) {
394
+ return Math.min(1, 2 * largestSize / cropSide);
395
+ }
396
+ function scaledDimensions({ width, height }, scale) {
397
+ return {
398
+ width: Math.max(1, Math.round(width * scale)),
399
+ height: Math.max(1, Math.round(height * scale))
400
+ };
401
+ }
402
+ function centredCrop({ width, height }) {
403
+ const size = Math.min(width, height);
404
+ return {
405
+ x: Math.floor((width - size) / 2),
406
+ y: Math.floor((height - size) / 2),
407
+ size
408
+ };
409
+ }
410
+ function assertCropShape(crop) {
411
+ if (typeof crop !== "object" || crop === null || ![crop.x, crop.y, crop.size].every((value) => isWhole(value))) {
412
+ throw new ImageError2("INVALID_CROP", "crop", "a crop is { x, y, size }, three whole numbers of 0 or more");
413
+ }
414
+ }
415
+ function assertCropFits(crop, image) {
416
+ if (crop.size < 1 || crop.x + crop.size > image.width || crop.y + crop.size > image.height) {
417
+ throw new ImageError2("INVALID_CROP", "crop", `a ${crop.size}px crop at (${crop.x}, ${crop.y}) does not fit the ${image.width}x${image.height} image`);
418
+ }
419
+ }
420
+ function scaleCrop(crop, scale, shrunk) {
421
+ const size = Math.max(1, Math.min(Math.round(crop.size * scale), shrunk.width, shrunk.height));
422
+ const clamp = (value, room) => Math.max(0, Math.min(Math.round(value * scale), room - size));
423
+ return {
424
+ x: clamp(crop.x, shrunk.width),
425
+ y: clamp(crop.y, shrunk.height),
426
+ size
427
+ };
428
+ }
429
+ function assertRectFits(crop, image) {
430
+ const ok = typeof crop === "object" && crop !== null && isWhole(crop.x) && isWhole(crop.y) && isWhole(crop.width, 1) && isWhole(crop.height, 1);
431
+ if (!ok) {
432
+ throw new ImageError2("INVALID_CROP", "crop", "a crop is { x, y, width, height }, whole numbers: x and y of 0 or more, width and height of 1 or more");
433
+ }
434
+ if (crop.x + crop.width > image.width || crop.y + crop.height > image.height) {
435
+ throw new ImageError2("INVALID_CROP", "crop", `a ${crop.width}x${crop.height} crop at (${crop.x}, ${crop.y}) does not fit the ${image.width}x${image.height} image`);
436
+ }
437
+ }
438
+ function shrinkScaleFor(crop, target) {
439
+ return Math.min(1, Math.max(2 * target.width / crop.width, 2 * target.height / crop.height));
440
+ }
441
+ function scaleRect(crop, scale, shrunk) {
442
+ const size = (value, room) => Math.max(1, Math.min(Math.round(value * scale), room));
443
+ const width = size(crop.width, shrunk.width);
444
+ const height = size(crop.height, shrunk.height);
445
+ const place = (value, room) => Math.max(0, Math.min(Math.round(value * scale), room));
446
+ return {
447
+ x: place(crop.x, shrunk.width - width),
448
+ y: place(crop.y, shrunk.height - height),
449
+ width,
450
+ height
451
+ };
452
+ }
453
+
454
+ // src/set/options.ts
455
+ var CONTENT_TYPES = Object.freeze({
456
+ webp: "image/webp",
457
+ png: "image/png"
458
+ });
459
+ function contentTypeOf(format) {
460
+ return CONTENT_TYPES[format];
461
+ }
462
+ var DEFAULT_SIZES = [256, 64];
463
+ var DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
464
+ var DEFAULT_MAX_PIXELS = 25000000;
465
+ var DEFAULT_QUALITY = 80;
466
+ var DEFAULT_CONCURRENCY = 2;
467
+ var MAX_CONCURRENCY = 64;
468
+ var MAX_SIZE = 4096;
469
+ function whole(name, value, min, max) {
470
+ if (!isWhole(value, min, max)) {
471
+ const range = max === undefined ? `${min} or more` : `${min} to ${max}`;
472
+ throw new TypeError(`${name} must be a whole number of ${range}, got ${String(value)}`);
473
+ }
474
+ return value;
475
+ }
476
+ function checkSizes(sizes) {
477
+ if (!Array.isArray(sizes) || sizes.length === 0) {
478
+ throw new TypeError("sizes must be a non-empty array of whole numbers");
479
+ }
480
+ for (const size of sizes)
481
+ whole("sizes[]", size, 1, MAX_SIZE);
482
+ if (new Set(sizes).size !== sizes.length) {
483
+ throw new TypeError(`sizes must be unique, got [${sizes.join(", ")}]`);
484
+ }
485
+ return Object.freeze([...sizes]);
486
+ }
487
+ function checkFormat(format) {
488
+ if (format !== "webp" && format !== "png") {
489
+ throw new TypeError(`format must be 'webp' or 'png', got ${String(format)}`);
490
+ }
491
+ return format;
492
+ }
493
+ function checkLossless(lossless) {
494
+ if (typeof lossless !== "boolean") {
495
+ throw new TypeError(`lossless must be a boolean, got ${String(lossless)}`);
496
+ }
497
+ return lossless;
498
+ }
499
+ function checkPngOptions(options) {
500
+ for (const name of ["lossless", "quality"]) {
501
+ if (options[name] !== undefined) {
502
+ throw new TypeError(`${name} applies to WebP only: a PNG is always lossless`);
503
+ }
504
+ }
505
+ }
506
+ function resolveOptions(options = {}) {
507
+ const sizes = checkSizes(options.sizes ?? DEFAULT_SIZES);
508
+ const format = checkFormat(options.format ?? "webp");
509
+ if (format === "png")
510
+ checkPngOptions(options);
511
+ return Object.freeze({
512
+ sizes,
513
+ maxBytes: whole("maxBytes", options.maxBytes ?? DEFAULT_MAX_BYTES, 1),
514
+ maxPixels: whole("maxPixels", options.maxPixels ?? DEFAULT_MAX_PIXELS, 1),
515
+ minSide: whole("minSide", options.minSide ?? Math.max(...sizes), 1),
516
+ quality: whole("quality", options.quality ?? DEFAULT_QUALITY, 1, 100),
517
+ concurrency: whole("concurrency", options.concurrency ?? DEFAULT_CONCURRENCY, 1, MAX_CONCURRENCY),
518
+ format,
519
+ lossless: checkLossless(options.lossless ?? false)
520
+ });
521
+ }
522
+
523
+ // src/process/bun-errors.ts
524
+ function refusal(code, reason, message, cause) {
525
+ const error = new ImageError2(code, reason, message);
526
+ error.cause = cause;
527
+ return error;
528
+ }
529
+ function mapBunError(error, format) {
530
+ const code = error?.code;
531
+ switch (code) {
532
+ case "ERR_IMAGE_TOO_MANY_PIXELS":
533
+ return refusal("TOO_LARGE", "pixels", "the image has too many pixels", error);
534
+ case "ERR_IMAGE_FORMAT_UNSUPPORTED":
535
+ return format === "heic" ? refusal("UNSUPPORTED_TYPE", "heic-unavailable", "this machine cannot decode HEIC (Linux cannot)", error) : refusal("UNSUPPORTED_TYPE", "format", `this machine cannot decode ${format}`, error);
536
+ case "ERR_IMAGE_DECODE_FAILED":
537
+ case "ERR_IMAGE_UNKNOWN_FORMAT":
538
+ return refusal("UNDECODABLE", "decode", `the ${format} image cannot be decoded`, error);
539
+ default:
540
+ return error;
541
+ }
542
+ }
543
+
544
+ // src/process/process.ts
545
+ async function guarded(format, step) {
546
+ try {
547
+ return await step();
548
+ } catch (error) {
549
+ throw mapBunError(error, format);
550
+ }
551
+ }
552
+ async function readDimensions(bytes, format, maxPixels) {
553
+ const { width, height } = await guarded(format, () => new Bun.Image(bytes, { maxPixels, autoOrient: true }).metadata());
554
+ return { width, height };
555
+ }
556
+ function shrink(bytes, format, image, scale, maxPixels) {
557
+ return guarded(format, () => {
558
+ let pipeline = new Bun.Image(bytes, { maxPixels, autoOrient: true });
559
+ if (scale < 1) {
560
+ const to = scaledDimensions(image, scale);
561
+ pipeline = pipeline.resize(to.width, to.height, { fit: "fill" });
562
+ }
563
+ return pipeline.png().bytes();
564
+ });
565
+ }
566
+ function variantOf(square, size, { format, quality, lossless }) {
567
+ return guarded("png", () => {
568
+ const resized = new Bun.Image(square).resize(size, size, { fit: "fill" });
569
+ if (format === "png")
570
+ return resized.png().bytes();
571
+ return resized.webp(lossless ? { quality, lossless } : { quality }).bytes();
572
+ }).then((bytes) => ({
573
+ size,
574
+ width: size,
575
+ height: size,
576
+ contentType: contentTypeOf(format),
577
+ bytes
578
+ }));
579
+ }
580
+ async function cropToPng(bytes, format, image, box, options) {
581
+ const scale = shrinkScale(box.size, Math.max(...options.sizes));
582
+ const square = await cropPng(await shrink(bytes, format, image, scale, options.maxPixels), (shrunk) => {
583
+ const { x, y, size } = scaleCrop(box, scale, shrunk);
584
+ return { x, y, width: size, height: size };
585
+ }, options.maxPixels);
586
+ return await encodePng(square);
587
+ }
588
+ async function processImage(input, { crop }, options, limit) {
589
+ const bytes = await readInput(input, options.maxBytes);
590
+ const format = sniffFormat(bytes);
591
+ if (format === undefined) {
592
+ throw new ImageError2("UNSUPPORTED_TYPE", "format", "the upload is not a JPEG, PNG, WebP or HEIC");
593
+ }
594
+ return limit(async () => {
595
+ const image = await readDimensions(bytes, format, options.maxPixels);
596
+ if (crop !== undefined) {
597
+ assertCropShape(crop);
598
+ assertCropFits(crop, image);
599
+ }
600
+ const box = crop ?? centredCrop(image);
601
+ if (box.size < options.minSide) {
602
+ throw new ImageError2("TOO_SMALL", "dimensions", crop ? `the crop is ${crop.size}px, under the ${options.minSide}px minimum` : `the image is ${image.width}x${image.height}, under ${options.minSide}px on its short side`);
603
+ }
604
+ const squarePng = await cropToPng(bytes, format, image, box, options);
605
+ const variants = await Promise.all(options.sizes.map((size) => variantOf(squarePng, size, options)));
606
+ return { source: { format, ...image }, variants };
607
+ });
608
+ }
609
+
610
+ // src/set/limit.ts
611
+ function createLimit(max) {
612
+ let running = 0;
613
+ const waiting = [];
614
+ const release = () => {
615
+ const next = waiting.shift();
616
+ if (next)
617
+ next();
618
+ else
619
+ running--;
620
+ };
621
+ return async (task) => {
622
+ if (running < max)
623
+ running++;
624
+ else
625
+ await new Promise((resolve) => waiting.push(resolve));
626
+ try {
627
+ return await task();
628
+ } finally {
629
+ release();
630
+ }
631
+ };
632
+ }
633
+
634
+ // src/render/render-image.ts
635
+ var RENDER_CONTENT_TYPES = Object.freeze({
636
+ jpeg: "image/jpeg",
637
+ webp: "image/webp",
638
+ png: "image/png"
639
+ });
640
+ var DEFAULT_MAX_BYTES2 = 5 * 1024 * 1024;
641
+ var DEFAULT_MAX_PIXELS2 = 25000000;
642
+ var DEFAULT_QUALITY2 = 80;
643
+ var MAX_SIDE = 8192;
644
+ var limit = createLimit(2);
645
+ function whole2(name, value, min, max) {
646
+ if (!isWhole(value, min, max)) {
647
+ const range = max === undefined ? `${min} or more` : `${min} to ${max}`;
648
+ throw new TypeError(`${name} must be a whole number of ${range}, got ${String(value)}`);
649
+ }
650
+ return value;
651
+ }
652
+ function checkOptions(options) {
653
+ const { format } = options;
654
+ if (format !== "jpeg" && format !== "webp" && format !== "png") {
655
+ throw new TypeError(`format must be 'jpeg', 'webp' or 'png', got ${String(format)}`);
656
+ }
657
+ if (format === "png" && options.quality !== undefined) {
658
+ throw new TypeError("quality applies to JPEG and WebP only: a PNG is always lossless");
659
+ }
660
+ return {
661
+ width: whole2("width", options.width, 1, MAX_SIDE),
662
+ height: whole2("height", options.height, 1, MAX_SIDE),
663
+ quality: whole2("quality", options.quality ?? DEFAULT_QUALITY2, 1, 100),
664
+ maxBytes: whole2("maxBytes", options.maxBytes ?? DEFAULT_MAX_BYTES2, 1),
665
+ maxPixels: whole2("maxPixels", options.maxPixels ?? DEFAULT_MAX_PIXELS2, 1)
666
+ };
667
+ }
668
+ function encode(bytes, sourceFormat, target, { format, quality, maxPixels, upright }) {
669
+ return guarded(sourceFormat, () => {
670
+ const resized = new Bun.Image(bytes, {
671
+ maxPixels,
672
+ autoOrient: upright
673
+ }).resize(target.width, target.height, { fit: "fill" });
674
+ if (format === "png")
675
+ return resized.png().bytes();
676
+ if (format === "jpeg")
677
+ return resized.jpeg({ quality }).bytes();
678
+ return resized.webp({ quality }).bytes();
679
+ });
680
+ }
681
+ async function cropToPng2(bytes, format, image, crop, target, maxPixels) {
682
+ const scale = shrinkScaleFor(crop, target);
683
+ const shrunk = await shrink(bytes, format, image, scale, maxPixels);
684
+ const region = await cropPng(shrunk, (size) => scaleRect(crop, scale, size), maxPixels);
685
+ return encodePng(region);
686
+ }
687
+ var coversImage = (crop, image) => crop.x === 0 && crop.y === 0 && crop.width === image.width && crop.height === image.height;
688
+ async function renderImage2(input, options) {
689
+ const { width, height, quality, maxBytes, maxPixels } = checkOptions(options);
690
+ const { signal, crop } = options;
691
+ signal?.throwIfAborted();
692
+ const bytes = await readInput(input, maxBytes);
693
+ signal?.throwIfAborted();
694
+ const format = sniffFormat(bytes);
695
+ if (format === undefined) {
696
+ throw new ImageError2("UNSUPPORTED_TYPE", "format", "the upload is not a JPEG, PNG, WebP or HEIC");
697
+ }
698
+ return limit(async () => {
699
+ signal?.throwIfAborted();
700
+ const image = await readDimensions(bytes, format, maxPixels);
701
+ signal?.throwIfAborted();
702
+ if (crop !== undefined)
703
+ assertRectFits(crop, image);
704
+ const kept = crop ?? image;
705
+ if (kept.width < width || kept.height < height) {
706
+ throw new ImageError2("TOO_SMALL", "dimensions", `the ${crop ? "crop" : "image"} is ${kept.width}x${kept.height}, under the ${width}x${height} asked for`);
707
+ }
708
+ const target = { width, height };
709
+ const encoding = { format: options.format, quality, maxPixels };
710
+ let out;
711
+ if (crop === undefined || coversImage(crop, image)) {
712
+ out = await encode(bytes, format, target, { ...encoding, upright: true });
713
+ } else {
714
+ const png = await cropToPng2(bytes, format, image, crop, target, maxPixels);
715
+ signal?.throwIfAborted();
716
+ out = await encode(png, "png", target, { ...encoding, upright: false });
717
+ }
718
+ signal?.throwIfAborted();
719
+ return {
720
+ source: { format, ...image },
721
+ bytes: out,
722
+ width,
723
+ height,
724
+ contentType: RENDER_CONTENT_TYPES[options.format]
725
+ };
726
+ });
727
+ }
728
+
729
+ export { readInput, isWhole, contentTypeOf, resolveOptions, processImage, createLimit, RENDER_CONTENT_TYPES, renderImage2 };
730
+
731
+ //# debugId=2CB4825C6688F53D64756E2164756E21
732
+ //# sourceMappingURL=index-pj79f6q4.js.map