react-smart-copy 1.12.0 → 1.13.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.
package/dist/image.js ADDED
@@ -0,0 +1,1284 @@
1
+ //#region src/core/errors.ts
2
+ function createCopyError(type, message, cause) {
3
+ return cause === void 0 ? {
4
+ type,
5
+ message
6
+ } : {
7
+ type,
8
+ message,
9
+ cause
10
+ };
11
+ }
12
+ /**
13
+ * Branded (not `instanceof`) so failures stay recognisable even when the core
14
+ * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
15
+ */
16
+ const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
17
+ /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
18
+ var CopyFailure = class extends Error {
19
+ constructor(copyError) {
20
+ super(copyError.message);
21
+ this[COPY_FAILURE_BRAND] = true;
22
+ this.name = "CopyFailure";
23
+ this.copyError = copyError;
24
+ }
25
+ };
26
+ /** Shorthand for throwing a classified failure. */
27
+ function copyFailure(type, message, cause) {
28
+ return new CopyFailure(createCopyError(type, message, cause));
29
+ }
30
+ //#endregion
31
+ //#region src/image/bytes.ts
32
+ /** Bounds-checked reads over a byte array: out-of-range reads return `null`, never garbage. */
33
+ var Bytes = class Bytes {
34
+ constructor(data) {
35
+ this.data = data;
36
+ this.length = data.length;
37
+ }
38
+ u8(at) {
39
+ return at >= 0 && at < this.length ? this.data[at] : null;
40
+ }
41
+ u16(at, littleEndian) {
42
+ if (at < 0 || at + 2 > this.length) return null;
43
+ const a = this.data[at];
44
+ const b = this.data[at + 1];
45
+ return littleEndian ? a | b << 8 : a << 8 | b;
46
+ }
47
+ u24le(at) {
48
+ if (at < 0 || at + 3 > this.length) return null;
49
+ return this.data[at] | this.data[at + 1] << 8 | this.data[at + 2] << 16;
50
+ }
51
+ u32(at, littleEndian) {
52
+ if (at < 0 || at + 4 > this.length) return null;
53
+ const a = this.data[at];
54
+ const b = this.data[at + 1];
55
+ const c = this.data[at + 2];
56
+ const d = this.data[at + 3];
57
+ return (littleEndian ? a | b << 8 | c << 16 | d << 24 : a << 24 | b << 16 | c << 8 | d) >>> 0;
58
+ }
59
+ /** `length` bytes as Latin-1 text (four-character codes, signatures), or `null` past the end. */
60
+ ascii(at, length) {
61
+ if (at < 0 || at + length > this.length) return null;
62
+ return String.fromCharCode(...this.data.subarray(at, at + length));
63
+ }
64
+ startsWith(at, signature) {
65
+ return this.ascii(at, signature.length) === signature;
66
+ }
67
+ /** The same bytes, ending at `end`: reads of a box or chunk then can't run into the next one. Offsets don't change. */
68
+ until(end) {
69
+ return end >= this.length ? this : new Bytes(this.data.subarray(0, end));
70
+ }
71
+ slice(start, end) {
72
+ return this.data.subarray(Math.max(0, start), Math.min(this.length, end));
73
+ }
74
+ };
75
+ const DEFAULT_IMAGE_MAX_INPUT_BYTES = 104857600;
76
+ /** Reads a Blob into memory, refusing anything larger than `maxBytes`. */
77
+ async function readBlob(blob, maxBytes) {
78
+ const candidate = blob;
79
+ if (typeof candidate !== "object" || candidate === null || typeof candidate.size !== "number") throw copyFailure("invalid-payload", "Expected an image Blob or File.");
80
+ if (blob.size > maxBytes) throw copyFailure("too-large", `The image is ${String(blob.size)} bytes; maxInputBytes is ${String(maxBytes)}.`);
81
+ return new Bytes(new Uint8Array(await blob.arrayBuffer()));
82
+ }
83
+ function concat(parts) {
84
+ let length = 0;
85
+ for (const part of parts) length += part.length;
86
+ const out = new Uint8Array(length);
87
+ let at = 0;
88
+ for (const part of parts) {
89
+ out.set(part, at);
90
+ at += part.length;
91
+ }
92
+ return out;
93
+ }
94
+ function u32be(value) {
95
+ return Uint8Array.of(value >>> 24 & 255, value >>> 16 & 255, value >>> 8 & 255, value & 255);
96
+ }
97
+ function u32le(value) {
98
+ return Uint8Array.of(value & 255, value >>> 8 & 255, value >>> 16 & 255, value >>> 24 & 255);
99
+ }
100
+ const latin1 = (text) => Uint8Array.from(text, (char) => char.charCodeAt(0));
101
+ /** A Blob (or a File with the same name and date, when the input was one) holding `parts`. */
102
+ function outputBlob(parts, type, like) {
103
+ const data = concat(parts);
104
+ const file = like;
105
+ if (typeof File === "function" && typeof file.name === "string") return new File([data], file.name, {
106
+ type,
107
+ lastModified: file.lastModified ?? Date.now()
108
+ });
109
+ return new Blob([data], { type });
110
+ }
111
+ //#endregion
112
+ //#region src/image/exif.ts
113
+ const ORIENTATION = 274;
114
+ const GPS_IFD = 34853;
115
+ const GPS_LATITUDE = 2;
116
+ const GPS_LONGITUDE = 4;
117
+ const THUMBNAIL_OFFSET = 513;
118
+ const STRIP_OFFSETS = 273;
119
+ /** Real files have a few dozen tags; a bound keeps hostile counts cheap. */
120
+ const MAX_ENTRIES = 512;
121
+ /** Reads an IFD's tags (value field only: enough for SHORT / LONG values and offsets). */
122
+ function readIfd(bytes, base, end, offset, littleEndian) {
123
+ const at = base + offset;
124
+ const count = bytes.u16(at, littleEndian);
125
+ if (count === null || offset < 8 || at + 2 + count * 12 + 4 > end || count > MAX_ENTRIES) return null;
126
+ const tags = /* @__PURE__ */ new Map();
127
+ for (let index = 0; index < count; index += 1) {
128
+ const entry = at + 2 + index * 12;
129
+ const tag = bytes.u16(entry, littleEndian);
130
+ const type = bytes.u16(entry + 2, littleEndian);
131
+ tags.set(tag, type === 3 ? bytes.u16(entry + 8, littleEndian) : bytes.u32(entry + 8, littleEndian));
132
+ }
133
+ return {
134
+ tags,
135
+ next: bytes.u32(at + 2 + count * 12, littleEndian)
136
+ };
137
+ }
138
+ /** Summarises the TIFF structure at `start`-`end` (an Exif payload without its `Exif\0\0` prefix). */
139
+ function readTiff(file, start, end) {
140
+ const bytes = file.until(end);
141
+ const order = bytes.ascii(start, 2);
142
+ if (order !== "II" && order !== "MM") return null;
143
+ const littleEndian = order === "II";
144
+ if (bytes.u16(start + 2, littleEndian) !== 42) return null;
145
+ const ifd0 = readIfd(bytes, start, end, bytes.u32(start + 4, littleEndian), littleEndian);
146
+ if (ifd0 === null) return null;
147
+ const value = ifd0.tags.get(ORIENTATION);
148
+ const orientation = value !== void 0 && value >= 1 && value <= 8 ? value : 1;
149
+ const gpsOffset = ifd0.tags.get(GPS_IFD);
150
+ const gpsIfd = gpsOffset === void 0 ? null : readIfd(bytes, start, end, gpsOffset, littleEndian);
151
+ const gps = gpsIfd !== null && (gpsIfd.tags.has(GPS_LATITUDE) || gpsIfd.tags.has(GPS_LONGITUDE));
152
+ const ifd1 = ifd0.next === 0 || ifd0.next === bytes.u32(start + 4, littleEndian) ? null : readIfd(bytes, start, end, ifd0.next, littleEndian);
153
+ return {
154
+ orientation,
155
+ gps,
156
+ thumbnail: ifd1 !== null && (ifd1.tags.has(THUMBNAIL_OFFSET) || ifd1.tags.has(STRIP_OFFSETS)),
157
+ onlyOrientation: ifd0.tags.size === 1 && value !== void 0 && ifd0.next === 0
158
+ };
159
+ }
160
+ /** Where the TIFF header starts in an Exif payload: after an optional `Exif\0\0` prefix. */
161
+ function tiffStart(bytes, start) {
162
+ return bytes.startsWith(start, "Exif\0\0") ? start + 6 : start;
163
+ }
164
+ /**
165
+ * The smallest valid TIFF block with only an Orientation tag: what is kept of
166
+ * Exif so a photo still displays the right way up. 26 bytes, little-endian.
167
+ */
168
+ function orientationTiff(orientation) {
169
+ return Uint8Array.of(73, 73, 42, 0, 8, 0, 0, 0, 1, 0, 18, 1, 3, 0, 1, 0, 0, 0, orientation, 0, 0, 0, 0, 0, 0, 0);
170
+ }
171
+ //#endregion
172
+ //#region src/image/types.ts
173
+ /** Every metadata kind, in a stable order. */
174
+ const METADATA_KINDS = Object.freeze([
175
+ "exif",
176
+ "gps",
177
+ "thumbnail",
178
+ "xmp",
179
+ "iptc",
180
+ "comment",
181
+ "text",
182
+ "icc",
183
+ "other"
184
+ ]);
185
+ const MIME_TYPES = {
186
+ jpeg: "image/jpeg",
187
+ png: "image/png",
188
+ gif: "image/gif",
189
+ webp: "image/webp",
190
+ avif: "image/avif",
191
+ heic: "image/heic",
192
+ bmp: "image/bmp"
193
+ };
194
+ /** Collects findings while a parser walks a file. */
195
+ var Found = class {
196
+ constructor() {
197
+ this.orientationOnly = false;
198
+ this.kinds = /* @__PURE__ */ new Set();
199
+ this.width = null;
200
+ this.height = null;
201
+ this.orientation = 1;
202
+ this.animated = false;
203
+ }
204
+ add(kind) {
205
+ this.kinds.add(kind);
206
+ }
207
+ /** Records an Exif block: `null` when it could not be read (still Exif). */
208
+ exif(summary) {
209
+ if (summary === null || !summary.onlyOrientation) this.add("exif");
210
+ if (summary === null) return;
211
+ if (summary.onlyOrientation) this.orientationOnly = true;
212
+ this.orientation = summary.orientation;
213
+ if (summary.gps) this.add("gps");
214
+ if (summary.thumbnail) this.add("thumbnail");
215
+ }
216
+ info(format) {
217
+ return {
218
+ format,
219
+ mimeType: format === null ? null : MIME_TYPES[format],
220
+ width: this.width,
221
+ height: this.height,
222
+ orientation: this.orientation,
223
+ animated: this.animated,
224
+ metadata: METADATA_KINDS.filter((kind) => this.kinds.has(kind))
225
+ };
226
+ }
227
+ };
228
+ //#endregion
229
+ //#region src/image/bmff.ts
230
+ /** Boxes between `start` and `end`. Bounded: a hostile file can't make this loop forever. */
231
+ function boxes(bytes, start, end) {
232
+ const out = [];
233
+ for (let at = start; at + 8 <= end && out.length < 4096;) {
234
+ let size = bytes.u32(at, false);
235
+ const type = bytes.ascii(at + 4, 4);
236
+ let body = at + 8;
237
+ if (size === 1) {
238
+ if (bytes.u32(at + 8, false) !== 0) break;
239
+ size = bytes.u32(at + 12, false) ?? 0;
240
+ body = at + 16;
241
+ } else if (size === 0) size = end - at;
242
+ if (size < body - at || at + size > end) break;
243
+ out.push({
244
+ type,
245
+ body,
246
+ end: at + size
247
+ });
248
+ at += size;
249
+ }
250
+ return out;
251
+ }
252
+ const child = (bytes, parent, type, skip = 0) => boxes(bytes, parent.body + skip, parent.end).find((box) => box.type === type);
253
+ /** Reads an unsigned big-endian integer of 0, 4 or 8 bytes (8-byte values must fit 32 bits). */
254
+ function sized(bytes, at, size) {
255
+ if (size === 0) return 0;
256
+ if (size === 4) return bytes.u32(at, false);
257
+ if (size === 8) return bytes.u32(at, false) === 0 ? bytes.u32(at + 4, false) : null;
258
+ return null;
259
+ }
260
+ /** Item ids of `Exif` items, and whether there is XMP (a `mime` item). */
261
+ function readItemInfo(file, iinf) {
262
+ const bytes = file.until(iinf.end);
263
+ const version = bytes.u8(iinf.body) ?? 0;
264
+ const entriesAt = iinf.body + 4 + (version === 0 ? 2 : 4);
265
+ const exif = [];
266
+ let xmp = false;
267
+ for (const infe of boxes(bytes, entriesAt, iinf.end)) {
268
+ if (infe.type !== "infe") continue;
269
+ const view = bytes.until(infe.end);
270
+ const infeVersion = view.u8(infe.body) ?? 0;
271
+ if (infeVersion < 2) continue;
272
+ const id = infeVersion === 2 ? view.u16(infe.body + 4, false) : view.u32(infe.body + 4, false);
273
+ const typeAt = infe.body + 4 + (infeVersion === 2 ? 2 : 4) + 2;
274
+ const itemType = view.ascii(typeAt, 4);
275
+ if (itemType === "Exif" && id !== null) exif.push(id);
276
+ if (itemType === "mime") xmp = true;
277
+ }
278
+ return {
279
+ exif,
280
+ xmp
281
+ };
282
+ }
283
+ /** Where item `id` is stored in the file (construction method 0, first extent), or `null`. */
284
+ function itemLocation(file, iloc, id) {
285
+ const bytes = file.until(iloc.end);
286
+ const version = bytes.u8(iloc.body) ?? 0;
287
+ const sizes = bytes.u16(iloc.body + 4, false) ?? 0;
288
+ const offsetSize = sizes >> 12;
289
+ const lengthSize = sizes >> 8 & 15;
290
+ const baseSize = sizes >> 4 & 15;
291
+ const indexSize = version === 1 || version === 2 ? sizes & 15 : 0;
292
+ let at = iloc.body + 6;
293
+ const count = version < 2 ? bytes.u16(at, false) : bytes.u32(at, false);
294
+ at += version < 2 ? 2 : 4;
295
+ for (let item = 0; item < (count ?? 0) && item < 4096; item += 1) {
296
+ const itemId = version < 2 ? bytes.u16(at, false) : bytes.u32(at, false);
297
+ at += version < 2 ? 2 : 4;
298
+ let method = 0;
299
+ if (version === 1 || version === 2) {
300
+ method = (bytes.u16(at, false) ?? 0) & 15;
301
+ at += 2;
302
+ }
303
+ at += 2;
304
+ const base = sized(bytes, at, baseSize);
305
+ at += baseSize;
306
+ const extents = bytes.u16(at, false) ?? 0;
307
+ at += 2;
308
+ let first = null;
309
+ for (let extent = 0; extent < extents; extent += 1) {
310
+ at += indexSize;
311
+ const offset = sized(bytes, at, offsetSize);
312
+ const length = sized(bytes, at + offsetSize, lengthSize);
313
+ at += offsetSize + lengthSize;
314
+ if (extent === 0 && base !== null && offset !== null && length !== null) first = {
315
+ start: base + offset,
316
+ end: base + offset + length
317
+ };
318
+ }
319
+ if (itemId === id) return method === 0 ? first : null;
320
+ }
321
+ return null;
322
+ }
323
+ /** AVIF and HEIC (HEIF): size, animation and metadata. Not strippable without re-encoding. */
324
+ function parseBmff(bytes, format) {
325
+ const found = new Found();
326
+ const top = boxes(bytes, 0, bytes.length);
327
+ const ftyp = top[0];
328
+ const brands = bytes.ascii(ftyp.body, Math.max(0, ftyp.end - ftyp.body));
329
+ found.animated = brands.includes("avis") || brands.includes("msf1") || brands.includes("hevs") || top.some((box) => box.type === "moov");
330
+ const meta = top.find((box) => box.type === "meta");
331
+ if (meta !== void 0) {
332
+ const ipco = ((iprp) => iprp === void 0 ? void 0 : child(bytes, iprp, "ipco"))(child(bytes, meta, "iprp", 4));
333
+ let area = 0;
334
+ for (const property of ipco === void 0 ? [] : boxes(bytes, ipco.body, ipco.end)) {
335
+ if (property.type === "colr") {
336
+ if (bytes.ascii(property.body, 4) !== "nclx") found.add("icc");
337
+ }
338
+ if (property.type !== "ispe" || property.end - property.body < 12) continue;
339
+ const width = bytes.u32(property.body + 4, false);
340
+ const height = bytes.u32(property.body + 8, false);
341
+ if (width * height > area) {
342
+ area = width * height;
343
+ found.width = width;
344
+ found.height = height;
345
+ }
346
+ }
347
+ const iinf = child(bytes, meta, "iinf", 4);
348
+ const iloc = child(bytes, meta, "iloc", 4);
349
+ const items = iinf === void 0 ? {
350
+ exif: [],
351
+ xmp: false
352
+ } : readItemInfo(bytes, iinf);
353
+ if (items.xmp) found.add("xmp");
354
+ for (const id of items.exif) {
355
+ found.add("exif");
356
+ const location = iloc === void 0 ? null : itemLocation(bytes, iloc, id);
357
+ const skip = location === null ? null : bytes.u32(location.start, false);
358
+ if (location === null || skip === null) continue;
359
+ const summary = readTiff(bytes, location.start + 4 + skip, location.end);
360
+ if (summary === null) continue;
361
+ if (summary.gps) found.add("gps");
362
+ if (summary.thumbnail) found.add("thumbnail");
363
+ }
364
+ }
365
+ return {
366
+ info: found.info(format),
367
+ strip: null
368
+ };
369
+ }
370
+ /** Which ISO BMFF image format the `ftyp` brands name, if any. */
371
+ function bmffFormat(bytes) {
372
+ if (bytes.ascii(4, 4) !== "ftyp") return null;
373
+ const size = bytes.u32(0, false);
374
+ const list = bytes.ascii(8, Math.max(0, Math.min(size, bytes.length) - 8)).match(/.{4}/g) ?? [];
375
+ if (list.some((brand) => brand === "avif" || brand === "avis")) return "avif";
376
+ if (list.some((brand) => [
377
+ "heic",
378
+ "heix",
379
+ "heim",
380
+ "heis",
381
+ "hevc",
382
+ "hevx",
383
+ "mif1",
384
+ "msf1"
385
+ ].includes(brand))) return "heic";
386
+ return null;
387
+ }
388
+ //#endregion
389
+ //#region src/image/gif.ts
390
+ /** The end of a run of data sub-blocks starting at `at` (after its terminating zero), or `null` if cut off. */
391
+ function skipSubBlocks(bytes, at) {
392
+ let position = at;
393
+ for (;;) {
394
+ const size = bytes.u8(position);
395
+ if (size === null) return null;
396
+ position += 1 + size;
397
+ if (size === 0) return position;
398
+ }
399
+ }
400
+ /** Application extensions that are part of the picture: looping and the colour profile. */
401
+ const ANIMATION_APPS = /* @__PURE__ */ new Set(["NETSCAPE2.0", "ANIMEXTS1.0"]);
402
+ function parseGif(bytes) {
403
+ const found = new Found();
404
+ found.width = bytes.u16(6, true);
405
+ found.height = bytes.u16(8, true);
406
+ const packed = bytes.u8(10) ?? 0;
407
+ const header = 13 + ((packed & 128) !== 0 ? 3 * 2 ** ((packed & 7) + 1) : 0);
408
+ const blocks = [];
409
+ let frames = 0;
410
+ let at = header;
411
+ let trailer = -1;
412
+ while (at < bytes.length) {
413
+ const introducer = bytes.u8(at);
414
+ if (introducer === 59) {
415
+ trailer = at;
416
+ break;
417
+ }
418
+ let end = null;
419
+ let kind = null;
420
+ if (introducer === 44) {
421
+ frames += 1;
422
+ const flags = bytes.u8(at + 9) ?? 0;
423
+ const table = (flags & 128) !== 0 ? 3 * 2 ** ((flags & 7) + 1) : 0;
424
+ end = skipSubBlocks(bytes, at + 10 + table + 1);
425
+ } else if (introducer === 33) {
426
+ const label = bytes.u8(at + 1);
427
+ if (label === 254) kind = "comment";
428
+ else if (label === 255) {
429
+ const app = bytes.u8(at + 2) === 11 ? bytes.ascii(at + 3, 11) ?? "" : "";
430
+ if (app === "ICCRGBG1012") kind = "icc";
431
+ else if (app === "XMP DataXMP") kind = "xmp";
432
+ else if (!ANIMATION_APPS.has(app)) kind = "other";
433
+ }
434
+ end = skipSubBlocks(bytes, at + 2);
435
+ }
436
+ if (end === null || end > bytes.length) break;
437
+ if (kind !== null) found.add(kind);
438
+ blocks.push({
439
+ start: at,
440
+ end,
441
+ kind
442
+ });
443
+ at = end;
444
+ }
445
+ found.animated = frames > 1;
446
+ if (trailer >= 0 && trailer + 1 < bytes.length) found.add("other");
447
+ const strip = (settings) => {
448
+ const removed = new Set(found.kinds);
449
+ const parts = [bytes.slice(0, header)];
450
+ for (const block of blocks) {
451
+ if (block.kind === "icc" && settings.colorProfile) removed.delete("icc");
452
+ else if (block.kind !== null) continue;
453
+ parts.push(bytes.slice(block.start, block.end));
454
+ }
455
+ parts.push(Uint8Array.of(59));
456
+ return {
457
+ parts,
458
+ removed
459
+ };
460
+ };
461
+ return {
462
+ info: found.info("gif"),
463
+ strip
464
+ };
465
+ }
466
+ //#endregion
467
+ //#region src/image/jpeg.ts
468
+ const SOI = 216;
469
+ const EOI = 217;
470
+ const SOS = 218;
471
+ const APP0 = 224;
472
+ const APP1 = 225;
473
+ const APP2 = 226;
474
+ const APP13 = 237;
475
+ const APP14 = 238;
476
+ const COM = 254;
477
+ /** SOF markers carry the frame size; C4 (DHT), C8 (JPG) and CC (DAC) are not frames. */
478
+ const isFrame = (marker) => marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204;
479
+ /** Markers without a length: TEM and the restart markers. */
480
+ const isStandalone = (marker) => marker === 1 || marker >= 208 && marker <= 215;
481
+ /** The JFIF APP0 segment with its thumbnail removed (the 14 fixed bytes after the identifier, size zeroed). */
482
+ function jfifWithoutThumbnail(bytes, segment) {
483
+ if (segment.end - segment.start < 18) return bytes.slice(segment.start, segment.end);
484
+ const head = bytes.slice(segment.start, segment.start + 18);
485
+ const out = new Uint8Array(head);
486
+ out[2] = 0;
487
+ out[3] = 16;
488
+ out[16] = 0;
489
+ out[17] = 0;
490
+ return out;
491
+ }
492
+ function classify(bytes, marker, body, end, found) {
493
+ if (marker === APP1) {
494
+ if (bytes.startsWith(body, "Exif\0")) {
495
+ found.exif(readTiff(bytes, tiffStart(bytes, body), end));
496
+ return "exif";
497
+ }
498
+ if (bytes.startsWith(body, "http://ns.adobe.com/")) {
499
+ found.add("xmp");
500
+ return "xmp";
501
+ }
502
+ }
503
+ if (marker === APP0) {
504
+ if (bytes.startsWith(body, "JFIF\0")) {
505
+ if (end - body >= 14 && bytes.u8(body + 12) * bytes.u8(body + 13) > 0) found.add("thumbnail");
506
+ return null;
507
+ }
508
+ if (bytes.startsWith(body, "JFXX\0")) {
509
+ found.add("thumbnail");
510
+ return "thumbnail";
511
+ }
512
+ }
513
+ if (marker === APP2 && bytes.startsWith(body, "ICC_PROFILE\0")) {
514
+ found.add("icc");
515
+ return "icc";
516
+ }
517
+ if (marker === APP14 && bytes.startsWith(body, "Adobe")) return null;
518
+ if (marker === APP13) {
519
+ found.add("iptc");
520
+ return "iptc";
521
+ }
522
+ if (marker === COM) {
523
+ found.add("comment");
524
+ return "comment";
525
+ }
526
+ if (marker >= APP0 && marker <= 239) {
527
+ found.add("other");
528
+ return "other";
529
+ }
530
+ return null;
531
+ }
532
+ /** Parses a JPEG from its markers: never decodes the image data, only skips over it. */
533
+ function parseJpeg(bytes) {
534
+ const found = new Found();
535
+ const segments = [];
536
+ let at = 2;
537
+ let end = bytes.length;
538
+ while (at + 1 < bytes.length) {
539
+ if (bytes.u8(at) !== 255) break;
540
+ const marker = bytes.u8(at + 1);
541
+ if (marker === 255) {
542
+ at += 1;
543
+ continue;
544
+ }
545
+ if (marker === SOI || isStandalone(marker)) {
546
+ segments.push({
547
+ marker,
548
+ start: at,
549
+ end: at + 2,
550
+ kind: null
551
+ });
552
+ at += 2;
553
+ continue;
554
+ }
555
+ if (marker === EOI) {
556
+ end = at + 2;
557
+ break;
558
+ }
559
+ const length = bytes.u16(at + 2, false);
560
+ if (length === null || length < 2 || at + 2 + length > bytes.length) break;
561
+ let segmentEnd = at + 2 + length;
562
+ const body = at + 4;
563
+ if (isFrame(marker)) {
564
+ const frame = bytes.until(segmentEnd);
565
+ found.height = frame.u16(body + 1, false);
566
+ found.width = frame.u16(body + 3, false);
567
+ }
568
+ if (marker === SOS) {
569
+ let scan = segmentEnd;
570
+ while (scan + 1 < bytes.length) {
571
+ if (bytes.u8(scan) === 255) {
572
+ const next = bytes.u8(scan + 1);
573
+ if (next !== 0 && next !== 255 && !isStandalone(next)) break;
574
+ }
575
+ scan += 1;
576
+ }
577
+ segmentEnd = scan + 1 < bytes.length ? scan : bytes.length;
578
+ }
579
+ segments.push({
580
+ marker,
581
+ start: at,
582
+ end: segmentEnd,
583
+ kind: classify(bytes.until(segmentEnd), marker, body, segmentEnd, found)
584
+ });
585
+ at = segmentEnd;
586
+ }
587
+ if (end < bytes.length) found.add("other");
588
+ const strip = (settings) => {
589
+ const removed = new Set(found.kinds);
590
+ const parts = [Uint8Array.of(255, SOI)];
591
+ let wroteExif = false;
592
+ const writeOrientation = () => {
593
+ if (wroteExif || !settings.orientation || found.orientation === 1) return;
594
+ const payload = [latin1("Exif\0\0"), orientationTiff(found.orientation)];
595
+ parts.push(Uint8Array.of(255, APP1, 0, 34), ...payload);
596
+ wroteExif = true;
597
+ };
598
+ for (const segment of segments) {
599
+ const { marker, kind } = segment;
600
+ if (marker === APP0 && kind === null) {
601
+ parts.push(jfifWithoutThumbnail(bytes, segment));
602
+ writeOrientation();
603
+ continue;
604
+ }
605
+ if (kind === "icc" && settings.colorProfile) removed.delete("icc");
606
+ else if (kind !== null) continue;
607
+ if (marker !== APP0 && (marker < APP0 || marker > 239)) writeOrientation();
608
+ parts.push(bytes.slice(segment.start, segment.end));
609
+ }
610
+ writeOrientation();
611
+ parts.push(Uint8Array.of(255, EOI));
612
+ return {
613
+ parts,
614
+ removed
615
+ };
616
+ };
617
+ return {
618
+ info: found.info("jpeg"),
619
+ strip,
620
+ orientationOnly: found.orientationOnly
621
+ };
622
+ }
623
+ //#endregion
624
+ //#region src/image/png.ts
625
+ let table = null;
626
+ /** CRC-32 (ISO 3309), as PNG chunks use it. */
627
+ function crc32(data) {
628
+ if (table === null) {
629
+ table = /* @__PURE__ */ new Uint32Array(256);
630
+ for (let n = 0; n < 256; n += 1) {
631
+ let c = n;
632
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
633
+ table[n] = c >>> 0;
634
+ }
635
+ }
636
+ let crc = 4294967295;
637
+ for (const byte of data) crc = table[(crc ^ byte) & 255] ^ crc >>> 8;
638
+ return (crc ^ 4294967295) >>> 0;
639
+ }
640
+ function pngChunk(type, data) {
641
+ const body = concat([latin1(type), data]);
642
+ return concat([
643
+ u32be(data.length),
644
+ body,
645
+ u32be(crc32(body))
646
+ ]);
647
+ }
648
+ /** Chunks that are part of the picture: how it is decoded, coloured, animated or sized. Everything else is dropped. */
649
+ const IMAGE_CHUNKS$1 = /* @__PURE__ */ new Set([
650
+ "IHDR",
651
+ "PLTE",
652
+ "IDAT",
653
+ "IEND",
654
+ "tRNS",
655
+ "gAMA",
656
+ "cHRM",
657
+ "sRGB",
658
+ "sBIT",
659
+ "pHYs",
660
+ "bKGD",
661
+ "hIST",
662
+ "sPLT",
663
+ "acTL",
664
+ "fcTL",
665
+ "fdAT",
666
+ "cICP",
667
+ "mDCV",
668
+ "cLLI"
669
+ ]);
670
+ function parsePng(bytes) {
671
+ const found = new Found();
672
+ const chunks = [];
673
+ found.width = bytes.u32(16, false);
674
+ found.height = bytes.u32(20, false);
675
+ for (let at = 8; at + 12 <= bytes.length;) {
676
+ const length = bytes.u32(at, false);
677
+ const type = bytes.ascii(at + 4, 4);
678
+ const end = at + 12 + length;
679
+ if (end > bytes.length) break;
680
+ chunks.push({
681
+ type,
682
+ start: at,
683
+ end
684
+ });
685
+ const data = at + 8;
686
+ const chunkBytes = bytes.until(data + length);
687
+ if (type === "acTL") found.animated = true;
688
+ else if (type === "iCCP") found.add("icc");
689
+ else if (type === "eXIf") found.exif(readTiff(chunkBytes, data, data + length));
690
+ else if (type === "iTXt" && chunkBytes.startsWith(data, "XML:com.adobe.xmp\0")) found.add("xmp");
691
+ else if (type === "tEXt" || type === "zTXt" || type === "iTXt" || type === "tIME") found.add("text");
692
+ else if (!IMAGE_CHUNKS$1.has(type)) found.add("other");
693
+ at = end;
694
+ if (type === "IEND") {
695
+ if (end < bytes.length) found.add("other");
696
+ break;
697
+ }
698
+ }
699
+ const strip = (settings) => {
700
+ const removed = new Set(found.kinds);
701
+ const parts = [bytes.slice(0, 8)];
702
+ for (const chunk of chunks) {
703
+ const keepIcc = chunk.type === "iCCP" && settings.colorProfile;
704
+ if (!IMAGE_CHUNKS$1.has(chunk.type) && !keepIcc) continue;
705
+ if (keepIcc) removed.delete("icc");
706
+ parts.push(bytes.slice(chunk.start, chunk.end));
707
+ if (chunk.type === "IHDR" && settings.orientation && found.orientation !== 1) parts.push(pngChunk("eXIf", orientationTiff(found.orientation)));
708
+ }
709
+ return {
710
+ parts,
711
+ removed
712
+ };
713
+ };
714
+ return {
715
+ info: found.info("png"),
716
+ strip,
717
+ orientationOnly: found.orientationOnly
718
+ };
719
+ }
720
+ //#endregion
721
+ //#region src/image/webp.ts
722
+ const IMAGE_CHUNKS = /* @__PURE__ */ new Set([
723
+ "VP8 ",
724
+ "VP8L",
725
+ "VP8X",
726
+ "ALPH",
727
+ "ANIM",
728
+ "ANMF"
729
+ ]);
730
+ const FLAG_ANIMATION = 2;
731
+ const FLAG_EXIF = 8;
732
+ /** A RIFF chunk for data of even length (the orientation block is 26 bytes), so it needs no padding byte. */
733
+ function riffChunk(type, data) {
734
+ return [
735
+ latin1(type),
736
+ u32le(data.length),
737
+ data
738
+ ];
739
+ }
740
+ function parseWebp(bytes) {
741
+ const found = new Found();
742
+ const chunks = [];
743
+ const riffEnd = Math.min(bytes.length, 8 + bytes.u32(4, true));
744
+ for (let at = 12; at + 8 <= riffEnd;) {
745
+ const type = bytes.ascii(at, 4);
746
+ const size = bytes.u32(at + 4, true);
747
+ const data = at + 8;
748
+ const end = Math.min(riffEnd, data + size + size % 2);
749
+ if (data + size > riffEnd) break;
750
+ chunks.push({
751
+ type,
752
+ start: at,
753
+ end
754
+ });
755
+ const chunkBytes = bytes.until(data + size);
756
+ if (type === "VP8X") {
757
+ found.animated = ((chunkBytes.u8(data) ?? 0) & FLAG_ANIMATION) !== 0;
758
+ const width = chunkBytes.u24le(data + 4);
759
+ const height = chunkBytes.u24le(data + 7);
760
+ found.width = width === null ? null : width + 1;
761
+ found.height = height === null ? null : height + 1;
762
+ } else if (type === "VP8 " && found.width === null) {
763
+ const width = chunkBytes.u16(data + 6, true);
764
+ const height = chunkBytes.u16(data + 8, true);
765
+ found.width = width === null ? null : width & 16383;
766
+ found.height = height === null ? null : height & 16383;
767
+ } else if (type === "VP8L" && found.width === null) {
768
+ const bits = chunkBytes.u32(data + 1, true);
769
+ found.width = bits === null ? null : (bits & 16383) + 1;
770
+ found.height = bits === null ? null : (bits >>> 14 & 16383) + 1;
771
+ } else if (type === "ANIM") found.animated = true;
772
+ else if (type === "ICCP") found.add("icc");
773
+ else if (type === "EXIF") found.exif(readTiff(chunkBytes, tiffStart(chunkBytes, data), data + size));
774
+ else if (type === "XMP ") found.add("xmp");
775
+ else if (!IMAGE_CHUNKS.has(type)) found.add("other");
776
+ at = end;
777
+ }
778
+ if (riffEnd < bytes.length) found.add("other");
779
+ const strip = (settings) => {
780
+ const removed = new Set(found.kinds);
781
+ const keepIcc = settings.colorProfile && found.kinds.has("icc");
782
+ if (keepIcc) removed.delete("icc");
783
+ const exif = settings.orientation && found.orientation !== 1 ? orientationTiff(found.orientation) : null;
784
+ const body = [];
785
+ for (const chunk of chunks) if (chunk.type === "VP8X") {
786
+ const header = new Uint8Array(bytes.slice(chunk.start, chunk.end));
787
+ let flags = header[8] & -13;
788
+ if (!keepIcc) flags &= -33;
789
+ if (exif !== null) flags |= FLAG_EXIF;
790
+ header[8] = flags;
791
+ body.push(header);
792
+ } else if (IMAGE_CHUNKS.has(chunk.type) || chunk.type === "ICCP" && keepIcc) body.push(bytes.slice(chunk.start, chunk.end));
793
+ if (exif !== null) body.push(...riffChunk("EXIF", exif));
794
+ let size = 4;
795
+ for (const part of body) size += part.length;
796
+ return {
797
+ parts: [
798
+ latin1("RIFF"),
799
+ u32le(size),
800
+ latin1("WEBP"),
801
+ ...body
802
+ ],
803
+ removed
804
+ };
805
+ };
806
+ return {
807
+ info: found.info("webp"),
808
+ strip,
809
+ orientationOnly: found.orientationOnly
810
+ };
811
+ }
812
+ //#endregion
813
+ //#region src/image/info.ts
814
+ /** Recognises the format from the bytes and parses it. */
815
+ function parse(bytes) {
816
+ if (bytes.u8(0) === 255 && bytes.u8(1) === 216 && bytes.u8(2) === 255) return parseJpeg(bytes);
817
+ if (bytes.u32(0, false) === 2303741511 && bytes.u32(4, false) === 218765834) return parsePng(bytes);
818
+ if (bytes.startsWith(0, "GIF87a") || bytes.startsWith(0, "GIF89a")) return parseGif(bytes);
819
+ if (bytes.startsWith(0, "RIFF") && bytes.startsWith(8, "WEBP")) return parseWebp(bytes);
820
+ const bmff = bmffFormat(bytes);
821
+ if (bmff !== null) return parseBmff(bytes, bmff);
822
+ if (bytes.startsWith(0, "BM") && bytes.length >= 26) {
823
+ const found = new Found();
824
+ found.width = bytes.u32(18, true);
825
+ found.height = Math.abs(bytes.u32(22, true) | 0);
826
+ return {
827
+ info: found.info("bmp"),
828
+ strip: () => ({
829
+ parts: [bytes.data],
830
+ removed: /* @__PURE__ */ new Set()
831
+ })
832
+ };
833
+ }
834
+ return {
835
+ info: new Found().info(null),
836
+ strip: null
837
+ };
838
+ }
839
+ function inputLimit(value) {
840
+ if (value === void 0) return DEFAULT_IMAGE_MAX_INPUT_BYTES;
841
+ if (value === Infinity || Number.isInteger(value) && value > 0) return value;
842
+ throw copyFailure("invalid-payload", `\`maxInputBytes\` must be a positive integer or Infinity (received ${String(value)}).`);
843
+ }
844
+ /**
845
+ * What an image file is and what it carries, read from its bytes without
846
+ * decoding the picture: format, stored size, orientation, animation, and the
847
+ * metadata in it (Exif, GPS location, thumbnails, XMP, IPTC, comments, colour
848
+ * profile, appended data). The claimed MIME type and file name are never
849
+ * trusted. Works anywhere, including on the server.
850
+ *
851
+ * @example
852
+ * const info = await readImageInfo(file);
853
+ * if (info.metadata.includes('gps')) warn('This photo contains its location.');
854
+ */
855
+ async function readImageInfo(blob, options = {}) {
856
+ return parse(await readBlob(blob, inputLimit(options.maxInputBytes))).info;
857
+ }
858
+ function flag(value, fallback, name) {
859
+ if (value === void 0) return fallback;
860
+ if (typeof value === "boolean") return value;
861
+ throw copyFailure("invalid-payload", `\`${name}\` must be a boolean.`);
862
+ }
863
+ /** Strips a parsed file; shared with `prepareImage`. Returns `null` when the format can't be stripped losslessly. */
864
+ function stripParsed(parsed, source, keepColorProfile, keepOrientation) {
865
+ if (parsed.strip === null) return null;
866
+ const { parts, removed } = parsed.strip({
867
+ colorProfile: keepColorProfile,
868
+ orientation: keepOrientation
869
+ });
870
+ const kinds = METADATA_KINDS.filter((kind) => removed.has(kind) || kind === "exif" && !keepOrientation && parsed.orientationOnly === true);
871
+ return {
872
+ blob: kinds.length === 0 ? source : outputBlob(parts, MIME_TYPES[parsed.info.format], source),
873
+ info: parsed.info,
874
+ removed: kinds
875
+ };
876
+ }
877
+ /**
878
+ * Removes metadata from a JPEG, PNG, WebP or GIF without re-encoding it: the
879
+ * picture stays bit-for-bit the same. Removes Exif (camera, dates, serial
880
+ * numbers, GPS location), embedded thumbnails, XMP, IPTC, comments, text chunks,
881
+ * multi-picture and depth images, content credentials and data appended after
882
+ * the image. Keeps the colour profile and orientation unless told otherwise.
883
+ * Works anywhere, including on the server.
884
+ *
885
+ * AVIF and HEIC can't be stripped losslessly: this throws `unsupported-format`
886
+ * for them (and for files that aren't images); `prepareImage` re-encodes them.
887
+ *
888
+ * @example
889
+ * const { blob, removed } = await stripMetadata(file);
890
+ * if (removed.includes('gps')) notice('Location removed from the photo.');
891
+ */
892
+ async function stripMetadata(blob, options = {}) {
893
+ const keepColorProfile = flag(options.keepColorProfile, true, "keepColorProfile");
894
+ const keepOrientation = flag(options.keepOrientation, true, "keepOrientation");
895
+ const parsed = parse(await readBlob(blob, inputLimit(options.maxInputBytes)));
896
+ const stripped = stripParsed(parsed, blob, keepColorProfile, keepOrientation);
897
+ if (stripped === null) throw copyFailure("unsupported-format", parsed.info.format === null ? "Not an image this module can read (JPEG, PNG, WebP, GIF, BMP, AVIF or HEIC)." : `${parsed.info.mimeType} metadata can't be removed without re-encoding; use prepareImage().`);
898
+ return stripped;
899
+ }
900
+ //#endregion
901
+ //#region src/capture/deadline.ts
902
+ /**
903
+ * Runs `task` with a timeout and an optional caller `AbortSignal`. The task
904
+ * receives a signal that fires on either, so cooperative work can stop early.
905
+ * Rejects with classified `timeout` / `aborted` failures.
906
+ */
907
+ function withDeadline(task, options) {
908
+ const { timeoutMs, label } = options;
909
+ const external = options.signal;
910
+ if (external?.aborted) return Promise.reject(copyFailure("aborted", `${label} was aborted.`, external.reason));
911
+ const controller = new AbortController();
912
+ return new Promise((resolve, reject) => {
913
+ const finish = (abort) => {
914
+ clearTimeout(timer);
915
+ external?.removeEventListener("abort", onAbort);
916
+ /* c8 ignore next -- abort=false path is never used; kept for future API flexibility */
917
+ if (abort) controller.abort();
918
+ };
919
+ const fail = (failure) => {
920
+ finish(true);
921
+ reject(failure);
922
+ };
923
+ const onAbort = () => {
924
+ fail(copyFailure("aborted", `${label} was aborted.`, external.reason));
925
+ };
926
+ const timer = timeoutMs === Infinity ? void 0 : setTimeout(() => {
927
+ fail(copyFailure("timeout", `${label} timed out after ${String(timeoutMs)} ms.`));
928
+ }, timeoutMs);
929
+ external?.addEventListener("abort", onAbort, { once: true });
930
+ new Promise((run) => {
931
+ run(task(controller.signal));
932
+ }).then((value) => {
933
+ finish(true);
934
+ resolve(value);
935
+ }, (cause) => {
936
+ finish(true);
937
+ reject(cause);
938
+ });
939
+ });
940
+ }
941
+ //#endregion
942
+ //#region src/image/prepare.ts
943
+ function createCanvas(width, height) {
944
+ if (typeof OffscreenCanvas === "function") return new OffscreenCanvas(width, height);
945
+ const canvas = document.createElement("canvas");
946
+ canvas.width = width;
947
+ canvas.height = height;
948
+ return canvas;
949
+ }
950
+ function context(canvas) {
951
+ const ctx = canvas.getContext("2d");
952
+ if (ctx === null) throw copyFailure("unsupported", "Canvas 2D rendering is not available.");
953
+ ctx.imageSmoothingEnabled = true;
954
+ ctx.imageSmoothingQuality = "high";
955
+ return ctx;
956
+ }
957
+ function toBlob(canvas, type, quality) {
958
+ if ("convertToBlob" in canvas) return canvas.convertToBlob({
959
+ type,
960
+ quality
961
+ });
962
+ return new Promise((resolve, reject) => {
963
+ canvas.toBlob((blob) => {
964
+ if (blob) resolve(blob);
965
+ else reject(copyFailure("blob-generation-failed", "The canvas produced no image (too large for this browser?)."));
966
+ }, type, quality);
967
+ });
968
+ }
969
+ /**
970
+ * Draws `image` at the target size. Large reductions halve the size in steps, as
971
+ * one big reduction skips pixels and makes text and edges shimmer.
972
+ */
973
+ function draw(image, target) {
974
+ let source = image.source;
975
+ let width = image.width;
976
+ let height = image.height;
977
+ while (width / 2 >= target.width && height / 2 >= target.height) {
978
+ width = Math.round(width / 2);
979
+ height = Math.round(height / 2);
980
+ const step = createCanvas(width, height);
981
+ context(step).drawImage(source, 0, 0, width, height);
982
+ source = step;
983
+ }
984
+ const canvas = createCanvas(target.width, target.height);
985
+ const ctx = context(canvas);
986
+ if (target.background !== null) {
987
+ ctx.fillStyle = target.background;
988
+ ctx.fillRect(0, 0, target.width, target.height);
989
+ }
990
+ ctx.drawImage(source, 0, 0, target.width, target.height);
991
+ return canvas;
992
+ }
993
+ /** The browser environment, or `null` where there is no `createImageBitmap` or canvas (servers, old browsers). */
994
+ function getDefaultImageEnvironment() {
995
+ if (typeof createImageBitmap !== "function" || typeof OffscreenCanvas !== "function" && typeof document === "undefined") return null;
996
+ return {
997
+ decode: async (blob) => {
998
+ const bitmap = await createImageBitmap(blob, { imageOrientation: "from-image" });
999
+ return {
1000
+ width: bitmap.width,
1001
+ height: bitmap.height,
1002
+ source: bitmap,
1003
+ close: () => {
1004
+ bitmap.close();
1005
+ }
1006
+ };
1007
+ },
1008
+ encode: (image, target) => toBlob(draw(image, target), target.type, target.quality)
1009
+ };
1010
+ }
1011
+ const DEFAULT_IMAGE_MAX_INPUT_PIXELS = 1e8;
1012
+ /** 4096 x 4096: the canvas area limit of Safari and iOS, the strictest mainstream engine. */
1013
+ const DEFAULT_IMAGE_MAX_PIXELS = 16777216;
1014
+ const DEFAULT_IMAGE_QUALITY = .85;
1015
+ const DEFAULT_IMAGE_MIN_QUALITY = .5;
1016
+ const DEFAULT_IMAGE_TIMEOUT_MS = 3e4;
1017
+ const invalid = (message) => copyFailure("invalid-payload", message);
1018
+ function limit(value, fallback, name) {
1019
+ if (value === void 0) return fallback;
1020
+ if (value === Infinity || Number.isInteger(value) && value > 0) return value;
1021
+ throw invalid(`\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
1022
+ }
1023
+ function unit(value, fallback, name) {
1024
+ if (value === void 0) return fallback;
1025
+ if (typeof value === "number" && value > 0 && value <= 1) return value;
1026
+ throw invalid(`\`${name}\` must be greater than 0 and at most 1 (received ${String(value)}).`);
1027
+ }
1028
+ function oneOf(value, allowed, fallback, name) {
1029
+ if (value === void 0) return fallback;
1030
+ if (allowed.includes(value)) return value;
1031
+ throw invalid(`\`${name}\` must be one of: ${allowed.map((option) => JSON.stringify(option)).join(", ")}.`);
1032
+ }
1033
+ const EXTENSIONS = {
1034
+ "image/png": "png",
1035
+ "image/jpeg": "jpg",
1036
+ "image/webp": "webp"
1037
+ };
1038
+ const LOSSLESS = /* @__PURE__ */ new Set(["image/png"]);
1039
+ /** The input's name with the extension of `type`. */
1040
+ function renamed(source, type) {
1041
+ const name = source.name;
1042
+ if (typeof name !== "string") return void 0;
1043
+ const dot = name.lastIndexOf(".");
1044
+ return `${dot > 0 ? name.slice(0, dot) : name}.${EXTENSIONS[type]}`;
1045
+ }
1046
+ /** Output types to try, best first. */
1047
+ function candidates(requested, info) {
1048
+ if (requested !== "auto") return [requested];
1049
+ switch (info.format) {
1050
+ case "jpeg": return ["image/jpeg"];
1051
+ case "webp": return ["image/webp", "image/jpeg"];
1052
+ case "png":
1053
+ case "gif":
1054
+ case "bmp": return [
1055
+ "image/png",
1056
+ "image/webp",
1057
+ "image/jpeg"
1058
+ ];
1059
+ default: return ["image/jpeg"];
1060
+ }
1061
+ }
1062
+ /**
1063
+ * Prepares an image for upload: removes metadata (location, camera, thumbnails),
1064
+ * makes it fit `maxWidth` / `maxHeight` / `maxPixels`, and compresses it under
1065
+ * `maxBytes`. When nothing has to change but the metadata, the picture is not
1066
+ * re-encoded at all, so screenshots and photos keep every pixel. Inputs are
1067
+ * checked against `maxInputPixels` from their header, before decoding.
1068
+ *
1069
+ * Needs a browser (`createImageBitmap` and a canvas) only when it has to
1070
+ * re-encode; elsewhere that is an `unsupported` error. Every failure is a typed
1071
+ * `CopyFailure`: `too-large`, `unsupported-format`, `timeout`, `aborted`, ...
1072
+ *
1073
+ * @example
1074
+ * usePaste({ accept: ['image'], onPaste: async ({ imageFiles }) => {
1075
+ * const image = await prepareImage(imageFiles[0], { maxWidth: 2048, maxBytes: 1_000_000 });
1076
+ * upload(image.file);
1077
+ * } });
1078
+ */
1079
+ async function prepareImage(source, options = {}) {
1080
+ const maxWidth = limit(options.maxWidth, Infinity, "maxWidth");
1081
+ const maxHeight = limit(options.maxHeight, Infinity, "maxHeight");
1082
+ const maxPixels = limit(options.maxPixels, DEFAULT_IMAGE_MAX_PIXELS, "maxPixels");
1083
+ const maxBytes = limit(options.maxBytes, Infinity, "maxBytes");
1084
+ const maxInputPixels = limit(options.maxInputPixels, DEFAULT_IMAGE_MAX_INPUT_PIXELS, "maxInputPixels");
1085
+ const timeoutMs = options.timeoutMs ?? 3e4;
1086
+ if (timeoutMs !== Infinity && !(typeof timeoutMs === "number" && timeoutMs > 0 && Number.isFinite(timeoutMs))) throw invalid(`\`timeoutMs\` must be > 0 or Infinity (received ${String(timeoutMs)}).`);
1087
+ const quality = unit(options.quality, DEFAULT_IMAGE_QUALITY, "quality");
1088
+ const minQuality = unit(options.minQuality, Math.min(DEFAULT_IMAGE_MIN_QUALITY, quality), "minQuality");
1089
+ if (minQuality > quality) throw invalid("`minQuality` must not be above `quality`.");
1090
+ const requested = oneOf(options.type, [
1091
+ "auto",
1092
+ "image/png",
1093
+ "image/jpeg",
1094
+ "image/webp"
1095
+ ], "auto", "type");
1096
+ const animated = oneOf(options.animated, [
1097
+ "keep",
1098
+ "first-frame",
1099
+ "reject"
1100
+ ], "keep", "animated");
1101
+ const keepColorProfile = flag(options.keepColorProfile, true, "keepColorProfile");
1102
+ const background = options.background ?? "#fff";
1103
+ if (typeof background !== "string") throw invalid("`background` must be a CSS colour string.");
1104
+ const maxInputBytes = inputLimit(options.maxInputBytes);
1105
+ return withDeadline(async (signal) => {
1106
+ const parsed = parse(await readBlob(source, maxInputBytes));
1107
+ const { info } = parsed;
1108
+ const original = {
1109
+ info,
1110
+ size: source.size
1111
+ };
1112
+ if (info.format === null && !source.type.startsWith("image/")) throw copyFailure("unsupported-format", "Not an image: the bytes match no image format and the type is not image/*.");
1113
+ if (info.width !== null && info.height !== null && info.width * info.height > maxInputPixels) throw copyFailure("too-large", `The image has ${String(info.width * info.height)} pixels; maxInputPixels is ${String(maxInputPixels)}.`);
1114
+ if (info.animated && animated === "reject") throw copyFailure("unsupported-format", "Animated images are not accepted (animated: \"reject\").");
1115
+ const fits = (width, height) => width === null || height === null || width <= maxWidth && height <= maxHeight && width * height <= maxPixels;
1116
+ const swapped = info.orientation >= 5 && (info.format === "jpeg" || info.format === "png");
1117
+ const shownWidth = swapped ? info.height : info.width;
1118
+ const shownHeight = swapped ? info.width : info.height;
1119
+ const keepsType = requested === "auto" || requested === info.mimeType;
1120
+ const keepAnimation = info.animated && animated === "keep";
1121
+ if (keepsType && (fits(shownWidth, shownHeight) || keepAnimation)) {
1122
+ const stripped = stripParsed(parsed, source, keepColorProfile, true);
1123
+ if (stripped !== null && stripped.blob.size <= maxBytes && fits(shownWidth, shownHeight)) return {
1124
+ file: stripped.blob,
1125
+ type: info.mimeType,
1126
+ width: shownWidth,
1127
+ height: shownHeight,
1128
+ size: stripped.blob.size,
1129
+ reencoded: false,
1130
+ resized: false,
1131
+ quality: null,
1132
+ removed: stripped.removed,
1133
+ original
1134
+ };
1135
+ }
1136
+ if (keepAnimation) throw copyFailure("too-large", "An animated image can only fit the size limits by losing its frames: use animated: \"first-frame\".");
1137
+ const environment = options.environment ?? getDefaultImageEnvironment();
1138
+ if (environment === null) throw copyFailure("unsupported", "Re-encoding an image needs createImageBitmap and a canvas (a browser).");
1139
+ let image;
1140
+ try {
1141
+ image = await environment.decode(source, signal);
1142
+ } catch (cause) {
1143
+ throw cause instanceof CopyFailure ? cause : copyFailure("unsupported-format", "This browser could not decode the image.", cause);
1144
+ }
1145
+ try {
1146
+ if (image.width * image.height > maxInputPixels) throw copyFailure("too-large", `The image has ${String(image.width * image.height)} pixels; maxInputPixels is ${String(maxInputPixels)}.`);
1147
+ const fit = Math.min(1, maxWidth / image.width, maxHeight / image.height, Math.sqrt(maxPixels / (image.width * image.height)));
1148
+ return await encodeWithin(environment, image, {
1149
+ info,
1150
+ source,
1151
+ requested,
1152
+ quality,
1153
+ minQuality,
1154
+ maxBytes,
1155
+ background,
1156
+ fit,
1157
+ signal,
1158
+ original
1159
+ });
1160
+ } finally {
1161
+ image.close();
1162
+ }
1163
+ }, {
1164
+ timeoutMs,
1165
+ signal: options.signal,
1166
+ label: "Preparing the image"
1167
+ });
1168
+ }
1169
+ /** Most encodes one image may take: a few quality steps at a few sizes. */
1170
+ const MAX_ENCODES = 24;
1171
+ /**
1172
+ * Thrown inside the search, never out of it: `unavailable` (this type can't be
1173
+ * encoded here, so 'auto' tries the next one) or `exhausted` (the encode budget is spent).
1174
+ */
1175
+ var SearchSignal = class extends Error {
1176
+ constructor(reason) {
1177
+ super(reason);
1178
+ this.reason = reason;
1179
+ }
1180
+ };
1181
+ /** Finds the best result under `maxBytes`: highest quality first, then the largest size. */
1182
+ async function encodeWithin(environment, image, settings) {
1183
+ const { info, requested, maxBytes, signal } = settings;
1184
+ let encodes = 0;
1185
+ let smallest = Infinity;
1186
+ const encode = async (type, scale, quality) => {
1187
+ if (signal.aborted) throw copyFailure("aborted", "Preparing the image was aborted.");
1188
+ if (encodes >= MAX_ENCODES) throw new SearchSignal("exhausted");
1189
+ encodes += 1;
1190
+ const width = Math.max(1, Math.round(image.width * scale));
1191
+ const height = Math.max(1, Math.round(image.height * scale));
1192
+ let blob;
1193
+ try {
1194
+ blob = await environment.encode(image, {
1195
+ width,
1196
+ height,
1197
+ type,
1198
+ quality,
1199
+ background: type === "image/jpeg" ? settings.background : null
1200
+ }, signal);
1201
+ } catch (cause) {
1202
+ throw cause instanceof CopyFailure ? cause : copyFailure("blob-generation-failed", `Encoding ${type} failed.`, cause);
1203
+ }
1204
+ if (blob.type !== type) {
1205
+ if (requested !== "auto") throw copyFailure("unsupported-format", `This browser can't encode ${type}.`);
1206
+ throw new SearchSignal("unavailable");
1207
+ }
1208
+ smallest = Math.min(smallest, blob.size);
1209
+ return blob;
1210
+ };
1211
+ const done = async (blob, type, scale, quality) => {
1212
+ const written = parse(new Bytes(new Uint8Array(await blob.arrayBuffer()))).info;
1213
+ const name = renamed(settings.source, type);
1214
+ return {
1215
+ file: typeof File === "function" && name !== void 0 ? new File([blob], name, {
1216
+ type,
1217
+ lastModified: settings.source.lastModified ?? Date.now()
1218
+ }) : blob,
1219
+ type,
1220
+ width: Math.max(1, Math.round(image.width * scale)),
1221
+ height: Math.max(1, Math.round(image.height * scale)),
1222
+ size: blob.size,
1223
+ reencoded: true,
1224
+ resized: scale < 1,
1225
+ quality,
1226
+ removed: METADATA_KINDS.filter((kind) => info.metadata.includes(kind) && !written.metadata.includes(kind)),
1227
+ original: settings.original
1228
+ };
1229
+ };
1230
+ /** Shrinks the scale by what the bytes say, between 50 % and 90 % per step. */
1231
+ const shrink = (scale, size) => scale * Math.max(.5, Math.min(.9, Math.sqrt(maxBytes / size) * .95));
1232
+ /** One output type: the best fit, or `null` when it can't fit. */
1233
+ const search = async (type) => {
1234
+ let scale = settings.fit;
1235
+ if (LOSSLESS.has(type)) {
1236
+ for (let attempt = 0; attempt < (requested === "auto" ? 1 : 8); attempt += 1) {
1237
+ const blob = await encode(type, scale, settings.quality);
1238
+ if (blob.size <= maxBytes) return done(blob, type, scale, null);
1239
+ scale = shrink(scale, blob.size);
1240
+ }
1241
+ return null;
1242
+ }
1243
+ for (let attempt = 0; attempt < 8; attempt += 1) {
1244
+ const top = await encode(type, scale, settings.quality);
1245
+ if (top.size <= maxBytes) return done(top, type, scale, settings.quality);
1246
+ let low = settings.minQuality;
1247
+ let high = settings.quality;
1248
+ const floor = await encode(type, scale, low);
1249
+ if (floor.size > maxBytes) {
1250
+ scale = shrink(scale, floor.size);
1251
+ continue;
1252
+ }
1253
+ let best = {
1254
+ blob: floor,
1255
+ quality: low
1256
+ };
1257
+ for (let step = 0; step < 4 && high - low > .02 && encodes < MAX_ENCODES; step += 1) {
1258
+ const middle = Math.round((low + high) / 2 * 100) / 100;
1259
+ const blob = await encode(type, scale, middle);
1260
+ if (blob.size <= maxBytes) {
1261
+ best = {
1262
+ blob,
1263
+ quality: middle
1264
+ };
1265
+ low = middle;
1266
+ } else high = middle;
1267
+ }
1268
+ return done(best.blob, type, scale, best.quality);
1269
+ }
1270
+ return null;
1271
+ };
1272
+ for (const type of candidates(requested, info)) try {
1273
+ const result = await search(type);
1274
+ if (result !== null) return result;
1275
+ } catch (signalled) {
1276
+ if (!(signalled instanceof SearchSignal)) throw signalled;
1277
+ if (signalled.reason === "exhausted") break;
1278
+ }
1279
+ throw copyFailure("too-large", smallest === Infinity ? "No output format could be encoded here." : `Could not get the image under maxBytes (${String(maxBytes)}); the smallest result was ${String(smallest)} bytes.`);
1280
+ }
1281
+ //#endregion
1282
+ export { DEFAULT_IMAGE_MAX_INPUT_BYTES, DEFAULT_IMAGE_MAX_INPUT_PIXELS, DEFAULT_IMAGE_MAX_PIXELS, DEFAULT_IMAGE_MIN_QUALITY, DEFAULT_IMAGE_QUALITY, DEFAULT_IMAGE_TIMEOUT_MS, METADATA_KINDS, getDefaultImageEnvironment, prepareImage, readImageInfo, stripMetadata };
1283
+
1284
+ //# sourceMappingURL=image.js.map