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

imageCompression.test.ts

448 lines15.8 KB

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