Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

imageCompression.test.ts

602 lines21.0 KB

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