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

attachmentDownload.test.ts

400 lines14.2 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2​
3const mocks = vi.hoisted(() => ({
4 directories: new Set<string>(),
5 deleted: vi.fn(),
6 download: vi.fn(),
7 copy: vi.fn(),
8 share: vi.fn(),
9 shareFromSource: vi.fn(),
10 available: vi.fn(),
11 uuid: vi.fn(),
12}));
13​
14vi.mock("expo-file-system", () => {
15 class Directory {
16 readonly uri: string;
17​
18 constructor(...parts: Array<string | Directory>) {
19 this.uri = parts.map((part) => (typeof part === "string" ? part : part.uri)).join("/");
20 }
21​
22 get name(): string {
23 return this.uri.split("/").at(-1)!;
24 }
25​
26 get exists(): boolean {
27 return mocks.directories.has(this.uri);
28 }
29​
30 create(): void {
31 mocks.directories.add(this.uri);
32 }
33​
34 list(): Directory[] {
35 const prefix = `${this.uri}/`;
36 return [...mocks.directories]
37 .filter((uri) => uri.startsWith(prefix) && !uri.slice(prefix.length).includes("/"))
38 .map((uri) => new Directory(uri));
39 }
40​
41 delete(): void {
42 mocks.deleted(this.uri);
43 mocks.directories.delete(this.uri);
44 }
45 }
46​
47 class File {
48 static downloadFileAsync = mocks.download;
49 readonly uri: string;
50​
51 constructor(source: Directory | string, name?: string) {
52 this.uri = typeof source === "string" ? source : `${source.uri}/${encodeURIComponent(name!)}`;
53 }
54​
55 async copy(destination: File): Promise<void> {
56 await mocks.copy(this.uri, destination.uri);
57 }
58 }
59​
60 return { Directory, File, Paths: { cache: "file:///cache" } };
61});
62​
63vi.mock("expo-sharing", () => ({
64 isAvailableAsync: mocks.available,
65 shareAsync: mocks.share,
66}));
67​
68vi.mock("./uuid", () => ({ uuidv4: mocks.uuid }));
69vi.mock("./shareFileFromSource", () => ({ shareFileFromSource: mocks.shareFromSource }));
70​
71import {
72 downloadAndShareAttachment,
73 downloadAttachmentForPreview,
74 shareLocalAttachment,
75} from "./attachmentDownload";
76import { isForegroundHandoffActive } from "./foreground-handoff";
77​
78const NOW = 1_787_990_400_000;
79const DAY_MS = 24 * 60 * 60_000;
80const CACHE = "file:///cache/t3-attachment-downloads";
81const input = {
82 url: "https://chosen-environment.example/api/assets/signed-token/report.pdf",
83 attachment: { name: "report.pdf", mimeType: "application/pdf" },
84};
85​
86beforeEach(() => {
87 mocks.directories.clear();
88 mocks.deleted.mockReset();
89 mocks.download.mockReset();
90 mocks.copy.mockReset();
91 mocks.share.mockReset();
92 mocks.shareFromSource.mockReset();
93 mocks.available.mockReset();
94 mocks.uuid.mockReset();
95 mocks.download.mockImplementation(async (_url: string, file: { uri: string }) => file);
96 mocks.copy.mockResolvedValue(undefined);
97 mocks.share.mockResolvedValue(undefined);
98 mocks.shareFromSource.mockResolvedValue(undefined);
99 mocks.available.mockResolvedValue(true);
100 let sequence = 0;
101 mocks.uuid.mockImplementation(
102 () => `00000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}`,
103 );
104 vi.spyOn(Date, "now").mockReturnValue(NOW);
105});
106​
107afterEach(() => {
108 vi.restoreAllMocks();
109 expect(isForegroundHandoffActive()).toBe(false);
110});
111​
112describe("downloadAndShareAttachment", () => {
113 it("downloads the chosen environment's signed URL and shares the local file", async () => {
114 const controller = new AbortController();
115 await downloadAndShareAttachment({ ...input, signal: controller.signal });
116​
117 expect(mocks.download).toHaveBeenCalledWith(
118 input.url,
119 expect.objectContaining({ uri: expect.stringMatching(/\/report\.pdf$/) }),
120 { signal: controller.signal },
121 );
122 expect(mocks.share).toHaveBeenCalledWith(
123 expect.stringMatching(/^file:\/\/\/cache\/.+\/report\.pdf$/),
124 {
125 mimeType: "application/pdf",
126 dialogTitle: "report.pdf",
127 },
128 );
129 expect(mocks.deleted).not.toHaveBeenCalled();
130 });
131​
132 it("shares videos even when the server serves their bytes inline", async () => {
133 await downloadAndShareAttachment({
134 url: "https://relay-environment.example/api/assets/signed-video/clip.mp4",
135 attachment: { name: "clip.mp4", mimeType: 'video/mp4; codecs="avc1"' },
136 signal: new AbortController().signal,
137 });
138​
139 expect(mocks.share).toHaveBeenCalledWith(expect.stringMatching(/\/clip\.mp4$/), {
140 mimeType: "video/mp4",
141 dialogTitle: "clip.mp4",
142 });
143 });
144​
145 it.each([
146 ["../../résumé.pdf", "résumé.pdf"],
147 ["C:\\folder\\clip.mp4", "clip.mp4"],
148 ["a?query#part%2F.txt", "a?query#part%2F.txt"],
149 ["Report #5 - 100%.pdf", "Report #5 - 100%.pdf"],
150 ["..", "attachment"],
151 [" ", "attachment"],
152 ["\ud800file\u0000.txt", "_file_.txt"],
153 [".env", ".env"],
154 ])("uses a safe basename for %j", async (name, expected) => {
155 await downloadAndShareAttachment({
156 ...input,
157 attachment: { ...input.attachment, name },
158 signal: new AbortController().signal,
159 });
160 const file = mocks.download.mock.calls[0]![1] as { uri: string };
161 expect(decodeURIComponent(file.uri.split("/").at(-1)!)).toBe(expected);
162 });
163​
164 it("preserves ordinary long filenames that fit within the filesystem limit", async () => {
165 const name =
166 "Project quarterly report with detailed implementation and delivery notes for August 2026.pdf";
167 await downloadAndShareAttachment({
168 ...input,
169 attachment: { ...input.attachment, name },
170 signal: new AbortController().signal,
171 });
172 const file = mocks.download.mock.calls[0]![1] as { uri: string };
173 expect(decodeURIComponent(file.uri.split("/").at(-1)!)).toBe(name);
174 });
175​
176 it("bounds the UTF-8 filename length while preserving its extension", async () => {
177 await downloadAndShareAttachment({
178 ...input,
179 attachment: { name: `${"🙂".repeat(80)}.mp4`, mimeType: "video/mp4" },
180 signal: new AbortController().signal,
181 });
182 const file = mocks.download.mock.calls[0]![1] as { uri: string };
183 const name = decodeURIComponent(file.uri.split("/").at(-1)!);
184 expect(name.endsWith(".mp4")).toBe(true);
185 expect(new TextEncoder().encode(name).length).toBeLessThanOrEqual(255);
186 });
187​
188 it("reports unavailable sharing before downloading or creating files", async () => {
189 mocks.available.mockResolvedValue(false);
190 await expect(
191 downloadAndShareAttachment({ ...input, signal: new AbortController().signal }),
192 ).rejects.toThrow("Saving and sharing files is unavailable on this device.");
193 expect(mocks.download).not.toHaveBeenCalled();
194 expect(mocks.directories.size).toBe(0);
195 });
196​
197 it("cleans an interrupted download only after the native request settles", async () => {
198 const started = Promise.withResolvers<void>();
199 const download = Promise.withResolvers<{ uri: string }>();
200 mocks.download.mockImplementation(() => {
201 started.resolve();
202 return download.promise;
203 });
204 const controller = new AbortController();
205 const task = downloadAndShareAttachment({ ...input, signal: controller.signal });
206 await started.promise;
207 controller.abort();
208 expect(mocks.deleted).not.toHaveBeenCalled();
209 download.reject(new Error("Canceled native request"));
210 await task;
211 expect(mocks.deleted).toHaveBeenCalledTimes(1);
212 expect(mocks.share).not.toHaveBeenCalled();
213 });
214​
215 it("does not open a late download after cancellation", async () => {
216 const started = Promise.withResolvers<{ uri: string }>();
217 const download = Promise.withResolvers<{ uri: string }>();
218 mocks.download.mockImplementation((_url: string, file: { uri: string }) => {
219 started.resolve(file);
220 return download.promise;
221 });
222 const controller = new AbortController();
223 const task = downloadAndShareAttachment({ ...input, signal: controller.signal });
224 const file = await started.promise;
225 controller.abort();
226 download.resolve(file);
227 await task;
228 expect(mocks.share).not.toHaveBeenCalled();
229 expect(mocks.deleted).toHaveBeenCalledTimes(1);
230 });
231​
232 it("retains an export when its row unmounts during the native handoff", async () => {
233 const opened = Promise.withResolvers<void>();
234 const share = Promise.withResolvers<void>();
235 mocks.share.mockImplementation(() => {
236 expect(isForegroundHandoffActive()).toBe(true);
237 opened.resolve();
238 return share.promise;
239 });
240 const controller = new AbortController();
241 const task = downloadAndShareAttachment({ ...input, signal: controller.signal });
242 await opened.promise;
243 controller.abort();
244 share.resolve();
245 await task;
246 expect(mocks.deleted).not.toHaveBeenCalled();
247 });
248​
249 it("cleans failed exports and releases the foreground handoff", async () => {
250 mocks.share.mockRejectedValue(new Error("No activity can open this file"));
251 await expect(
252 downloadAndShareAttachment({ ...input, signal: new AbortController().signal }),
253 ).rejects.toThrow("Could not open the share sheet. Try again.");
254 expect(mocks.deleted).toHaveBeenCalledTimes(1);
255 });
256​
257 it("removes expired exports while leaving recent and unrelated cache entries alone", async () => {
258 const old = `${CACHE}/${NOW - DAY_MS - 1}-00000000-0000-4000-8000-000000000010`;
259 const recent = `${CACHE}/${NOW - DAY_MS + 1}-00000000-0000-4000-8000-000000000011`;
260 const unrelated = `${CACHE}/unrelated`;
261 mocks.directories.add(old).add(recent).add(unrelated);
262​
263 await downloadAndShareAttachment({ ...input, signal: new AbortController().signal });
264 expect(mocks.deleted.mock.calls).toEqual([[old]]);
265 expect(mocks.directories.has(recent)).toBe(true);
266 expect(mocks.directories.has(unrelated)).toBe(true);
267 });
268​
269 it("does not prune an active export even if it passes the cache expiry", async () => {
270 const opened = Promise.withResolvers<void>();
271 const share = Promise.withResolvers<void>();
272 mocks.share.mockImplementationOnce(() => {
273 opened.resolve();
274 return share.promise;
275 });
276 const first = downloadAndShareAttachment({ ...input, signal: new AbortController().signal });
277 await opened.promise;
278 vi.mocked(Date.now).mockReturnValue(NOW + DAY_MS + 1);
279​
280 await downloadAndShareAttachment({ ...input, signal: new AbortController().signal });
281 expect(mocks.deleted).not.toHaveBeenCalled();
282 share.resolve();
283 await first;
284 });
285});
286​
287describe("attachment preview files", () => {
288 it("does not start a native request after cancellation during setup", async () => {
289 const controller = new AbortController();
290 const loading = downloadAttachmentForPreview({ ...input, signal: controller.signal });
291 controller.abort();
292 await expect(loading).resolves.toBeNull();
293 expect(mocks.download).not.toHaveBeenCalled();
294 expect(mocks.share).not.toHaveBeenCalled();
295 });
296​
297 it("downloads for playback without requiring a share sheet and removes the file on close", async () => {
298 mocks.available.mockResolvedValue(false);
299 const file = await downloadAttachmentForPreview({
300 ...input,
301 signal: new AbortController().signal,
302 });
303 expect(file?.uri.endsWith("/report.pdf")).toBe(true);
304 expect(mocks.available).not.toHaveBeenCalled();
305 expect(mocks.deleted).not.toHaveBeenCalled();
306 file?.dispose();
307 file?.dispose();
308 expect(mocks.deleted).toHaveBeenCalledTimes(1);
309 });
310​
311 it.each([undefined, "share-button"])(
312 "keeps a shared preview after its owner closes (source: %s)",
313 async (sourceIdentifier) => {
314 const opened = Promise.withResolvers<void>();
315 const sharing = Promise.withResolvers<void>();
316 const nativeShare = sourceIdentifier ? mocks.shareFromSource : mocks.share;
317 nativeShare.mockImplementationOnce(() => {
318 opened.resolve();
319 return sharing.promise;
320 });
321 const file = await downloadAttachmentForPreview({
322 ...input,
323 signal: new AbortController().signal,
324 });
325 const share = file!.share(new AbortController().signal, sourceIdentifier);
326 await opened.promise;
327 file!.dispose();
328 expect(mocks.deleted).not.toHaveBeenCalled();
329 expect(isForegroundHandoffActive()).toBe(true);
330 sharing.resolve();
331 await share;
332 expect(isForegroundHandoffActive()).toBe(false);
333 expect(mocks.deleted).not.toHaveBeenCalled();
334 expect(mocks.download).toHaveBeenCalledTimes(1);
335 expect(mocks.copy).not.toHaveBeenCalled();
336 },
337 );
338​
339 it.each([undefined, "share-button"])(
340 "does not share a disposed preview after availability checking (source: %s)",
341 async (sourceIdentifier) => {
342 const checking = Promise.withResolvers<void>();
343 const available = Promise.withResolvers<boolean>();
344 mocks.available.mockImplementation(() => {
345 checking.resolve();
346 return available.promise;
347 });
348 const file = await downloadAttachmentForPreview({
349 ...input,
350 signal: new AbortController().signal,
351 });
352 const share = file!.share(new AbortController().signal, sourceIdentifier);
353 await checking.promise;
354 file!.dispose();
355 available.resolve(true);
356 await share;
357 expect(mocks.share).not.toHaveBeenCalled();
358 expect(mocks.shareFromSource).not.toHaveBeenCalled();
359 expect(mocks.deleted).toHaveBeenCalledTimes(1);
360 },
361 );
362​
363 it("copies a local original before sharing without downloading or deleting the source", async () => {
364 const uri = "file:///documents/draft/report.pdf";
365 await shareLocalAttachment({
366 uri,
367 attachment: input.attachment,
368 signal: new AbortController().signal,
369 });
370 expect(mocks.copy).toHaveBeenCalledWith(
371 uri,
372 expect.stringMatching(/^file:\/\/\/cache\/.+\/report\.pdf$/),
373 );
374 expect(mocks.share).toHaveBeenCalledWith(mocks.copy.mock.calls[0]![1], expect.any(Object));
375 expect(mocks.download).not.toHaveBeenCalled();
376 expect(mocks.deleted).not.toHaveBeenCalled();
377 });
378​
379 it("waits for a local copy to finish before cleaning up a canceled share", async () => {
380 const copying = Promise.withResolvers<void>();
381 const copied = Promise.withResolvers<void>();
382 mocks.copy.mockImplementation(() => {
383 copying.resolve();
384 return copied.promise;
385 });
386 const controller = new AbortController();
387 const task = shareLocalAttachment({
388 uri: "file:///documents/draft/report.pdf",
389 attachment: input.attachment,
390 signal: controller.signal,
391 });
392 await copying.promise;
393 controller.abort();
394 expect(mocks.deleted).not.toHaveBeenCalled();
395 copied.resolve();
396 await task;
397 expect(mocks.share).not.toHaveBeenCalled();
398 expect(mocks.deleted).toHaveBeenCalledTimes(1);
399 });
400});