Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
3import {
4 compressImageForStash,
5 compressImageToByteLimit,
6 dataUrlToFile,
7 isHeicImageFile,
8 MAX_COMPRESSIBLE_SOURCE_BYTES,
9 MAX_STASH_IMAGE_DATA_URL_CHARS,
10 prepareImageForAttachment,
11} from "./imageCompression";
12
13import type { SnapShotSource } from "@t3tools/contracts";
14import { hydrateImagesFromPersisted } from "../composerDraftStore";
15import { resizeSnapShotSource } from "./snapShotSource";
16
17const mocks = vi.hoisted(() => ({
18 heicTo: vi.fn(),
19}));
20
21vi.mock("heic-to/csp", () => ({
22 heicTo: mocks.heicTo,
23}));
24
25/**
26 * jsdom has no real canvas/codec, so the re-encode path is exercised with
27 * stubbed `createImageBitmap` + `OffscreenCanvas`. The encoder stub returns a
28 * payload whose size scales with quality, mirroring how a real JPEG encoder
29 * shrinks as quality drops — enough to verify the ladder logic and budget
30 * enforcement without pulling in a native canvas.
31 */
32
33const originalCreateImageBitmap = globalThis.createImageBitmap;
34const originalOffscreenCanvas = globalThis.OffscreenCanvas;
35
36function makeFile(sizeBytes: number, type = "image/png"): File {
37 return new File([new Uint8Array(sizeBytes).fill(7)], "shot.png", { type });
38}
39
40function makeHeicFile(options?: {
41 name?: string;
42 type?: string;
43 width?: number;
44 height?: number;
45 lastModified?: number;
46}): File {
47 const encoder = new TextEncoder();
48 const makeBox = (name: string, ...contents: Uint8Array[]) => {
49 const bytes = new Uint8Array(8 + contents.reduce((size, content) => size + content.length, 0));
50 new DataView(bytes.buffer).setUint32(0, bytes.length);
51 bytes.set(encoder.encode(name), 4);
52 let offset = 8;
53 for (const content of contents) {
54 bytes.set(content, offset);
55 offset += content.length;
56 }
57 return bytes;
58 };
59
60 const dimensions = new Uint8Array(12);
61 const view = new DataView(dimensions.buffer);
62 view.setUint32(4, options?.width ?? 4000);
63 view.setUint32(8, options?.height ?? 3000);
64 const properties = makeBox("iprp", makeBox("ipco", makeBox("ispe", dimensions)));
65
66 return new File(
67 [
68 makeBox("ftyp", encoder.encode("heic"), new Uint8Array(4)),
69 makeBox("meta", new Uint8Array(4), properties),
70 ],
71 options?.name ?? "photo.heic",
72 {
73 type: options?.type ?? "image/heic",
74 ...(options?.lastModified !== undefined ? { lastModified: options.lastModified } : {}),
75 },
76 );
77}
78
79/**
80 * Installs a fake bitmap + canvas whose encoded size follows `sizeForQuality`.
81 * `supportsWebp: false` makes `convertToBlob` hand back a differently-typed
82 * blob for WebP requests, which is how a real browser signals it cannot
83 * encode that format.
84 */
85function stubCanvasPipeline(
86 sizeForQuality: (quality: number) => number,
87 options?: { supportsWebp?: boolean },
88) {
89 const supportsWebp = options?.supportsWebp ?? true;
90 const close = vi.fn();
91 const fillRect = vi.fn();
92 vi.stubGlobal(
93 "createImageBitmap",
94 vi.fn(async () => ({ width: 4000, height: 3000, close })),
95 );
96 vi.stubGlobal(
97 "OffscreenCanvas",
98 class {
99 constructor(
100 public width: number,
101 public height: number,
102 ) {}
103 getContext() {
104 return {
105 fillStyle: "",
106 fillRect,
107 drawImage: vi.fn(),
108 };
109 }
110 async convertToBlob({ type, quality }: { type: string; quality: number }) {
111 const resolvedType = type === "image/webp" && !supportsWebp ? "image/png" : type;
112 return new Blob([new Uint8Array(sizeForQuality(quality))], { type: resolvedType });
113 }
114 },
115 );
116 return { close, fillRect };
117}
118
119afterEach(() => {
120 mocks.heicTo.mockReset();
121 vi.unstubAllGlobals();
122 globalThis.createImageBitmap = originalCreateImageBitmap;
123 globalThis.OffscreenCanvas = originalOffscreenCanvas;
124});
125
126describe("dataUrlToFile", () => {
127 it("decodes a captured image without a fetch request", async () => {
128 const file = dataUrlToFile("data:image/png;base64,AAEC/w==", "window.png", "image/png");
129
130 expect(file.name).toBe("window.png");
131 expect(file.type).toBe("image/png");
132 expect([...new Uint8Array(await file.arrayBuffer())]).toEqual([0, 1, 2, 255]);
133 });
134});
135
136describe("compressImageForStash", () => {
137 it("stores a small image verbatim without re-encoding", async () => {
138 const bitmapSpy = vi.fn();
139 vi.stubGlobal("createImageBitmap", bitmapSpy);
140
141 const result = await compressImageForStash(makeFile(1024));
142
143 expect(result.ok).toBe(true);
144 expect(result.ok && result.image.recompressed).toBe(false);
145 expect(result.ok && result.image.mimeType).toBe("image/png");
146 expect(result.ok && result.image.dataUrl.startsWith("data:image/png")).toBe(true);
147 // Untouched payloads must not pay for a decode.
148 expect(bitmapSpy).not.toHaveBeenCalled();
149 });
150
151 it("re-encodes an oversized image to WebP within the budget", async () => {
152 // Comfortably under budget at the very first quality step.
153 const { close, fillRect } = stubCanvasPipeline(() => 120_000);
154
155 const result = await compressImageForStash(makeFile(4_000_000));
156
157 expect(result.ok).toBe(true);
158 expect(result.ok && result.image.recompressed).toBe(true);
159 expect(result.ok && result.image.mimeType).toBe("image/webp");
160 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
161 // sizeBytes should describe the re-encoded payload, not the 4MB original.
162 expect(result.ok && result.image.sizeBytes).toBeLessThan(4_000_000);
163 // WebP keeps alpha, so no white matte should be painted.
164 expect(fillRect).not.toHaveBeenCalled();
165 expect(close).toHaveBeenCalled();
166 });
167
168 it("falls back to JPEG with a white matte when WebP encoding is unavailable", async () => {
169 const { fillRect } = stubCanvasPipeline(() => 120_000, { supportsWebp: false });
170
171 const result = await compressImageForStash(makeFile(4_000_000));
172
173 expect(result.ok && result.image.recompressed).toBe(true);
174 expect(result.ok && result.image.mimeType).toBe("image/jpeg");
175 // JPEG has no alpha, so transparent regions must be matted white.
176 expect(fillRect).toHaveBeenCalled();
177 });
178
179 it("steps quality down until the encoded image fits", async () => {
180 // Only the lowest quality step (0.68) lands under the budget.
181 const { close } = stubCanvasPipeline((quality) => (quality <= 0.68 ? 400_000 : 3_000_000));
182
183 const result = await compressImageForStash(makeFile(9_000_000));
184
185 expect(result.ok && result.image.recompressed).toBe(true);
186 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
187 expect(close).toHaveBeenCalled();
188 });
189
190 it("reports too-large when even the smallest encoding overflows the budget", async () => {
191 const { close } = stubCanvasPipeline(() => 8_000_000);
192
193 const result = await compressImageForStash(makeFile(9_000_000));
194
195 expect(result).toEqual({ ok: false, reason: "too-large" });
196 // The bitmap must still be released on the give-up path.
197 expect(close).toHaveBeenCalled();
198 });
199
200 it("reports too-large for an oversized image when the browser cannot re-encode", async () => {
201 vi.stubGlobal("createImageBitmap", undefined);
202 vi.stubGlobal("OffscreenCanvas", undefined);
203
204 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
205 ok: false,
206 reason: "too-large",
207 });
208 });
209
210 it("reports unreadable when the image fails to decode", async () => {
211 vi.stubGlobal(
212 "createImageBitmap",
213 vi.fn(async () => {
214 throw new Error("corrupt image");
215 }),
216 );
217 vi.stubGlobal(
218 "OffscreenCanvas",
219 class {
220 getContext() {
221 return null;
222 }
223 },
224 );
225
226 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
227 ok: false,
228 reason: "unreadable",
229 });
230 });
231
232 it("compressImageToByteLimit passes small files through byte-for-byte", async () => {
233 const bitmapSpy = vi.fn();
234 vi.stubGlobal("createImageBitmap", bitmapSpy);
235
236 const original = makeFile(1024);
237 const result = await compressImageToByteLimit(original, 10 * 1024 * 1024);
238
239 expect(result.ok).toBe(true);
240 expect(result.ok && result.recompressed).toBe(false);
241 // Pass-through must be the same File object, not a copy.
242 expect(result.ok && result.file).toBe(original);
243 expect(bitmapSpy).not.toHaveBeenCalled();
244 });
245
246 it("compressImageToByteLimit re-encodes an oversized file under the byte cap", async () => {
247 stubCanvasPipeline(() => 200_000);
248
249 const result = await compressImageToByteLimit(makeFile(2_000_000), 1_000_000);
250
251 expect(result.ok).toBe(true);
252 expect(result.ok && result.recompressed).toBe(true);
253 expect(result.ok && result.file.type).toBe("image/webp");
254 // The re-encoded name must match the new container format.
255 expect(result.ok && result.file.name).toBe("shot.webp");
256 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
257 });
258
259 it("compressImageToByteLimit refuses sources above the decode-safety ceiling", async () => {
260 const bitmapSpy = vi.fn();
261 vi.stubGlobal("createImageBitmap", bitmapSpy);
262
263 const result = await compressImageToByteLimit(
264 makeFile(MAX_COMPRESSIBLE_SOURCE_BYTES + 1),
265 10 * 1024 * 1024,
266 );
267
268 expect(result).toEqual({ ok: false, reason: "too-large" });
269 // The whole point of the ceiling is to never decode such a file.
270 expect(bitmapSpy).not.toHaveBeenCalled();
271 });
272
273 it("compressImageToByteLimit reports too-large when no encoding fits", async () => {
274 const { close } = stubCanvasPipeline(() => 3_000_000);
275
276 const result = await compressImageToByteLimit(makeFile(2_000_000), 1_000_000);
277
278 expect(result).toEqual({ ok: false, reason: "too-large" });
279 expect(close).toHaveBeenCalled();
280 });
281
282 it("shrinks below the source size when the image is already under MAX_DIMENSION", async () => {
283 // A small-but-heavy source (e.g. a dense PNG): only a real downscale can
284 // get it under budget, since quality alone is stubbed to never suffice.
285 let smallestRequested = Number.POSITIVE_INFINITY;
286 const close = vi.fn();
287 vi.stubGlobal(
288 "createImageBitmap",
289 vi.fn(async () => ({ width: 800, height: 600, close })),
290 );
291 vi.stubGlobal(
292 "OffscreenCanvas",
293 class {
294 constructor(
295 public width: number,
296 public height: number,
297 ) {
298 smallestRequested = Math.min(smallestRequested, width);
299 }
300 getContext() {
301 return { fillStyle: "", fillRect: vi.fn(), drawImage: vi.fn() };
302 }
303 async convertToBlob({ type }: { type: string; quality: number }) {
304 // Only a genuinely downscaled pass fits the budget.
305 const size = smallestRequested < 800 ? 100_000 : 5_000_000;
306 return new Blob([new Uint8Array(size)], { type });
307 }
308 },
309 );
310
311 const result = await compressImageForStash(makeFile(4_000_000));
312
313 expect(result.ok).toBe(true);
314 // Fallback passes must scale off the bitmap, not a fixed 2048 ceiling
315 // that would never go below an 800px source.
316 expect(smallestRequested).toBeLessThan(800);
317 });
318});
319
320describe("HEIC attachment preparation", () => {
321 it("recognizes HEIC and HEIF MIME types and case-insensitive file extensions", () => {
322 expect(isHeicImageFile({ name: "photo.bin", type: "image/heic" })).toBe(true);
323 expect(isHeicImageFile({ name: "photo.bin", type: "image/heif" })).toBe(true);
324 expect(isHeicImageFile({ name: "photo.heic", type: "image/heic-sequence" })).toBe(false);
325 expect(isHeicImageFile({ name: "photo.heif", type: "image/heif-sequence" })).toBe(false);
326 expect(isHeicImageFile({ name: "IMG_1234.HEIC", type: "" })).toBe(true);
327 expect(isHeicImageFile({ name: "photo.heif", type: "application/octet-stream" })).toBe(true);
328 expect(isHeicImageFile({ name: "photo.png", type: "image/png" })).toBe(false);
329 expect(isHeicImageFile({ name: "photo.heic", type: "image/png" })).toBe(false);
330 expect(isHeicImageFile({ name: "photo.heif", type: "image/jpeg" })).toBe(false);
331 });
332
333 it("converts a HEIC photo with a missing MIME type into a named JPEG", async () => {
334 const original = makeHeicFile({
335 name: "IMG_1234.HEIC",
336 type: "",
337 lastModified: 123,
338 });
339 mocks.heicTo.mockResolvedValueOnce(
340 new Blob([new Uint8Array([4, 5, 6, 7])], { type: "image/jpeg" }),
341 );
342
343 const result = await prepareImageForAttachment(original, 1024);
344
345 expect(mocks.heicTo).toHaveBeenCalledWith({
346 blob: original,
347 type: "image/jpeg",
348 quality: 0.92,
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("keeps oversized converted photos in JPEG format while shrinking them", async () => {
358 const original = makeHeicFile({
359 name: "photo.heif",
360 type: "image/heif",
361 });
362 mocks.heicTo.mockResolvedValueOnce(
363 new Blob([new Uint8Array(2_000_000)], { type: "image/jpeg" }),
364 );
365 const { fillRect } = stubCanvasPipeline(() => 200_000);
366
367 const result = await prepareImageForAttachment(original, 1_000_000);
368
369 expect(result.ok && result.file.name).toBe("photo.jpg");
370 expect(result.ok && result.file.type).toBe("image/jpeg");
371 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
372 expect(fillRect).toHaveBeenCalled();
373 });
374
375 it("compresses JPEG intermediates above the source safety ceiling", async () => {
376 const original = makeHeicFile({
377 name: "large.heic",
378 type: "image/heic",
379 });
380 mocks.heicTo.mockResolvedValueOnce(
381 new Blob([new Uint8Array(MAX_COMPRESSIBLE_SOURCE_BYTES + 1)], {
382 type: "image/jpeg",
383 }),
384 );
385 const { close } = stubCanvasPipeline(() => 200_000);
386
387 const result = await prepareImageForAttachment(original, 1_000_000);
388
389 expect(result.ok && result.file.name).toBe("large.jpg");
390 expect(result.ok && result.file.type).toBe("image/jpeg");
391 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
392 expect(close).toHaveBeenCalled();
393 });
394
395 it.each([
396 { label: "24 MP", width: 5712, height: 4284 },
397 { label: "48 MP", width: 8064, height: 6048 },
398 ])("accepts $label HEIC photos", async ({ width, height }) => {
399 const original = makeHeicFile({ width, height });
400 mocks.heicTo.mockResolvedValueOnce(new Blob(["jpeg"], { type: "image/jpeg" }));
401
402 const result = await prepareImageForAttachment(original, 1024);
403
404 expect(result.ok && result.file.type).toBe("image/jpeg");
405 expect(mocks.heicTo).toHaveBeenCalledOnce();
406 });
407
408 it("rejects oversized HEIC dimensions before loading the decoder", async () => {
409 const original = makeHeicFile({ width: 16_000, height: 4001 });
410
411 expect(await prepareImageForAttachment(original, 1024)).toEqual({
412 ok: false,
413 reason: "too-large",
414 });
415 expect(mocks.heicTo).not.toHaveBeenCalled();
416 });
417
418 it("rejects invalid HEIC metadata before loading the decoder", async () => {
419 const original = new File([new Uint8Array([1, 2, 3])], "broken.heic", {
420 type: "image/heic",
421 });
422
423 expect(await prepareImageForAttachment(original, 1024)).toEqual({
424 ok: false,
425 reason: "unreadable",
426 });
427 expect(mocks.heicTo).not.toHaveBeenCalled();
428 });
429
430 it("reports unreadable when HEIC decoding fails", async () => {
431 const original = makeHeicFile({
432 name: "broken.heic",
433 type: "image/heic",
434 });
435 mocks.heicTo.mockRejectedValueOnce(new Error("Invalid HEIC image"));
436
437 expect(await prepareImageForAttachment(original, 1024)).toEqual({
438 ok: false,
439 reason: "unreadable",
440 });
441 });
442
443 it("rejects unsafe HEIC sources before loading the decoder", async () => {
444 const original = new File(["photo"], "large.heic", { type: "image/heic" });
445 Object.defineProperty(original, "size", { value: MAX_COMPRESSIBLE_SOURCE_BYTES + 1 });
446
447 expect(await prepareImageForAttachment(original, 1024)).toEqual({
448 ok: false,
449 reason: "too-large",
450 });
451 expect(mocks.heicTo).not.toHaveBeenCalled();
452 });
453
454 it("leaves supported images untouched without loading the HEIC decoder", async () => {
455 const original = makeFile(1024);
456
457 const result = await prepareImageForAttachment(original, 2048);
458
459 expect(result.ok && result.file).toBe(original);
460 expect(result.ok && result.recompressed).toBe(false);
461 expect(mocks.heicTo).not.toHaveBeenCalled();
462 });
463});
464
465describe("snapshot coordinates after compression", () => {
466 const source: SnapShotSource = {
467 kind: "snap-shot",
468 capturedAt: "2026-09-01T00:00:00.000Z",
469 appName: "Editor",
470 windowTitle: "main.ts",
471 accessibility: {
472 format: "element-tree",
473 coordinateSpace: "captured-image",
474 imageSize: { width: 2560, height: 1600 },
475 truncated: false,
476 root: {
477 role: "window",
478 bounds: { x: 0, y: 0, width: 2560, height: 1600 },
479 children: [
480 {
481 role: "button",
482 name: "Save",
483 bounds: { x: 2400, y: 1400, width: 100, height: 100 },
484 children: [],
485 },
486 { role: "static_text", name: "Untitled", bounds: null, children: [] },
487 ],
488 },
489 },
490 };
491
492 it.each(["stash", "delivery"])(
493 "rescales the source and restores it with the compressed %s image",
494 async (path) => {
495 stubCanvasPipeline(() => 100);
496 vi.stubGlobal(
497 "createImageBitmap",
498 vi.fn(async () => ({ width: 2560, height: 1600, close: vi.fn() })),
499 );
500 const original = makeFile(2000);
501 const compressed =
502 path === "stash"
503 ? await compressImageForStash(original, 1000)
504 : await compressImageToByteLimit(original, 1000);
505 expect(compressed.ok).toBe(true);
506 if (!compressed.ok) throw new Error("Compression failed");
507 const image =
508 "image" in compressed
509 ? compressed.image
510 : {
511 ...compressed,
512 mimeType: compressed.file.type,
513 sizeBytes: compressed.file.size,
514 dataUrl: `data:${compressed.file.type};base64,${Buffer.from(await compressed.file.arrayBuffer()).toString("base64")}`,
515 };
516 expect(image.imageSize).toEqual({ width: 2048, height: 1280 });
517 const resized = resizeSnapShotSource(source, image.imageSize);
518 const [restored] = hydrateImagesFromPersisted([
519 {
520 id: "capture",
521 name: "window.webp",
522 mimeType: image.mimeType,
523 sizeBytes: image.sizeBytes,
524 dataUrl: image.dataUrl,
525 source: resized,
526 },
527 ]);
528 expect(restored?.source?.accessibility).toMatchObject({
529 imageSize: { width: 2048, height: 1280 },
530 root: {
531 bounds: { x: 0, y: 0, width: 2048, height: 1280 },
532 children: [{ bounds: { x: 1920, y: 1120, width: 80, height: 80 } }, { bounds: null }],
533 },
534 });
535 expect(source.accessibility).toMatchObject({ imageSize: { width: 2560, height: 1600 } });
536 },
537 );
538
539 it("keeps uncompressed sources unchanged", () => {
540 expect(resizeSnapShotSource(source)).toBe(source);
541 });
542});