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

binaryPreview.worker.test.ts

556 lines20.5 KB

1import * as NodeZlib from "node:zlib";
2​
3import JSZip from "jszip";
4import { expect, it, vi } from "vite-plus/test";
5​
6import {
7 ARCHIVE_ENTRY_MAX_BYTES,
8 compareArchiveRows,
9 formatArchiveModifiedDate,
10 type BinaryWorkerRequest,
11 type BinaryWorkerResult,
12} from "./binaryPreviewProtocol";
13​
14async function startWorker() {
15 const worker = new EventTarget();
16 let receive = (_result: BinaryWorkerResult) => {};
17 vi.stubGlobal(
18 "self",
19 Object.assign(worker, { postMessage: (result: BinaryWorkerResult) => receive(result) }),
20 );
21 vi.resetModules();
22 await import("./binaryPreview.worker");
23 return (input: BinaryWorkerRequest) =>
24 new Promise<BinaryWorkerResult>((resolve) => {
25 receive = resolve;
26 worker.dispatchEvent(new MessageEvent("message", { data: input }));
27 });
29​
30it.each([ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_ENTRY_MAX_BYTES + 1])(
31 "only copies previewable TAR payloads with a %i-byte entry",
32 async (size) => {
33 const encode = (value: string) => new TextEncoder().encode(value);
34 const large = new Uint8Array(size).fill(97);
35 const entries = [
36 { path: "before.txt", bytes: encode("before") },
37 { path: "large.txt", bytes: large },
38 { path: "empty.txt", bytes: new Uint8Array() },
39 { path: "large-link.txt", bytes: new Uint8Array(), link: "large.txt" },
40 { path: "after.txt", bytes: encode("after") },
41 ];
42 const contents = (entry: (typeof entries)[number]) => (entry.link ? large : entry.bytes);
43 const bytes = new Uint8Array(
44 entries.reduce(
45 (length, entry) => length + 512 + Math.ceil(entry.bytes.length / 512) * 512,
46 1024,
47 ),
48 );
49 let offset = 0;
50 for (const entry of entries) {
51 const write = (position: number, value: string) =>
52 bytes.set(encode(value), offset + position);
53 write(0, entry.path);
54 write(124, entry.bytes.length.toString(8).padStart(11, "0") + "\0");
55 write(136, "00000000000\0");
56 bytes.fill(32, offset + 148, offset + 156);
57 write(156, entry.link ? "1" : "0");
58 if (entry.link) write(157, entry.link);
59 write(
60 148,
61 bytes
62 .subarray(offset, offset + 512)
63 .reduce((sum, byte) => sum + byte, 0)
64 .toString(8)
65 .padStart(6, "0") + "\0 ",
66 );
67 bytes.set(entry.bytes, offset + 512);
68 offset += 512 + Math.ceil(entry.bytes.length / 512) * 512;
69 }
70​
71 try {
72 const request = await startWorker();
73 using copies = vi.spyOn(Uint8Array.prototype, "slice");
74 expect(
75 await request({ type: "open", kind: "archive", name: "mixed.tar", bytes: bytes.buffer }),
76 ).toEqual({
77 type: "archive",
78 entries: entries.map((entry) => ({
79 path: entry.path,
80 size: contents(entry).length,
81 directory: false,
82 modified: "1970-01-01T00:00:00.000Z",
83 })),
84 });
85 const copiedBytes = copies.mock.results.reduce(
86 (total, result) => total + (result.type === "return" ? result.value.byteLength : 0),
87 0,
88 );
89 expect(copiedBytes).toBe(11 + (size <= ARCHIVE_ENTRY_MAX_BYTES ? size : 0));
90 for (const entry of entries) {
91 const result = await request({ type: "entry", path: entry.path });
92 const expected = contents(entry);
93 if (expected.length > ARCHIVE_ENTRY_MAX_BYTES) {
94 expect(result).toEqual({
95 type: "error",
96 code: "archive-entry-too-large",
97 message: "archive-entry-too-large",
98 });
99 } else {
100 if (result.type !== "entry") throw new Error("Expected entry");
101 expect(result.path).toBe(entry.path);
102 expect(result.bytes.length).toBe(expected.length);
103 expect(result.bytes.every((byte, index) => byte === expected[index])).toBe(true);
104 }
105 }
106 expect(await request({ type: "entry", path: "missing.txt" })).toEqual({
107 type: "error",
108 code: "archive-entry-unavailable",
109 message: "archive-entry-unavailable",
110 });
111 } finally {
112 vi.unstubAllGlobals();
113 }
114 },
115);
116​
117it.each([
118 { timeZone: "Asia/Tokyo", tarEvening: "11/26/2026", tarNight: "11/25/2026" },
119 { timeZone: "America/Chicago", tarEvening: "11/25/2026", tarNight: "11/24/2026" },
120 { timeZone: "America/Nuuk", tarEvening: "11/25/2026", tarNight: "11/24/2026" },
121])(
122 "formats archived ZIP dates and local TAR instants in $timeZone",
123 async ({ timeZone, tarEvening, tarNight }) => {
124 const zip = new JSZip();
125 // JSZip writes the UTC parts of these dates as the entries' DOS wall-clock fields.
126 zip.file("evening.txt", "a", { date: new Date(Date.UTC(2026, 10, 25, 20, 0)) });
127 zip.file("night.txt", "b", { date: new Date(Date.UTC(2026, 10, 25, 1, 30)) });
128 zip.file("dst-midnight.txt", "c", { date: new Date(Date.UTC(2026, 2, 28, 23, 30)) });
129 const bytes = await zip.generateAsync({ type: "arraybuffer" });
130 const previous = process.env.TZ;
131 process.env.TZ = timeZone;
132 try {
133 const request = await startWorker();
134 const result = await request({ type: "open", kind: "archive", name: "times.zip", bytes });
135 if (result.type !== "archive") throw new Error("Expected archive");
136 expect(result.entries.map(({ modified }) => modified)).toEqual([
137 "2026-11-25T20:00:00.000",
138 "2026-11-25T01:30:00.000",
139 "2026-03-28T23:30:00.000",
140 ]);
141 expect(
142 result.entries.map(({ modified }) => formatArchiveModifiedDate(modified, "en-US")),
143 ).toEqual(["11/25/2026", "11/25/2026", "3/28/2026"]);
144 expect([
145 formatArchiveModifiedDate("2026-11-25T20:00:00.000Z", "en-US"),
146 formatArchiveModifiedDate("2026-11-25T01:30:00.000Z", "en-US"),
147 formatArchiveModifiedDate(null, "en-US"),
148 ]).toEqual([tarEvening, tarNight, "-"]);
149 } finally {
150 if (previous === undefined) delete process.env.TZ;
151 else process.env.TZ = previous;
152 vi.unstubAllGlobals();
153 }
154 },
155);
156​
157it("sorts archive folders first, then numbered names in natural order", () => {
158 const rows = ["page10.txt", "vol10", "page2.txt", "vol2", "page1.txt", "vol1"].map((path) => ({
159 path,
160 directory: path.startsWith("vol"),
161 }));
162 expect(rows.sort(compareArchiveRows).map(({ path }) => path)).toEqual([
163 "vol1",
164 "vol2",
165 "vol10",
166 "page1.txt",
167 "page2.txt",
168 "page10.txt",
169 ]);
170});
171​
172it("formats singular and plural byte labels for SQLite BLOB cells", async () => {
173 const { default: initSqlJs } = await import("sql.js");
174 const SQL = await initSqlJs();
175 const db = new SQL.Database();
176 db.run(
177 "CREATE TABLE blobs(empty BLOB, one BLOB, four BLOB); INSERT INTO blobs VALUES (X'', X'FF', X'DEADBEEF');",
178 );
179 const bytes = db.export().slice().buffer;
180 db.close();
181​
182 try {
183 const request = await startWorker();
184 await request({ type: "open", kind: "sqlite", name: "blobs.sqlite", bytes });
185 expect(await request({ type: "rows", table: "blobs", page: 0 })).toEqual({
186 type: "rows",
187 table: "blobs",
188 page: 0,
189 columns: ["empty", "one", "four"],
190 rows: [["[blob: 0 bytes]", "[blob: 1 byte]", "[blob: 4 bytes]"]],
191 });
192 } finally {
193 vi.unstubAllGlobals();
194 }
195});
196​
197it("reads GNU base-256 TAR modification dates, including ones before 1970", async () => {
198 const encode = (value: string) => new TextEncoder().encode(value);
199 const entries = [
200 { path: "before-epoch.txt", mtime: new Uint8Array(12).fill(0xff) },
201 { path: "far-future.txt", mtime: Uint8Array.of(0x80, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0) },
202 { path: "out-of-range.txt", mtime: Uint8Array.of(0x80, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0) },
203 ];
204 const bytes = new Uint8Array(entries.length * 512 + 1024);
205 entries.forEach((entry, index) => {
206 const offset = index * 512;
207 bytes.set(encode(entry.path), offset);
208 bytes.set(encode("00000000000\0"), offset + 124);
209 bytes.set(entry.mtime, offset + 136);
210 bytes.fill(32, offset + 148, offset + 156);
211 bytes.set(encode("0"), offset + 156);
212 const sum = bytes.subarray(offset, offset + 512).reduce((acc, byte) => acc + byte, 0);
213 bytes.set(encode(sum.toString(8).padStart(6, "0") + "\0 "), offset + 148);
214 });
215​
216 try {
217 const request = await startWorker();
218 const result = await request({
219 type: "open",
220 kind: "archive",
221 name: "gnu.tar",
222 bytes: bytes.buffer,
223 });
224 if (result.type !== "archive") throw new Error(`Expected archive, got ${result.type}`);
225 expect(result.entries.map(({ modified }) => modified)).toEqual([
226 "1969-12-31T23:59:59.000Z",
227 "2242-03-16T12:56:32.000Z",
228 null,
229 ]);
230 } finally {
231 vi.unstubAllGlobals();
232 }
233});
234​
235it("reads GNU base-256 TAR entry sizes", async () => {
236 const encode = (value: string) => new TextEncoder().encode(value);
237 const bytes = new Uint8Array(2048);
238 bytes.set(encode("hello.txt"), 0);
239 bytes.set(Uint8Array.of(0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3), 124);
240 bytes.set(encode("00000000000\0"), 136);
241 bytes.fill(32, 148, 156);
242 bytes.set(encode("0"), 156);
243 bytes.set(Uint8Array.of(0x68, 0x69, 0x0a), 512);
244 const sum = bytes.subarray(0, 512).reduce((acc, byte) => acc + byte, 0);
245 bytes.set(encode(sum.toString(8).padStart(6, "0") + "\0 "), 148);
246​
247 try {
248 const request = await startWorker();
249 expect(
250 await request({ type: "open", kind: "archive", name: "sample.tar", bytes: bytes.buffer }),
251 ).toEqual({
252 type: "archive",
253 entries: [
254 { path: "hello.txt", size: 3, directory: false, modified: "1970-01-01T00:00:00.000Z" },
255 ],
256 });
257 const result = await request({ type: "entry", path: "hello.txt" });
258 if (result.type !== "entry") throw new Error(`Expected entry, got ${result.type}`);
259 expect([...result.bytes]).toEqual([0x68, 0x69, 0x0a]);
260 } finally {
261 vi.unstubAllGlobals();
262 }
263});
264​
265it("keeps TAR member names that differ only by a leading U+FEFF distinct", async () => {
266 const encode = (value: string) => new TextEncoder().encode(value);
267 const entries = [
268 { type: "0", path: "\uFEFFreport.txt", contents: "ONE" },
269 { type: "0", path: "report.txt", contents: "TWO" },
270 { type: "L", path: "././@LongLink", contents: "\uFEFFnotes.txt\0" },
271 { type: "0", path: "notes.txt", contents: "THREE" },
272 ];
273 const bytes = new Uint8Array(entries.length * 1024 + 1024);
274 entries.forEach((entry, index) => {
275 const offset = index * 1024;
276 const contents = encode(entry.contents);
277 bytes.set(encode(entry.path), offset);
278 bytes.set(encode(contents.length.toString(8).padStart(11, "0") + "\0"), offset + 124);
279 bytes.set(encode("00000000000\0"), offset + 136);
280 bytes.fill(32, offset + 148, offset + 156);
281 bytes.set(encode(entry.type), offset + 156);
282 const sum = bytes.subarray(offset, offset + 512).reduce((acc, byte) => acc + byte, 0);
283 bytes.set(encode(sum.toString(8).padStart(6, "0") + "\0 "), offset + 148);
284 bytes.set(contents, offset + 512);
285 });
286​
287 try {
288 const request = await startWorker();
289 const result = await request({
290 type: "open",
291 kind: "archive",
292 name: "test.tar",
293 bytes: bytes.buffer,
294 });
295 if (result.type !== "archive") throw new Error(`Expected archive, got ${result.type}`);
296 expect(result.entries.map(({ path }) => path)).toEqual([
297 "\uFEFFreport.txt",
298 "report.txt",
299 "\uFEFFnotes.txt",
300 ]);
301 const decoded = [];
302 for (const { path } of result.entries) {
303 const entry = await request({ type: "entry", path });
304 decoded.push(entry.type === "entry" ? new TextDecoder().decode(entry.bytes) : entry.type);
305 }
306 expect(decoded).toEqual(["ONE", "TWO", "THREE"]);
307 } finally {
308 vi.unstubAllGlobals();
309 }
310});
311​
312it("opens a plain TAR whose first member name starts with 0x1F", async () => {
313 const encode = (value: string) => new TextEncoder().encode(value);
314 const path = "\x1fhello.txt";
315 const contents = encode("hi\n");
316 const bytes = new Uint8Array(512 * 2 + 1024);
317 bytes.set(encode(path), 0);
318 bytes.set(encode("000644 \0"), 100);
319 bytes.set(encode(contents.length.toString(8).padStart(11, "0") + "\0"), 124);
320 bytes.set(encode("00000000000\0"), 136);
321 bytes.fill(32, 148, 156);
322 bytes.set(encode("0"), 156);
323 bytes.set(encode("ustar\x0000"), 257);
324 const sum = bytes.subarray(0, 512).reduce((acc, byte) => acc + byte, 0);
325 bytes.set(encode(sum.toString(8).padStart(6, "0") + "\0 "), 148);
326 bytes.set(contents, 512);
327​
328 try {
329 const request = await startWorker();
330 expect(
331 await request({ type: "open", kind: "archive", name: "sample.tar", bytes: bytes.buffer }),
332 ).toEqual({
333 type: "archive",
334 entries: [{ path, size: 3, directory: false, modified: "1970-01-01T00:00:00.000Z" }],
335 });
336 const entry = await request({ type: "entry", path });
337 if (entry.type !== "entry") throw new Error(`Expected entry, got ${entry.type}`);
338 expect([...entry.bytes]).toEqual([0x68, 0x69, 0x0a]);
339 } finally {
340 vi.unstubAllGlobals();
341 }
342});
343​
344it("lists and opens a contiguous-file TAR member (typeflag 7) as a file", async () => {
345 const encode = (value: string) => new TextEncoder().encode(value);
346 const bytes = new Uint8Array(2048);
347 bytes.set(encode("hello.txt"), 0);
348 bytes.set(encode("0000644\0"), 100);
349 bytes.set(encode("0000000\0"), 108);
350 bytes.set(encode("0000000\0"), 116);
351 bytes.set(encode("00000000005\0"), 124);
352 bytes.set(encode("00000000000\0"), 136);
353 bytes.fill(32, 148, 156);
354 bytes.set(encode("7"), 156);
355 bytes.set(encode("ustar\x0000"), 257);
356 const sum = bytes.subarray(0, 512).reduce((acc, byte) => acc + byte, 0);
357 bytes.set(encode(sum.toString(8).padStart(6, "0") + "\0 "), 148);
358 bytes.set(encode("hello"), 512);
359​
360 try {
361 const request = await startWorker();
362 expect(
363 await request({ type: "open", kind: "archive", name: "proof.tar", bytes: bytes.buffer }),
364 ).toEqual({
365 type: "archive",
366 entries: [
367 { path: "hello.txt", size: 5, directory: false, modified: "1970-01-01T00:00:00.000Z" },
368 ],
369 });
370 const entry = await request({ type: "entry", path: "hello.txt" });
371 if (entry.type !== "entry") throw new Error(`Expected entry, got ${entry.type}`);
372 expect(new TextDecoder().decode(entry.bytes)).toBe("hello");
373 } finally {
374 vi.unstubAllGlobals();
375 }
376});
377​
378it("opens a gzip file made of several members, as `cat a.gz b.gz > c.gz` writes it", async () => {
379 const bytes = Buffer.concat([NodeZlib.gzipSync("first\n"), NodeZlib.gzipSync("second\n")]);
380 try {
381 const request = await startWorker();
382 expect(
383 await request({
384 type: "open",
385 kind: "archive",
386 name: "joined.gz",
387 bytes: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
388 }),
389 ).toEqual({
390 type: "archive",
391 entries: [{ path: "joined", size: 13, directory: false, modified: null }],
392 });
393 const entry = await request({ type: "entry", path: "joined" });
394 if (entry.type !== "entry") throw new Error(`Expected entry, got ${entry.type}`);
395 expect(new TextDecoder().decode(entry.bytes)).toBe("first\nsecond\n");
396 } finally {
397 vi.unstubAllGlobals();
398 }
399});
400​
401it("opens joined gzip members when the first one's data holds a gzip header byte run", async () => {
402 const bytes = Buffer.concat([
403 NodeZlib.gzipSync(Buffer.from([0x1f, 0x8b, 0x08, 0x00, 0x0a]), { level: 0 }),
404 NodeZlib.gzipSync("second\n"),
405 ]);
406 try {
407 const request = await startWorker();
408 expect(
409 await request({
410 type: "open",
411 kind: "archive",
412 name: "run.gz",
413 bytes: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
414 }),
415 ).toEqual({
416 type: "archive",
417 entries: [{ path: "run", size: 12, directory: false, modified: null }],
418 });
419 } finally {
420 vi.unstubAllGlobals();
421 }
422});
423​
424it("bounds the decodes spent on gzip header byte runs without limiting real members", async () => {
425 let decoders = 0;
426 vi.stubGlobal(
427 "DecompressionStream",
428 class extends DecompressionStream {
429 constructor(format: CompressionFormat) {
430 super(format);
431 decoders++;
432 }
433 },
434 );
435 const open = async (name: string, bytes: Buffer<ArrayBuffer>) =>
436 (await startWorker())({
437 type: "open",
438 kind: "archive",
439 name,
440 bytes: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
441 });
442 try {
443 const members = Array.from({ length: 20 }, (_, index) => NodeZlib.gzipSync(`${index}`));
444 expect(await open("many.gz", Buffer.concat(members))).toMatchObject({
445 type: "archive",
446 entries: [{ path: "many", size: 30 }],
447 });
448 decoders = 0;
449 const runs = Buffer.alloc(3000).map((_, index) => [0x1f, 0x8b, 0x08][index % 3]!);
450 const crafted = Buffer.concat([NodeZlib.gzipSync(runs, { level: 0 }), members[0]!]);
451 expect(await open("crafted.gz", crafted)).toMatchObject({ type: "error" });
452 expect(decoders).toBeLessThan(20);
453 } finally {
454 vi.unstubAllGlobals();
455 }
456});
457​
458it("lists v7 TAR folders, marked only by a trailing slash, as folders", async () => {
459 const encode = (value: string) => new TextEncoder().encode(value);
460 // bsdtar --format=v7 writes folders as plain members whose names end in a slash.
461 const entries = [
462 { path: "d/", contents: "" },
463 { path: "d/sub/", contents: "" },
464 { path: "d/sub/f.txt", contents: "hi\n" },
465 ];
466 const bytes = new Uint8Array(5 * 512 + 1024);
467 let offset = 0;
468 for (const entry of entries) {
469 const contents = encode(entry.contents);
470 bytes.set(encode(entry.path), offset);
471 bytes.set(encode(contents.length.toString(8).padStart(11, "0") + "\0"), offset + 124);
472 bytes.set(encode("00000000000\0"), offset + 136);
473 bytes.fill(32, offset + 148, offset + 156);
474 bytes.set(encode("0"), offset + 156);
475 const sum = bytes.subarray(offset, offset + 512).reduce((acc, byte) => acc + byte, 0);
476 bytes.set(encode(sum.toString(8).padStart(6, "0") + "\0 "), offset + 148);
477 bytes.set(contents, offset + 512);
478 offset += 512 + Math.ceil(contents.length / 512) * 512;
479 }
480​
481 try {
482 const request = await startWorker();
483 const result = await request({
484 type: "open",
485 kind: "archive",
486 name: "v7.tar",
487 bytes: bytes.buffer,
488 });
489 if (result.type !== "archive") throw new Error(`Expected archive, got ${result.type}`);
490 expect(result.entries.map(({ path, directory }) => ({ path, directory }))).toEqual([
491 { path: "d/", directory: true },
492 { path: "d/sub/", directory: true },
493 { path: "d/sub/f.txt", directory: false },
494 ]);
495 } finally {
496 vi.unstubAllGlobals();
497 }
498});
499​
500it("opens TAR members whose header uses a signed-byte checksum", async () => {
501 const encode = (value: string) => new TextEncoder().encode(value);
502 // Old SunOS/BSD tar summed header bytes as signed chars; "é" makes that sum differ.
503 const signedTar = (checksumOffset: number) => {
504 const bytes = new Uint8Array(2048);
505 bytes.set(encode("café.txt"), 0);
506 bytes.set(encode("00000000005\0"), 124);
507 bytes.set(encode("00000000000\0"), 136);
508 bytes.fill(32, 148, 156);
509 bytes.set(encode("0"), 156);
510 const sum = bytes
511 .subarray(0, 512)
512 .reduce((acc, byte) => acc + (byte < 128 ? byte : byte - 256), 0);
513 bytes.set(encode((sum + checksumOffset).toString(8).padStart(6, "0") + "\0 "), 148);
514 bytes.set(encode("hello"), 512);
515 return bytes;
516 };
517 // A blank checksum reads as 0, and these high-bit bytes bring the signed sum to 0 as well.
518 const blankChecksum = new Uint8Array(1536);
519 blankChecksum.set([0x80, 0x80]);
520​
521 try {
522 const request = await startWorker();
523 const open = (bytes: Uint8Array<ArrayBuffer>) =>
524 request({ type: "open", kind: "archive", name: "signed.tar", bytes: bytes.buffer });
525 expect(await open(signedTar(0))).toMatchObject({
526 type: "archive",
527 entries: [{ path: "café.txt", size: 5, directory: false }],
528 });
529 expect(await open(signedTar(1))).toMatchObject({ type: "error", code: "tar-header-damaged" });
530 expect(await open(blankChecksum)).toMatchObject({ type: "error", code: "tar-header-damaged" });
531 } finally {
532 vi.unstubAllGlobals();
533 }
534});
535​
536it("shows no date for a ZIP member whose stored date was never set", async () => {
537 // Written by Go's archive/zip with no Modified time, which leaves the DOS date and time at 0.
538 const goZip =
539 "UEsDBBQACAAIAAAAAAAAAAAAAAAAAAAAAAAFAAAAYS50eHQAAgD9/2hpAwBQSwcIrCqT2AkAAAACAAAAUEsBAhQAFAAIAAgAAAAAAKwqk9gJAAAAAgAAAAUAAAAAAAAAAAAAAAAAAAAAAGEudHh0UEsFBgAAAAABAAEAMwAAADwAAAAAAA==";
540 try {
541 const request = await startWorker();
542 expect(
543 await request({
544 type: "open",
545 kind: "archive",
546 name: "go.zip",
547 bytes: Uint8Array.from(atob(goZip), (char) => char.charCodeAt(0)).buffer,
548 }),
549 ).toEqual({
550 type: "archive",
551 entries: [{ path: "a.txt", size: 2, directory: false, modified: null }],
552 });
553 } finally {
554 vi.unstubAllGlobals();
555 }
556});