@mountra/mountra-sdk 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -0
- package/README.md +120 -14
- package/dist/index.cjs +1643 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +384 -2
- package/dist/index.d.ts +384 -2
- package/dist/index.js +1636 -15
- package/dist/index.js.map +1 -1
- package/package.json +10 -8
package/dist/index.js
CHANGED
|
@@ -1,3 +1,1543 @@
|
|
|
1
|
+
// src/file.ts
|
|
2
|
+
function normalizeMountraFileLocator(locator, fallbackWorkspace = {}) {
|
|
3
|
+
if (!locator || typeof locator !== "object") {
|
|
4
|
+
throw new TypeError("Mountra file locator is required");
|
|
5
|
+
}
|
|
6
|
+
const hasPath = locator.path !== void 0;
|
|
7
|
+
const hasIno = locator.ino !== void 0;
|
|
8
|
+
if (hasPath === hasIno) {
|
|
9
|
+
throw new TypeError("Mountra file locator requires exactly one of path or ino");
|
|
10
|
+
}
|
|
11
|
+
const workspaceId = locator.workspaceId ?? locator.wsid ?? fallbackWorkspace.workspaceId;
|
|
12
|
+
if (locator.workspaceId !== void 0 && locator.wsid !== void 0 && String(locator.workspaceId) !== String(locator.wsid)) {
|
|
13
|
+
throw new TypeError("workspaceId and wsid must identify the same workspace");
|
|
14
|
+
}
|
|
15
|
+
const workspaceCuid = locator.workspaceCuid ?? fallbackWorkspace.workspaceCuid;
|
|
16
|
+
if (workspaceCuid === void 0 && workspaceId === void 0) {
|
|
17
|
+
throw new TypeError("workspaceCuid, workspaceId, or wsid is required");
|
|
18
|
+
}
|
|
19
|
+
if (hasPath) {
|
|
20
|
+
const path = normalizePath(locator.path);
|
|
21
|
+
return {
|
|
22
|
+
...workspaceCuid !== void 0 ? { workspaceCuid } : {},
|
|
23
|
+
...workspaceId !== void 0 ? { workspaceId } : {},
|
|
24
|
+
path
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
...workspaceCuid !== void 0 ? { workspaceCuid } : {},
|
|
29
|
+
...workspaceId !== void 0 ? { workspaceId } : {},
|
|
30
|
+
ino: normalizeIno(locator.ino)
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
var MountraFile = class {
|
|
34
|
+
constructor(client, locator) {
|
|
35
|
+
this.client = client;
|
|
36
|
+
this.locator = Object.freeze({ ...locator });
|
|
37
|
+
}
|
|
38
|
+
client;
|
|
39
|
+
locator;
|
|
40
|
+
get workspaceCuid() {
|
|
41
|
+
return this.locator.workspaceCuid;
|
|
42
|
+
}
|
|
43
|
+
get workspaceId() {
|
|
44
|
+
return this.locator.workspaceId;
|
|
45
|
+
}
|
|
46
|
+
/** `wsid` is the short alias used by the file-object API. */
|
|
47
|
+
get wsid() {
|
|
48
|
+
return this.locator.workspaceId;
|
|
49
|
+
}
|
|
50
|
+
get path() {
|
|
51
|
+
return "path" in this.locator ? this.locator.path : void 0;
|
|
52
|
+
}
|
|
53
|
+
get ino() {
|
|
54
|
+
return "ino" in this.locator ? this.locator.ino : void 0;
|
|
55
|
+
}
|
|
56
|
+
export(options = {}) {
|
|
57
|
+
return this.client.exportFile({ ...options, ...this.locator });
|
|
58
|
+
}
|
|
59
|
+
download(options = {}) {
|
|
60
|
+
return this.client.downloadFile({ ...options, ...this.locator });
|
|
61
|
+
}
|
|
62
|
+
async resume(options = {}) {
|
|
63
|
+
const { downloadKey, ...resumeOptions } = options;
|
|
64
|
+
const checkpoints = await this.client.listResumableDownloads();
|
|
65
|
+
const candidates = checkpoints.filter(
|
|
66
|
+
(checkpoint2) => checkpoint2.fileHandle && matchesLocator(checkpoint2.request, this.locator)
|
|
67
|
+
);
|
|
68
|
+
const checkpoint = downloadKey ? candidates.find((candidate) => candidate.key === downloadKey) : [...candidates].sort((left, right) => right.updatedAt - left.updatedAt)[0];
|
|
69
|
+
if (!checkpoint) {
|
|
70
|
+
if (downloadKey) {
|
|
71
|
+
throw new Error("Download checkpoint does not belong to this Mountra file");
|
|
72
|
+
}
|
|
73
|
+
throw new Error("No resumable download was found for this Mountra file");
|
|
74
|
+
}
|
|
75
|
+
return this.client.resumeDownload(checkpoint.key, resumeOptions);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
function matchesLocator(request, locator) {
|
|
79
|
+
if (locator.workspaceCuid !== void 0 && request.workspaceCuid !== locator.workspaceCuid) {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
if (locator.workspaceId !== void 0 && String(request.workspaceId) !== String(locator.workspaceId)) {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
if ("path" in locator) {
|
|
86
|
+
if (request.path === void 0 || request.ino !== void 0) {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
return normalizePath(request.path) === locator.path;
|
|
91
|
+
} catch {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return String(request.ino) === String(locator.ino) && request.path === void 0;
|
|
96
|
+
}
|
|
97
|
+
function normalizePath(value) {
|
|
98
|
+
if (!value || !value.trim()) {
|
|
99
|
+
throw new TypeError("Mountra file path cannot be empty");
|
|
100
|
+
}
|
|
101
|
+
const raw = value.trim();
|
|
102
|
+
const absolute = raw.startsWith("/") ? raw : `/${raw}`;
|
|
103
|
+
const segments = absolute.split("/").filter((segment) => segment.length > 0 && segment !== ".");
|
|
104
|
+
const stack = [];
|
|
105
|
+
for (const segment of segments) {
|
|
106
|
+
if (segment === "..") {
|
|
107
|
+
stack.pop();
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
stack.push(segment);
|
|
111
|
+
}
|
|
112
|
+
return stack.length === 0 ? "/" : `/${stack.join("/")}`;
|
|
113
|
+
}
|
|
114
|
+
function normalizeIno(value) {
|
|
115
|
+
if (typeof value === "number") {
|
|
116
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
117
|
+
throw new TypeError("Mountra file ino must be a non-negative safe integer");
|
|
118
|
+
}
|
|
119
|
+
return value;
|
|
120
|
+
}
|
|
121
|
+
if (!/^\d+$/.test(value)) {
|
|
122
|
+
throw new TypeError("Mountra file ino must be a non-negative integer string");
|
|
123
|
+
}
|
|
124
|
+
return value;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// src/cache.ts
|
|
128
|
+
var DEFAULT_MAX_BYTES = 512 * 1024 * 1024;
|
|
129
|
+
var DEFAULT_MAX_CHUNK_BYTES = 128 * 1024 * 1024;
|
|
130
|
+
var DEFAULT_TTL_MS = 5 * 60 * 1e3;
|
|
131
|
+
function copyFile(file) {
|
|
132
|
+
return { ...file, chunks: file.chunks.map((chunk) => ({ ...chunk })) };
|
|
133
|
+
}
|
|
134
|
+
function memoryKey(workspace, key) {
|
|
135
|
+
return JSON.stringify([workspace, key]);
|
|
136
|
+
}
|
|
137
|
+
var InMemoryDownloadCacheStore = class {
|
|
138
|
+
files = /* @__PURE__ */ new Map();
|
|
139
|
+
/** Map iteration order is the LRU order: the first entry is the least recently used. */
|
|
140
|
+
chunks = /* @__PURE__ */ new Map();
|
|
141
|
+
bytes = 0;
|
|
142
|
+
async getFile(workspace, fileKey) {
|
|
143
|
+
const entry = this.files.get(memoryKey(workspace, fileKey));
|
|
144
|
+
return entry ? copyFile(entry.file) : null;
|
|
145
|
+
}
|
|
146
|
+
async putFile(workspace, fileKey, file) {
|
|
147
|
+
this.files.set(memoryKey(workspace, fileKey), { workspace, file: copyFile(file) });
|
|
148
|
+
}
|
|
149
|
+
async removeFile(workspace, fileKey) {
|
|
150
|
+
this.files.delete(memoryKey(workspace, fileKey));
|
|
151
|
+
}
|
|
152
|
+
async getChunk(workspace, storageKey) {
|
|
153
|
+
const key = memoryKey(workspace, storageKey);
|
|
154
|
+
const entry = this.chunks.get(key);
|
|
155
|
+
if (!entry) {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
this.chunks.delete(key);
|
|
159
|
+
this.chunks.set(key, entry);
|
|
160
|
+
return entry.data;
|
|
161
|
+
}
|
|
162
|
+
async putChunk(workspace, storageKey, data, maxBytes) {
|
|
163
|
+
const key = memoryKey(workspace, storageKey);
|
|
164
|
+
this.removeChunk(key);
|
|
165
|
+
if (data.size > maxBytes) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
this.chunks.set(key, { workspace, data });
|
|
169
|
+
this.bytes += data.size;
|
|
170
|
+
for (const candidate of this.chunks.keys()) {
|
|
171
|
+
if (this.bytes <= maxBytes) {
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
this.removeChunk(candidate);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
async clear(workspace) {
|
|
178
|
+
for (const [key, entry] of this.chunks) {
|
|
179
|
+
if (workspace === void 0 || entry.workspace === workspace) {
|
|
180
|
+
this.removeChunk(key);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
for (const [key, entry] of this.files) {
|
|
184
|
+
if (workspace === void 0 || entry.workspace === workspace) {
|
|
185
|
+
this.files.delete(key);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
async usage(workspace) {
|
|
190
|
+
const usage = { bytes: 0, chunks: 0 };
|
|
191
|
+
for (const entry of this.chunks.values()) {
|
|
192
|
+
if (workspace === void 0 || entry.workspace === workspace) {
|
|
193
|
+
usage.bytes += entry.data.size;
|
|
194
|
+
usage.chunks += 1;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return usage;
|
|
198
|
+
}
|
|
199
|
+
removeChunk(key) {
|
|
200
|
+
const entry = this.chunks.get(key);
|
|
201
|
+
if (entry) {
|
|
202
|
+
this.chunks.delete(key);
|
|
203
|
+
this.bytes -= entry.data.size;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
var CACHE_DATABASE_NAME = "mountra-sdk-download-cache";
|
|
208
|
+
var CACHE_DATABASE_VERSION = 1;
|
|
209
|
+
var FILES_STORE = "files";
|
|
210
|
+
var CHUNKS_STORE = "chunks";
|
|
211
|
+
var CHUNK_DATA_STORE = "chunk-data";
|
|
212
|
+
var META_STORE = "meta";
|
|
213
|
+
var LRU_INDEX = "lastUsed";
|
|
214
|
+
var USAGE_KEY = "bytes";
|
|
215
|
+
var CLOCK_KEY = "clock";
|
|
216
|
+
function getIndexedDb() {
|
|
217
|
+
return globalThis.indexedDB ?? null;
|
|
218
|
+
}
|
|
219
|
+
function workspaceRange(workspace) {
|
|
220
|
+
return IDBKeyRange.bound([workspace], [workspace, []]);
|
|
221
|
+
}
|
|
222
|
+
function sameKey(left, right) {
|
|
223
|
+
return Array.isArray(left) && left[0] === right[0] && left[1] === right[1];
|
|
224
|
+
}
|
|
225
|
+
async function nextClock(meta) {
|
|
226
|
+
const clock = (await requestResult(meta.get(CLOCK_KEY)) ?? 0) + 1;
|
|
227
|
+
await requestResult(meta.put(clock, CLOCK_KEY));
|
|
228
|
+
return clock;
|
|
229
|
+
}
|
|
230
|
+
function requestResult(request) {
|
|
231
|
+
return new Promise((resolve, reject) => {
|
|
232
|
+
request.onsuccess = () => resolve(request.result);
|
|
233
|
+
request.onerror = () => reject(request.error ?? new Error("IndexedDB request failed"));
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
async function runTransaction(database, storeNames, mode, body) {
|
|
237
|
+
const transaction = database.transaction(storeNames, mode);
|
|
238
|
+
const done = new Promise((resolve, reject) => {
|
|
239
|
+
transaction.oncomplete = () => resolve();
|
|
240
|
+
transaction.onerror = () => reject(transaction.error ?? new Error("IndexedDB transaction failed"));
|
|
241
|
+
transaction.onabort = () => reject(transaction.error ?? new Error("IndexedDB transaction aborted"));
|
|
242
|
+
});
|
|
243
|
+
done.catch(() => void 0);
|
|
244
|
+
let result;
|
|
245
|
+
try {
|
|
246
|
+
result = await body(transaction);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
try {
|
|
249
|
+
transaction.abort();
|
|
250
|
+
} catch {
|
|
251
|
+
}
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
await done;
|
|
255
|
+
return result;
|
|
256
|
+
}
|
|
257
|
+
var IndexedDBDownloadCacheStore = class {
|
|
258
|
+
databaseName;
|
|
259
|
+
fallback = new InMemoryDownloadCacheStore();
|
|
260
|
+
databasePromise;
|
|
261
|
+
constructor(options = {}) {
|
|
262
|
+
this.databaseName = options.databaseName ?? CACHE_DATABASE_NAME;
|
|
263
|
+
}
|
|
264
|
+
async getFile(workspace, fileKey) {
|
|
265
|
+
const database = await this.openDatabase();
|
|
266
|
+
if (!database) {
|
|
267
|
+
return this.fallback.getFile(workspace, fileKey);
|
|
268
|
+
}
|
|
269
|
+
return runTransaction(database, [FILES_STORE], "readonly", async (transaction) => {
|
|
270
|
+
const file = await requestResult(
|
|
271
|
+
transaction.objectStore(FILES_STORE).get([workspace, fileKey])
|
|
272
|
+
);
|
|
273
|
+
return file ? copyFile(file) : null;
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
async putFile(workspace, fileKey, file) {
|
|
277
|
+
const database = await this.openDatabase();
|
|
278
|
+
if (!database) {
|
|
279
|
+
return this.fallback.putFile(workspace, fileKey, file);
|
|
280
|
+
}
|
|
281
|
+
await runTransaction(database, [FILES_STORE], "readwrite", async (transaction) => {
|
|
282
|
+
await requestResult(transaction.objectStore(FILES_STORE).put(copyFile(file), [workspace, fileKey]));
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
async removeFile(workspace, fileKey) {
|
|
286
|
+
const database = await this.openDatabase();
|
|
287
|
+
if (!database) {
|
|
288
|
+
return this.fallback.removeFile(workspace, fileKey);
|
|
289
|
+
}
|
|
290
|
+
await runTransaction(database, [FILES_STORE], "readwrite", async (transaction) => {
|
|
291
|
+
await requestResult(transaction.objectStore(FILES_STORE).delete([workspace, fileKey]));
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
async getChunk(workspace, storageKey) {
|
|
295
|
+
const database = await this.openDatabase();
|
|
296
|
+
if (!database) {
|
|
297
|
+
return this.fallback.getChunk(workspace, storageKey);
|
|
298
|
+
}
|
|
299
|
+
const key = [workspace, storageKey];
|
|
300
|
+
return runTransaction(
|
|
301
|
+
database,
|
|
302
|
+
[CHUNKS_STORE, CHUNK_DATA_STORE, META_STORE],
|
|
303
|
+
"readwrite",
|
|
304
|
+
async (transaction) => {
|
|
305
|
+
const chunks = transaction.objectStore(CHUNKS_STORE);
|
|
306
|
+
const record = await requestResult(chunks.get(key));
|
|
307
|
+
if (!record) {
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
const data = await requestResult(
|
|
311
|
+
transaction.objectStore(CHUNK_DATA_STORE).get(key)
|
|
312
|
+
);
|
|
313
|
+
const meta = transaction.objectStore(META_STORE);
|
|
314
|
+
if (!data) {
|
|
315
|
+
const bytes = await requestResult(meta.get(USAGE_KEY)) ?? 0;
|
|
316
|
+
await requestResult(chunks.delete(key));
|
|
317
|
+
await requestResult(meta.put(Math.max(bytes - record.size, 0), USAGE_KEY));
|
|
318
|
+
return null;
|
|
319
|
+
}
|
|
320
|
+
await requestResult(chunks.put({ size: record.size, lastUsed: await nextClock(meta) }, key));
|
|
321
|
+
return data;
|
|
322
|
+
}
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
async putChunk(workspace, storageKey, data, maxBytes) {
|
|
326
|
+
const database = await this.openDatabase();
|
|
327
|
+
if (!database) {
|
|
328
|
+
return this.fallback.putChunk(workspace, storageKey, data, maxBytes);
|
|
329
|
+
}
|
|
330
|
+
const key = [workspace, storageKey];
|
|
331
|
+
await runTransaction(
|
|
332
|
+
database,
|
|
333
|
+
[CHUNKS_STORE, CHUNK_DATA_STORE, META_STORE],
|
|
334
|
+
"readwrite",
|
|
335
|
+
async (transaction) => {
|
|
336
|
+
const chunks = transaction.objectStore(CHUNKS_STORE);
|
|
337
|
+
const chunkData = transaction.objectStore(CHUNK_DATA_STORE);
|
|
338
|
+
const meta = transaction.objectStore(META_STORE);
|
|
339
|
+
let bytes = await requestResult(meta.get(USAGE_KEY)) ?? 0;
|
|
340
|
+
const existing = await requestResult(chunks.get(key));
|
|
341
|
+
if (existing) {
|
|
342
|
+
bytes -= existing.size;
|
|
343
|
+
await requestResult(chunks.delete(key));
|
|
344
|
+
await requestResult(chunkData.delete(key));
|
|
345
|
+
}
|
|
346
|
+
if (data.size <= maxBytes) {
|
|
347
|
+
await requestResult(chunks.put({ size: data.size, lastUsed: await nextClock(meta) }, key));
|
|
348
|
+
await requestResult(chunkData.put(data, key));
|
|
349
|
+
bytes += data.size;
|
|
350
|
+
}
|
|
351
|
+
if (bytes > maxBytes) {
|
|
352
|
+
const cursorRequest = chunks.index(LRU_INDEX).openCursor();
|
|
353
|
+
let cursor = await requestResult(cursorRequest);
|
|
354
|
+
while (cursor && bytes > maxBytes) {
|
|
355
|
+
if (!sameKey(cursor.primaryKey, key)) {
|
|
356
|
+
bytes -= cursor.value.size;
|
|
357
|
+
await requestResult(chunkData.delete(cursor.primaryKey));
|
|
358
|
+
await requestResult(cursor.delete());
|
|
359
|
+
}
|
|
360
|
+
cursor.continue();
|
|
361
|
+
cursor = await requestResult(cursorRequest);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
await requestResult(meta.put(Math.max(bytes, 0), USAGE_KEY));
|
|
365
|
+
}
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
async clear(workspace) {
|
|
369
|
+
const database = await this.openDatabase();
|
|
370
|
+
if (!database) {
|
|
371
|
+
return this.fallback.clear(workspace);
|
|
372
|
+
}
|
|
373
|
+
await runTransaction(
|
|
374
|
+
database,
|
|
375
|
+
[FILES_STORE, CHUNKS_STORE, CHUNK_DATA_STORE, META_STORE],
|
|
376
|
+
"readwrite",
|
|
377
|
+
async (transaction) => {
|
|
378
|
+
const files = transaction.objectStore(FILES_STORE);
|
|
379
|
+
const chunks = transaction.objectStore(CHUNKS_STORE);
|
|
380
|
+
const chunkData = transaction.objectStore(CHUNK_DATA_STORE);
|
|
381
|
+
const meta = transaction.objectStore(META_STORE);
|
|
382
|
+
if (workspace === void 0) {
|
|
383
|
+
await requestResult(files.clear());
|
|
384
|
+
await requestResult(chunks.clear());
|
|
385
|
+
await requestResult(chunkData.clear());
|
|
386
|
+
await requestResult(meta.put(0, USAGE_KEY));
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
const range = workspaceRange(workspace);
|
|
390
|
+
const removed = await requestResult(chunks.getAll(range));
|
|
391
|
+
const bytes = await requestResult(meta.get(USAGE_KEY)) ?? 0;
|
|
392
|
+
await requestResult(files.delete(range));
|
|
393
|
+
await requestResult(chunks.delete(range));
|
|
394
|
+
await requestResult(chunkData.delete(range));
|
|
395
|
+
await requestResult(
|
|
396
|
+
meta.put(Math.max(bytes - removed.reduce((total, record) => total + record.size, 0), 0), USAGE_KEY)
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
async usage(workspace) {
|
|
402
|
+
const database = await this.openDatabase();
|
|
403
|
+
if (!database) {
|
|
404
|
+
return this.fallback.usage(workspace);
|
|
405
|
+
}
|
|
406
|
+
return runTransaction(database, [CHUNKS_STORE], "readonly", async (transaction) => {
|
|
407
|
+
const records = await requestResult(
|
|
408
|
+
transaction.objectStore(CHUNKS_STORE).getAll(workspace === void 0 ? void 0 : workspaceRange(workspace))
|
|
409
|
+
);
|
|
410
|
+
return {
|
|
411
|
+
bytes: records.reduce((total, record) => total + record.size, 0),
|
|
412
|
+
chunks: records.length
|
|
413
|
+
};
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
async openDatabase() {
|
|
417
|
+
if (!this.databasePromise) {
|
|
418
|
+
const indexedDb = getIndexedDb();
|
|
419
|
+
if (!indexedDb) {
|
|
420
|
+
this.databasePromise = Promise.resolve(null);
|
|
421
|
+
} else {
|
|
422
|
+
this.databasePromise = new Promise((resolve) => {
|
|
423
|
+
let request;
|
|
424
|
+
try {
|
|
425
|
+
request = indexedDb.open(this.databaseName, CACHE_DATABASE_VERSION);
|
|
426
|
+
} catch {
|
|
427
|
+
resolve(null);
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
request.onupgradeneeded = () => {
|
|
431
|
+
const database = request.result;
|
|
432
|
+
if (!database.objectStoreNames.contains(FILES_STORE)) {
|
|
433
|
+
database.createObjectStore(FILES_STORE);
|
|
434
|
+
}
|
|
435
|
+
if (!database.objectStoreNames.contains(CHUNKS_STORE)) {
|
|
436
|
+
database.createObjectStore(CHUNKS_STORE).createIndex(LRU_INDEX, "lastUsed");
|
|
437
|
+
}
|
|
438
|
+
if (!database.objectStoreNames.contains(CHUNK_DATA_STORE)) {
|
|
439
|
+
database.createObjectStore(CHUNK_DATA_STORE);
|
|
440
|
+
}
|
|
441
|
+
if (!database.objectStoreNames.contains(META_STORE)) {
|
|
442
|
+
database.createObjectStore(META_STORE);
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
request.onsuccess = () => {
|
|
446
|
+
const database = request.result;
|
|
447
|
+
database.onversionchange = () => {
|
|
448
|
+
database.close();
|
|
449
|
+
this.databasePromise = void 0;
|
|
450
|
+
};
|
|
451
|
+
resolve(database);
|
|
452
|
+
};
|
|
453
|
+
request.onerror = () => resolve(null);
|
|
454
|
+
request.onblocked = () => resolve(null);
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
return this.databasePromise;
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
function isImmutableStorageKey(storageKey) {
|
|
462
|
+
return /(?:^|\/)blobs\/sha256\/[0-9a-f]{64}$/.test(storageKey);
|
|
463
|
+
}
|
|
464
|
+
function workspaceCacheKey(baseUrl, selector) {
|
|
465
|
+
const workspaceCuid = selector.workspaceCuid?.trim();
|
|
466
|
+
const workspaceId = selector.workspaceId !== void 0 ? String(selector.workspaceId).trim() : "";
|
|
467
|
+
const workspace = workspaceCuid || workspaceId;
|
|
468
|
+
return workspace ? JSON.stringify([baseUrl, workspace]) : null;
|
|
469
|
+
}
|
|
470
|
+
function fileCacheKey(target) {
|
|
471
|
+
try {
|
|
472
|
+
if (target.ino !== void 0) {
|
|
473
|
+
return `ino:${BigInt(target.ino).toString()}`;
|
|
474
|
+
}
|
|
475
|
+
if (target.path !== void 0) {
|
|
476
|
+
return `path:${normalizePath(target.path)}`;
|
|
477
|
+
}
|
|
478
|
+
} catch {
|
|
479
|
+
}
|
|
480
|
+
return null;
|
|
481
|
+
}
|
|
482
|
+
function isValidLayout(file) {
|
|
483
|
+
let offset = 0;
|
|
484
|
+
for (const [index, chunk] of file.chunks.entries()) {
|
|
485
|
+
if (chunk.index !== index || chunk.offset !== offset || chunk.size < 0) {
|
|
486
|
+
return false;
|
|
487
|
+
}
|
|
488
|
+
offset += chunk.size;
|
|
489
|
+
}
|
|
490
|
+
return file.chunks.length > 0 && offset === file.size;
|
|
491
|
+
}
|
|
492
|
+
var DownloadCache = class {
|
|
493
|
+
maxBytes;
|
|
494
|
+
maxChunkBytes;
|
|
495
|
+
ttlMs;
|
|
496
|
+
store;
|
|
497
|
+
constructor(options) {
|
|
498
|
+
this.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
499
|
+
if (!Number.isSafeInteger(this.maxBytes) || this.maxBytes <= 0) {
|
|
500
|
+
throw new RangeError("downloadCache.maxBytes must be a positive safe integer");
|
|
501
|
+
}
|
|
502
|
+
const maxChunkBytes = options.maxChunkBytes ?? DEFAULT_MAX_CHUNK_BYTES;
|
|
503
|
+
if (!Number.isSafeInteger(maxChunkBytes) || maxChunkBytes <= 0) {
|
|
504
|
+
throw new RangeError("downloadCache.maxChunkBytes must be a positive safe integer");
|
|
505
|
+
}
|
|
506
|
+
this.maxChunkBytes = Math.min(maxChunkBytes, this.maxBytes);
|
|
507
|
+
this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
508
|
+
if (Number.isNaN(this.ttlMs) || this.ttlMs < 0) {
|
|
509
|
+
throw new RangeError("downloadCache.ttlMs must be a non-negative number");
|
|
510
|
+
}
|
|
511
|
+
this.store = options.store ?? new IndexedDBDownloadCacheStore();
|
|
512
|
+
}
|
|
513
|
+
/** Return a file that has not expired together with all of its chunk bytes. */
|
|
514
|
+
async loadFile(workspace, fileKey) {
|
|
515
|
+
try {
|
|
516
|
+
const file = await this.store.getFile(workspace, fileKey);
|
|
517
|
+
if (!file) {
|
|
518
|
+
return null;
|
|
519
|
+
}
|
|
520
|
+
if (file.expiresAt <= Date.now() || !isValidLayout(file)) {
|
|
521
|
+
await this.store.removeFile(workspace, fileKey);
|
|
522
|
+
return null;
|
|
523
|
+
}
|
|
524
|
+
const chunks = /* @__PURE__ */ new Map();
|
|
525
|
+
for (const chunk of file.chunks) {
|
|
526
|
+
const data = await this.readChunk(workspace, chunk);
|
|
527
|
+
if (!data) {
|
|
528
|
+
return null;
|
|
529
|
+
}
|
|
530
|
+
chunks.set(chunk.index, data);
|
|
531
|
+
}
|
|
532
|
+
return { file, chunks };
|
|
533
|
+
} catch {
|
|
534
|
+
return null;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
async readChunk(workspace, chunk) {
|
|
538
|
+
if (chunk.size === 0) {
|
|
539
|
+
return new Blob([]);
|
|
540
|
+
}
|
|
541
|
+
if (!isImmutableStorageKey(chunk.storageKey)) {
|
|
542
|
+
return null;
|
|
543
|
+
}
|
|
544
|
+
try {
|
|
545
|
+
const data = await this.store.getChunk(workspace, chunk.storageKey);
|
|
546
|
+
return data && data.size === chunk.size ? data : null;
|
|
547
|
+
} catch {
|
|
548
|
+
return null;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
canStoreChunk(chunk) {
|
|
552
|
+
return isImmutableStorageKey(chunk.storageKey) && chunk.size <= this.maxChunkBytes;
|
|
553
|
+
}
|
|
554
|
+
/** Returns whether the chunk is now cached. */
|
|
555
|
+
async storeChunk(workspace, chunk, data) {
|
|
556
|
+
if (chunk.size === 0) {
|
|
557
|
+
return true;
|
|
558
|
+
}
|
|
559
|
+
if (!this.canStoreChunk(chunk) || data.size !== chunk.size) {
|
|
560
|
+
return false;
|
|
561
|
+
}
|
|
562
|
+
try {
|
|
563
|
+
await this.store.putChunk(workspace, chunk.storageKey, data, this.maxBytes);
|
|
564
|
+
return true;
|
|
565
|
+
} catch {
|
|
566
|
+
return false;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
async storeFile(workspace, fileKey, file) {
|
|
570
|
+
if (this.ttlMs <= 0) {
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
const cachedAt = Date.now();
|
|
574
|
+
try {
|
|
575
|
+
await this.store.putFile(workspace, fileKey, {
|
|
576
|
+
path: file.path,
|
|
577
|
+
size: file.size,
|
|
578
|
+
...file.contentType ? { contentType: file.contentType } : {},
|
|
579
|
+
chunks: file.chunks.map(({ index, offset, size, storageKey }) => ({
|
|
580
|
+
index,
|
|
581
|
+
offset,
|
|
582
|
+
size,
|
|
583
|
+
storageKey
|
|
584
|
+
})),
|
|
585
|
+
cachedAt,
|
|
586
|
+
expiresAt: cachedAt + this.ttlMs
|
|
587
|
+
});
|
|
588
|
+
} catch {
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
async invalidateFiles(workspace, fileKeys) {
|
|
592
|
+
await Promise.all(
|
|
593
|
+
fileKeys.map((fileKey) => this.store.removeFile(workspace, fileKey).catch(() => void 0))
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
clear(workspace) {
|
|
597
|
+
return this.store.clear(workspace);
|
|
598
|
+
}
|
|
599
|
+
usage(workspace) {
|
|
600
|
+
return this.store.usage(workspace);
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
|
|
604
|
+
// src/download.ts
|
|
605
|
+
function copyCheckpoint(checkpoint) {
|
|
606
|
+
return {
|
|
607
|
+
...checkpoint,
|
|
608
|
+
request: { ...checkpoint.request },
|
|
609
|
+
chunks: checkpoint.chunks.map((chunk) => ({ ...chunk }))
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
var InMemoryDownloadCheckpointStore = class {
|
|
613
|
+
records = /* @__PURE__ */ new Map();
|
|
614
|
+
async load(key) {
|
|
615
|
+
const value = this.records.get(key);
|
|
616
|
+
return value ? copyCheckpoint(value) : null;
|
|
617
|
+
}
|
|
618
|
+
async save(key, checkpoint) {
|
|
619
|
+
this.records.set(key, copyCheckpoint(checkpoint));
|
|
620
|
+
}
|
|
621
|
+
async remove(key) {
|
|
622
|
+
this.records.delete(key);
|
|
623
|
+
}
|
|
624
|
+
async list() {
|
|
625
|
+
return [...this.records.values()].map(copyCheckpoint);
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
var DOWNLOAD_DATABASE_NAME = "mountra-sdk";
|
|
629
|
+
var DOWNLOAD_DATABASE_VERSION = 1;
|
|
630
|
+
var DOWNLOAD_STORE_NAME = "download-checkpoints";
|
|
631
|
+
function getIndexedDb2() {
|
|
632
|
+
return globalThis.indexedDB ?? null;
|
|
633
|
+
}
|
|
634
|
+
var IndexedDBDownloadCheckpointStore = class {
|
|
635
|
+
fallback = new InMemoryDownloadCheckpointStore();
|
|
636
|
+
databasePromise;
|
|
637
|
+
async load(key) {
|
|
638
|
+
const database = await this.openDatabase();
|
|
639
|
+
if (!database) {
|
|
640
|
+
return this.fallback.load(key);
|
|
641
|
+
}
|
|
642
|
+
try {
|
|
643
|
+
const value = await this.request(
|
|
644
|
+
database,
|
|
645
|
+
"readonly",
|
|
646
|
+
(store) => store.get(key)
|
|
647
|
+
);
|
|
648
|
+
return value ? copyCheckpoint(value) : null;
|
|
649
|
+
} catch {
|
|
650
|
+
return this.fallback.load(key);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
async save(key, checkpoint) {
|
|
654
|
+
const value = copyCheckpoint(checkpoint);
|
|
655
|
+
const database = await this.openDatabase();
|
|
656
|
+
if (!database) {
|
|
657
|
+
await this.fallback.save(key, value);
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
try {
|
|
661
|
+
await this.request(database, "readwrite", (store) => store.put(value, key));
|
|
662
|
+
} catch {
|
|
663
|
+
await this.fallback.save(key, value);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
async remove(key) {
|
|
667
|
+
const database = await this.openDatabase();
|
|
668
|
+
if (!database) {
|
|
669
|
+
await this.fallback.remove(key);
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
try {
|
|
673
|
+
await this.request(database, "readwrite", (store) => store.delete(key));
|
|
674
|
+
} catch {
|
|
675
|
+
await this.fallback.remove(key);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
async list() {
|
|
679
|
+
const database = await this.openDatabase();
|
|
680
|
+
if (!database) {
|
|
681
|
+
return this.fallback.list();
|
|
682
|
+
}
|
|
683
|
+
try {
|
|
684
|
+
const values = await this.request(
|
|
685
|
+
database,
|
|
686
|
+
"readonly",
|
|
687
|
+
(store) => store.getAll()
|
|
688
|
+
);
|
|
689
|
+
return values.map(copyCheckpoint);
|
|
690
|
+
} catch {
|
|
691
|
+
return this.fallback.list();
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
async openDatabase() {
|
|
695
|
+
if (!this.databasePromise) {
|
|
696
|
+
const indexedDb = getIndexedDb2();
|
|
697
|
+
if (!indexedDb) {
|
|
698
|
+
this.databasePromise = Promise.resolve(null);
|
|
699
|
+
} else {
|
|
700
|
+
this.databasePromise = new Promise((resolve) => {
|
|
701
|
+
let request;
|
|
702
|
+
try {
|
|
703
|
+
request = indexedDb.open(DOWNLOAD_DATABASE_NAME, DOWNLOAD_DATABASE_VERSION);
|
|
704
|
+
} catch {
|
|
705
|
+
resolve(null);
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
request.onupgradeneeded = () => {
|
|
709
|
+
if (!request.result.objectStoreNames.contains(DOWNLOAD_STORE_NAME)) {
|
|
710
|
+
request.result.createObjectStore(DOWNLOAD_STORE_NAME);
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
request.onsuccess = () => resolve(request.result);
|
|
714
|
+
request.onerror = () => resolve(null);
|
|
715
|
+
request.onblocked = () => resolve(null);
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
return this.databasePromise;
|
|
720
|
+
}
|
|
721
|
+
request(database, mode, createRequest) {
|
|
722
|
+
return new Promise((resolve, reject) => {
|
|
723
|
+
let transaction;
|
|
724
|
+
let request;
|
|
725
|
+
try {
|
|
726
|
+
transaction = database.transaction(DOWNLOAD_STORE_NAME, mode);
|
|
727
|
+
request = createRequest(transaction.objectStore(DOWNLOAD_STORE_NAME));
|
|
728
|
+
} catch (error) {
|
|
729
|
+
reject(error);
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
let result;
|
|
733
|
+
request.onsuccess = () => {
|
|
734
|
+
result = request.result;
|
|
735
|
+
};
|
|
736
|
+
request.onerror = () => reject(request.error ?? new Error("IndexedDB request failed"));
|
|
737
|
+
transaction.oncomplete = () => resolve(result);
|
|
738
|
+
transaction.onerror = () => reject(transaction.error ?? new Error("IndexedDB transaction failed"));
|
|
739
|
+
transaction.onabort = () => reject(transaction.error ?? new Error("IndexedDB transaction aborted"));
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
var DownloadHttpError = class extends Error {
|
|
744
|
+
status;
|
|
745
|
+
constructor(status, message) {
|
|
746
|
+
super(message);
|
|
747
|
+
this.name = "DownloadHttpError";
|
|
748
|
+
this.status = status;
|
|
749
|
+
}
|
|
750
|
+
};
|
|
751
|
+
function getShowSaveFilePicker() {
|
|
752
|
+
return globalThis.showSaveFilePicker ?? null;
|
|
753
|
+
}
|
|
754
|
+
function isRecord(value) {
|
|
755
|
+
return typeof value === "object" && value !== null;
|
|
756
|
+
}
|
|
757
|
+
function readSafeNumber(value, field) {
|
|
758
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
|
|
759
|
+
throw new TypeError(`Mountra export response field ${field} is invalid`);
|
|
760
|
+
}
|
|
761
|
+
return value;
|
|
762
|
+
}
|
|
763
|
+
function readString(value, field) {
|
|
764
|
+
if (typeof value !== "string" || !value) {
|
|
765
|
+
throw new TypeError(`Mountra export response field ${field} is invalid`);
|
|
766
|
+
}
|
|
767
|
+
return value;
|
|
768
|
+
}
|
|
769
|
+
function ensureExportFileResponse(value) {
|
|
770
|
+
if (!isRecord(value)) {
|
|
771
|
+
throw new TypeError("Mountra export response is invalid");
|
|
772
|
+
}
|
|
773
|
+
const response = {
|
|
774
|
+
path: readString(value.path, "path"),
|
|
775
|
+
storageKey: readString(value.storage_key, "storage_key"),
|
|
776
|
+
url: readString(value.url, "url"),
|
|
777
|
+
timeout: readSafeNumber(value.timeout, "timeout"),
|
|
778
|
+
size: readSafeNumber(value.size, "size")
|
|
779
|
+
};
|
|
780
|
+
try {
|
|
781
|
+
new URL(response.url);
|
|
782
|
+
} catch {
|
|
783
|
+
throw new TypeError("Mountra export response field url is invalid");
|
|
784
|
+
}
|
|
785
|
+
if (typeof value.content_type === "string" && value.content_type) {
|
|
786
|
+
response.contentType = value.content_type;
|
|
787
|
+
}
|
|
788
|
+
if (typeof value.chunk_method === "string") {
|
|
789
|
+
response.chunkMethod = value.chunk_method;
|
|
790
|
+
}
|
|
791
|
+
if (typeof value.is_fast_path === "boolean") {
|
|
792
|
+
response.isFastPath = value.is_fast_path;
|
|
793
|
+
}
|
|
794
|
+
if (Array.isArray(value.chunks)) {
|
|
795
|
+
response.chunks = value.chunks.map((rawChunk, position) => {
|
|
796
|
+
if (!isRecord(rawChunk)) {
|
|
797
|
+
throw new TypeError(`Mountra export response chunk ${position} is invalid`);
|
|
798
|
+
}
|
|
799
|
+
const chunk = {
|
|
800
|
+
index: readSafeNumber(rawChunk.index, `chunks[${position}].index`),
|
|
801
|
+
offset: readSafeNumber(rawChunk.offset, `chunks[${position}].offset`),
|
|
802
|
+
size: readSafeNumber(rawChunk.size, `chunks[${position}].size`),
|
|
803
|
+
storageKey: readString(rawChunk.storage_key, `chunks[${position}].storage_key`),
|
|
804
|
+
url: readString(rawChunk.url, `chunks[${position}].url`)
|
|
805
|
+
};
|
|
806
|
+
try {
|
|
807
|
+
new URL(chunk.url);
|
|
808
|
+
} catch {
|
|
809
|
+
throw new TypeError(`Mountra export response chunk ${position} URL is invalid`);
|
|
810
|
+
}
|
|
811
|
+
return chunk;
|
|
812
|
+
});
|
|
813
|
+
response.chunks.sort((left, right) => left.index - right.index);
|
|
814
|
+
response.chunks.forEach((chunk, index) => {
|
|
815
|
+
if (chunk.index !== index || chunk.offset + chunk.size > response.size || index > 0 && response.chunks[index - 1].offset + response.chunks[index - 1].size !== chunk.offset) {
|
|
816
|
+
throw new TypeError("Mountra export response has an invalid chunk layout");
|
|
817
|
+
}
|
|
818
|
+
});
|
|
819
|
+
const finalChunk = response.chunks[response.chunks.length - 1];
|
|
820
|
+
if (finalChunk && finalChunk.offset + finalChunk.size !== response.size) {
|
|
821
|
+
throw new TypeError("Mountra export response chunks do not cover the complete file");
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
return response;
|
|
825
|
+
}
|
|
826
|
+
function validateRetryOption(value, name) {
|
|
827
|
+
if (value === void 0) {
|
|
828
|
+
return void 0;
|
|
829
|
+
}
|
|
830
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
831
|
+
throw new RangeError(`${name} must be a non-negative safe integer`);
|
|
832
|
+
}
|
|
833
|
+
return value;
|
|
834
|
+
}
|
|
835
|
+
function throwIfAborted(signal) {
|
|
836
|
+
if (signal?.aborted) {
|
|
837
|
+
throw new DOMException("The download was aborted", "AbortError");
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
function isAbortError(error, signal) {
|
|
841
|
+
return signal?.aborted === true || error instanceof DOMException && error.name === "AbortError";
|
|
842
|
+
}
|
|
843
|
+
function isRetryableError(error) {
|
|
844
|
+
if (error instanceof DownloadHttpError) {
|
|
845
|
+
return [408, 425, 429, 500, 502, 503, 504].includes(error.status);
|
|
846
|
+
}
|
|
847
|
+
return true;
|
|
848
|
+
}
|
|
849
|
+
function waitForRetry(delayMs, signal) {
|
|
850
|
+
if (delayMs <= 0) {
|
|
851
|
+
throwIfAborted(signal);
|
|
852
|
+
return Promise.resolve();
|
|
853
|
+
}
|
|
854
|
+
return new Promise((resolve, reject) => {
|
|
855
|
+
let timer;
|
|
856
|
+
const onAbort = () => {
|
|
857
|
+
if (timer !== void 0) {
|
|
858
|
+
clearTimeout(timer);
|
|
859
|
+
}
|
|
860
|
+
signal?.removeEventListener("abort", onAbort);
|
|
861
|
+
reject(new DOMException("The download was aborted", "AbortError"));
|
|
862
|
+
};
|
|
863
|
+
timer = setTimeout(() => {
|
|
864
|
+
signal?.removeEventListener("abort", onAbort);
|
|
865
|
+
resolve();
|
|
866
|
+
}, delayMs);
|
|
867
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
868
|
+
if (signal?.aborted) {
|
|
869
|
+
onAbort();
|
|
870
|
+
}
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
var SpeedWindow = class {
|
|
874
|
+
samples = [];
|
|
875
|
+
record(bytes, at) {
|
|
876
|
+
this.samples.push({ at, bytes });
|
|
877
|
+
const cutoff = at - 1e3;
|
|
878
|
+
while (this.samples.length > 1 && this.samples[0].at < cutoff) {
|
|
879
|
+
this.samples.shift();
|
|
880
|
+
}
|
|
881
|
+
const first = this.samples[0];
|
|
882
|
+
if (!first || first.bytes === bytes) {
|
|
883
|
+
return 0;
|
|
884
|
+
}
|
|
885
|
+
const seconds = Math.max((at - first.at) / 1e3, 1e-3);
|
|
886
|
+
return (bytes - first.bytes) / seconds;
|
|
887
|
+
}
|
|
888
|
+
};
|
|
889
|
+
var BlobDownloadSink = class {
|
|
890
|
+
parts = [];
|
|
891
|
+
/** Parts arrive in file order, so the position is implied. */
|
|
892
|
+
async write(bytes, _position) {
|
|
893
|
+
this.parts.push(bytes instanceof Blob ? bytes : bytes.slice());
|
|
894
|
+
}
|
|
895
|
+
async flush() {
|
|
896
|
+
}
|
|
897
|
+
async finalize() {
|
|
898
|
+
}
|
|
899
|
+
blob(contentType) {
|
|
900
|
+
const buffers = this.parts.map((part) => {
|
|
901
|
+
if (part instanceof Blob) {
|
|
902
|
+
return part;
|
|
903
|
+
}
|
|
904
|
+
const buffer = new ArrayBuffer(part.byteLength);
|
|
905
|
+
new Uint8Array(buffer).set(part);
|
|
906
|
+
return buffer;
|
|
907
|
+
});
|
|
908
|
+
return new Blob(buffers, contentType ? { type: contentType } : void 0);
|
|
909
|
+
}
|
|
910
|
+
};
|
|
911
|
+
var FileSystemDownloadSink = class {
|
|
912
|
+
constructor(handle) {
|
|
913
|
+
this.handle = handle;
|
|
914
|
+
}
|
|
915
|
+
handle;
|
|
916
|
+
writable = null;
|
|
917
|
+
position = 0;
|
|
918
|
+
openedOnce = false;
|
|
919
|
+
async write(bytes, position) {
|
|
920
|
+
if (!this.writable) {
|
|
921
|
+
const keepExistingData = this.openedOnce || position > 0;
|
|
922
|
+
this.writable = await this.handle.createWritable({ keepExistingData });
|
|
923
|
+
if (position > 0) {
|
|
924
|
+
await this.writable.seek(position);
|
|
925
|
+
}
|
|
926
|
+
this.position = position;
|
|
927
|
+
this.openedOnce = true;
|
|
928
|
+
}
|
|
929
|
+
if (this.position !== position) {
|
|
930
|
+
throw new Error("File System Access writer position does not match the download checkpoint");
|
|
931
|
+
}
|
|
932
|
+
await this.writable.write(bytes);
|
|
933
|
+
this.position += bytes instanceof Blob ? bytes.size : bytes.byteLength;
|
|
934
|
+
}
|
|
935
|
+
async flush() {
|
|
936
|
+
if (this.writable) {
|
|
937
|
+
const writable = this.writable;
|
|
938
|
+
await writable.close();
|
|
939
|
+
this.writable = null;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
async finalize(size) {
|
|
943
|
+
if (!this.writable) {
|
|
944
|
+
this.writable = await this.handle.createWritable({ keepExistingData: this.openedOnce });
|
|
945
|
+
this.openedOnce = true;
|
|
946
|
+
await this.writable.seek(size);
|
|
947
|
+
}
|
|
948
|
+
await this.writable.truncate(size);
|
|
949
|
+
const writable = this.writable;
|
|
950
|
+
this.writable = null;
|
|
951
|
+
await writable.close();
|
|
952
|
+
}
|
|
953
|
+
async abort() {
|
|
954
|
+
if (!this.writable) {
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
const writable = this.writable;
|
|
958
|
+
this.writable = null;
|
|
959
|
+
if (writable.abort) {
|
|
960
|
+
await writable.abort();
|
|
961
|
+
} else {
|
|
962
|
+
await writable.close();
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
};
|
|
966
|
+
function downloadRequestFromOptions(options) {
|
|
967
|
+
if (options.path === void 0 && options.ino === void 0) {
|
|
968
|
+
throw new TypeError("download target requires path or ino");
|
|
969
|
+
}
|
|
970
|
+
if (options.path !== void 0 && !options.path.trim()) {
|
|
971
|
+
throw new TypeError("download path cannot be empty");
|
|
972
|
+
}
|
|
973
|
+
return {
|
|
974
|
+
...options.workspaceCuid !== void 0 ? { workspaceCuid: options.workspaceCuid } : {},
|
|
975
|
+
...options.workspaceId !== void 0 ? { workspaceId: options.workspaceId } : {},
|
|
976
|
+
...options.path !== void 0 ? { path: options.path } : {},
|
|
977
|
+
...options.ino !== void 0 ? { ino: options.ino } : {},
|
|
978
|
+
...options.timeout !== void 0 ? { timeout: options.timeout } : {},
|
|
979
|
+
...options.contentDisposition !== void 0 ? { contentDisposition: options.contentDisposition } : {},
|
|
980
|
+
...options.downloadFilename !== void 0 ? { downloadFilename: options.downloadFilename } : {}
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
function requestBodyFromCheckpoint(request) {
|
|
984
|
+
return {
|
|
985
|
+
...request.workspaceCuid !== void 0 ? { workspace_cuid: request.workspaceCuid } : {},
|
|
986
|
+
...request.workspaceId !== void 0 ? { workspace_id: request.workspaceId } : {},
|
|
987
|
+
...request.path !== void 0 ? { path: request.path } : {},
|
|
988
|
+
...request.ino !== void 0 ? { ino: request.ino } : {},
|
|
989
|
+
...request.timeout !== void 0 ? { timeout: request.timeout } : {},
|
|
990
|
+
...request.contentDisposition !== void 0 ? { content_disposition: request.contentDisposition } : {},
|
|
991
|
+
...request.downloadFilename !== void 0 ? { download_filename: request.downloadFilename } : {}
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
function requestKey(request, baseUrl) {
|
|
995
|
+
return encodeURIComponent(
|
|
996
|
+
JSON.stringify({
|
|
997
|
+
baseUrl,
|
|
998
|
+
workspaceCuid: request.workspaceCuid ?? null,
|
|
999
|
+
workspaceId: request.workspaceId ?? null,
|
|
1000
|
+
path: request.path ?? null,
|
|
1001
|
+
ino: request.ino ?? null
|
|
1002
|
+
})
|
|
1003
|
+
);
|
|
1004
|
+
}
|
|
1005
|
+
function buildDownloadChunks(exported, useClientAssembly) {
|
|
1006
|
+
if (useClientAssembly && exported.chunks && exported.chunks.length > 1) {
|
|
1007
|
+
return exported.chunks;
|
|
1008
|
+
}
|
|
1009
|
+
return [
|
|
1010
|
+
{
|
|
1011
|
+
index: 0,
|
|
1012
|
+
offset: 0,
|
|
1013
|
+
size: exported.size,
|
|
1014
|
+
storageKey: exported.storageKey,
|
|
1015
|
+
url: exported.url
|
|
1016
|
+
}
|
|
1017
|
+
];
|
|
1018
|
+
}
|
|
1019
|
+
function buildDownloadKey(plan, baseUrl, request) {
|
|
1020
|
+
return encodeURIComponent(
|
|
1021
|
+
JSON.stringify({
|
|
1022
|
+
request: requestKey(request, baseUrl),
|
|
1023
|
+
path: plan.path,
|
|
1024
|
+
size: plan.size,
|
|
1025
|
+
chunks: plan.chunks.map((chunk) => [chunk.index, chunk.offset, chunk.size, chunk.storageKey])
|
|
1026
|
+
})
|
|
1027
|
+
);
|
|
1028
|
+
}
|
|
1029
|
+
function checkpointMatches(checkpoint, plan) {
|
|
1030
|
+
if (checkpoint.version !== 1 || checkpoint.path !== plan.path || checkpoint.size !== plan.size) {
|
|
1031
|
+
return false;
|
|
1032
|
+
}
|
|
1033
|
+
if (checkpoint.chunks.length !== plan.chunks.length) {
|
|
1034
|
+
return false;
|
|
1035
|
+
}
|
|
1036
|
+
return checkpoint.chunks.every((saved, index) => {
|
|
1037
|
+
const current = plan.chunks[index];
|
|
1038
|
+
return Boolean(
|
|
1039
|
+
current && saved.index === current.index && saved.offset === current.offset && saved.size === current.size && saved.storageKey === current.storageKey && saved.downloadedBytes >= 0 && saved.downloadedBytes <= saved.size
|
|
1040
|
+
);
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
function createCheckpoint(key, baseUrl, request, plan, fileHandle) {
|
|
1044
|
+
return {
|
|
1045
|
+
version: 1,
|
|
1046
|
+
key,
|
|
1047
|
+
requestKey: requestKey(request, baseUrl),
|
|
1048
|
+
request: { ...request },
|
|
1049
|
+
path: plan.path,
|
|
1050
|
+
size: plan.size,
|
|
1051
|
+
chunks: plan.chunks.map((chunk) => ({
|
|
1052
|
+
index: chunk.index,
|
|
1053
|
+
offset: chunk.offset,
|
|
1054
|
+
size: chunk.size,
|
|
1055
|
+
storageKey: chunk.storageKey,
|
|
1056
|
+
downloadedBytes: 0,
|
|
1057
|
+
completed: chunk.size === 0
|
|
1058
|
+
})),
|
|
1059
|
+
...fileHandle ? { fileHandle } : {},
|
|
1060
|
+
updatedAt: Date.now()
|
|
1061
|
+
};
|
|
1062
|
+
}
|
|
1063
|
+
function totalDownloadedBytes(checkpoint) {
|
|
1064
|
+
return checkpoint.chunks.reduce((total, chunk) => total + chunk.downloadedBytes, 0);
|
|
1065
|
+
}
|
|
1066
|
+
function completedChunkCount(checkpoint) {
|
|
1067
|
+
return checkpoint.chunks.filter((chunk) => chunk.completed).length;
|
|
1068
|
+
}
|
|
1069
|
+
function defaultFilename(path, requested) {
|
|
1070
|
+
const candidate = requested?.trim() || path.split("/").filter(Boolean).pop() || "download";
|
|
1071
|
+
return candidate.replace(/[\\/\r\n]/g, "_") || "download";
|
|
1072
|
+
}
|
|
1073
|
+
function triggerBrowserDownload(blob, filename) {
|
|
1074
|
+
const documentValue = globalThis.document;
|
|
1075
|
+
const urlApi = globalThis.URL;
|
|
1076
|
+
if (!documentValue || !urlApi?.createObjectURL) {
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
const url = urlApi.createObjectURL(blob);
|
|
1080
|
+
const anchor = documentValue.createElement("a");
|
|
1081
|
+
anchor.href = url;
|
|
1082
|
+
anchor.download = filename;
|
|
1083
|
+
anchor.style.display = "none";
|
|
1084
|
+
documentValue.body?.appendChild(anchor);
|
|
1085
|
+
anchor.click();
|
|
1086
|
+
anchor.remove();
|
|
1087
|
+
setTimeout(() => urlApi.revokeObjectURL(url), 0);
|
|
1088
|
+
}
|
|
1089
|
+
var MountraDownloader = class {
|
|
1090
|
+
transport;
|
|
1091
|
+
constructor(transport) {
|
|
1092
|
+
this.transport = transport;
|
|
1093
|
+
}
|
|
1094
|
+
async exportFile(options) {
|
|
1095
|
+
return this.exportRequest(this.resolveRequest(options), options.signal);
|
|
1096
|
+
}
|
|
1097
|
+
async downloadFile(options) {
|
|
1098
|
+
const preferFileSystemAccess = options.preferFileSystemAccess !== false;
|
|
1099
|
+
const fileHandle = options.fileHandle ?? (preferFileSystemAccess && getShowSaveFilePicker() ? await this.pickSaveFile(options.downloadFilename ?? options.path?.split("/").filter(Boolean).pop()) : void 0);
|
|
1100
|
+
const request = this.resolveRequest(options);
|
|
1101
|
+
const plan = await this.loadCachedPlan(request, options.cache) ?? this.planExport(
|
|
1102
|
+
await this.exportRequest(request, options.signal),
|
|
1103
|
+
request,
|
|
1104
|
+
options.cache,
|
|
1105
|
+
fileHandle
|
|
1106
|
+
);
|
|
1107
|
+
return this.downloadResolved(plan, request, options, fileHandle, false);
|
|
1108
|
+
}
|
|
1109
|
+
async downloadExport(exported, options = { path: exported.path }) {
|
|
1110
|
+
let fileHandle = options.fileHandle;
|
|
1111
|
+
if (!fileHandle && options.preferFileSystemAccess !== false && getShowSaveFilePicker()) {
|
|
1112
|
+
fileHandle = await this.pickSaveFile(
|
|
1113
|
+
options.downloadFilename ?? defaultFilename(exported.path),
|
|
1114
|
+
exported.contentType
|
|
1115
|
+
);
|
|
1116
|
+
}
|
|
1117
|
+
const request = this.resolveRequest(
|
|
1118
|
+
options.path === void 0 && options.ino === void 0 ? { ...options, path: exported.path } : options
|
|
1119
|
+
);
|
|
1120
|
+
return this.downloadResolved(
|
|
1121
|
+
this.planExport(exported, request, options.cache, fileHandle),
|
|
1122
|
+
request,
|
|
1123
|
+
options,
|
|
1124
|
+
fileHandle,
|
|
1125
|
+
false
|
|
1126
|
+
);
|
|
1127
|
+
}
|
|
1128
|
+
async resumeDownload(downloadKey, options = {}) {
|
|
1129
|
+
if (!downloadKey.trim()) {
|
|
1130
|
+
throw new TypeError("downloadKey is required");
|
|
1131
|
+
}
|
|
1132
|
+
const checkpoint = await this.transport.checkpointStore.load(downloadKey);
|
|
1133
|
+
if (!checkpoint || !checkpoint.fileHandle) {
|
|
1134
|
+
throw new Error("No resumable File System Access download was found");
|
|
1135
|
+
}
|
|
1136
|
+
await this.ensureWritePermission(checkpoint.fileHandle);
|
|
1137
|
+
const exported = await this.exportFile({
|
|
1138
|
+
...checkpoint.request,
|
|
1139
|
+
signal: options.signal
|
|
1140
|
+
});
|
|
1141
|
+
return this.downloadResolved(
|
|
1142
|
+
this.planExport(exported, checkpoint.request, void 0, checkpoint.fileHandle),
|
|
1143
|
+
checkpoint.request,
|
|
1144
|
+
options,
|
|
1145
|
+
checkpoint.fileHandle,
|
|
1146
|
+
true
|
|
1147
|
+
);
|
|
1148
|
+
}
|
|
1149
|
+
listResumableDownloads() {
|
|
1150
|
+
return this.transport.checkpointStore.list();
|
|
1151
|
+
}
|
|
1152
|
+
clearDownloadCheckpoint(downloadKey) {
|
|
1153
|
+
return this.transport.checkpointStore.remove(downloadKey);
|
|
1154
|
+
}
|
|
1155
|
+
/** Drop the cached layout of a file that was just written, so the next download sees the new content. */
|
|
1156
|
+
async invalidateCachedFile(selector, target) {
|
|
1157
|
+
await this.cachedFileScope(selector, target)?.invalidate();
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Cache a file this client just uploaded, so downloading it needs no
|
|
1161
|
+
* network. Falls back to invalidation when any chunk cannot be cached.
|
|
1162
|
+
*/
|
|
1163
|
+
async cacheUploadedFile(selector, file, mode = "default") {
|
|
1164
|
+
const scope = this.cachedFileScope(selector, file);
|
|
1165
|
+
if (!scope) {
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
await scope.invalidate();
|
|
1169
|
+
if (mode === "no-store") {
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
let complete = true;
|
|
1173
|
+
for (const chunk of file.chunks) {
|
|
1174
|
+
complete = await scope.cache.storeChunk(scope.workspace, chunk, chunk.data) && complete;
|
|
1175
|
+
}
|
|
1176
|
+
if (complete) {
|
|
1177
|
+
for (const fileKey of scope.fileKeys) {
|
|
1178
|
+
await scope.cache.storeFile(scope.workspace, fileKey, file);
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
cachedFileScope(selector, target) {
|
|
1183
|
+
const cache = this.transport.cache;
|
|
1184
|
+
const workspace = workspaceCacheKey(this.transport.baseUrl, selector);
|
|
1185
|
+
if (!cache || workspace === null) {
|
|
1186
|
+
return null;
|
|
1187
|
+
}
|
|
1188
|
+
const fileKeys = [
|
|
1189
|
+
target.path !== void 0 ? fileCacheKey({ path: target.path }) : null,
|
|
1190
|
+
target.ino !== void 0 ? fileCacheKey({ ino: target.ino }) : null
|
|
1191
|
+
].filter((fileKey) => fileKey !== null);
|
|
1192
|
+
return {
|
|
1193
|
+
cache,
|
|
1194
|
+
workspace,
|
|
1195
|
+
fileKeys,
|
|
1196
|
+
invalidate: () => cache.invalidateFiles(workspace, fileKeys)
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
async clearCache(selector) {
|
|
1200
|
+
const cache = this.transport.cache;
|
|
1201
|
+
if (!cache) {
|
|
1202
|
+
return;
|
|
1203
|
+
}
|
|
1204
|
+
await cache.clear(selector === void 0 ? void 0 : this.requireCacheWorkspace(selector));
|
|
1205
|
+
}
|
|
1206
|
+
async cacheUsage(selector) {
|
|
1207
|
+
const cache = this.transport.cache;
|
|
1208
|
+
if (!cache) {
|
|
1209
|
+
return { bytes: 0, chunks: 0 };
|
|
1210
|
+
}
|
|
1211
|
+
return cache.usage(selector === void 0 ? void 0 : this.requireCacheWorkspace(selector));
|
|
1212
|
+
}
|
|
1213
|
+
requireCacheWorkspace(selector) {
|
|
1214
|
+
const workspace = workspaceCacheKey(this.transport.baseUrl, selector);
|
|
1215
|
+
if (workspace === null) {
|
|
1216
|
+
throw new TypeError("workspaceCuid or workspaceId is required");
|
|
1217
|
+
}
|
|
1218
|
+
return workspace;
|
|
1219
|
+
}
|
|
1220
|
+
/** Fall back to the client workspace only when the request names none, as uploads do. */
|
|
1221
|
+
resolveRequest(options) {
|
|
1222
|
+
const hasWorkspace = options.workspaceCuid !== void 0 || options.workspaceId !== void 0;
|
|
1223
|
+
return downloadRequestFromOptions(
|
|
1224
|
+
hasWorkspace ? options : {
|
|
1225
|
+
...options,
|
|
1226
|
+
workspaceCuid: this.transport.clientSelector.workspaceCuid,
|
|
1227
|
+
workspaceId: this.transport.clientSelector.workspaceId
|
|
1228
|
+
}
|
|
1229
|
+
);
|
|
1230
|
+
}
|
|
1231
|
+
async exportRequest(request, signal) {
|
|
1232
|
+
return ensureExportFileResponse(
|
|
1233
|
+
await this.transport.requestJson("/file/export", requestBodyFromCheckpoint(request), signal)
|
|
1234
|
+
);
|
|
1235
|
+
}
|
|
1236
|
+
cacheScope(request, mode = "default") {
|
|
1237
|
+
const cache = this.transport.cache;
|
|
1238
|
+
if (!cache || mode === "no-store") {
|
|
1239
|
+
return null;
|
|
1240
|
+
}
|
|
1241
|
+
const workspace = workspaceCacheKey(this.transport.baseUrl, request);
|
|
1242
|
+
const fileKey = fileCacheKey(request);
|
|
1243
|
+
return workspace !== null && fileKey !== null ? { cache, workspace, fileKey } : null;
|
|
1244
|
+
}
|
|
1245
|
+
/** A plan that needs no network at all, when the cached layout is fresh and every chunk is cached. */
|
|
1246
|
+
async loadCachedPlan(request, mode) {
|
|
1247
|
+
const scope = this.cacheScope(request, mode);
|
|
1248
|
+
if (!scope || mode === "no-cache") {
|
|
1249
|
+
return null;
|
|
1250
|
+
}
|
|
1251
|
+
const cached = await scope.cache.loadFile(scope.workspace, scope.fileKey);
|
|
1252
|
+
if (!cached) {
|
|
1253
|
+
return null;
|
|
1254
|
+
}
|
|
1255
|
+
return {
|
|
1256
|
+
path: cached.file.path,
|
|
1257
|
+
size: cached.file.size,
|
|
1258
|
+
...cached.file.contentType ? { contentType: cached.file.contentType } : {},
|
|
1259
|
+
chunks: cached.file.chunks,
|
|
1260
|
+
cachedChunks: cached.chunks
|
|
1261
|
+
};
|
|
1262
|
+
}
|
|
1263
|
+
planExport(exported, request, mode, fileHandle) {
|
|
1264
|
+
const useClientAssembly = (exported.chunks?.length ?? 0) > 1 && (Boolean(fileHandle) || this.cacheScope(request, mode) !== null);
|
|
1265
|
+
return {
|
|
1266
|
+
path: exported.path,
|
|
1267
|
+
size: exported.size,
|
|
1268
|
+
...exported.contentType ? { contentType: exported.contentType } : {},
|
|
1269
|
+
chunks: buildDownloadChunks(exported, useClientAssembly),
|
|
1270
|
+
exported
|
|
1271
|
+
};
|
|
1272
|
+
}
|
|
1273
|
+
async pickSaveFile(requestedFilename, contentType) {
|
|
1274
|
+
const picker = getShowSaveFilePicker();
|
|
1275
|
+
if (!picker) {
|
|
1276
|
+
throw new Error("File System Access API is not available");
|
|
1277
|
+
}
|
|
1278
|
+
const types = contentType ? [{ description: contentType, accept: { [contentType]: ["." + (requestedFilename?.split(".").pop() || "bin")] } }] : void 0;
|
|
1279
|
+
return picker({
|
|
1280
|
+
suggestedName: requestedFilename?.trim() || "download",
|
|
1281
|
+
...types ? { types } : {}
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
async ensureWritePermission(handle) {
|
|
1285
|
+
if (!handle.queryPermission && !handle.requestPermission) {
|
|
1286
|
+
return;
|
|
1287
|
+
}
|
|
1288
|
+
const descriptor = { mode: "readwrite" };
|
|
1289
|
+
const current = await handle.queryPermission?.(descriptor);
|
|
1290
|
+
if (current === "granted") {
|
|
1291
|
+
return;
|
|
1292
|
+
}
|
|
1293
|
+
const requested = await handle.requestPermission?.(descriptor);
|
|
1294
|
+
if (requested !== void 0 && requested !== "granted") {
|
|
1295
|
+
throw new DOMException("Write permission was not granted", "NotAllowedError");
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
async downloadResolved(plan, request, options, fileHandle, forceResume) {
|
|
1299
|
+
const chunks = plan.chunks;
|
|
1300
|
+
const key = buildDownloadKey(plan, this.transport.baseUrl, request);
|
|
1301
|
+
const existing = await this.transport.checkpointStore.load(key);
|
|
1302
|
+
const resumeRequested = !("resume" in options) || options.resume !== false;
|
|
1303
|
+
let checkpoint = existing && checkpointMatches(existing, plan) && (forceResume || resumeRequested) && (forceResume || fileHandle && await this.isSameFileHandle(existing.fileHandle, fileHandle)) ? existing : createCheckpoint(key, this.transport.baseUrl, request, plan, fileHandle);
|
|
1304
|
+
const cacheScope = this.cacheScope(request, "cache" in options ? options.cache : void 0);
|
|
1305
|
+
const cachedChunkIndexes = /* @__PURE__ */ new Set();
|
|
1306
|
+
let cachedBytes = 0;
|
|
1307
|
+
if (fileHandle) {
|
|
1308
|
+
checkpoint.fileHandle = fileHandle;
|
|
1309
|
+
}
|
|
1310
|
+
const resumed = totalDownloadedBytes(checkpoint) > 0;
|
|
1311
|
+
const maxRetries = validateRetryOption(options.maxRetries, "maxRetries") ?? 3;
|
|
1312
|
+
const retryDelayMs = validateRetryOption(options.retryDelayMs, "retryDelayMs") ?? 500;
|
|
1313
|
+
const sink = fileHandle ? new FileSystemDownloadSink(fileHandle) : new BlobDownloadSink();
|
|
1314
|
+
const speedWindow = new SpeedWindow();
|
|
1315
|
+
const startedAt = Date.now();
|
|
1316
|
+
let retryCount = 0;
|
|
1317
|
+
let lastCheckpointAt = 0;
|
|
1318
|
+
const emit = (phase, currentChunkIndex) => {
|
|
1319
|
+
const downloadedBytes = totalDownloadedBytes(checkpoint);
|
|
1320
|
+
const speedBytesPerSecond = speedWindow.record(downloadedBytes, Date.now());
|
|
1321
|
+
const remainingBytes = Math.max(plan.size - downloadedBytes, 0);
|
|
1322
|
+
options.onProgress?.({
|
|
1323
|
+
phase,
|
|
1324
|
+
downloadedBytes,
|
|
1325
|
+
totalBytes: plan.size,
|
|
1326
|
+
downloadedChunks: completedChunkCount(checkpoint),
|
|
1327
|
+
totalChunks: checkpoint.chunks.length,
|
|
1328
|
+
...currentChunkIndex !== void 0 ? { currentChunkIndex } : {},
|
|
1329
|
+
speedBytesPerSecond,
|
|
1330
|
+
...speedBytesPerSecond > 0 && remainingBytes > 0 ? { estimatedRemainingSeconds: remainingBytes / speedBytesPerSecond } : {},
|
|
1331
|
+
elapsedMs: Date.now() - startedAt,
|
|
1332
|
+
retryCount
|
|
1333
|
+
});
|
|
1334
|
+
};
|
|
1335
|
+
const persist = async (force) => {
|
|
1336
|
+
const now = Date.now();
|
|
1337
|
+
if (!force && now - lastCheckpointAt < 1e3) {
|
|
1338
|
+
return;
|
|
1339
|
+
}
|
|
1340
|
+
await sink.flush();
|
|
1341
|
+
checkpoint.updatedAt = now;
|
|
1342
|
+
await this.transport.checkpointStore.save(key, checkpoint);
|
|
1343
|
+
lastCheckpointAt = now;
|
|
1344
|
+
};
|
|
1345
|
+
await this.transport.checkpointStore.save(key, checkpoint);
|
|
1346
|
+
try {
|
|
1347
|
+
for (const chunk of chunks) {
|
|
1348
|
+
const savedChunk = checkpoint.chunks[chunk.index];
|
|
1349
|
+
if (!savedChunk) {
|
|
1350
|
+
throw new Error(`Missing download checkpoint for chunk ${chunk.index}`);
|
|
1351
|
+
}
|
|
1352
|
+
if (savedChunk.completed) {
|
|
1353
|
+
continue;
|
|
1354
|
+
}
|
|
1355
|
+
const cached = plan.cachedChunks?.get(chunk.index) ?? (cacheScope ? await cacheScope.cache.readChunk(cacheScope.workspace, chunk) : null);
|
|
1356
|
+
if (cached) {
|
|
1357
|
+
throwIfAborted(options.signal);
|
|
1358
|
+
const remaining = cached.slice(savedChunk.downloadedBytes);
|
|
1359
|
+
await sink.write(remaining, chunk.offset + savedChunk.downloadedBytes);
|
|
1360
|
+
cachedBytes += remaining.size;
|
|
1361
|
+
savedChunk.downloadedBytes = chunk.size;
|
|
1362
|
+
savedChunk.completed = true;
|
|
1363
|
+
cachedChunkIndexes.add(chunk.index);
|
|
1364
|
+
emit("downloading", chunk.index);
|
|
1365
|
+
await persist(false);
|
|
1366
|
+
continue;
|
|
1367
|
+
}
|
|
1368
|
+
const url = chunk.url;
|
|
1369
|
+
if (!url) {
|
|
1370
|
+
throw new Error(`Chunk ${chunk.index} is no longer in the download cache`);
|
|
1371
|
+
}
|
|
1372
|
+
const capture = cacheScope && savedChunk.downloadedBytes === 0 && cacheScope.cache.canStoreChunk(chunk) ? [] : null;
|
|
1373
|
+
let attempt = 0;
|
|
1374
|
+
while (true) {
|
|
1375
|
+
throwIfAborted(options.signal);
|
|
1376
|
+
const rangeStart = savedChunk.downloadedBytes;
|
|
1377
|
+
try {
|
|
1378
|
+
const response = await this.transport.fetchImpl(url, {
|
|
1379
|
+
method: "GET",
|
|
1380
|
+
...rangeStart > 0 ? { headers: { Range: `bytes=${rangeStart}-` } } : {},
|
|
1381
|
+
...options.signal ? { signal: options.signal } : {}
|
|
1382
|
+
});
|
|
1383
|
+
if (!response.ok) {
|
|
1384
|
+
throw new DownloadHttpError(
|
|
1385
|
+
response.status,
|
|
1386
|
+
`Download for chunk ${chunk.index} failed with HTTP ${response.status}`
|
|
1387
|
+
);
|
|
1388
|
+
}
|
|
1389
|
+
await this.consumeResponse(
|
|
1390
|
+
response,
|
|
1391
|
+
chunk,
|
|
1392
|
+
savedChunk,
|
|
1393
|
+
sink,
|
|
1394
|
+
plan.size,
|
|
1395
|
+
emit,
|
|
1396
|
+
persist,
|
|
1397
|
+
capture,
|
|
1398
|
+
options.signal
|
|
1399
|
+
);
|
|
1400
|
+
if (savedChunk.downloadedBytes !== savedChunk.size) {
|
|
1401
|
+
throw new Error(
|
|
1402
|
+
`Download for chunk ${chunk.index} ended at ${savedChunk.downloadedBytes} of ${savedChunk.size} bytes`
|
|
1403
|
+
);
|
|
1404
|
+
}
|
|
1405
|
+
savedChunk.completed = true;
|
|
1406
|
+
await persist(true);
|
|
1407
|
+
if (cacheScope && capture && await cacheScope.cache.storeChunk(cacheScope.workspace, chunk, new Blob(capture))) {
|
|
1408
|
+
cachedChunkIndexes.add(chunk.index);
|
|
1409
|
+
}
|
|
1410
|
+
emit("downloading", chunk.index);
|
|
1411
|
+
break;
|
|
1412
|
+
} catch (error) {
|
|
1413
|
+
await persist(true);
|
|
1414
|
+
if (isAbortError(error, options.signal) || !isRetryableError(error) || attempt >= maxRetries) {
|
|
1415
|
+
throw error;
|
|
1416
|
+
}
|
|
1417
|
+
attempt += 1;
|
|
1418
|
+
retryCount += 1;
|
|
1419
|
+
emit("retrying", chunk.index);
|
|
1420
|
+
await waitForRetry(Math.min(retryDelayMs * 2 ** (attempt - 1), 3e4), options.signal);
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
if (totalDownloadedBytes(checkpoint) !== plan.size) {
|
|
1425
|
+
throw new Error("Download completed with an unexpected byte count");
|
|
1426
|
+
}
|
|
1427
|
+
if (fileHandle) {
|
|
1428
|
+
await sink.finalize(plan.size);
|
|
1429
|
+
} else {
|
|
1430
|
+
await sink.finalize();
|
|
1431
|
+
}
|
|
1432
|
+
await this.transport.checkpointStore.remove(key);
|
|
1433
|
+
if (cacheScope && plan.exported && chunks.every((chunk) => chunk.size === 0 || cachedChunkIndexes.has(chunk.index))) {
|
|
1434
|
+
await cacheScope.cache.storeFile(cacheScope.workspace, cacheScope.fileKey, plan);
|
|
1435
|
+
}
|
|
1436
|
+
emit("completed");
|
|
1437
|
+
const blob = sink instanceof BlobDownloadSink ? sink.blob(plan.contentType) : void 0;
|
|
1438
|
+
if (blob) {
|
|
1439
|
+
const filename = "downloadFilename" in options ? options.downloadFilename : void 0;
|
|
1440
|
+
triggerBrowserDownload(blob, defaultFilename(plan.path, filename));
|
|
1441
|
+
}
|
|
1442
|
+
return {
|
|
1443
|
+
...plan.exported ? { export: plan.exported } : {},
|
|
1444
|
+
downloadKey: key,
|
|
1445
|
+
downloadedBytes: plan.size,
|
|
1446
|
+
cachedBytes,
|
|
1447
|
+
resumed,
|
|
1448
|
+
...fileHandle ? { fileHandle } : {},
|
|
1449
|
+
...blob ? { blob } : {}
|
|
1450
|
+
};
|
|
1451
|
+
} catch (error) {
|
|
1452
|
+
await persist(true);
|
|
1453
|
+
throw error;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
async consumeResponse(response, chunk, savedChunk, sink, totalSize, emit, persist, capture, signal) {
|
|
1457
|
+
const sourceOffset = savedChunk.downloadedBytes;
|
|
1458
|
+
let bytesToSkip = response.status === 200 && sourceOffset > 0 ? sourceOffset : 0;
|
|
1459
|
+
const reader = response.body?.getReader();
|
|
1460
|
+
if (!reader) {
|
|
1461
|
+
const body = new Uint8Array(await response.arrayBuffer());
|
|
1462
|
+
await this.consumeBytes(body, bytesToSkip, chunk, savedChunk, sink, totalSize, emit, persist, capture, signal);
|
|
1463
|
+
return;
|
|
1464
|
+
}
|
|
1465
|
+
try {
|
|
1466
|
+
while (true) {
|
|
1467
|
+
throwIfAborted(signal);
|
|
1468
|
+
const next = await reader.read();
|
|
1469
|
+
if (next.done) {
|
|
1470
|
+
break;
|
|
1471
|
+
}
|
|
1472
|
+
const bytes = next.value;
|
|
1473
|
+
if (bytesToSkip > 0) {
|
|
1474
|
+
const skipped = Math.min(bytesToSkip, bytes.byteLength);
|
|
1475
|
+
bytesToSkip -= skipped;
|
|
1476
|
+
if (skipped === bytes.byteLength) {
|
|
1477
|
+
continue;
|
|
1478
|
+
}
|
|
1479
|
+
await this.consumeBytes(
|
|
1480
|
+
bytes.subarray(skipped),
|
|
1481
|
+
0,
|
|
1482
|
+
chunk,
|
|
1483
|
+
savedChunk,
|
|
1484
|
+
sink,
|
|
1485
|
+
totalSize,
|
|
1486
|
+
emit,
|
|
1487
|
+
persist,
|
|
1488
|
+
capture,
|
|
1489
|
+
signal
|
|
1490
|
+
);
|
|
1491
|
+
} else {
|
|
1492
|
+
await this.consumeBytes(bytes, 0, chunk, savedChunk, sink, totalSize, emit, persist, capture, signal);
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
} finally {
|
|
1496
|
+
reader.releaseLock();
|
|
1497
|
+
}
|
|
1498
|
+
if (bytesToSkip > 0) {
|
|
1499
|
+
throw new Error(`Download response did not contain the saved offset for chunk ${chunk.index}`);
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
async consumeBytes(bytes, offset, chunk, savedChunk, sink, totalSize, emit, persist, capture, signal) {
|
|
1503
|
+
const remaining = chunk.size - savedChunk.downloadedBytes;
|
|
1504
|
+
const writableBytes = bytes.byteLength - offset;
|
|
1505
|
+
if (writableBytes > remaining) {
|
|
1506
|
+
throw new Error(`Download response for chunk ${chunk.index} is larger than expected`);
|
|
1507
|
+
}
|
|
1508
|
+
if (writableBytes === 0) {
|
|
1509
|
+
return;
|
|
1510
|
+
}
|
|
1511
|
+
throwIfAborted(signal);
|
|
1512
|
+
const payload = bytes.subarray(offset);
|
|
1513
|
+
const position = chunk.offset + savedChunk.downloadedBytes;
|
|
1514
|
+
await sink.write(payload, position);
|
|
1515
|
+
capture?.push(payload.slice());
|
|
1516
|
+
savedChunk.downloadedBytes += payload.byteLength;
|
|
1517
|
+
emit("downloading", chunk.index);
|
|
1518
|
+
await persist(false);
|
|
1519
|
+
if (savedChunk.downloadedBytes > totalSize) {
|
|
1520
|
+
throw new Error("Download byte count exceeded the exported file size");
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
async isSameFileHandle(savedHandle, selectedHandle) {
|
|
1524
|
+
if (!savedHandle) {
|
|
1525
|
+
return false;
|
|
1526
|
+
}
|
|
1527
|
+
if (savedHandle === selectedHandle) {
|
|
1528
|
+
return true;
|
|
1529
|
+
}
|
|
1530
|
+
if (savedHandle.isSameEntry) {
|
|
1531
|
+
try {
|
|
1532
|
+
return await savedHandle.isSameEntry(selectedHandle);
|
|
1533
|
+
} catch {
|
|
1534
|
+
return false;
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
return false;
|
|
1538
|
+
}
|
|
1539
|
+
};
|
|
1540
|
+
|
|
1
1541
|
// src/upload.ts
|
|
2
1542
|
var JUMBO_CHUNK_THRESHOLD_BYTES = 128 * 1024 * 1024;
|
|
3
1543
|
var MIN_S3_MULTIPART_PART_SIZE_BYTES = 5 * 1024 * 1024;
|
|
@@ -17,7 +1557,7 @@ var MountraApiError = class extends Error {
|
|
|
17
1557
|
};
|
|
18
1558
|
var memoryCheckpointRecords = /* @__PURE__ */ new Map();
|
|
19
1559
|
function parseJumboCheckpoint(value) {
|
|
20
|
-
if (!
|
|
1560
|
+
if (!isRecord2(value) || value.version !== 1 || typeof value.storageKey !== "string") {
|
|
21
1561
|
return null;
|
|
22
1562
|
}
|
|
23
1563
|
if (typeof value.chunkIndex !== "number" || typeof value.chunkSize !== "number" || typeof value.chunkSha256 !== "string" || typeof value.partSize !== "number" || typeof value.uploadId !== "string" || !Array.isArray(value.parts)) {
|
|
@@ -25,7 +1565,7 @@ function parseJumboCheckpoint(value) {
|
|
|
25
1565
|
}
|
|
26
1566
|
const parts = [];
|
|
27
1567
|
for (const part of value.parts) {
|
|
28
|
-
if (!
|
|
1568
|
+
if (!isRecord2(part)) {
|
|
29
1569
|
return null;
|
|
30
1570
|
}
|
|
31
1571
|
if (typeof part.partNumber !== "number" || typeof part.etag !== "string" || typeof part.size !== "number" || typeof part.sha256 !== "string") {
|
|
@@ -198,17 +1738,17 @@ function getWorkspaceBody(clientSelector, requestSelector) {
|
|
|
198
1738
|
...workspaceId !== void 0 ? { workspace_id: workspaceId } : {}
|
|
199
1739
|
};
|
|
200
1740
|
}
|
|
201
|
-
function
|
|
1741
|
+
function throwIfAborted2(signal) {
|
|
202
1742
|
if (!signal?.aborted) {
|
|
203
1743
|
return;
|
|
204
1744
|
}
|
|
205
1745
|
throw new DOMException("The upload was aborted", "AbortError");
|
|
206
1746
|
}
|
|
207
|
-
function
|
|
1747
|
+
function isRecord2(value) {
|
|
208
1748
|
return typeof value === "object" && value !== null;
|
|
209
1749
|
}
|
|
210
1750
|
function parseApiErrorBody(body) {
|
|
211
|
-
if (!
|
|
1751
|
+
if (!isRecord2(body)) {
|
|
212
1752
|
return {};
|
|
213
1753
|
}
|
|
214
1754
|
return {
|
|
@@ -217,7 +1757,7 @@ function parseApiErrorBody(body) {
|
|
|
217
1757
|
};
|
|
218
1758
|
}
|
|
219
1759
|
function ensurePrepareResponse(value) {
|
|
220
|
-
if (!
|
|
1760
|
+
if (!isRecord2(value) || typeof value.upload_id !== "string") {
|
|
221
1761
|
throw new TypeError("Mountra prepare response is invalid");
|
|
222
1762
|
}
|
|
223
1763
|
if (!Array.isArray(value.upload_targets)) {
|
|
@@ -226,13 +1766,13 @@ function ensurePrepareResponse(value) {
|
|
|
226
1766
|
return value;
|
|
227
1767
|
}
|
|
228
1768
|
function ensureFinishResponse(value) {
|
|
229
|
-
if (!
|
|
1769
|
+
if (!isRecord2(value) || typeof value.upload_id !== "string") {
|
|
230
1770
|
throw new TypeError("Mountra finish response is invalid");
|
|
231
1771
|
}
|
|
232
1772
|
return value;
|
|
233
1773
|
}
|
|
234
1774
|
function ensureUploadStatusResponse(value) {
|
|
235
|
-
if (!
|
|
1775
|
+
if (!isRecord2(value) || typeof value.upload_id !== "string") {
|
|
236
1776
|
throw new TypeError("Mountra upload status response is invalid");
|
|
237
1777
|
}
|
|
238
1778
|
if (!Array.isArray(value.chunks)) {
|
|
@@ -250,8 +1790,7 @@ function splitFileIntoChunks(file, chunkCount = 1) {
|
|
|
250
1790
|
}
|
|
251
1791
|
const chunkSize = Math.ceil(file.size / chunkCount);
|
|
252
1792
|
const chunks = [];
|
|
253
|
-
for (let index = 0;
|
|
254
|
-
const offset = index * chunkSize;
|
|
1793
|
+
for (let index = 0, offset = 0; offset < file.size; index += 1, offset += chunkSize) {
|
|
255
1794
|
const end = Math.min(offset + chunkSize, file.size);
|
|
256
1795
|
chunks.push({
|
|
257
1796
|
index,
|
|
@@ -283,6 +1822,7 @@ var MountraClient = class {
|
|
|
283
1822
|
jumboChunkUploader;
|
|
284
1823
|
jumboChunkCheckpointStore;
|
|
285
1824
|
jumboPartSize;
|
|
1825
|
+
downloader;
|
|
286
1826
|
constructor(options) {
|
|
287
1827
|
this.baseUrl = normalizeBaseUrl(options.baseUrl);
|
|
288
1828
|
this.apiPrefix = normalizeApiPrefix(options.apiPrefix ?? "/api");
|
|
@@ -301,6 +1841,46 @@ var MountraClient = class {
|
|
|
301
1841
|
throw new Error("fetch is not available; provide fetch in MountraClientOptions");
|
|
302
1842
|
}
|
|
303
1843
|
this.fetchImpl = fetchImpl;
|
|
1844
|
+
this.downloader = new MountraDownloader({
|
|
1845
|
+
baseUrl: this.baseUrl,
|
|
1846
|
+
clientSelector: this.clientSelector,
|
|
1847
|
+
fetchImpl: this.fetchImpl,
|
|
1848
|
+
checkpointStore: options.downloadCheckpointStore ?? new IndexedDBDownloadCheckpointStore(),
|
|
1849
|
+
cache: options.downloadCache ? new DownloadCache(options.downloadCache) : null,
|
|
1850
|
+
requestJson: (path, body, signal) => this.requestJson(path, body, signal)
|
|
1851
|
+
});
|
|
1852
|
+
}
|
|
1853
|
+
async exportFile(options) {
|
|
1854
|
+
return this.downloader.exportFile(options);
|
|
1855
|
+
}
|
|
1856
|
+
async downloadFile(options) {
|
|
1857
|
+
return this.downloader.downloadFile(options);
|
|
1858
|
+
}
|
|
1859
|
+
async downloadExport(exported, options) {
|
|
1860
|
+
return this.downloader.downloadExport(exported, options);
|
|
1861
|
+
}
|
|
1862
|
+
async resumeDownload(downloadKey, options) {
|
|
1863
|
+
return this.downloader.resumeDownload(downloadKey, options);
|
|
1864
|
+
}
|
|
1865
|
+
listResumableDownloads() {
|
|
1866
|
+
return this.downloader.listResumableDownloads();
|
|
1867
|
+
}
|
|
1868
|
+
clearDownloadCheckpoint(downloadKey) {
|
|
1869
|
+
return this.downloader.clearDownloadCheckpoint(downloadKey);
|
|
1870
|
+
}
|
|
1871
|
+
/** Clear the download cache of one workspace, or of every workspace when none is given. */
|
|
1872
|
+
clearDownloadCache(selector) {
|
|
1873
|
+
return this.downloader.clearCache(selector);
|
|
1874
|
+
}
|
|
1875
|
+
getDownloadCacheUsage(selector) {
|
|
1876
|
+
return this.downloader.cacheUsage(selector);
|
|
1877
|
+
}
|
|
1878
|
+
/** Create a stable resource object for one file in this or another workspace. */
|
|
1879
|
+
file(locator) {
|
|
1880
|
+
return new MountraFile(
|
|
1881
|
+
this,
|
|
1882
|
+
normalizeMountraFileLocator(locator, this.clientSelector)
|
|
1883
|
+
);
|
|
304
1884
|
}
|
|
305
1885
|
async prepareUpload(file, options) {
|
|
306
1886
|
const chunks = splitFileIntoChunks(file, options.chunkCount ?? 1);
|
|
@@ -308,7 +1888,7 @@ var MountraClient = class {
|
|
|
308
1888
|
const contentHash = await sha256Hex(file);
|
|
309
1889
|
const chunkMethod = chunks.length === 1 ? "none" : "fix";
|
|
310
1890
|
const contentType = options.contentType ?? ("type" in file ? file.type : void 0);
|
|
311
|
-
|
|
1891
|
+
throwIfAborted2(options.signal);
|
|
312
1892
|
const response = ensurePrepareResponse(
|
|
313
1893
|
await this.requestJson("/upload/prepare", {
|
|
314
1894
|
...getWorkspaceBody(this.clientSelector, options),
|
|
@@ -411,7 +1991,7 @@ var MountraClient = class {
|
|
|
411
1991
|
if (!chunk || target.chunk_index !== position) {
|
|
412
1992
|
throw new Error("Mountra upload targets must contain contiguous chunk indexes");
|
|
413
1993
|
}
|
|
414
|
-
|
|
1994
|
+
throwIfAborted2(options.signal);
|
|
415
1995
|
if (isJumboChunk(chunk.size)) {
|
|
416
1996
|
const checkpointKey = this.buildJumboCheckpointKey(context, target, options);
|
|
417
1997
|
jumboCheckpointKeys.add(checkpointKey);
|
|
@@ -454,7 +2034,7 @@ var MountraClient = class {
|
|
|
454
2034
|
totalChunks: orderedTargets.length
|
|
455
2035
|
});
|
|
456
2036
|
}
|
|
457
|
-
|
|
2037
|
+
throwIfAborted2(options.signal);
|
|
458
2038
|
options.onProgress?.({
|
|
459
2039
|
phase: "finishing",
|
|
460
2040
|
uploadedBytes: file.size,
|
|
@@ -475,6 +2055,26 @@ var MountraClient = class {
|
|
|
475
2055
|
if (finished.finish_status !== "completed") {
|
|
476
2056
|
throw new Error(`Mountra upload did not finish successfully: ${finished.finish_status}`);
|
|
477
2057
|
}
|
|
2058
|
+
await this.downloader.cacheUploadedFile(
|
|
2059
|
+
this.cacheWorkspace(options),
|
|
2060
|
+
{
|
|
2061
|
+
path: finished.path,
|
|
2062
|
+
...finished.ino !== void 0 ? { ino: finished.ino } : {},
|
|
2063
|
+
size: context.fileSize,
|
|
2064
|
+
...context.contentType ? { contentType: context.contentType } : {},
|
|
2065
|
+
chunks: orderedTargets.map((target) => {
|
|
2066
|
+
const chunk = chunks[target.chunk_index];
|
|
2067
|
+
return {
|
|
2068
|
+
index: chunk.index,
|
|
2069
|
+
offset: chunk.offset,
|
|
2070
|
+
size: chunk.size,
|
|
2071
|
+
storageKey: target.storage_key,
|
|
2072
|
+
data: chunk.blob
|
|
2073
|
+
};
|
|
2074
|
+
})
|
|
2075
|
+
},
|
|
2076
|
+
options.cache
|
|
2077
|
+
);
|
|
478
2078
|
await Promise.all(
|
|
479
2079
|
[...jumboCheckpointKeys].map(
|
|
480
2080
|
(checkpointKey) => this.jumboChunkCheckpointStore.remove(checkpointKey)
|
|
@@ -558,7 +2158,7 @@ var MountraClient = class {
|
|
|
558
2158
|
let uploadedBytes = 0;
|
|
559
2159
|
let uploadedParts = 0;
|
|
560
2160
|
for (let partNumber = 1; partNumber <= totalParts; partNumber += 1) {
|
|
561
|
-
|
|
2161
|
+
throwIfAborted2(options.signal);
|
|
562
2162
|
const start = (partNumber - 1) * this.jumboPartSize;
|
|
563
2163
|
const partBlob = chunk.blob.slice(start, Math.min(start + this.jumboPartSize, chunk.size));
|
|
564
2164
|
const partHash = await sha256Hex(partBlob);
|
|
@@ -650,12 +2250,26 @@ var MountraClient = class {
|
|
|
650
2250
|
if (!uploadId.trim()) {
|
|
651
2251
|
throw new TypeError("uploadId is required");
|
|
652
2252
|
}
|
|
653
|
-
|
|
2253
|
+
const finished = ensureFinishResponse(
|
|
654
2254
|
await this.requestJson("/upload/finish", {
|
|
655
2255
|
...getWorkspaceBody(this.clientSelector, selector),
|
|
656
2256
|
upload_id: uploadId
|
|
657
2257
|
})
|
|
658
2258
|
);
|
|
2259
|
+
if (finished.finish_status === "completed") {
|
|
2260
|
+
await this.downloader.invalidateCachedFile(this.cacheWorkspace(selector), {
|
|
2261
|
+
path: finished.path,
|
|
2262
|
+
...finished.ino !== void 0 ? { ino: finished.ino } : {}
|
|
2263
|
+
});
|
|
2264
|
+
}
|
|
2265
|
+
return finished;
|
|
2266
|
+
}
|
|
2267
|
+
/** Same workspace resolution as `getWorkspaceBody`, so the cache key matches what Mountra used. */
|
|
2268
|
+
cacheWorkspace(selector) {
|
|
2269
|
+
return {
|
|
2270
|
+
workspaceCuid: selector.workspaceCuid ?? this.clientSelector.workspaceCuid,
|
|
2271
|
+
workspaceId: selector.workspaceId ?? this.clientSelector.workspaceId
|
|
2272
|
+
};
|
|
659
2273
|
}
|
|
660
2274
|
endpoint(path) {
|
|
661
2275
|
return `${this.baseUrl}${this.apiPrefix}${path}`;
|
|
@@ -694,13 +2308,20 @@ function createMountraClient(options) {
|
|
|
694
2308
|
}
|
|
695
2309
|
export {
|
|
696
2310
|
DEFAULT_S3_MULTIPART_PART_SIZE_BYTES,
|
|
2311
|
+
DownloadHttpError,
|
|
2312
|
+
InMemoryDownloadCacheStore,
|
|
2313
|
+
InMemoryDownloadCheckpointStore,
|
|
697
2314
|
InMemoryJumboChunkCheckpointStore,
|
|
2315
|
+
IndexedDBDownloadCacheStore,
|
|
2316
|
+
IndexedDBDownloadCheckpointStore,
|
|
698
2317
|
JUMBO_CHUNK_THRESHOLD_BYTES,
|
|
699
2318
|
LocalStorageJumboChunkCheckpointStore,
|
|
700
2319
|
MAX_S3_MULTIPART_PARTS,
|
|
701
2320
|
MIN_S3_MULTIPART_PART_SIZE_BYTES,
|
|
702
2321
|
MountraApiError,
|
|
703
2322
|
MountraClient,
|
|
2323
|
+
MountraDownloader,
|
|
2324
|
+
MountraFile,
|
|
704
2325
|
MountraClient as MountraSDK,
|
|
705
2326
|
S3MultipartUploader,
|
|
706
2327
|
createMountraClient,
|