Open History to see the last commit
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 { readImageColorSpace } from "./imageCanvas";
17import { resizeSnapShotSource } from "./snapShotSource";
18
19const mocks = vi.hoisted(() => ({
20 heicTo: vi.fn(),
21}));
22
23vi.mock("heic-to/csp", () => ({
24 heicTo: mocks.heicTo,
25}));
26
27const originalCreateImageBitmap = globalThis.createImageBitmap;
28const originalOffscreenCanvas = globalThis.OffscreenCanvas;
29
30beforeEach(() => {
31 vi.stubGlobal(
32 "FileReader",
33 class extends EventTarget {
34 result: string | null = null;
35 error: unknown = null;
36 async readAsDataURL(blob: Blob) {
37 try {
38 const bytes = await blob.arrayBuffer();
39 this.result = `data:${blob.type || "application/octet-stream"};base64,${Buffer.from(bytes).toString("base64")}`;
40 this.dispatchEvent(new Event("load"));
41 } catch (error) {
42 this.error = error;
43 this.dispatchEvent(new Event("error"));
44 }
45 }
46 },
47 );
48});
49
50function makeFile(sizeBytes: number, type = "image/png"): File {
51 return new File([new Uint8Array(sizeBytes).fill(7)], "shot.png", { type });
52}
53
54function makeHeicFile(options?: {
55 name?: string;
56 type?: string;
57 width?: number;
58 height?: number;
59 lastModified?: number;
60 paddingBytes?: number;
61}): File {
62 const encoder = new TextEncoder();
63 const makeBox = (name: string, ...contents: Uint8Array[]) => {
64 const bytes = new Uint8Array(8 + contents.reduce((size, content) => size + content.length, 0));
65 new DataView(bytes.buffer).setUint32(0, bytes.length);
66 bytes.set(encoder.encode(name), 4);
67 let offset = 8;
68 for (const content of contents) {
69 bytes.set(content, offset);
70 offset += content.length;
71 }
72 return bytes;
73 };
74
75 const dimensions = new Uint8Array(12);
76 const view = new DataView(dimensions.buffer);
77 view.setUint32(4, options?.width ?? 4000);
78 view.setUint32(8, options?.height ?? 3000);
79 const properties = makeBox("iprp", makeBox("ipco", makeBox("ispe", dimensions)));
80
81 return new File(
82 [
83 makeBox("ftyp", encoder.encode("heic"), new Uint8Array(4)),
84 ...(options?.paddingBytes ? [makeBox("free", new Uint8Array(options.paddingBytes))] : []),
85 makeBox("meta", new Uint8Array(4), properties),
86 ],
87 options?.name ?? "photo.heic",
88 {
89 type: options?.type ?? "image/heic",
90 ...(options?.lastModified !== undefined ? { lastModified: options.lastModified } : {}),
91 },
92 );
93}
94
95function stubCanvasPipeline(
96 sizeForQuality: (quality: number) => number,
97 options?: { supportsWebp?: boolean; htmlCanvas?: boolean },
98) {
99 const supportsWebp = options?.supportsWebp ?? true;
100 const close = vi.fn();
101 const fillRect = vi.fn();
102 const canvasSizes: Array<{ width: number; height: number }> = [];
103 vi.stubGlobal(
104 "createImageBitmap",
105 vi.fn(async () => ({ width: 4000, height: 3000, close })),
106 );
107 vi.stubGlobal(
108 "OffscreenCanvas",
109 class {
110 constructor(
111 public width: number,
112 public height: number,
113 ) {
114 canvasSizes.push({ width, height });
115 }
116 getContext() {
117 return {
118 fillStyle: "",
119 fillRect,
120 drawImage: vi.fn(),
121 };
122 }
123 async convertToBlob({ type, quality }: { type: string; quality: number }) {
124 const resolvedType = type === "image/webp" && !supportsWebp ? "image/png" : type;
125 return new Blob([new Uint8Array(sizeForQuality(quality))], { type: resolvedType });
126 }
127 },
128 );
129 if (options?.htmlCanvas) {
130 const Canvas = globalThis.OffscreenCanvas;
131 class HtmlCanvas extends Canvas {
132 toBlob(callback: BlobCallback, type: string, quality: number) {
133 void this.convertToBlob({ type, quality }).then(callback);
134 }
135 }
136 vi.stubGlobal("OffscreenCanvas", undefined);
137 vi.stubGlobal("HTMLCanvasElement", HtmlCanvas);
138 vi.stubGlobal("document", { createElement: () => new HtmlCanvas(0, 0) });
139 }
140 return { close, fillRect, canvasSizes };
141}
142
143afterEach(() => {
144 mocks.heicTo.mockReset();
145 vi.unstubAllGlobals();
146 globalThis.createImageBitmap = originalCreateImageBitmap;
147 globalThis.OffscreenCanvas = originalOffscreenCanvas;
148});
149
150describe("compressImageForStash", () => {
151 it("keeps the exact data URL budget boundary and original bytes", async () => {
152 const original = makeFile(3);
153 const dataUrl = "data:image/png;base64,BwcH";
154
155 const result = await compressImageForStash(original, dataUrl.length);
156
157 expect(result.ok && result.image.dataUrl).toBe(dataUrl);
158 expect(result.ok && result.image.recompressed).toBe(false);
159 expect(await compressImageForStash(original, dataUrl.length - 1)).toEqual({
160 ok: false,
161 reason: "too-large",
162 });
163 });
164
165 it("compresses an oversized source before reading it as a data URL", async () => {
166 stubCanvasPipeline(() => 120_000);
167 const original = makeFile(4_000_000);
168 const read = vi.spyOn(original, "arrayBuffer").mockRejectedValue(new Error("unneeded read"));
169
170 const result = await compressImageForStash(original);
171
172 expect(result.ok && result.image.recompressed).toBe(true);
173 expect(read).not.toHaveBeenCalled();
174 });
175
176 it("encodes on the main thread when the image worker fails during the canvas snapshot", async () => {
177 stubCanvasPipeline(() => 120_000);
178 const workers: EventTarget[] = [];
179 const postMessage = vi.fn();
180 vi.stubGlobal(
181 "Worker",
182 class extends EventTarget {
183 postMessage = postMessage;
184 terminate() {}
185 constructor() {
186 super();
187 workers.push(this);
188 }
189 },
190 );
191 vi.mocked(createImageBitmap).mockImplementation(async (source) => {
192 if (source instanceof OffscreenCanvas) workers[0]?.dispatchEvent(new Event("error"));
193 return { width: 4000, height: 3000, close() {} } as ImageBitmap;
194 });
195
196 const result = await compressImageForStash(makeFile(4_000_000));
197
198 expect(result.ok && result.image.mimeType).toBe("image/webp");
199 expect(workers).toHaveLength(1);
200 expect(postMessage).not.toHaveBeenCalled();
201 });
202
203 it("re-encodes an oversized image to WebP within the budget", async () => {
204 const { close, fillRect } = stubCanvasPipeline(() => 120_000);
205
206 const result = await compressImageForStash(makeFile(4_000_000));
207
208 expect(result.ok).toBe(true);
209 expect(result.ok && result.image.recompressed).toBe(true);
210 expect(result.ok && result.image.mimeType).toBe("image/webp");
211 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
212 expect(result.ok && result.image.sizeBytes).toBeLessThan(4_000_000);
213 expect(fillRect).not.toHaveBeenCalled();
214 expect(close).toHaveBeenCalled();
215 });
216
217 it("falls back to JPEG with a white matte when WebP encoding is unavailable", async () => {
218 const { fillRect } = stubCanvasPipeline(() => 120_000, { supportsWebp: false });
219
220 const result = await compressImageForStash(makeFile(4_000_000));
221
222 expect(result.ok && result.image.recompressed).toBe(true);
223 expect(result.ok && result.image.mimeType).toBe("image/jpeg");
224 expect(fillRect).toHaveBeenCalled();
225 });
226
227 it("steps quality down until the encoded image fits", async () => {
228 const { close } = stubCanvasPipeline((quality) => (quality <= 0.68 ? 400_000 : 3_000_000));
229
230 const result = await compressImageForStash(makeFile(9_000_000));
231
232 expect(result.ok && result.image.recompressed).toBe(true);
233 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
234 expect(close).toHaveBeenCalled();
235 });
236
237 it("reports too-large when even the smallest encoding overflows the budget", async () => {
238 const { close } = stubCanvasPipeline(() => 8_000_000);
239
240 const result = await compressImageForStash(makeFile(9_000_000));
241
242 expect(result).toEqual({ ok: false, reason: "too-large" });
243 expect(close).toHaveBeenCalled();
244 });
245
246 it("reports unreadable when the image fails to decode", async () => {
247 vi.stubGlobal(
248 "createImageBitmap",
249 vi.fn(async () => {
250 throw new Error("corrupt image");
251 }),
252 );
253 vi.stubGlobal(
254 "OffscreenCanvas",
255 class {
256 getContext() {
257 return null;
258 }
259 },
260 );
261
262 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
263 ok: false,
264 reason: "unreadable",
265 });
266 });
267
268 it("compressImageToByteLimit refuses sources above the decode-safety ceiling", async () => {
269 const bitmapSpy = vi.fn();
270 vi.stubGlobal("createImageBitmap", bitmapSpy);
271
272 const result = await compressImageToByteLimit(
273 makeFile(MAX_COMPRESSIBLE_SOURCE_BYTES + 1),
274 10 * 1024 * 1024,
275 );
276
277 expect(result).toEqual({ ok: false, reason: "too-large" });
278 expect(bitmapSpy).not.toHaveBeenCalled();
279 });
280});
281
282describe("composer image thumbnails", () => {
283 it("gives the compressed file its source's thumbnail without decoding it again", async () => {
284 stubCanvasPipeline(() => 3);
285 const source = makeFile(3);
286 const compressed = makeFile(2, "image/webp");
287 // Compression can finish before the placeholder's thumbnail does.
288 const pendingThumbnail = createComposerImageThumbnail(source);
289
290 await inheritComposerImageThumbnail(source, compressed);
291
292 const sourceThumbnail = await pendingThumbnail;
293 expect(sourceThumbnail).toMatch(/^data:image\/png;base64,/);
294 expect(readComposerImageThumbnail(compressed)).toBe(sourceThumbnail);
295 expect(await createComposerImageThumbnail(compressed)).toBe(sourceThumbnail);
296 expect(createImageBitmap).toHaveBeenCalledTimes(1);
297 });
298});
299
300describe("HEIC attachment preparation", () => {
301 it("shares the native decode and shows its thumbnail before JPEG encoding finishes", async () => {
302 const { close } = stubCanvasPipeline(() => 3);
303 let finishEncoding!: (blob: Blob) => void;
304 const jpeg = new Promise<Blob>((resolve) => {
305 finishEncoding = resolve;
306 });
307 const Canvas = globalThis.OffscreenCanvas;
308 vi.stubGlobal(
309 "OffscreenCanvas",
310 class extends Canvas {
311 override convertToBlob(options?: ImageEncodeOptions) {
312 return options?.type === "image/jpeg" ? jpeg : super.convertToBlob(options);
313 }
314 },
315 );
316 const original = makeHeicFile();
317 const preparation = prepareImageForAttachment(original, 1024);
318 const queued = prepareImageForAttachment(makeHeicFile({ name: "next.heic" }), 1024);
319 const results = Promise.all([preparation, queued]);
320 try {
321 const thumbnail = await createComposerImageThumbnail(original);
322 expect(thumbnail).toMatch(/^data:image\/png;base64,/);
323 expect(mocks.heicTo).not.toHaveBeenCalled();
324 expect(createImageBitmap).toHaveBeenCalledTimes(1);
325 expect(close).not.toHaveBeenCalled();
326 } finally {
327 finishEncoding(new Blob([new Uint8Array(4)], { type: "image/jpeg" }));
328 await results;
329 }
330 const [result, next] = await results;
331 expect(result.ok && result.file.type).toBe("image/jpeg");
332 expect(result.ok && result.file.size).toBe(4);
333 expect(next.ok).toBe(true);
334 expect(close).toHaveBeenCalledTimes(2);
335 });
336
337 it("converts a HEIC photo with a missing MIME type into a named JPEG", async () => {
338 const original = makeHeicFile({
339 name: "IMG_1234.HEIC",
340 type: "",
341 lastModified: 123,
342 });
343 const { close } = stubCanvasPipeline(() => 4);
344 vi.mocked(createImageBitmap).mockRejectedValue(new Error("HEIC is not supported natively"));
345 mocks.heicTo.mockResolvedValueOnce({ width: 4000, height: 3000, close });
346
347 const result = await prepareImageForAttachment(original, 1024);
348
349 expect(mocks.heicTo).toHaveBeenCalledWith({
350 blob: original,
351 type: "bitmap",
352 });
353 expect(result.ok && result.file.name).toBe("IMG_1234.jpg");
354 expect(result.ok && result.file.type).toBe("image/jpeg");
355 expect(result.ok && result.file.size).toBe(4);
356 expect(result.ok && result.file.lastModified).toBe(123);
357 expect(result.ok && result.recompressed).toBe(true);
358 });
359
360 it("resizes decoded HEIC pixels before encoding the JPEG", async () => {
361 const original = makeHeicFile({
362 name: "large.heic",
363 type: "image/heic",
364 });
365 const { close, canvasSizes } = stubCanvasPipeline(() => 200_000);
366 vi.mocked(createImageBitmap).mockRejectedValue(new Error("HEIC is not supported natively"));
367 mocks.heicTo.mockResolvedValueOnce({ width: 4000, height: 3000, close });
368
369 const result = await prepareImageForAttachment(original, 1_000_000);
370
371 expect(result.ok && result.file.name).toBe("large.jpg");
372 expect(result.ok && result.file.type).toBe("image/jpeg");
373 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
374 expect(close).toHaveBeenCalledTimes(1);
375 expect(createImageBitmap).toHaveBeenCalledTimes(1);
376 expect(canvasSizes).toEqual([
377 { width: 2000, height: 1500 },
378 { width: 256, height: 256 },
379 ]);
380 });
381
382 it("rejects oversized HEIC dimensions before loading the decoder", async () => {
383 const original = makeHeicFile({ width: 16_000, height: 4001 });
384
385 expect(await prepareImageForAttachment(original, 1024)).toEqual({
386 ok: false,
387 reason: "too-large",
388 });
389 expect(mocks.heicTo).not.toHaveBeenCalled();
390 });
391
392 it("finds HEIC metadata after a top-level box larger than the metadata read limit", async () => {
393 const original = makeHeicFile({ paddingBytes: 2 * 1024 * 1024 });
394 const { close } = stubCanvasPipeline(() => 4);
395 vi.mocked(createImageBitmap).mockRejectedValue(new Error("HEIC is not supported natively"));
396 mocks.heicTo.mockResolvedValueOnce({ width: 4000, height: 3000, close });
397
398 const result = await prepareImageForAttachment(original, 1024);
399
400 expect(mocks.heicTo).toHaveBeenCalledTimes(1);
401 expect(result.ok && result.file.type).toBe("image/jpeg");
402 });
403
404 it("rejects unsafe HEIC sources before loading the decoder", async () => {
405 const original = new File(["photo"], "large.heic", { type: "image/heic" });
406 Object.defineProperty(original, "size", { value: MAX_COMPRESSIBLE_SOURCE_BYTES + 1 });
407
408 expect(await prepareImageForAttachment(original, 1024)).toEqual({
409 ok: false,
410 reason: "too-large",
411 });
412 expect(mocks.heicTo).not.toHaveBeenCalled();
413 });
414});
415
416describe("attachment max edge", () => {
417 const u32 = (n: number) => [(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff];
418 const u16 = (n: number) => [(n >>> 8) & 0xff, n & 0xff];
419 const pngHeader = (width: number, height: number) => [
420 0x89,
421 0x50,
422 0x4e,
423 0x47,
424 0x0d,
425 0x0a,
426 0x1a,
427 0x0a,
428 ...u32(13),
429 0x49,
430 0x48,
431 0x44,
432 0x52,
433 ...u32(width),
434 ...u32(height),
435 8,
436 6,
437 0,
438 0,
439 0,
440 ];
441 const jpegHeader = (width: number, height: number) => [
442 0xff,
443 0xd8,
444 0xff,
445 0xc0,
446 ...u16(17),
447 8,
448 ...u16(height),
449 ...u16(width),
450 ];
451 const image = (header: number[], name: string, type: string) =>
452 new File([new Uint8Array([...header, ...new Uint8Array(2048).fill(7)])], name, { type });
453
454 function stubDecoder(bitmapSize: { width: number; height: number }) {
455 const decode = vi.fn(async () => ({ ...bitmapSize, close: vi.fn() }));
456 const canvases: Array<{ width: number; height: number }> = [];
457 const encodes: Array<{ type: string; quality: number }> = [];
458 const fillRect = vi.fn();
459 vi.stubGlobal("createImageBitmap", decode);
460 vi.stubGlobal(
461 "OffscreenCanvas",
462 class {
463 constructor(width: number, height: number) {
464 canvases.push({ width, height });
465 }
466 getContext() {
467 return { fillRect, drawImage: vi.fn() };
468 }
469 async convertToBlob(options: { type: string; quality: number }) {
470 encodes.push(options);
471 return new Blob([new Uint8Array(500_000)], { type: options.type });
472 }
473 },
474 );
475 return { decode, canvases, encodes, fillRect };
476 }
477
478 it("scales a large PNG screenshot under the byte cap to 2000px and keeps it a PNG", async () => {
479 const { decode, canvases, encodes, fillRect } = stubDecoder({ width: 3024, height: 1964 });
480 const original = image(pngHeader(3024, 1964), "shot.png", "image/png");
481
482 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
483
484 expect(decode).toHaveBeenCalledExactlyOnceWith(original, { imageOrientation: "from-image" });
485 expect(canvases).toEqual([{ width: 2000, height: 1299 }]);
486 expect(encodes.map(({ type }) => type)).toEqual(["image/png"]);
487 expect(fillRect).not.toHaveBeenCalled();
488 expect(result.ok && result.recompressed).toBe(true);
489 expect(result.ok && result.imageSize).toEqual({ width: 2000, height: 1299 });
490 expect(result.ok && result.file.name).toBe("shot.png");
491 expect(result.ok && result.file.type).toBe("image/png");
492 });
493
494 it("scales a rotated JPEG by its displayed size and keeps it a JPEG", async () => {
495 const { canvases, encodes } = stubDecoder({ width: 3024, height: 4032 });
496 const original = image(jpegHeader(4032, 3024), "photo.jpg", "image/jpeg");
497
498 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
499
500 expect(canvases).toEqual([{ width: 1500, height: 2000 }]);
501 expect(encodes).toEqual([{ type: "image/jpeg", quality: 0.92 }]);
502 expect(result.ok && result.file.type).toBe("image/jpeg");
503 expect(result.ok && result.imageSize).toEqual({ width: 1500, height: 2000 });
504 });
505
506 it.each([
507 { label: "a 2000px PNG", header: pngHeader(2000, 1200), type: "image/png" },
508 {
509 label: "a 3000px GIF",
510 header: [0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0xb8, 0x0b, 0x10, 0x04],
511 type: "image/gif",
512 },
513 ])("passes $label through without decoding it", async ({ header, type }) => {
514 const { decode } = stubDecoder({ width: 3000, height: 1040 });
515 const original = image(header, "image", type);
516
517 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
518
519 expect(result.ok && result.file).toBe(original);
520 expect(result.ok && result.recompressed).toBe(false);
521 expect(decode).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: 2000, height: 1250 });
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: 2000, height: 1250 },
590 root: {
591 bounds: { x: 0, y: 0, width: 2000, height: 1250 },
592 children: [{ bounds: { x: 1875, y: 1094, width: 78, height: 78 } }, { bounds: null }],
593 },
594 });
595 expect(source.accessibility).toMatchObject({ imageSize: { width: 2560, height: 1600 } });
596 },
597 );
598});
599
600describe("readImageColorSpace", () => {
601 function displayP3IccProfile(): Uint8Array {
602 const primaries = [
603 [0x7258595a, 0.5151, 0.2412, -0.0011],
604 [0x6758595a, 0.292, 0.6922, 0.0419],
605 [0x6258595a, 0.1571, 0.0666, 0.7841],
606 ];
607 const profile = new DataView(new ArrayBuffer(132 + primaries.length * 32));
608 profile.setUint32(128, primaries.length);
609 primaries.forEach(([signature, ...xyz], index) => {
610 const tag = 132 + primaries.length * 12 + index * 20;
611 profile.setUint32(132 + index * 12, signature!);
612 profile.setUint32(136 + index * 12, tag);
613 profile.setUint32(140 + index * 12, 20);
614 profile.setUint32(tag, 0x58595a20);
615 xyz.forEach((value, axis) => profile.setInt32(tag + 8 + axis * 4, Math.round(value * 65536)));
616 });
617 return new Uint8Array(profile.buffer);
618 }
619
620 function jpegIccSegment(sequence: number, count: number, chunk: Uint8Array): number[] {
621 const payload = [
622 ..."ICC_PROFILE\0".split("").map((char) => char.charCodeAt(0)),
623 sequence,
624 count,
625 ...chunk,
626 ];
627 const length = payload.length + 2;
628 return [0xff, 0xe2, length >> 8, length & 0xff, ...payload];
629 }
630
631 const jpeg = (...prefix: number[]) =>
632 new Blob([
633 new Uint8Array([
634 0xff,
635 0xd8,
636 ...prefix,
637 ...jpegIccSegment(1, 1, displayP3IccProfile()),
638 0xff,
639 0xd9,
640 ]),
641 ]);
642
643 it("skips JPEG fill bytes and standalone markers before the ICC profile", async () => {
644 await expect(readImageColorSpace(jpeg())).resolves.toBe("display-p3");
645 await expect(readImageColorSpace(jpeg(0xff))).resolves.toBe("display-p3");
646 await expect(readImageColorSpace(jpeg(0xff, 0x01, 0xff, 0xd0))).resolves.toBe("display-p3");
647 });
648
649 it("assembles JPEG ICC profile chunks by sequence number, not file order", async () => {
650 const profile = displayP3IccProfile();
651 const first = jpegIccSegment(1, 2, profile.subarray(0, 120));
652 const second = jpegIccSegment(2, 2, profile.subarray(120));
653 const jpegFrom = (...segments: number[][]) =>
654 new Blob([new Uint8Array([0xff, 0xd8, ...segments.flat(), 0xff, 0xd9])]);
655
656 await expect(readImageColorSpace(jpegFrom(first, second))).resolves.toBe("display-p3");
657 await expect(readImageColorSpace(jpegFrom(second, first))).resolves.toBe("display-p3");
658 const stray = jpegIccSegment(0, 1, profile.subarray(0, 4));
659 await expect(readImageColorSpace(jpegFrom(stray, second, first))).resolves.toBe("display-p3");
660 await expect(readImageColorSpace(jpegFrom(second))).resolves.toBe("srgb");
661 });
662});