Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2
3import {
4 createComposerImageThumbnail,
5 compressImageForStash,
6 compressImageToByteLimit,
7 dataUrlToFile,
8 isHeicImageFile,
9 MAX_COMPRESSIBLE_SOURCE_BYTES,
10 MAX_STASH_IMAGE_DATA_URL_CHARS,
11 prepareImageForAttachment,
12} from "./imageCompression";
13
14import type { SnapShotSource } from "@t3tools/contracts";
15import { hydrateImagesFromPersisted } from "../composerDraftStore";
16import { resizeSnapShotSource } from "./snapShotSource";
17
18const mocks = vi.hoisted(() => ({
19 heicTo: vi.fn(),
20}));
21
22vi.mock("heic-to/csp", () => ({
23 heicTo: mocks.heicTo,
24}));
25
26const originalCreateImageBitmap = globalThis.createImageBitmap;
27const originalOffscreenCanvas = globalThis.OffscreenCanvas;
28
29beforeEach(() => {
30 vi.stubGlobal(
31 "FileReader",
32 class extends EventTarget {
33 result: string | null = null;
34 error: unknown = null;
35 async readAsDataURL(blob: Blob) {
36 try {
37 const bytes = await blob.arrayBuffer();
38 this.result = `data:${blob.type || "application/octet-stream"};base64,${Buffer.from(bytes).toString("base64")}`;
39 this.dispatchEvent(new Event("load"));
40 } catch (error) {
41 this.error = error;
42 this.dispatchEvent(new Event("error"));
43 }
44 }
45 },
46 );
47});
48
49function makeFile(sizeBytes: number, type = "image/png"): File {
50 return new File([new Uint8Array(sizeBytes).fill(7)], "shot.png", { type });
51}
52
53function makeHeicFile(options?: {
54 name?: string;
55 type?: string;
56 width?: number;
57 height?: number;
58 lastModified?: number;
59}): File {
60 const encoder = new TextEncoder();
61 const makeBox = (name: string, ...contents: Uint8Array[]) => {
62 const bytes = new Uint8Array(8 + contents.reduce((size, content) => size + content.length, 0));
63 new DataView(bytes.buffer).setUint32(0, bytes.length);
64 bytes.set(encoder.encode(name), 4);
65 let offset = 8;
66 for (const content of contents) {
67 bytes.set(content, offset);
68 offset += content.length;
69 }
70 return bytes;
71 };
72
73 const dimensions = new Uint8Array(12);
74 const view = new DataView(dimensions.buffer);
75 view.setUint32(4, options?.width ?? 4000);
76 view.setUint32(8, options?.height ?? 3000);
77 const properties = makeBox("iprp", makeBox("ipco", makeBox("ispe", dimensions)));
78
79 return new File(
80 [
81 makeBox("ftyp", encoder.encode("heic"), new Uint8Array(4)),
82 makeBox("meta", new Uint8Array(4), properties),
83 ],
84 options?.name ?? "photo.heic",
85 {
86 type: options?.type ?? "image/heic",
87 ...(options?.lastModified !== undefined ? { lastModified: options.lastModified } : {}),
88 },
89 );
90}
91
92function stubCanvasPipeline(
93 sizeForQuality: (quality: number) => number,
94 options?: { supportsWebp?: boolean; htmlCanvas?: boolean },
95) {
96 const supportsWebp = options?.supportsWebp ?? true;
97 const close = vi.fn();
98 const fillRect = vi.fn();
99 vi.stubGlobal(
100 "createImageBitmap",
101 vi.fn(async () => ({ width: 4000, height: 3000, close })),
102 );
103 vi.stubGlobal(
104 "OffscreenCanvas",
105 class {
106 constructor(
107 public width: number,
108 public height: number,
109 ) {}
110 getContext() {
111 return {
112 fillStyle: "",
113 fillRect,
114 drawImage: vi.fn(),
115 };
116 }
117 async convertToBlob({ type, quality }: { type: string; quality: number }) {
118 const resolvedType = type === "image/webp" && !supportsWebp ? "image/png" : type;
119 return new Blob([new Uint8Array(sizeForQuality(quality))], { type: resolvedType });
120 }
121 },
122 );
123 if (options?.htmlCanvas) {
124 const Canvas = globalThis.OffscreenCanvas;
125 class HtmlCanvas extends Canvas {
126 toBlob(callback: BlobCallback, type: string, quality: number) {
127 void this.convertToBlob({ type, quality }).then(callback);
128 }
129 }
130 vi.stubGlobal("OffscreenCanvas", undefined);
131 vi.stubGlobal("HTMLCanvasElement", HtmlCanvas);
132 vi.stubGlobal("document", { createElement: () => new HtmlCanvas(0, 0) });
133 }
134 return { close, fillRect };
135}
136
137afterEach(() => {
138 mocks.heicTo.mockReset();
139 vi.unstubAllGlobals();
140 globalThis.createImageBitmap = originalCreateImageBitmap;
141 globalThis.OffscreenCanvas = originalOffscreenCanvas;
142});
143
144describe("composer image thumbnails", () => {
145 it("decodes a tall original once and caches a bounded center crop", async () => {
146 const close = vi.fn();
147 const bitmap = { width: 2304, height: 32766, close };
148 const decode = vi.fn(async () => bitmap);
149 const drawImage = vi.fn();
150 const dimensions: number[][] = [];
151 vi.stubGlobal("createImageBitmap", decode);
152 vi.stubGlobal(
153 "OffscreenCanvas",
154 class {
155 constructor(width: number, height: number) {
156 dimensions.push([width, height]);
157 }
158 getContext() {
159 return { drawImage };
160 }
161 async convertToBlob() {
162 return new Blob(["thumbnail"], { type: "image/png" });
163 }
164 },
165 );
166 const original = new File(["original bytes"], "tall.png", { type: "image/png" });
167 const [first, second] = await Promise.all([
168 createComposerImageThumbnail(original),
169 createComposerImageThumbnail(original),
170 ]);
171 expect(first).toBe("data:image/png;base64,dGh1bWJuYWls");
172 expect(second).toBe(first);
173 expect(await createComposerImageThumbnail(original)).toBe(first);
174 expect(decode).toHaveBeenCalledExactlyOnceWith(original);
175 expect(dimensions).toEqual([[256, 256]]);
176 expect(drawImage).toHaveBeenCalledWith(bitmap, 0, 15231, 2304, 2304, 0, 0, 256, 256);
177 expect(close).toHaveBeenCalledOnce();
178 expect(await original.text()).toBe("original bytes");
179 });
180
181 it("releases the decoded image when thumbnail encoding fails", async () => {
182 const close = vi.fn();
183 vi.stubGlobal(
184 "createImageBitmap",
185 vi.fn(async () => ({ width: 500, height: 500, close })),
186 );
187 vi.stubGlobal(
188 "OffscreenCanvas",
189 class {
190 getContext() {
191 return { drawImage: vi.fn() };
192 }
193 async convertToBlob() {
194 throw new Error("encoder unavailable");
195 }
196 },
197 );
198 expect(await createComposerImageThumbnail(makeFile(5))).toBeNull();
199 expect(close).toHaveBeenCalledOnce();
200 });
201});
202
203describe("dataUrlToFile", () => {
204 it("decodes a captured image without a fetch request", async () => {
205 const file = dataUrlToFile("data:image/png;base64,AAEC/w==", "window.png", "image/png");
206
207 expect(file.name).toBe("window.png");
208 expect(file.type).toBe("image/png");
209 expect([...new Uint8Array(await file.arrayBuffer())]).toEqual([0, 1, 2, 255]);
210 });
211});
212
213describe("compressImageForStash", () => {
214 it.each([true, false])(
215 "encodes with HTML canvas when WebP support is %s",
216 async (supportsWebp) => {
217 const { close } = stubCanvasPipeline(() => 120_000, { htmlCanvas: true, supportsWebp });
218
219 const result = await compressImageToByteLimit(makeFile(2_000_000), 1_000_000);
220
221 expect(result.ok && result.file.type).toBe(supportsWebp ? "image/webp" : "image/jpeg");
222 expect(result.ok && result.file.size).toBe(120_000);
223 expect(close).toHaveBeenCalledOnce();
224 },
225 );
226
227 it("keeps the exact data URL budget boundary and original bytes", async () => {
228 const original = makeFile(3);
229 const dataUrl = "data:image/png;base64,BwcH";
230
231 const result = await compressImageForStash(original, dataUrl.length);
232
233 expect(result.ok && result.image.dataUrl).toBe(dataUrl);
234 expect(result.ok && result.image.recompressed).toBe(false);
235 expect(await compressImageForStash(original, dataUrl.length - 1)).toEqual({
236 ok: false,
237 reason: "too-large",
238 });
239 });
240
241 it("reports unreadable if reading a small image fails", async () => {
242 const original = makeFile(3);
243 vi.spyOn(original, "arrayBuffer").mockRejectedValue(new Error("read failed"));
244
245 expect(await compressImageForStash(original)).toEqual({ ok: false, reason: "unreadable" });
246 });
247
248 it("compresses an oversized source before reading it as a data URL", async () => {
249 stubCanvasPipeline(() => 120_000);
250 const original = makeFile(4_000_000);
251 const read = vi.spyOn(original, "arrayBuffer").mockRejectedValue(new Error("unneeded read"));
252
253 const result = await compressImageForStash(original);
254
255 expect(result.ok && result.image.recompressed).toBe(true);
256 expect(read).not.toHaveBeenCalled();
257 });
258
259 it("stores a small image verbatim without re-encoding", async () => {
260 const bitmapSpy = vi.fn();
261 vi.stubGlobal("createImageBitmap", bitmapSpy);
262
263 const result = await compressImageForStash(makeFile(1024));
264
265 expect(result.ok).toBe(true);
266 expect(result.ok && result.image.recompressed).toBe(false);
267 expect(result.ok && result.image.mimeType).toBe("image/png");
268 expect(result.ok && result.image.dataUrl.startsWith("data:image/png")).toBe(true);
269 expect(bitmapSpy).not.toHaveBeenCalled();
270 });
271
272 it("re-encodes an oversized image to WebP within the budget", async () => {
273 const { close, fillRect } = stubCanvasPipeline(() => 120_000);
274
275 const result = await compressImageForStash(makeFile(4_000_000));
276
277 expect(result.ok).toBe(true);
278 expect(result.ok && result.image.recompressed).toBe(true);
279 expect(result.ok && result.image.mimeType).toBe("image/webp");
280 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
281 expect(result.ok && result.image.sizeBytes).toBeLessThan(4_000_000);
282 expect(fillRect).not.toHaveBeenCalled();
283 expect(close).toHaveBeenCalled();
284 });
285
286 it("falls back to JPEG with a white matte when WebP encoding is unavailable", async () => {
287 const { fillRect } = stubCanvasPipeline(() => 120_000, { supportsWebp: false });
288
289 const result = await compressImageForStash(makeFile(4_000_000));
290
291 expect(result.ok && result.image.recompressed).toBe(true);
292 expect(result.ok && result.image.mimeType).toBe("image/jpeg");
293 expect(fillRect).toHaveBeenCalled();
294 });
295
296 it("steps quality down until the encoded image fits", async () => {
297 const { close } = stubCanvasPipeline((quality) => (quality <= 0.68 ? 400_000 : 3_000_000));
298
299 const result = await compressImageForStash(makeFile(9_000_000));
300
301 expect(result.ok && result.image.recompressed).toBe(true);
302 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
303 expect(close).toHaveBeenCalled();
304 });
305
306 it("reports too-large when even the smallest encoding overflows the budget", async () => {
307 const { close } = stubCanvasPipeline(() => 8_000_000);
308
309 const result = await compressImageForStash(makeFile(9_000_000));
310
311 expect(result).toEqual({ ok: false, reason: "too-large" });
312 expect(close).toHaveBeenCalled();
313 });
314
315 it("reports too-large for an oversized image when the browser cannot re-encode", async () => {
316 vi.stubGlobal("createImageBitmap", undefined);
317 vi.stubGlobal("OffscreenCanvas", undefined);
318
319 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
320 ok: false,
321 reason: "too-large",
322 });
323 });
324
325 it("reports unreadable when the image fails to decode", async () => {
326 vi.stubGlobal(
327 "createImageBitmap",
328 vi.fn(async () => {
329 throw new Error("corrupt image");
330 }),
331 );
332 vi.stubGlobal(
333 "OffscreenCanvas",
334 class {
335 getContext() {
336 return null;
337 }
338 },
339 );
340
341 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
342 ok: false,
343 reason: "unreadable",
344 });
345 });
346
347 it("compressImageToByteLimit passes small files through byte-for-byte", async () => {
348 const bitmapSpy = vi.fn();
349 vi.stubGlobal("createImageBitmap", bitmapSpy);
350
351 const original = makeFile(1024);
352 const result = await compressImageToByteLimit(original, 10 * 1024 * 1024);
353
354 expect(result.ok).toBe(true);
355 expect(result.ok && result.recompressed).toBe(false);
356 expect(result.ok && result.file).toBe(original);
357 expect(bitmapSpy).not.toHaveBeenCalled();
358 });
359
360 it("compressImageToByteLimit re-encodes an oversized file under the byte cap", async () => {
361 stubCanvasPipeline(() => 200_000);
362
363 const result = await compressImageToByteLimit(makeFile(2_000_000), 1_000_000);
364
365 expect(result.ok).toBe(true);
366 expect(result.ok && result.recompressed).toBe(true);
367 expect(result.ok && result.file.type).toBe("image/webp");
368 expect(result.ok && result.file.name).toBe("shot.webp");
369 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
370 });
371
372 it("compressImageToByteLimit refuses sources above the decode-safety ceiling", async () => {
373 const bitmapSpy = vi.fn();
374 vi.stubGlobal("createImageBitmap", bitmapSpy);
375
376 const result = await compressImageToByteLimit(
377 makeFile(MAX_COMPRESSIBLE_SOURCE_BYTES + 1),
378 10 * 1024 * 1024,
379 );
380
381 expect(result).toEqual({ ok: false, reason: "too-large" });
382 expect(bitmapSpy).not.toHaveBeenCalled();
383 });
384
385 it("compressImageToByteLimit reports too-large when no encoding fits", async () => {
386 const { close } = stubCanvasPipeline(() => 3_000_000);
387
388 const result = await compressImageToByteLimit(makeFile(2_000_000), 1_000_000);
389
390 expect(result).toEqual({ ok: false, reason: "too-large" });
391 expect(close).toHaveBeenCalled();
392 });
393
394 it("shrinks below the source size when the image is already under MAX_DIMENSION", async () => {
395 let smallestRequested = Number.POSITIVE_INFINITY;
396 const close = vi.fn();
397 vi.stubGlobal(
398 "createImageBitmap",
399 vi.fn(async () => ({ width: 800, height: 600, close })),
400 );
401 vi.stubGlobal(
402 "OffscreenCanvas",
403 class {
404 constructor(
405 public width: number,
406 public height: number,
407 ) {
408 smallestRequested = Math.min(smallestRequested, width);
409 }
410 getContext() {
411 return { fillStyle: "", fillRect: vi.fn(), drawImage: vi.fn() };
412 }
413 async convertToBlob({ type }: { type: string; quality: number }) {
414 const size = smallestRequested < 800 ? 100_000 : 5_000_000;
415 return new Blob([new Uint8Array(size)], { type });
416 }
417 },
418 );
419
420 const result = await compressImageForStash(makeFile(4_000_000));
421
422 expect(result.ok).toBe(true);
423 expect(smallestRequested).toBeLessThan(800);
424 });
425});
426
427describe("HEIC attachment preparation", () => {
428 it("recognizes HEIC and HEIF MIME types and case-insensitive file extensions", () => {
429 expect(isHeicImageFile({ name: "photo.bin", type: "image/heic" })).toBe(true);
430 expect(isHeicImageFile({ name: "photo.bin", type: "image/heif" })).toBe(true);
431 expect(isHeicImageFile({ name: "photo.heic", type: "image/heic-sequence" })).toBe(false);
432 expect(isHeicImageFile({ name: "photo.heif", type: "image/heif-sequence" })).toBe(false);
433 expect(isHeicImageFile({ name: "IMG_1234.HEIC", type: "" })).toBe(true);
434 expect(isHeicImageFile({ name: "photo.heif", type: "application/octet-stream" })).toBe(true);
435 expect(isHeicImageFile({ name: "photo.png", type: "image/png" })).toBe(false);
436 expect(isHeicImageFile({ name: "photo.heic", type: "image/png" })).toBe(false);
437 expect(isHeicImageFile({ name: "photo.heif", type: "image/jpeg" })).toBe(false);
438 });
439
440 it("converts a HEIC photo with a missing MIME type into a named JPEG", async () => {
441 const original = makeHeicFile({
442 name: "IMG_1234.HEIC",
443 type: "",
444 lastModified: 123,
445 });
446 mocks.heicTo.mockResolvedValueOnce(
447 new Blob([new Uint8Array([4, 5, 6, 7])], { type: "image/jpeg" }),
448 );
449
450 const result = await prepareImageForAttachment(original, 1024);
451
452 expect(mocks.heicTo).toHaveBeenCalledWith({
453 blob: original,
454 type: "image/jpeg",
455 quality: 0.92,
456 });
457 expect(result.ok && result.file.name).toBe("IMG_1234.jpg");
458 expect(result.ok && result.file.type).toBe("image/jpeg");
459 expect(result.ok && result.file.size).toBe(4);
460 expect(result.ok && result.file.lastModified).toBe(123);
461 expect(result.ok && result.recompressed).toBe(true);
462 });
463
464 it("keeps oversized converted photos in JPEG format while shrinking them", async () => {
465 const original = makeHeicFile({
466 name: "photo.heif",
467 type: "image/heif",
468 });
469 mocks.heicTo.mockResolvedValueOnce(
470 new Blob([new Uint8Array(2_000_000)], { type: "image/jpeg" }),
471 );
472 const { fillRect } = stubCanvasPipeline(() => 200_000);
473
474 const result = await prepareImageForAttachment(original, 1_000_000);
475
476 expect(result.ok && result.file.name).toBe("photo.jpg");
477 expect(result.ok && result.file.type).toBe("image/jpeg");
478 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
479 expect(fillRect).toHaveBeenCalled();
480 });
481
482 it("compresses JPEG intermediates above the source safety ceiling", async () => {
483 const original = makeHeicFile({
484 name: "large.heic",
485 type: "image/heic",
486 });
487 mocks.heicTo.mockResolvedValueOnce(
488 new Blob([new Uint8Array(MAX_COMPRESSIBLE_SOURCE_BYTES + 1)], {
489 type: "image/jpeg",
490 }),
491 );
492 const { close } = stubCanvasPipeline(() => 200_000);
493
494 const result = await prepareImageForAttachment(original, 1_000_000);
495
496 expect(result.ok && result.file.name).toBe("large.jpg");
497 expect(result.ok && result.file.type).toBe("image/jpeg");
498 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
499 expect(close).toHaveBeenCalled();
500 });
501
502 it.each([
503 { label: "24 MP", width: 5712, height: 4284 },
504 { label: "48 MP", width: 8064, height: 6048 },
505 ])("accepts $label HEIC photos", async ({ width, height }) => {
506 const original = makeHeicFile({ width, height });
507 mocks.heicTo.mockResolvedValueOnce(new Blob(["jpeg"], { type: "image/jpeg" }));
508
509 const result = await prepareImageForAttachment(original, 1024);
510
511 expect(result.ok && result.file.type).toBe("image/jpeg");
512 expect(mocks.heicTo).toHaveBeenCalledOnce();
513 });
514
515 it("rejects oversized HEIC dimensions before loading the decoder", async () => {
516 const original = makeHeicFile({ width: 16_000, height: 4001 });
517
518 expect(await prepareImageForAttachment(original, 1024)).toEqual({
519 ok: false,
520 reason: "too-large",
521 });
522 expect(mocks.heicTo).not.toHaveBeenCalled();
523 });
524
525 it("rejects invalid HEIC metadata before loading the decoder", async () => {
526 const original = new File([new Uint8Array([1, 2, 3])], "broken.heic", {
527 type: "image/heic",
528 });
529
530 expect(await prepareImageForAttachment(original, 1024)).toEqual({
531 ok: false,
532 reason: "unreadable",
533 });
534 expect(mocks.heicTo).not.toHaveBeenCalled();
535 });
536
537 it("reports unreadable when HEIC decoding fails", async () => {
538 const original = makeHeicFile({
539 name: "broken.heic",
540 type: "image/heic",
541 });
542 mocks.heicTo.mockRejectedValueOnce(new Error("Invalid HEIC image"));
543
544 expect(await prepareImageForAttachment(original, 1024)).toEqual({
545 ok: false,
546 reason: "unreadable",
547 });
548 });
549
550 it("rejects unsafe HEIC sources before loading the decoder", async () => {
551 const original = new File(["photo"], "large.heic", { type: "image/heic" });
552 Object.defineProperty(original, "size", { value: MAX_COMPRESSIBLE_SOURCE_BYTES + 1 });
553
554 expect(await prepareImageForAttachment(original, 1024)).toEqual({
555 ok: false,
556 reason: "too-large",
557 });
558 expect(mocks.heicTo).not.toHaveBeenCalled();
559 });
560
561 it("leaves supported images untouched without loading the HEIC decoder", async () => {
562 const original = makeFile(1024);
563
564 const result = await prepareImageForAttachment(original, 2048);
565
566 expect(result.ok && result.file).toBe(original);
567 expect(result.ok && result.recompressed).toBe(false);
568 expect(mocks.heicTo).not.toHaveBeenCalled();
569 });
570});
571
572describe("attachment max edge", () => {
573 const u32 = (n: number) => [(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff];
574 const u16 = (n: number) => [(n >>> 8) & 0xff, n & 0xff];
575 const pngHeader = (width: number, height: number) => [
576 0x89,
577 0x50,
578 0x4e,
579 0x47,
580 0x0d,
581 0x0a,
582 0x1a,
583 0x0a,
584 ...u32(13),
585 0x49,
586 0x48,
587 0x44,
588 0x52,
589 ...u32(width),
590 ...u32(height),
591 8,
592 6,
593 0,
594 0,
595 0,
596 ];
597 const jpegHeader = (width: number, height: number) => [
598 0xff,
599 0xd8,
600 0xff,
601 0xc0,
602 ...u16(17),
603 8,
604 ...u16(height),
605 ...u16(width),
606 ];
607 const image = (header: number[], name: string, type: string) =>
608 new File([new Uint8Array([...header, ...new Uint8Array(2048).fill(7)])], name, { type });
609
610 function stubDecoder(bitmapSize: { width: number; height: number }) {
611 const decode = vi.fn(async () => ({ ...bitmapSize, close: vi.fn() }));
612 const canvases: Array<{ width: number; height: number }> = [];
613 const encodes: Array<{ type: string; quality: number }> = [];
614 const fillRect = vi.fn();
615 vi.stubGlobal("createImageBitmap", decode);
616 vi.stubGlobal(
617 "OffscreenCanvas",
618 class {
619 constructor(width: number, height: number) {
620 canvases.push({ width, height });
621 }
622 getContext() {
623 return { fillRect, drawImage: vi.fn() };
624 }
625 async convertToBlob(options: { type: string; quality: number }) {
626 encodes.push(options);
627 return new Blob([new Uint8Array(500_000)], { type: options.type });
628 }
629 },
630 );
631 return { decode, canvases, encodes, fillRect };
632 }
633
634 it("scales a large PNG screenshot under the byte cap to 2000px and keeps it a PNG", async () => {
635 const { decode, canvases, encodes, fillRect } = stubDecoder({ width: 3024, height: 1964 });
636 const original = image(pngHeader(3024, 1964), "shot.png", "image/png");
637
638 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
639
640 expect(decode).toHaveBeenCalledExactlyOnceWith(original, { imageOrientation: "from-image" });
641 expect(canvases).toEqual([{ width: 2000, height: 1299 }]);
642 expect(encodes.map(({ type }) => type)).toEqual(["image/png"]);
643 expect(fillRect).not.toHaveBeenCalled();
644 expect(result.ok && result.recompressed).toBe(true);
645 expect(result.ok && result.imageSize).toEqual({ width: 2000, height: 1299 });
646 expect(result.ok && result.file.name).toBe("shot.png");
647 expect(result.ok && result.file.type).toBe("image/png");
648 });
649
650 it("scales a rotated JPEG by its displayed size and keeps it a JPEG", async () => {
651 const { canvases, encodes } = stubDecoder({ width: 3024, height: 4032 });
652 const original = image(jpegHeader(4032, 3024), "photo.jpg", "image/jpeg");
653
654 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
655
656 expect(canvases).toEqual([{ width: 1500, height: 2000 }]);
657 expect(encodes).toEqual([{ type: "image/jpeg", quality: 0.92 }]);
658 expect(result.ok && result.file.type).toBe("image/jpeg");
659 expect(result.ok && result.imageSize).toEqual({ width: 1500, height: 2000 });
660 });
661
662 it.each([
663 { label: "a 2000px PNG", header: pngHeader(2000, 1200), type: "image/png" },
664 {
665 label: "a 3000px GIF",
666 header: [0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0xb8, 0x0b, 0x10, 0x04],
667 type: "image/gif",
668 },
669 ])("passes $label through without decoding it", async ({ header, type }) => {
670 const { decode } = stubDecoder({ width: 3000, height: 1040 });
671 const original = image(header, "image", type);
672
673 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
674
675 expect(result.ok && result.file).toBe(original);
676 expect(result.ok && result.recompressed).toBe(false);
677 expect(decode).not.toHaveBeenCalled();
678 });
679});
680
681describe("snapshot coordinates after compression", () => {
682 const source: SnapShotSource = {
683 kind: "snap-shot",
684 capturedAt: "2026-09-01T00:00:00.000Z",
685 appName: "Editor",
686 windowTitle: "main.ts",
687 accessibility: {
688 format: "element-tree",
689 coordinateSpace: "captured-image",
690 imageSize: { width: 2560, height: 1600 },
691 truncated: false,
692 root: {
693 role: "window",
694 bounds: { x: 0, y: 0, width: 2560, height: 1600 },
695 children: [
696 {
697 role: "button",
698 name: "Save",
699 bounds: { x: 2400, y: 1400, width: 100, height: 100 },
700 children: [],
701 },
702 { role: "static_text", name: "Untitled", bounds: null, children: [] },
703 ],
704 },
705 },
706 };
707
708 it.each(["stash", "delivery"])(
709 "rescales the source and restores it with the compressed %s image",
710 async (path) => {
711 stubCanvasPipeline(() => 100);
712 vi.stubGlobal(
713 "createImageBitmap",
714 vi.fn(async () => ({ width: 2560, height: 1600, close: vi.fn() })),
715 );
716 const original = makeFile(2000);
717 const compressed =
718 path === "stash"
719 ? await compressImageForStash(original, 1000)
720 : await compressImageToByteLimit(original, 1000);
721 expect(compressed.ok).toBe(true);
722 if (!compressed.ok) throw new Error("Compression failed");
723 const image =
724 "image" in compressed
725 ? compressed.image
726 : {
727 ...compressed,
728 mimeType: compressed.file.type,
729 sizeBytes: compressed.file.size,
730 dataUrl: `data:${compressed.file.type};base64,${Buffer.from(await compressed.file.arrayBuffer()).toString("base64")}`,
731 };
732 expect(image.imageSize).toEqual({ width: 2000, height: 1250 });
733 const resized = resizeSnapShotSource(source, image.imageSize);
734 const [restored] = hydrateImagesFromPersisted([
735 {
736 id: "capture",
737 name: "window.webp",
738 mimeType: image.mimeType,
739 sizeBytes: image.sizeBytes,
740 dataUrl: image.dataUrl,
741 source: resized,
742 },
743 ]);
744 expect(restored?.source?.accessibility).toMatchObject({
745 imageSize: { width: 2000, height: 1250 },
746 root: {
747 bounds: { x: 0, y: 0, width: 2000, height: 1250 },
748 children: [{ bounds: { x: 1875, y: 1094, width: 78, height: 78 } }, { bounds: null }],
749 },
750 });
751 expect(source.accessibility).toMatchObject({ imageSize: { width: 2560, height: 1600 } });
752 },
753 );
754
755 it("keeps uncompressed sources unchanged", () => {
756 expect(resizeSnapShotSource(source)).toBe(source);
757 });
758});