Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
3import { compressImageForStash, MAX_STASH_IMAGE_DATA_URL_CHARS } from "./stashImageCompression";
4
5/**
6 * jsdom has no real canvas/codec, so the re-encode path is exercised with
7 * stubbed `createImageBitmap` + `OffscreenCanvas`. The encoder stub returns a
8 * payload whose size scales with quality, mirroring how a real JPEG encoder
9 * shrinks as quality drops — enough to verify the ladder logic and budget
10 * enforcement without pulling in a native canvas.
11 */
12
13const originalCreateImageBitmap = globalThis.createImageBitmap;
14const originalOffscreenCanvas = globalThis.OffscreenCanvas;
15
16function makeFile(sizeBytes: number, type = "image/png"): File {
17 return new File([new Uint8Array(sizeBytes).fill(7)], "shot.png", { type });
18}
19
20/**
21 * Installs a fake bitmap + canvas whose encoded size follows `sizeForQuality`.
22 * `supportsWebp: false` makes `convertToBlob` hand back a differently-typed
23 * blob for WebP requests, which is how a real browser signals it cannot
24 * encode that format.
25 */
26function stubCanvasPipeline(
27 sizeForQuality: (quality: number) => number,
28 options?: { supportsWebp?: boolean },
29) {
30 const supportsWebp = options?.supportsWebp ?? true;
31 const close = vi.fn();
32 const fillRect = vi.fn();
33 vi.stubGlobal(
34 "createImageBitmap",
35 vi.fn(async () => ({ width: 4000, height: 3000, close })),
36 );
37 vi.stubGlobal(
38 "OffscreenCanvas",
39 class {
40 constructor(
41 public width: number,
42 public height: number,
43 ) {}
44 getContext() {
45 return {
46 fillStyle: "",
47 fillRect,
48 drawImage: vi.fn(),
49 };
50 }
51 async convertToBlob({ type, quality }: { type: string; quality: number }) {
52 const resolvedType = type === "image/webp" && !supportsWebp ? "image/png" : type;
53 return new Blob([new Uint8Array(sizeForQuality(quality))], { type: resolvedType });
54 }
55 },
56 );
57 return { close, fillRect };
58}
59
60afterEach(() => {
61 vi.unstubAllGlobals();
62 globalThis.createImageBitmap = originalCreateImageBitmap;
63 globalThis.OffscreenCanvas = originalOffscreenCanvas;
64});
65
66describe("compressImageForStash", () => {
67 it("stores a small image verbatim without re-encoding", async () => {
68 const bitmapSpy = vi.fn();
69 vi.stubGlobal("createImageBitmap", bitmapSpy);
70
71 const result = await compressImageForStash(makeFile(1024));
72
73 expect(result.ok).toBe(true);
74 expect(result.ok && result.image.recompressed).toBe(false);
75 expect(result.ok && result.image.mimeType).toBe("image/png");
76 expect(result.ok && result.image.dataUrl.startsWith("data:image/png")).toBe(true);
77 // Untouched payloads must not pay for a decode.
78 expect(bitmapSpy).not.toHaveBeenCalled();
79 });
80
81 it("re-encodes an oversized image to WebP within the budget", async () => {
82 // Comfortably under budget at the very first quality step.
83 const { close, fillRect } = stubCanvasPipeline(() => 120_000);
84
85 const result = await compressImageForStash(makeFile(4_000_000));
86
87 expect(result.ok).toBe(true);
88 expect(result.ok && result.image.recompressed).toBe(true);
89 expect(result.ok && result.image.mimeType).toBe("image/webp");
90 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
91 // sizeBytes should describe the re-encoded payload, not the 4MB original.
92 expect(result.ok && result.image.sizeBytes).toBeLessThan(4_000_000);
93 // WebP keeps alpha, so no white matte should be painted.
94 expect(fillRect).not.toHaveBeenCalled();
95 expect(close).toHaveBeenCalled();
96 });
97
98 it("falls back to JPEG with a white matte when WebP encoding is unavailable", async () => {
99 const { fillRect } = stubCanvasPipeline(() => 120_000, { supportsWebp: false });
100
101 const result = await compressImageForStash(makeFile(4_000_000));
102
103 expect(result.ok && result.image.recompressed).toBe(true);
104 expect(result.ok && result.image.mimeType).toBe("image/jpeg");
105 // JPEG has no alpha, so transparent regions must be matted white.
106 expect(fillRect).toHaveBeenCalled();
107 });
108
109 it("steps quality down until the encoded image fits", async () => {
110 // Only the lowest quality step (0.68) lands under the budget.
111 const { close } = stubCanvasPipeline((quality) => (quality <= 0.68 ? 400_000 : 3_000_000));
112
113 const result = await compressImageForStash(makeFile(9_000_000));
114
115 expect(result.ok && result.image.recompressed).toBe(true);
116 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
117 expect(close).toHaveBeenCalled();
118 });
119
120 it("reports too-large when even the smallest encoding overflows the budget", async () => {
121 const { close } = stubCanvasPipeline(() => 8_000_000);
122
123 const result = await compressImageForStash(makeFile(9_000_000));
124
125 expect(result).toEqual({ ok: false, reason: "too-large" });
126 // The bitmap must still be released on the give-up path.
127 expect(close).toHaveBeenCalled();
128 });
129
130 it("reports too-large for an oversized image when the browser cannot re-encode", async () => {
131 vi.stubGlobal("createImageBitmap", undefined);
132 vi.stubGlobal("OffscreenCanvas", undefined);
133
134 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
135 ok: false,
136 reason: "too-large",
137 });
138 });
139
140 it("reports unreadable when the image fails to decode", async () => {
141 vi.stubGlobal(
142 "createImageBitmap",
143 vi.fn(async () => {
144 throw new Error("corrupt image");
145 }),
146 );
147 vi.stubGlobal(
148 "OffscreenCanvas",
149 class {
150 getContext() {
151 return null;
152 }
153 },
154 );
155
156 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
157 ok: false,
158 reason: "unreadable",
159 });
160 });
161
162 it("shrinks below the source size when the image is already under MAX_DIMENSION", async () => {
163 // A small-but-heavy source (e.g. a dense PNG): only a real downscale can
164 // get it under budget, since quality alone is stubbed to never suffice.
165 let smallestRequested = Number.POSITIVE_INFINITY;
166 const close = vi.fn();
167 vi.stubGlobal(
168 "createImageBitmap",
169 vi.fn(async () => ({ width: 800, height: 600, close })),
170 );
171 vi.stubGlobal(
172 "OffscreenCanvas",
173 class {
174 constructor(
175 public width: number,
176 public height: number,
177 ) {
178 smallestRequested = Math.min(smallestRequested, width);
179 }
180 getContext() {
181 return { fillStyle: "", fillRect: vi.fn(), drawImage: vi.fn() };
182 }
183 async convertToBlob({ type }: { type: string; quality: number }) {
184 // Only a genuinely downscaled pass fits the budget.
185 const size = smallestRequested < 800 ? 100_000 : 5_000_000;
186 return new Blob([new Uint8Array(size)], { type });
187 }
188 },
189 );
190
191 const result = await compressImageForStash(makeFile(4_000_000));
192
193 expect(result.ok).toBe(true);
194 // Fallback passes must scale off the bitmap, not a fixed 2048 ceiling
195 // that would never go below an 800px source.
196 expect(smallestRequested).toBeLessThan(800);
197 });
198});