1import type { PreviewAnnotationPayload } from "@t3tools/contracts";
2import { afterEach, describe, expect, it, vi } from "vite-plus/test";
3
4import { capturePreviewAnnotationScreenshot } from "./previewAnnotation";
5
6const annotation: PreviewAnnotationPayload = {
7 id: "annotation_1",
8 pageUrl: "http://localhost:3000",
9 pageTitle: "Example",
10 comment: "Make these cards feel related.",
11 elements: [],
12 regions: [],
13 strokes: [],
14 styleChanges: [],
15 screenshot: {
16 dataUrl:
17 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=",
18 width: 1,
19 height: 1,
20 cropRect: { x: 0, y: 0, width: 1, height: 1 },
21 },
22 createdAt: "2026-06-11T00:00:00.000Z",
23};
24
25describe("preview annotation capture", () => {
26 afterEach(() => {
27 vi.unstubAllGlobals();
28 });
29
30 it("preserves the PNG bytes, MIME type, and filename without fetching", async () => {
31 const fetch = vi.fn().mockRejectedValue(new TypeError("Blocked by connect-src"));
32 vi.stubGlobal("fetch", fetch);
33 const capture = capturePreviewAnnotationScreenshot(annotation);
34 expect(capture.status).toBe("captured");
35 if (capture.status !== "captured") throw new Error("Expected a screenshot file");
36 expect(capture.file.name).toBe("preview-annotation-annotation_1.png");
37 expect(capture.file.type).toBe("image/png");
38 expect(Buffer.from(await capture.file.arrayBuffer()).toString("hex")).toBe(
39 "89504e470d0a1a0a0000000d4948445200000001000000010804000000b51c0c020000000b4944415478da63fcff1f0003030200efa2a75b0000000049454e44ae426082",
40 );
41 expect(fetch).not.toHaveBeenCalled();
42 });
43
44 it("reports none when the annotation carries no crop", () => {
45 const capture = capturePreviewAnnotationScreenshot({ ...annotation, screenshot: null });
46 expect(capture).toEqual({ status: "none" });
47 });
48
49 it.each(["data:image/jpeg;base64,AA==", "data:image/png;base64,", "data:image/png;base64,%%%"])(
50 "reports a malformed screenshot as failed: %s",
51 (dataUrl) => {
52 const picked = { ...annotation, screenshot: { ...annotation.screenshot!, dataUrl } };
53 expect(capturePreviewAnnotationScreenshot(picked)).toEqual({ status: "failed" });
54 },
55 );
56});