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

imageCompression.test.ts

514 lines17.1 KB

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