Open History to see the last commit
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 share: vi.fn(),
8 available: vi.fn(),
9 uuid: vi.fn(),
10}));
11
12vi.mock("expo-file-system", () => {
13 class Directory {
14 readonly uri: string;
15
16 constructor(...parts: Array<string | Directory>) {
17 this.uri = parts.map((part) => (typeof part === "string" ? part : part.uri)).join("/");
18 }
19
20 get name(): string {
21 return this.uri.split("/").at(-1)!;
22 }
23
24 get exists(): boolean {
25 return mocks.directories.has(this.uri);
26 }
27
28 create(): void {
29 mocks.directories.add(this.uri);
30 }
31
32 list(): Directory[] {
33 const prefix = `${this.uri}/`;
34 return [...mocks.directories]
35 .filter((uri) => uri.startsWith(prefix) && !uri.slice(prefix.length).includes("/"))
36 .map((uri) => new Directory(uri));
37 }
38
39 delete(): void {
40 mocks.deleted(this.uri);
41 mocks.directories.delete(this.uri);
42 }
43 }
44
45 class File {
46 static downloadFileAsync = mocks.download;
47 readonly uri: string;
48
49 constructor(directory: Directory, name: string) {
50 this.uri = `${directory.uri}/${encodeURIComponent(name)}`;
51 }
52 }
53
54 return { Directory, File, Paths: { cache: "file:///cache" } };
55});
56
57vi.mock("expo-sharing", () => ({
58 isAvailableAsync: mocks.available,
59 shareAsync: mocks.share,
60}));
61
62vi.mock("./uuid", () => ({ uuidv4: mocks.uuid }));
63
64import { downloadAndShareAttachment } from "./attachmentDownload";
65import { isForegroundHandoffActive } from "./foreground-handoff";
66
67const NOW = 1_787_990_400_000;
68const DAY_MS = 24 * 60 * 60_000;
69const CACHE = "file:///cache/t3-attachment-downloads";
70const input = {
71 url: "https://chosen-environment.example/api/assets/signed-token/report.pdf",
72 attachment: { name: "report.pdf", mimeType: "application/pdf" },
73};
74
75beforeEach(() => {
76 mocks.directories.clear();
77 mocks.deleted.mockReset();
78 mocks.download.mockReset();
79 mocks.share.mockReset();
80 mocks.available.mockReset();
81 mocks.uuid.mockReset();
82 mocks.download.mockImplementation(async (_url: string, file: { uri: string }) => file);
83 mocks.share.mockResolvedValue(undefined);
84 mocks.available.mockResolvedValue(true);
85 let sequence = 0;
86 mocks.uuid.mockImplementation(
87 () => `00000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}`,
88 );
89 vi.spyOn(Date, "now").mockReturnValue(NOW);
90});
91
92afterEach(() => {
93 vi.restoreAllMocks();
94 expect(isForegroundHandoffActive()).toBe(false);
95});
96
97describe("downloadAndShareAttachment", () => {
98 it("downloads the chosen environment's signed URL and shares the local file", async () => {
99 const controller = new AbortController();
100 await downloadAndShareAttachment({ ...input, signal: controller.signal });
101
102 expect(mocks.download).toHaveBeenCalledWith(
103 input.url,
104 expect.objectContaining({ uri: expect.stringMatching(/\/report\.pdf$/) }),
105 { signal: controller.signal },
106 );
107 expect(mocks.share).toHaveBeenCalledWith(
108 expect.stringMatching(/^file:\/\/\/cache\/.+\/report\.pdf$/),
109 {
110 mimeType: "application/pdf",
111 dialogTitle: "report.pdf",
112 },
113 );
114 expect(mocks.deleted).not.toHaveBeenCalled();
115 });
116
117 it("shares videos even when the server serves their bytes inline", async () => {
118 await downloadAndShareAttachment({
119 url: "https://relay-environment.example/api/assets/signed-video/clip.mp4",
120 attachment: { name: "clip.mp4", mimeType: 'video/mp4; codecs="avc1"' },
121 signal: new AbortController().signal,
122 });
123
124 expect(mocks.share).toHaveBeenCalledWith(expect.stringMatching(/\/clip\.mp4$/), {
125 mimeType: "video/mp4",
126 dialogTitle: "clip.mp4",
127 });
128 });
129
130 it.each([
131 ["../../résumé.pdf", "résumé.pdf"],
132 ["C:\\folder\\clip.mp4", "clip.mp4"],
133 ["a?query#part%2F.txt", "a?query#part%2F.txt"],
134 ["Report #5 - 100%.pdf", "Report #5 - 100%.pdf"],
135 ["..", "attachment"],
136 [" ", "attachment"],
137 ["\ud800file\u0000.txt", "_file_.txt"],
138 [".env", ".env"],
139 ])("uses a safe basename for %j", async (name, expected) => {
140 await downloadAndShareAttachment({
141 ...input,
142 attachment: { ...input.attachment, name },
143 signal: new AbortController().signal,
144 });
145 const file = mocks.download.mock.calls[0]![1] as { uri: string };
146 expect(decodeURIComponent(file.uri.split("/").at(-1)!)).toBe(expected);
147 });
148
149 it("preserves ordinary long filenames that fit within the filesystem limit", async () => {
150 const name =
151 "Project quarterly report with detailed implementation and delivery notes for August 2026.pdf";
152 await downloadAndShareAttachment({
153 ...input,
154 attachment: { ...input.attachment, name },
155 signal: new AbortController().signal,
156 });
157 const file = mocks.download.mock.calls[0]![1] as { uri: string };
158 expect(decodeURIComponent(file.uri.split("/").at(-1)!)).toBe(name);
159 });
160
161 it("bounds the UTF-8 filename length while preserving its extension", async () => {
162 await downloadAndShareAttachment({
163 ...input,
164 attachment: { name: `${"🙂".repeat(80)}.mp4`, mimeType: "video/mp4" },
165 signal: new AbortController().signal,
166 });
167 const file = mocks.download.mock.calls[0]![1] as { uri: string };
168 const name = decodeURIComponent(file.uri.split("/").at(-1)!);
169 expect(name.endsWith(".mp4")).toBe(true);
170 expect(new TextEncoder().encode(name).length).toBeLessThanOrEqual(255);
171 });
172
173 it("reports unavailable sharing before downloading or creating files", async () => {
174 mocks.available.mockResolvedValue(false);
175 await expect(
176 downloadAndShareAttachment({ ...input, signal: new AbortController().signal }),
177 ).rejects.toThrow("Saving and sharing files is unavailable on this device.");
178 expect(mocks.download).not.toHaveBeenCalled();
179 expect(mocks.directories.size).toBe(0);
180 });
181
182 it("cleans an interrupted download only after the native request settles", async () => {
183 const started = Promise.withResolvers<void>();
184 const download = Promise.withResolvers<{ uri: string }>();
185 mocks.download.mockImplementation(() => {
186 started.resolve();
187 return download.promise;
188 });
189 const controller = new AbortController();
190 const task = downloadAndShareAttachment({ ...input, signal: controller.signal });
191 await started.promise;
192 controller.abort();
193 expect(mocks.deleted).not.toHaveBeenCalled();
194 download.reject(new Error("Canceled native request"));
195 await task;
196 expect(mocks.deleted).toHaveBeenCalledTimes(1);
197 expect(mocks.share).not.toHaveBeenCalled();
198 });
199
200 it("does not open a late download after cancellation", async () => {
201 const started = Promise.withResolvers<{ uri: string }>();
202 const download = Promise.withResolvers<{ uri: string }>();
203 mocks.download.mockImplementation((_url: string, file: { uri: string }) => {
204 started.resolve(file);
205 return download.promise;
206 });
207 const controller = new AbortController();
208 const task = downloadAndShareAttachment({ ...input, signal: controller.signal });
209 const file = await started.promise;
210 controller.abort();
211 download.resolve(file);
212 await task;
213 expect(mocks.share).not.toHaveBeenCalled();
214 expect(mocks.deleted).toHaveBeenCalledTimes(1);
215 });
216
217 it("retains an export when its row unmounts during the native handoff", async () => {
218 const opened = Promise.withResolvers<void>();
219 const share = Promise.withResolvers<void>();
220 mocks.share.mockImplementation(() => {
221 expect(isForegroundHandoffActive()).toBe(true);
222 opened.resolve();
223 return share.promise;
224 });
225 const controller = new AbortController();
226 const task = downloadAndShareAttachment({ ...input, signal: controller.signal });
227 await opened.promise;
228 controller.abort();
229 share.resolve();
230 await task;
231 expect(mocks.deleted).not.toHaveBeenCalled();
232 });
233
234 it("cleans failed exports and releases the foreground handoff", async () => {
235 mocks.share.mockRejectedValue(new Error("No activity can open this file"));
236 await expect(
237 downloadAndShareAttachment({ ...input, signal: new AbortController().signal }),
238 ).rejects.toThrow("Could not open the share sheet. Try again.");
239 expect(mocks.deleted).toHaveBeenCalledTimes(1);
240 });
241
242 it("removes expired exports while leaving recent and unrelated cache entries alone", async () => {
243 const old = `${CACHE}/${NOW - DAY_MS - 1}-00000000-0000-4000-8000-000000000010`;
244 const recent = `${CACHE}/${NOW - DAY_MS + 1}-00000000-0000-4000-8000-000000000011`;
245 const unrelated = `${CACHE}/unrelated`;
246 mocks.directories.add(old).add(recent).add(unrelated);
247
248 await downloadAndShareAttachment({ ...input, signal: new AbortController().signal });
249 expect(mocks.deleted.mock.calls).toEqual([[old]]);
250 expect(mocks.directories.has(recent)).toBe(true);
251 expect(mocks.directories.has(unrelated)).toBe(true);
252 });
253
254 it("does not prune an active export even if it passes the cache expiry", async () => {
255 const opened = Promise.withResolvers<void>();
256 const share = Promise.withResolvers<void>();
257 mocks.share.mockImplementationOnce(() => {
258 opened.resolve();
259 return share.promise;
260 });
261 const first = downloadAndShareAttachment({ ...input, signal: new AbortController().signal });
262 await opened.promise;
263 vi.mocked(Date.now).mockReturnValue(NOW + DAY_MS + 1);
264
265 await downloadAndShareAttachment({ ...input, signal: new AbortController().signal });
266 expect(mocks.deleted).not.toHaveBeenCalled();
267 share.resolve();
268 await first;
269 });
270});