Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2
3import {
4 compressImageForStash,
5 compressImageToByteLimit,
6 createComposerImageThumbnail,
7 inheritComposerImageThumbnail,
8 MAX_COMPRESSIBLE_SOURCE_BYTES,
9 MAX_STASH_IMAGE_DATA_URL_CHARS,
10 prepareImageForAttachment,
11 readComposerImageThumbnail,
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 const canvasSizes: Array<{ width: number; height: number }> = [];
100 vi.stubGlobal(
101 "createImageBitmap",
102 vi.fn(async () => ({ width: 4000, height: 3000, close })),
103 );
104 vi.stubGlobal(
105 "OffscreenCanvas",
106 class {
107 constructor(
108 public width: number,
109 public height: number,
110 ) {
111 canvasSizes.push({ width, height });
112 }
113 getContext() {
114 return {
115 fillStyle: "",
116 fillRect,
117 drawImage: vi.fn(),
118 };
119 }
120 async convertToBlob({ type, quality }: { type: string; quality: number }) {
121 const resolvedType = type === "image/webp" && !supportsWebp ? "image/png" : type;
122 return new Blob([new Uint8Array(sizeForQuality(quality))], { type: resolvedType });
123 }
124 },
125 );
126 if (options?.htmlCanvas) {
127 const Canvas = globalThis.OffscreenCanvas;
128 class HtmlCanvas extends Canvas {
129 toBlob(callback: BlobCallback, type: string, quality: number) {
130 void this.convertToBlob({ type, quality }).then(callback);
131 }
132 }
133 vi.stubGlobal("OffscreenCanvas", undefined);
134 vi.stubGlobal("HTMLCanvasElement", HtmlCanvas);
135 vi.stubGlobal("document", { createElement: () => new HtmlCanvas(0, 0) });
136 }
137 return { close, fillRect, canvasSizes };
138}
139
140afterEach(() => {
141 mocks.heicTo.mockReset();
142 vi.unstubAllGlobals();
143 globalThis.createImageBitmap = originalCreateImageBitmap;
144 globalThis.OffscreenCanvas = originalOffscreenCanvas;
145});
146
147describe("compressImageForStash", () => {
148 it("keeps the exact data URL budget boundary and original bytes", async () => {
149 const original = makeFile(3);
150 const dataUrl = "data:image/png;base64,BwcH";
151
152 const result = await compressImageForStash(original, dataUrl.length);
153
154 expect(result.ok && result.image.dataUrl).toBe(dataUrl);
155 expect(result.ok && result.image.recompressed).toBe(false);
156 expect(await compressImageForStash(original, dataUrl.length - 1)).toEqual({
157 ok: false,
158 reason: "too-large",
159 });
160 });
161
162 it("compresses an oversized source before reading it as a data URL", async () => {
163 stubCanvasPipeline(() => 120_000);
164 const original = makeFile(4_000_000);
165 const read = vi.spyOn(original, "arrayBuffer").mockRejectedValue(new Error("unneeded read"));
166
167 const result = await compressImageForStash(original);
168
169 expect(result.ok && result.image.recompressed).toBe(true);
170 expect(read).not.toHaveBeenCalled();
171 });
172
173 it("encodes on the main thread when the image worker fails during the canvas snapshot", async () => {
174 stubCanvasPipeline(() => 120_000);
175 const workers: EventTarget[] = [];
176 const postMessage = vi.fn();
177 vi.stubGlobal(
178 "Worker",
179 class extends EventTarget {
180 postMessage = postMessage;
181 terminate() {}
182 constructor() {
183 super();
184 workers.push(this);
185 }
186 },
187 );
188 vi.mocked(createImageBitmap).mockImplementation(async (source) => {
189 if (source instanceof OffscreenCanvas) workers[0]?.dispatchEvent(new Event("error"));
190 return { width: 4000, height: 3000, close() {} } as ImageBitmap;
191 });
192
193 const result = await compressImageForStash(makeFile(4_000_000));
194
195 expect(result.ok && result.image.mimeType).toBe("image/webp");
196 expect(workers).toHaveLength(1);
197 expect(postMessage).not.toHaveBeenCalled();
198 });
199
200 it("re-encodes an oversized image to WebP within the budget", async () => {
201 const { close, fillRect } = stubCanvasPipeline(() => 120_000);
202
203 const result = await compressImageForStash(makeFile(4_000_000));
204
205 expect(result.ok).toBe(true);
206 expect(result.ok && result.image.recompressed).toBe(true);
207 expect(result.ok && result.image.mimeType).toBe("image/webp");
208 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
209 expect(result.ok && result.image.sizeBytes).toBeLessThan(4_000_000);
210 expect(fillRect).not.toHaveBeenCalled();
211 expect(close).toHaveBeenCalled();
212 });
213
214 it("falls back to JPEG with a white matte when WebP encoding is unavailable", async () => {
215 const { fillRect } = stubCanvasPipeline(() => 120_000, { supportsWebp: false });
216
217 const result = await compressImageForStash(makeFile(4_000_000));
218
219 expect(result.ok && result.image.recompressed).toBe(true);
220 expect(result.ok && result.image.mimeType).toBe("image/jpeg");
221 expect(fillRect).toHaveBeenCalled();
222 });
223
224 it("steps quality down until the encoded image fits", async () => {
225 const { close } = stubCanvasPipeline((quality) => (quality <= 0.68 ? 400_000 : 3_000_000));
226
227 const result = await compressImageForStash(makeFile(9_000_000));
228
229 expect(result.ok && result.image.recompressed).toBe(true);
230 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
231 expect(close).toHaveBeenCalled();
232 });
233
234 it("reports too-large when even the smallest encoding overflows the budget", async () => {
235 const { close } = stubCanvasPipeline(() => 8_000_000);
236
237 const result = await compressImageForStash(makeFile(9_000_000));
238
239 expect(result).toEqual({ ok: false, reason: "too-large" });
240 expect(close).toHaveBeenCalled();
241 });
242
243 it("reports unreadable when the image fails to decode", async () => {
244 vi.stubGlobal(
245 "createImageBitmap",
246 vi.fn(async () => {
247 throw new Error("corrupt image");
248 }),
249 );
250 vi.stubGlobal(
251 "OffscreenCanvas",
252 class {
253 getContext() {
254 return null;
255 }
256 },
257 );
258
259 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
260 ok: false,
261 reason: "unreadable",
262 });
263 });
264
265 it("compressImageToByteLimit refuses sources above the decode-safety ceiling", async () => {
266 const bitmapSpy = vi.fn();
267 vi.stubGlobal("createImageBitmap", bitmapSpy);
268
269 const result = await compressImageToByteLimit(
270 makeFile(MAX_COMPRESSIBLE_SOURCE_BYTES + 1),
271 10 * 1024 * 1024,
272 );
273
274 expect(result).toEqual({ ok: false, reason: "too-large" });
275 expect(bitmapSpy).not.toHaveBeenCalled();
276 });
277});
278
279describe("composer image thumbnails", () => {
280 it("gives the compressed file its source's thumbnail without decoding it again", async () => {
281 stubCanvasPipeline(() => 3);
282 const source = makeFile(3);
283 const compressed = makeFile(2, "image/webp");
284 // Compression can finish before the placeholder's thumbnail does.
285 const pendingThumbnail = createComposerImageThumbnail(source);
286
287 await inheritComposerImageThumbnail(source, compressed);
288
289 const sourceThumbnail = await pendingThumbnail;
290 expect(sourceThumbnail).toMatch(/^data:image\/png;base64,/);
291 expect(readComposerImageThumbnail(compressed)).toBe(sourceThumbnail);
292 expect(await createComposerImageThumbnail(compressed)).toBe(sourceThumbnail);
293 expect(createImageBitmap).toHaveBeenCalledTimes(1);
294 });
295});
296
297describe("HEIC attachment preparation", () => {
298 it("shares the native decode and shows its thumbnail before JPEG encoding finishes", async () => {
299 const { close } = stubCanvasPipeline(() => 3);
300 let finishEncoding!: (blob: Blob) => void;
301 const jpeg = new Promise<Blob>((resolve) => {
302 finishEncoding = resolve;
303 });
304 const Canvas = globalThis.OffscreenCanvas;
305 vi.stubGlobal(
306 "OffscreenCanvas",
307 class extends Canvas {
308 override convertToBlob(options?: ImageEncodeOptions) {
309 return options?.type === "image/jpeg" ? jpeg : super.convertToBlob(options);
310 }
311 },
312 );
313 const original = makeHeicFile();
314 const preparation = prepareImageForAttachment(original, 1024);
315 const queued = prepareImageForAttachment(makeHeicFile({ name: "next.heic" }), 1024);
316 const results = Promise.all([preparation, queued]);
317 try {
318 const thumbnail = await createComposerImageThumbnail(original);
319 expect(thumbnail).toMatch(/^data:image\/png;base64,/);
320 expect(mocks.heicTo).not.toHaveBeenCalled();
321 expect(createImageBitmap).toHaveBeenCalledTimes(1);
322 expect(close).not.toHaveBeenCalled();
323 } finally {
324 finishEncoding(new Blob([new Uint8Array(4)], { type: "image/jpeg" }));
325 await results;
326 }
327 const [result, next] = await results;
328 expect(result.ok && result.file.type).toBe("image/jpeg");
329 expect(result.ok && result.file.size).toBe(4);
330 expect(next.ok).toBe(true);
331 expect(close).toHaveBeenCalledTimes(2);
332 });
333
334 it("converts a HEIC photo with a missing MIME type into a named JPEG", async () => {
335 const original = makeHeicFile({
336 name: "IMG_1234.HEIC",
337 type: "",
338 lastModified: 123,
339 });
340 const { close } = stubCanvasPipeline(() => 4);
341 vi.mocked(createImageBitmap).mockRejectedValue(new Error("HEIC is not supported natively"));
342 mocks.heicTo.mockResolvedValueOnce({ width: 4000, height: 3000, close });
343
344 const result = await prepareImageForAttachment(original, 1024);
345
346 expect(mocks.heicTo).toHaveBeenCalledWith({
347 blob: original,
348 type: "bitmap",
349 });
350 expect(result.ok && result.file.name).toBe("IMG_1234.jpg");
351 expect(result.ok && result.file.type).toBe("image/jpeg");
352 expect(result.ok && result.file.size).toBe(4);
353 expect(result.ok && result.file.lastModified).toBe(123);
354 expect(result.ok && result.recompressed).toBe(true);
355 });
356
357 it("resizes decoded HEIC pixels before encoding the JPEG", async () => {
358 const original = makeHeicFile({
359 name: "large.heic",
360 type: "image/heic",
361 });
362 const { close, canvasSizes } = stubCanvasPipeline(() => 200_000);
363 vi.mocked(createImageBitmap).mockRejectedValue(new Error("HEIC is not supported natively"));
364 mocks.heicTo.mockResolvedValueOnce({ width: 4000, height: 3000, close });
365
366 const result = await prepareImageForAttachment(original, 1_000_000);
367
368 expect(result.ok && result.file.name).toBe("large.jpg");
369 expect(result.ok && result.file.type).toBe("image/jpeg");
370 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
371 expect(close).toHaveBeenCalledTimes(1);
372 expect(createImageBitmap).toHaveBeenCalledTimes(1);
373 expect(canvasSizes).toEqual([
374 { width: 2000, height: 1500 },
375 { width: 256, height: 256 },
376 ]);
377 });
378
379 it("rejects oversized HEIC dimensions before loading the decoder", async () => {
380 const original = makeHeicFile({ width: 16_000, height: 4001 });
381
382 expect(await prepareImageForAttachment(original, 1024)).toEqual({
383 ok: false,
384 reason: "too-large",
385 });
386 expect(mocks.heicTo).not.toHaveBeenCalled();
387 });
388
389 it("rejects unsafe HEIC sources before loading the decoder", async () => {
390 const original = new File(["photo"], "large.heic", { type: "image/heic" });
391 Object.defineProperty(original, "size", { value: MAX_COMPRESSIBLE_SOURCE_BYTES + 1 });
392
393 expect(await prepareImageForAttachment(original, 1024)).toEqual({
394 ok: false,
395 reason: "too-large",
396 });
397 expect(mocks.heicTo).not.toHaveBeenCalled();
398 });
399});
400
401describe("attachment max edge", () => {
402 const u32 = (n: number) => [(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff];
403 const u16 = (n: number) => [(n >>> 8) & 0xff, n & 0xff];
404 const pngHeader = (width: number, height: number) => [
405 0x89,
406 0x50,
407 0x4e,
408 0x47,
409 0x0d,
410 0x0a,
411 0x1a,
412 0x0a,
413 ...u32(13),
414 0x49,
415 0x48,
416 0x44,
417 0x52,
418 ...u32(width),
419 ...u32(height),
420 8,
421 6,
422 0,
423 0,
424 0,
425 ];
426 const jpegHeader = (width: number, height: number) => [
427 0xff,
428 0xd8,
429 0xff,
430 0xc0,
431 ...u16(17),
432 8,
433 ...u16(height),
434 ...u16(width),
435 ];
436 const image = (header: number[], name: string, type: string) =>
437 new File([new Uint8Array([...header, ...new Uint8Array(2048).fill(7)])], name, { type });
438
439 function stubDecoder(bitmapSize: { width: number; height: number }) {
440 const decode = vi.fn(async () => ({ ...bitmapSize, close: vi.fn() }));
441 const canvases: Array<{ width: number; height: number }> = [];
442 const encodes: Array<{ type: string; quality: number }> = [];
443 const fillRect = vi.fn();
444 vi.stubGlobal("createImageBitmap", decode);
445 vi.stubGlobal(
446 "OffscreenCanvas",
447 class {
448 constructor(width: number, height: number) {
449 canvases.push({ width, height });
450 }
451 getContext() {
452 return { fillRect, drawImage: vi.fn() };
453 }
454 async convertToBlob(options: { type: string; quality: number }) {
455 encodes.push(options);
456 return new Blob([new Uint8Array(500_000)], { type: options.type });
457 }
458 },
459 );
460 return { decode, canvases, encodes, fillRect };
461 }
462
463 it("scales a large PNG screenshot under the byte cap to 2000px and keeps it a PNG", async () => {
464 const { decode, canvases, encodes, fillRect } = stubDecoder({ width: 3024, height: 1964 });
465 const original = image(pngHeader(3024, 1964), "shot.png", "image/png");
466
467 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
468
469 expect(decode).toHaveBeenCalledExactlyOnceWith(original, { imageOrientation: "from-image" });
470 expect(canvases).toEqual([{ width: 2000, height: 1299 }]);
471 expect(encodes.map(({ type }) => type)).toEqual(["image/png"]);
472 expect(fillRect).not.toHaveBeenCalled();
473 expect(result.ok && result.recompressed).toBe(true);
474 expect(result.ok && result.imageSize).toEqual({ width: 2000, height: 1299 });
475 expect(result.ok && result.file.name).toBe("shot.png");
476 expect(result.ok && result.file.type).toBe("image/png");
477 });
478
479 it("scales a rotated JPEG by its displayed size and keeps it a JPEG", async () => {
480 const { canvases, encodes } = stubDecoder({ width: 3024, height: 4032 });
481 const original = image(jpegHeader(4032, 3024), "photo.jpg", "image/jpeg");
482
483 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
484
485 expect(canvases).toEqual([{ width: 1500, height: 2000 }]);
486 expect(encodes).toEqual([{ type: "image/jpeg", quality: 0.92 }]);
487 expect(result.ok && result.file.type).toBe("image/jpeg");
488 expect(result.ok && result.imageSize).toEqual({ width: 1500, height: 2000 });
489 });
490
491 it.each([
492 { label: "a 2000px PNG", header: pngHeader(2000, 1200), type: "image/png" },
493 {
494 label: "a 3000px GIF",
495 header: [0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0xb8, 0x0b, 0x10, 0x04],
496 type: "image/gif",
497 },
498 ])("passes $label through without decoding it", async ({ header, type }) => {
499 const { decode } = stubDecoder({ width: 3000, height: 1040 });
500 const original = image(header, "image", type);
501
502 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
503
504 expect(result.ok && result.file).toBe(original);
505 expect(result.ok && result.recompressed).toBe(false);
506 expect(decode).not.toHaveBeenCalled();
507 });
508});
509
510describe("snapshot coordinates after compression", () => {
511 const source: SnapShotSource = {
512 kind: "snap-shot",
513 capturedAt: "2026-09-01T00:00:00.000Z",
514 appName: "Editor",
515 windowTitle: "main.ts",
516 accessibility: {
517 format: "element-tree",
518 coordinateSpace: "captured-image",
519 imageSize: { width: 2560, height: 1600 },
520 truncated: false,
521 root: {
522 role: "window",
523 bounds: { x: 0, y: 0, width: 2560, height: 1600 },
524 children: [
525 {
526 role: "button",
527 name: "Save",
528 bounds: { x: 2400, y: 1400, width: 100, height: 100 },
529 children: [],
530 },
531 { role: "static_text", name: "Untitled", bounds: null, children: [] },
532 ],
533 },
534 },
535 };
536
537 it.each(["stash", "delivery"])(
538 "rescales the source and restores it with the compressed %s image",
539 async (path) => {
540 stubCanvasPipeline(() => 100);
541 vi.stubGlobal(
542 "createImageBitmap",
543 vi.fn(async () => ({ width: 2560, height: 1600, close: vi.fn() })),
544 );
545 const original = makeFile(2000);
546 const compressed =
547 path === "stash"
548 ? await compressImageForStash(original, 1000)
549 : await compressImageToByteLimit(original, 1000);
550 expect(compressed.ok).toBe(true);
551 if (!compressed.ok) throw new Error("Compression failed");
552 const image =
553 "image" in compressed
554 ? compressed.image
555 : {
556 ...compressed,
557 mimeType: compressed.file.type,
558 sizeBytes: compressed.file.size,
559 dataUrl: `data:${compressed.file.type};base64,${Buffer.from(await compressed.file.arrayBuffer()).toString("base64")}`,
560 };
561 expect(image.imageSize).toEqual({ width: 2000, height: 1250 });
562 const resized = resizeSnapShotSource(source, image.imageSize);
563 const [restored] = hydrateImagesFromPersisted([
564 {
565 id: "capture",
566 name: "window.webp",
567 mimeType: image.mimeType,
568 sizeBytes: image.sizeBytes,
569 dataUrl: image.dataUrl,
570 source: resized,
571 },
572 ]);
573 expect(restored?.source?.accessibility).toMatchObject({
574 imageSize: { width: 2000, height: 1250 },
575 root: {
576 bounds: { x: 0, y: 0, width: 2000, height: 1250 },
577 children: [{ bounds: { x: 1875, y: 1094, width: 78, height: 78 } }, { bounds: null }],
578 },
579 });
580 expect(source.accessibility).toMatchObject({ imageSize: { width: 2560, height: 1600 } });
581 },
582 );
583});