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

binaryPreview.worker.test.ts

167 lines5.9 KB

1import JSZip from "jszip";
2import { expect, it, vi } from "vite-plus/test";
3​
4import {
5 ARCHIVE_ENTRY_MAX_BYTES,
6 type BinaryWorkerRequest,
7 type BinaryWorkerResult,
8} from "./binaryPreviewProtocol";
9​
10async function startWorker() {
11 const worker = new EventTarget();
12 let receive = (_result: BinaryWorkerResult) => {};
13 vi.stubGlobal(
14 "self",
15 Object.assign(worker, { postMessage: (result: BinaryWorkerResult) => receive(result) }),
16 );
17 vi.resetModules();
18 await import("./binaryPreview.worker");
19 return (input: BinaryWorkerRequest) =>
20 new Promise<BinaryWorkerResult>((resolve) => {
21 receive = resolve;
22 worker.dispatchEvent(new MessageEvent("message", { data: input }));
23 });
25​
26it.each([ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_ENTRY_MAX_BYTES + 1])(
27 "only copies previewable TAR payloads with a %i-byte entry",
28 async (size) => {
29 const encode = (value: string) => new TextEncoder().encode(value);
30 const large = new Uint8Array(size).fill(97);
31 const entries = [
32 { path: "before.txt", bytes: encode("before") },
33 { path: "large.txt", bytes: large },
34 { path: "empty.txt", bytes: new Uint8Array() },
35 { path: "large-link.txt", bytes: new Uint8Array(), link: "large.txt" },
36 { path: "after.txt", bytes: encode("after") },
37 ];
38 const contents = (entry: (typeof entries)[number]) => (entry.link ? large : entry.bytes);
39 const bytes = new Uint8Array(
40 entries.reduce(
41 (length, entry) => length + 512 + Math.ceil(entry.bytes.length / 512) * 512,
42 1024,
43 ),
44 );
45 let offset = 0;
46 for (const entry of entries) {
47 const write = (position: number, value: string) =>
48 bytes.set(encode(value), offset + position);
49 write(0, entry.path);
50 write(124, entry.bytes.length.toString(8).padStart(11, "0") + "\0");
51 write(136, "00000000000\0");
52 bytes.fill(32, offset + 148, offset + 156);
53 write(156, entry.link ? "1" : "0");
54 if (entry.link) write(157, entry.link);
55 write(
56 148,
57 bytes
58 .subarray(offset, offset + 512)
59 .reduce((sum, byte) => sum + byte, 0)
60 .toString(8)
61 .padStart(6, "0") + "\0 ",
62 );
63 bytes.set(entry.bytes, offset + 512);
64 offset += 512 + Math.ceil(entry.bytes.length / 512) * 512;
65 }
66​
67 try {
68 const request = await startWorker();
69 using copies = vi.spyOn(Uint8Array.prototype, "slice");
70 expect(
71 await request({ type: "open", kind: "archive", name: "mixed.tar", bytes: bytes.buffer }),
72 ).toEqual({
73 type: "archive",
74 entries: entries.map((entry) => ({
75 path: entry.path,
76 size: contents(entry).length,
77 directory: false,
78 modified: "1970-01-01T00:00:00.000Z",
79 })),
80 });
81 const copiedBytes = copies.mock.results.reduce(
82 (total, result) => total + (result.type === "return" ? result.value.byteLength : 0),
83 0,
84 );
85 expect(copiedBytes).toBe(11 + (size <= ARCHIVE_ENTRY_MAX_BYTES ? size : 0));
86 for (const entry of entries) {
87 const result = await request({ type: "entry", path: entry.path });
88 const expected = contents(entry);
89 if (expected.length > ARCHIVE_ENTRY_MAX_BYTES) {
90 expect(result).toEqual({
91 type: "error",
92 code: "archive-entry-too-large",
93 message: "archive-entry-too-large",
94 });
95 } else {
96 if (result.type !== "entry") throw new Error("Expected entry");
97 expect(result.path).toBe(entry.path);
98 expect(result.bytes.length).toBe(expected.length);
99 expect(result.bytes.every((byte, index) => byte === expected[index])).toBe(true);
100 }
101 }
102 expect(await request({ type: "entry", path: "missing.txt" })).toEqual({
103 type: "error",
104 code: "archive-entry-unavailable",
105 message: "archive-entry-unavailable",
106 });
107 } finally {
108 vi.unstubAllGlobals();
109 }
110 },
111);
112​
113it.each(["Asia/Tokyo", "America/Chicago"])(
114 "shows ZIP modified times as the archived wall-clock time in %s",
115 async (timeZone) => {
116 const zip = new JSZip();
117 // JSZip writes the UTC parts of these dates as the entries' DOS wall-clock fields.
118 zip.file("evening.txt", "a", { date: new Date(Date.UTC(2026, 10, 25, 20, 0)) });
119 zip.file("night.txt", "b", { date: new Date(Date.UTC(2026, 10, 25, 1, 30)) });
120 const bytes = await zip.generateAsync({ type: "arraybuffer" });
121 const previous = process.env.TZ;
122 process.env.TZ = timeZone;
123 try {
124 const request = await startWorker();
125 const result = await request({ type: "open", kind: "archive", name: "times.zip", bytes });
126 if (result.type !== "archive") throw new Error("Expected archive");
127 expect(
128 result.entries.map(({ modified }) => {
129 const date = new Date(modified!);
130 return [date.toLocaleDateString("en-US"), date.getHours(), date.getMinutes()];
131 }),
132 ).toEqual([
133 ["11/25/2026", 20, 0],
134 ["11/25/2026", 1, 30],
135 ]);
136 } finally {
137 if (previous === undefined) delete process.env.TZ;
138 else process.env.TZ = previous;
139 vi.unstubAllGlobals();
140 }
141 },
142);
143​
144it("formats singular and plural byte labels for SQLite BLOB cells", async () => {
145 const { default: initSqlJs } = await import("sql.js");
146 const SQL = await initSqlJs();
147 const db = new SQL.Database();
148 db.run(
149 "CREATE TABLE blobs(empty BLOB, one BLOB, four BLOB); INSERT INTO blobs VALUES (X'', X'FF', X'DEADBEEF');",
150 );
151 const bytes = db.export().slice().buffer;
152 db.close();
153​
154 try {
155 const request = await startWorker();
156 await request({ type: "open", kind: "sqlite", name: "blobs.sqlite", bytes });
157 expect(await request({ type: "rows", table: "blobs", page: 0 })).toEqual({
158 type: "rows",
159 table: "blobs",
160 page: 0,
161 columns: ["empty", "one", "four"],
162 rows: [["[blob: 0 bytes]", "[blob: 1 byte]", "[blob: 4 bytes]"]],
163 });
164 } finally {
165 vi.unstubAllGlobals();
166 }
167});