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