@dimah-s3/react 1.0.1 → 1.1.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/README.md +1 -0
- package/dist/api.d.ts +2 -2
- package/dist/create-s3-client.d.ts +1 -1
- package/dist/engine.d.ts +2 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +508 -0
- package/dist/engine.js.map +1 -0
- package/dist/helpers/format-dimah-error.d.ts.map +1 -1
- package/dist/helpers/index.d.ts +2 -0
- package/dist/helpers/index.d.ts.map +1 -1
- package/dist/helpers/load-route-catalog.d.ts +18 -0
- package/dist/helpers/load-route-catalog.d.ts.map +1 -0
- package/dist/hooks/index.d.ts +1 -0
- package/dist/hooks/index.d.ts.map +1 -1
- package/dist/hooks/use-delete.d.ts +7 -3
- package/dist/hooks/use-delete.d.ts.map +1 -1
- package/dist/hooks/use-download.d.ts +6 -4
- package/dist/hooks/use-download.d.ts.map +1 -1
- package/dist/hooks/use-file-upload.d.ts +4 -4
- package/dist/hooks/use-file-upload.d.ts.map +1 -1
- package/dist/hooks/use-multi-file-upload.d.ts +4 -4
- package/dist/hooks/use-multi-file-upload.d.ts.map +1 -1
- package/dist/hooks/use-multi-upload.d.ts +1 -3
- package/dist/hooks/use-multi-upload.d.ts.map +1 -1
- package/dist/hooks/use-object-url.d.ts +30 -0
- package/dist/hooks/use-object-url.d.ts.map +1 -0
- package/dist/hooks/use-route-upload-policy.d.ts +13 -0
- package/dist/hooks/use-route-upload-policy.d.ts.map +1 -0
- package/dist/hooks/use-upload.d.ts +4 -4
- package/dist/hooks/use-upload.d.ts.map +1 -1
- package/dist/index.d.ts +8 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +728 -304
- package/dist/index.js.map +1 -1
- package/dist/store/local-storage-store.d.ts +1 -1
- package/dist/store/memory-store.d.ts +1 -1
- package/dist/translations/types.d.ts +2 -3
- package/dist/translations/types.d.ts.map +1 -1
- package/dist/types/error.d.ts +1 -0
- package/dist/types/error.d.ts.map +1 -1
- package/dist/types/multi-upload.d.ts +2 -0
- package/dist/types/multi-upload.d.ts.map +1 -1
- package/dist/types/upload-store.d.ts +27 -13
- package/dist/types/upload-store.d.ts.map +1 -1
- package/dist/types/upload.d.ts +40 -26
- package/dist/types/upload.d.ts.map +1 -1
- package/dist/upload/index.d.ts +2 -0
- package/dist/upload/index.d.ts.map +1 -1
- package/dist/upload/multipart.d.ts +2 -2
- package/dist/upload/multipart.d.ts.map +1 -1
- package/dist/upload/presigned-http.d.ts +1 -1
- package/dist/upload/resume-key.d.ts +6 -0
- package/dist/upload/resume-key.d.ts.map +1 -0
- package/dist/upload/upload-file.d.ts +3 -3
- package/dist/upload/upload-file.d.ts.map +1 -1
- package/dist/upload/upload-files.d.ts +2 -4
- package/dist/upload/upload-files.d.ts.map +1 -1
- package/dist/upload/upload-part.d.ts +1 -1
- package/dist/upload/upload-part.d.ts.map +1 -1
- package/dist/upload/xhr-upload.d.ts.map +1 -1
- package/package.json +12 -8
package/dist/index.js
CHANGED
|
@@ -1,11 +1,50 @@
|
|
|
1
|
-
import { createS3Client as createS3Client$1, formatFileSize, isDimahS3Error, S3_ERROR_CODES, validateFile,
|
|
2
|
-
export { DimahS3Error, S3_ERROR_CODES, buildObjectKey,
|
|
1
|
+
import { DimahS3Error, createS3Client as createS3Client$1, sha256File, formatFileSize, isDimahS3Error, S3_ERROR_CODES, validateFile, parseFileName } from '@dimah-s3/core';
|
|
2
|
+
export { DimahS3Error, S3_ERROR_CODES, buildContentDisposition, buildObjectKey, buildPublicObjectUrl, fileNameFromKey, formatFileSize, isAPIError, isDimahS3Error, isS3ErrorCode, matchesMagicBytes, sanitizeFileName, sha256Base64, sha256File, sniffContentType, validateFile } from '@dimah-s3/core';
|
|
3
3
|
import { createContext, useContext, useCallback, useRef, useEffect, useState, useLayoutEffect } from 'react';
|
|
4
4
|
import { TranslationProvider, useTranslations } from '@fuma-translate/react';
|
|
5
5
|
import { jsx } from 'react/jsx-runtime';
|
|
6
6
|
import { produce } from 'immer';
|
|
7
7
|
import { ErrorCode, useDropzone } from 'react-dropzone';
|
|
8
8
|
|
|
9
|
+
var S3UploadError = class extends DimahS3Error {
|
|
10
|
+
phase;
|
|
11
|
+
constructor(message, code, status = 400, phase) {
|
|
12
|
+
super(status, { message, code });
|
|
13
|
+
this.name = "S3UploadError";
|
|
14
|
+
this.phase = phase;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
function toUploadError(err, phase) {
|
|
18
|
+
if (err instanceof S3UploadError) {
|
|
19
|
+
if (err.phase == null) {
|
|
20
|
+
return new S3UploadError(
|
|
21
|
+
err.message,
|
|
22
|
+
err.code ?? "UPLOAD_ERROR",
|
|
23
|
+
err.statusCode,
|
|
24
|
+
phase
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
return err;
|
|
28
|
+
}
|
|
29
|
+
if (isAbortError(err)) {
|
|
30
|
+
throw err;
|
|
31
|
+
}
|
|
32
|
+
if (isDimahS3Error(err)) return err;
|
|
33
|
+
const message = err instanceof Error ? err.message : "Upload failed";
|
|
34
|
+
return new S3UploadError(message, "UPLOAD_ERROR", 500, phase);
|
|
35
|
+
}
|
|
36
|
+
function toHookError(err, fallback = "Request failed") {
|
|
37
|
+
if (isDimahS3Error(err)) return err;
|
|
38
|
+
const message = err instanceof Error ? err.message : fallback;
|
|
39
|
+
return new DimahS3Error("BAD_REQUEST", { message });
|
|
40
|
+
}
|
|
41
|
+
function isAbortError(err) {
|
|
42
|
+
return typeof DOMException !== "undefined" && err instanceof DOMException && err.name === "AbortError" || err instanceof Error && err.name === "AbortError" || typeof err === "object" && err !== null && err.name === "AbortError";
|
|
43
|
+
}
|
|
44
|
+
function hookBlockedError(message) {
|
|
45
|
+
return new DimahS3Error("BAD_REQUEST", { message });
|
|
46
|
+
}
|
|
47
|
+
|
|
9
48
|
// src/api.ts
|
|
10
49
|
function defineApi(input) {
|
|
11
50
|
return input;
|
|
@@ -42,9 +81,9 @@ function createS3Client(options) {
|
|
|
42
81
|
var STORAGE_PREFIX = "dimah-s3:upload:";
|
|
43
82
|
function createLocalStorageStore() {
|
|
44
83
|
return {
|
|
45
|
-
get(
|
|
84
|
+
get(resumeKey, fileSize) {
|
|
46
85
|
try {
|
|
47
|
-
const raw = localStorage.getItem(STORAGE_PREFIX +
|
|
86
|
+
const raw = localStorage.getItem(STORAGE_PREFIX + resumeKey);
|
|
48
87
|
if (!raw) return null;
|
|
49
88
|
const stored = JSON.parse(raw);
|
|
50
89
|
return stored.fileSize === fileSize ? stored : null;
|
|
@@ -55,15 +94,15 @@ function createLocalStorageStore() {
|
|
|
55
94
|
set(upload) {
|
|
56
95
|
try {
|
|
57
96
|
localStorage.setItem(
|
|
58
|
-
STORAGE_PREFIX + upload.
|
|
97
|
+
STORAGE_PREFIX + upload.resumeKey,
|
|
59
98
|
JSON.stringify(upload)
|
|
60
99
|
);
|
|
61
100
|
} catch {
|
|
62
101
|
}
|
|
63
102
|
},
|
|
64
|
-
delete(
|
|
103
|
+
delete(resumeKey) {
|
|
65
104
|
try {
|
|
66
|
-
localStorage.removeItem(STORAGE_PREFIX +
|
|
105
|
+
localStorage.removeItem(STORAGE_PREFIX + resumeKey);
|
|
67
106
|
} catch {
|
|
68
107
|
}
|
|
69
108
|
}
|
|
@@ -74,54 +113,19 @@ function createLocalStorageStore() {
|
|
|
74
113
|
function createMemoryStore() {
|
|
75
114
|
const map = /* @__PURE__ */ new Map();
|
|
76
115
|
return {
|
|
77
|
-
get(
|
|
78
|
-
const stored = map.get(
|
|
116
|
+
get(resumeKey, fileSize) {
|
|
117
|
+
const stored = map.get(resumeKey);
|
|
79
118
|
if (!stored) return null;
|
|
80
119
|
return stored.fileSize === fileSize ? stored : null;
|
|
81
120
|
},
|
|
82
121
|
set(upload) {
|
|
83
|
-
map.set(upload.
|
|
122
|
+
map.set(upload.resumeKey, upload);
|
|
84
123
|
},
|
|
85
|
-
delete(
|
|
86
|
-
map.delete(
|
|
124
|
+
delete(resumeKey) {
|
|
125
|
+
map.delete(resumeKey);
|
|
87
126
|
}
|
|
88
127
|
};
|
|
89
128
|
}
|
|
90
|
-
var S3UploadError = class extends DimahS3Error {
|
|
91
|
-
phase;
|
|
92
|
-
constructor(message, code, status = 400, phase) {
|
|
93
|
-
super(status, { message, code });
|
|
94
|
-
this.name = "S3UploadError";
|
|
95
|
-
this.phase = phase;
|
|
96
|
-
}
|
|
97
|
-
};
|
|
98
|
-
function toUploadError(err, phase) {
|
|
99
|
-
if (err instanceof S3UploadError) {
|
|
100
|
-
if (err.phase == null) {
|
|
101
|
-
return new S3UploadError(
|
|
102
|
-
err.message,
|
|
103
|
-
err.code ?? "UPLOAD_ERROR",
|
|
104
|
-
err.statusCode,
|
|
105
|
-
phase
|
|
106
|
-
);
|
|
107
|
-
}
|
|
108
|
-
return err;
|
|
109
|
-
}
|
|
110
|
-
if (err?.name === "AbortError") {
|
|
111
|
-
throw err;
|
|
112
|
-
}
|
|
113
|
-
if (isDimahS3Error(err)) return err;
|
|
114
|
-
const message = err instanceof Error ? err.message : "Upload failed";
|
|
115
|
-
return new S3UploadError(message, "UPLOAD_ERROR", 500, phase);
|
|
116
|
-
}
|
|
117
|
-
function toHookError(err, fallback = "Request failed") {
|
|
118
|
-
if (isDimahS3Error(err)) return err;
|
|
119
|
-
const message = err instanceof Error ? err.message : fallback;
|
|
120
|
-
return new DimahS3Error("BAD_REQUEST", { message });
|
|
121
|
-
}
|
|
122
|
-
function hookBlockedError(message) {
|
|
123
|
-
return new DimahS3Error("BAD_REQUEST", { message });
|
|
124
|
-
}
|
|
125
129
|
|
|
126
130
|
// src/upload/constants.ts
|
|
127
131
|
var DEFAULT_MULTIPART_THRESHOLD = 50 * 1024 * 1024;
|
|
@@ -165,6 +169,10 @@ function sendXhrUpload(options) {
|
|
|
165
169
|
onProgress
|
|
166
170
|
} = options;
|
|
167
171
|
return new Promise((resolve, reject) => {
|
|
172
|
+
if (signal?.aborted) {
|
|
173
|
+
reject(new DOMException("Upload aborted", "AbortError"));
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
168
176
|
const xhr = new XMLHttpRequest();
|
|
169
177
|
const onAbort = () => {
|
|
170
178
|
xhr.abort();
|
|
@@ -256,10 +264,10 @@ function uploadPut(file, url, headers, onProgress, signal) {
|
|
|
256
264
|
}
|
|
257
265
|
|
|
258
266
|
// src/upload/upload-part.ts
|
|
259
|
-
function uploadPart(blob,
|
|
267
|
+
function uploadPart(blob, url, partLoaded, reportProgress, signal) {
|
|
260
268
|
return sendXhrUpload({
|
|
261
269
|
method: "PUT",
|
|
262
|
-
url
|
|
270
|
+
url,
|
|
263
271
|
body: blob,
|
|
264
272
|
signal,
|
|
265
273
|
errorLabel: "Part upload",
|
|
@@ -273,59 +281,60 @@ function uploadPart(blob, presignedUrl, partLoaded, reportProgress, signal) {
|
|
|
273
281
|
});
|
|
274
282
|
}
|
|
275
283
|
|
|
284
|
+
// src/upload/resume-key.ts
|
|
285
|
+
function multipartResumeKey(route, file) {
|
|
286
|
+
return `${route}:${file.name}:${file.size}:${file.lastModified}`;
|
|
287
|
+
}
|
|
288
|
+
|
|
276
289
|
// src/upload/multipart.ts
|
|
277
290
|
function resolvePartSize(partIndex, totalParts, partSize, fileSize) {
|
|
278
291
|
return partIndex === totalParts - 1 ? fileSize - partIndex * partSize : partSize;
|
|
279
292
|
}
|
|
280
|
-
async function uploadMultipart(api, file,
|
|
281
|
-
const
|
|
282
|
-
const contentType =
|
|
293
|
+
async function uploadMultipart(api, file, route, partSize, concurrentParts, onProgress, signal, requestOptions, retryConfig, uploadStore, onPartUpload, onMultipartInit) {
|
|
294
|
+
const rawContentType = requestOptions?.contentType ?? file.type;
|
|
295
|
+
const contentType = rawContentType.trim() === "" ? void 0 : rawContentType;
|
|
296
|
+
const fileName = requestOptions?.fileName || file.name;
|
|
297
|
+
const resumeKey = multipartResumeKey(route, file);
|
|
283
298
|
const store = uploadStore != null && uploadStore !== false ? uploadStore : null;
|
|
299
|
+
const completedPartNumbers = /* @__PURE__ */ new Set();
|
|
300
|
+
const initUpload = async () => {
|
|
301
|
+
const result = await api.multipart.init({
|
|
302
|
+
route,
|
|
303
|
+
contentType,
|
|
304
|
+
fileSize: file.size,
|
|
305
|
+
fileName,
|
|
306
|
+
metadata: requestOptions?.metadata,
|
|
307
|
+
checksum: requestOptions?.checksum
|
|
308
|
+
});
|
|
309
|
+
await store?.set({
|
|
310
|
+
resumeKey,
|
|
311
|
+
uploadId: result.uploadId,
|
|
312
|
+
key: result.key,
|
|
313
|
+
fileSize: file.size
|
|
314
|
+
});
|
|
315
|
+
onMultipartInit?.(result.uploadId, result.key);
|
|
316
|
+
return { uploadId: result.uploadId, key: result.key };
|
|
317
|
+
};
|
|
318
|
+
const existing = store ? await store.get(resumeKey, file.size) : null;
|
|
284
319
|
let uploadId;
|
|
285
320
|
let key;
|
|
286
|
-
const completedPartNumbers = /* @__PURE__ */ new Set();
|
|
287
|
-
const existing = store ? await store.get(objectKey, file.size) : null;
|
|
288
321
|
if (existing) {
|
|
289
322
|
try {
|
|
290
323
|
const { parts: parts2 } = await api.multipart.listParts({
|
|
324
|
+
route,
|
|
291
325
|
key: existing.key,
|
|
292
|
-
uploadId: existing.uploadId
|
|
293
|
-
bucket: bucket ?? existing.bucket
|
|
326
|
+
uploadId: existing.uploadId
|
|
294
327
|
});
|
|
295
328
|
uploadId = existing.uploadId;
|
|
296
329
|
key = existing.key;
|
|
297
330
|
for (const p of parts2) completedPartNumbers.add(p.partNumber);
|
|
298
331
|
onMultipartInit?.(uploadId, key);
|
|
299
332
|
} catch {
|
|
300
|
-
await store?.delete(
|
|
301
|
-
|
|
302
|
-
key: objectKey,
|
|
303
|
-
contentType,
|
|
304
|
-
fileSize: file.size,
|
|
305
|
-
fileName: requestOptions?.fileName !== null ? requestOptions?.fileName ?? file.name : void 0,
|
|
306
|
-
metadata: requestOptions?.metadata,
|
|
307
|
-
bucket,
|
|
308
|
-
acl: requestOptions?.acl
|
|
309
|
-
});
|
|
310
|
-
uploadId = result.uploadId;
|
|
311
|
-
key = result.key;
|
|
312
|
-
await store?.set({ uploadId, key, fileSize: file.size, bucket });
|
|
313
|
-
onMultipartInit?.(uploadId, key);
|
|
333
|
+
await store?.delete(resumeKey);
|
|
334
|
+
({ uploadId, key } = await initUpload());
|
|
314
335
|
}
|
|
315
336
|
} else {
|
|
316
|
-
|
|
317
|
-
key: objectKey,
|
|
318
|
-
contentType,
|
|
319
|
-
fileSize: file.size,
|
|
320
|
-
fileName: requestOptions?.fileName !== null ? requestOptions?.fileName ?? file.name : void 0,
|
|
321
|
-
metadata: requestOptions?.metadata,
|
|
322
|
-
bucket,
|
|
323
|
-
acl: requestOptions?.acl
|
|
324
|
-
});
|
|
325
|
-
uploadId = result.uploadId;
|
|
326
|
-
key = result.key;
|
|
327
|
-
await store?.set({ uploadId, key, fileSize: file.size, bucket });
|
|
328
|
-
onMultipartInit?.(uploadId, key);
|
|
337
|
+
({ uploadId, key } = await initUpload());
|
|
329
338
|
}
|
|
330
339
|
const totalParts = Math.ceil(file.size / partSize);
|
|
331
340
|
const partProgress = Array.from(
|
|
@@ -365,17 +374,17 @@ async function uploadMultipart(api, file, objectKey, partSize, concurrentParts,
|
|
|
365
374
|
batch.push(
|
|
366
375
|
withRetry(
|
|
367
376
|
async () => {
|
|
368
|
-
const {
|
|
377
|
+
const { url } = await api.multipart.signPart({
|
|
378
|
+
route,
|
|
369
379
|
key,
|
|
370
380
|
uploadId,
|
|
371
381
|
partNumber,
|
|
372
|
-
partSize: blob.size
|
|
373
|
-
bucket
|
|
382
|
+
partSize: blob.size
|
|
374
383
|
});
|
|
375
384
|
partProgress[i].bytes = 0;
|
|
376
385
|
await uploadPart(
|
|
377
386
|
blob,
|
|
378
|
-
|
|
387
|
+
url,
|
|
379
388
|
partProgress[i],
|
|
380
389
|
reportProgress,
|
|
381
390
|
signal
|
|
@@ -393,17 +402,23 @@ async function uploadMultipart(api, file, objectKey, partSize, concurrentParts,
|
|
|
393
402
|
}
|
|
394
403
|
parts.sort((a, b) => a.partNumber - b.partNumber);
|
|
395
404
|
const result = await api.multipart.complete({
|
|
405
|
+
route,
|
|
396
406
|
key,
|
|
397
407
|
uploadId,
|
|
398
|
-
parts
|
|
399
|
-
bucket
|
|
408
|
+
parts
|
|
400
409
|
});
|
|
401
|
-
await store?.delete(
|
|
410
|
+
await store?.delete(resumeKey);
|
|
402
411
|
onProgress?.({ loaded: file.size, total: file.size, percent: 100 });
|
|
403
|
-
return
|
|
412
|
+
return {
|
|
413
|
+
key,
|
|
414
|
+
eTag: result.eTag,
|
|
415
|
+
contentLength: result.contentLength,
|
|
416
|
+
contentType: result.contentType,
|
|
417
|
+
fileName: result.fileName
|
|
418
|
+
};
|
|
404
419
|
} catch (err) {
|
|
405
420
|
if (store === null) {
|
|
406
|
-
api.multipart.abort({ key, uploadId
|
|
421
|
+
api.multipart.abort({ route, key, uploadId }).catch(() => {
|
|
407
422
|
});
|
|
408
423
|
}
|
|
409
424
|
throw err;
|
|
@@ -415,48 +430,51 @@ function getUploadTransport(api) {
|
|
|
415
430
|
const transport = api.uploadTransport;
|
|
416
431
|
return typeof transport === "function" ? transport : void 0;
|
|
417
432
|
}
|
|
418
|
-
async function uploadFile(api, file,
|
|
419
|
-
const
|
|
420
|
-
const useMultipart = config.multipart === true && file.size >=
|
|
433
|
+
async function uploadFile(api, file, config, callbacks = {}, signal, requestOptions) {
|
|
434
|
+
const { route } = config;
|
|
435
|
+
const useMultipart = config.multipart === true && file.size >= DEFAULT_MULTIPART_THRESHOLD;
|
|
421
436
|
const concurrentParts = config.concurrentParts ?? DEFAULT_CONCURRENT_PARTS;
|
|
422
|
-
const
|
|
423
|
-
const contentType =
|
|
437
|
+
const rawContentType = requestOptions?.contentType ?? file.type;
|
|
438
|
+
const contentType = rawContentType.trim() === "" ? void 0 : rawContentType;
|
|
439
|
+
const fileName = requestOptions?.fileName || file.name;
|
|
440
|
+
const checksum = requestOptions?.checksum ?? (config.checksum ? await sha256File(file) : void 0);
|
|
424
441
|
try {
|
|
425
442
|
if (useMultipart) {
|
|
426
|
-
callbacks.onPhaseChange?.("
|
|
427
|
-
|
|
428
|
-
const eTag = await uploadMultipart(
|
|
443
|
+
callbacks.onPhaseChange?.("presigning");
|
|
444
|
+
return await uploadMultipart(
|
|
429
445
|
api,
|
|
430
446
|
file,
|
|
431
|
-
|
|
432
|
-
|
|
447
|
+
route,
|
|
448
|
+
DEFAULT_PART_SIZE,
|
|
433
449
|
concurrentParts,
|
|
434
450
|
callbacks.onProgress,
|
|
435
451
|
signal,
|
|
436
|
-
requestOptions,
|
|
452
|
+
{ ...requestOptions, checksum },
|
|
437
453
|
config.retry,
|
|
438
454
|
config.uploadStore,
|
|
439
455
|
callbacks.onPartUpload,
|
|
440
456
|
(uploadId, serverKey) => {
|
|
441
|
-
|
|
457
|
+
callbacks.onPhaseChange?.("uploading");
|
|
442
458
|
callbacks.onMultipartInit?.(uploadId, serverKey);
|
|
443
459
|
}
|
|
444
460
|
);
|
|
445
|
-
return { key, eTag };
|
|
446
461
|
}
|
|
447
|
-
|
|
462
|
+
callbacks.onPhaseChange?.("presigning");
|
|
463
|
+
const presign = await withRetry(
|
|
464
|
+
async () => api.upload({
|
|
465
|
+
route,
|
|
466
|
+
contentType,
|
|
467
|
+
fileSize: file.size,
|
|
468
|
+
fileName,
|
|
469
|
+
metadata: requestOptions?.metadata,
|
|
470
|
+
checksum
|
|
471
|
+
}),
|
|
472
|
+
config.retry,
|
|
473
|
+
signal
|
|
474
|
+
);
|
|
475
|
+
callbacks.onPhaseChange?.("uploading");
|
|
476
|
+
await withRetry(
|
|
448
477
|
async () => {
|
|
449
|
-
callbacks.onPhaseChange?.("presigning");
|
|
450
|
-
const presign = await api.upload({
|
|
451
|
-
key: objectKey,
|
|
452
|
-
contentType,
|
|
453
|
-
fileSize: file.size,
|
|
454
|
-
fileName: requestOptions?.fileName !== null ? requestOptions?.fileName ?? file.name : void 0,
|
|
455
|
-
metadata: requestOptions?.metadata,
|
|
456
|
-
bucket: requestOptions?.bucket,
|
|
457
|
-
acl: requestOptions?.acl
|
|
458
|
-
});
|
|
459
|
-
callbacks.onPhaseChange?.("uploading");
|
|
460
478
|
const transport = getUploadTransport(api);
|
|
461
479
|
if (transport) {
|
|
462
480
|
await transport(file, presign, {
|
|
@@ -467,7 +485,7 @@ async function uploadFile(api, file, objectKey, config = {}, callbacks = {}, sig
|
|
|
467
485
|
await uploadPut(
|
|
468
486
|
file,
|
|
469
487
|
presign.url,
|
|
470
|
-
presign.headers
|
|
488
|
+
presign.headers,
|
|
471
489
|
callbacks.onProgress,
|
|
472
490
|
signal
|
|
473
491
|
);
|
|
@@ -475,28 +493,38 @@ async function uploadFile(api, file, objectKey, config = {}, callbacks = {}, sig
|
|
|
475
493
|
await uploadSimple(
|
|
476
494
|
file,
|
|
477
495
|
presign.url,
|
|
478
|
-
presign.fields
|
|
496
|
+
presign.fields,
|
|
479
497
|
callbacks.onProgress,
|
|
480
498
|
signal
|
|
481
499
|
);
|
|
482
500
|
}
|
|
483
|
-
callbacks.onPhaseChange?.("finalizing");
|
|
484
|
-
const confirmed = await api.confirm({
|
|
485
|
-
key: presign.key,
|
|
486
|
-
bucket: presign.bucket
|
|
487
|
-
});
|
|
488
|
-
return { key: presign.key, eTag: confirmed.eTag };
|
|
489
501
|
},
|
|
490
502
|
config.retry,
|
|
491
503
|
signal
|
|
492
504
|
);
|
|
505
|
+
callbacks.onPhaseChange?.("finalizing");
|
|
506
|
+
const confirmed = await withRetry(
|
|
507
|
+
async () => api.confirm({
|
|
508
|
+
route,
|
|
509
|
+
key: presign.key
|
|
510
|
+
}),
|
|
511
|
+
config.retry,
|
|
512
|
+
signal
|
|
513
|
+
);
|
|
514
|
+
return {
|
|
515
|
+
key: confirmed.key,
|
|
516
|
+
eTag: confirmed.eTag,
|
|
517
|
+
contentLength: confirmed.contentLength,
|
|
518
|
+
contentType: confirmed.contentType,
|
|
519
|
+
fileName: confirmed.fileName
|
|
520
|
+
};
|
|
493
521
|
} catch (err) {
|
|
494
522
|
throw toUploadError(err, "uploading");
|
|
495
523
|
}
|
|
496
524
|
}
|
|
497
525
|
|
|
498
526
|
// src/upload/upload-files.ts
|
|
499
|
-
async function uploadFiles(api, items, config
|
|
527
|
+
async function uploadFiles(api, items, config, callbacks = {}, signal, getRequestOptions) {
|
|
500
528
|
const results = items.map((item) => ({
|
|
501
529
|
...item,
|
|
502
530
|
status: "pending",
|
|
@@ -524,7 +552,6 @@ async function uploadFiles(api, items, config = {}, callbacks = {}, signal, getR
|
|
|
524
552
|
const result = await uploadFile(
|
|
525
553
|
api,
|
|
526
554
|
item.file,
|
|
527
|
-
item.objectKey,
|
|
528
555
|
config,
|
|
529
556
|
{
|
|
530
557
|
onProgress: (progress) => {
|
|
@@ -549,11 +576,7 @@ async function uploadFiles(api, items, config = {}, callbacks = {}, signal, getR
|
|
|
549
576
|
callbacks.onFileSuccess?.(item.id, result);
|
|
550
577
|
reportTotalProgress();
|
|
551
578
|
} catch (err) {
|
|
552
|
-
if (err
|
|
553
|
-
item.status = "error";
|
|
554
|
-
item.error = toHookError(err, "Upload cancelled");
|
|
555
|
-
return;
|
|
556
|
-
}
|
|
579
|
+
if (isAbortError(err)) throw err;
|
|
557
580
|
const error = toHookError(err, "Upload failed");
|
|
558
581
|
item.status = "error";
|
|
559
582
|
item.error = error;
|
|
@@ -674,17 +697,15 @@ function useFormatDimahError() {
|
|
|
674
697
|
});
|
|
675
698
|
case S3_ERROR_CODES.INVALID_KEY.code:
|
|
676
699
|
return t("Object key is invalid", { note: "API error" });
|
|
677
|
-
case S3_ERROR_CODES.
|
|
678
|
-
return t("
|
|
700
|
+
case S3_ERROR_CODES.UNKNOWN_ROUTE.code:
|
|
701
|
+
return t("Unknown file route", { note: "API error" });
|
|
702
|
+
case S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.code:
|
|
703
|
+
return t("File type is not allowed", { note: "API error" });
|
|
679
704
|
case S3_ERROR_CODES.S3_NETWORK_ERROR.code:
|
|
680
705
|
return t("Could not reach storage ({code})", {
|
|
681
706
|
note: "API error",
|
|
682
707
|
variables: { code: param(err.params, "code", "UNKNOWN") }
|
|
683
708
|
});
|
|
684
|
-
case S3_ERROR_CODES.FILE_SIZE_REQUIRED_UPLOAD.code:
|
|
685
|
-
return t("File size is required", { note: "upload" });
|
|
686
|
-
case S3_ERROR_CODES.FILE_SIZE_REQUIRED_MULTIPART.code:
|
|
687
|
-
return t("File size is required", { note: "multipart" });
|
|
688
709
|
case S3_ERROR_CODES.MULTIPART_PART_MISSING.code:
|
|
689
710
|
return t("Uploaded part {partNumber} was not found", {
|
|
690
711
|
note: "API error",
|
|
@@ -726,6 +747,43 @@ function createThrottledSpeedUpdater(tracker, intervalMs = 500) {
|
|
|
726
747
|
};
|
|
727
748
|
}
|
|
728
749
|
|
|
750
|
+
// src/helpers/load-route-catalog.ts
|
|
751
|
+
var catalogByApi = /* @__PURE__ */ new WeakMap();
|
|
752
|
+
function loadRouteCatalog(api) {
|
|
753
|
+
const cached = catalogByApi.get(api);
|
|
754
|
+
if (cached) return cached;
|
|
755
|
+
const pending = api.catalog().catch((err) => {
|
|
756
|
+
catalogByApi.delete(api);
|
|
757
|
+
throw err;
|
|
758
|
+
});
|
|
759
|
+
catalogByApi.set(api, pending);
|
|
760
|
+
return pending;
|
|
761
|
+
}
|
|
762
|
+
function mergeRouteUploadPolicy(catalog, route, overrides) {
|
|
763
|
+
const upload = catalog?.routes[route]?.upload;
|
|
764
|
+
const fromCatalog = upload?.enabled === true ? {
|
|
765
|
+
accept: upload.fileTypes,
|
|
766
|
+
maxFileSize: upload.maxFileSize,
|
|
767
|
+
multipart: upload.multipart ? true : void 0,
|
|
768
|
+
checksum: upload.checksum
|
|
769
|
+
} : {};
|
|
770
|
+
return {
|
|
771
|
+
accept: overrides.accept ?? fromCatalog.accept,
|
|
772
|
+
maxFileSize: overrides.maxFileSize ?? fromCatalog.maxFileSize,
|
|
773
|
+
multipart: overrides.multipart ?? fromCatalog.multipart,
|
|
774
|
+
checksum: overrides.checksum ?? fromCatalog.checksum
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
async function resolveRouteUploadPolicy(api, route, overrides) {
|
|
778
|
+
if (!api) return overrides;
|
|
779
|
+
try {
|
|
780
|
+
const catalog = await loadRouteCatalog(api);
|
|
781
|
+
return mergeRouteUploadPolicy(catalog, route, overrides);
|
|
782
|
+
} catch {
|
|
783
|
+
return overrides;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
729
787
|
// src/helpers/speed-tracker.ts
|
|
730
788
|
function createSpeedTracker(windowMs = 3e3) {
|
|
731
789
|
const samples = [];
|
|
@@ -811,8 +869,10 @@ function useFileUpload(options) {
|
|
|
811
869
|
const optsRef = useLiveRef(options);
|
|
812
870
|
const apiRef = useLiveRef(contextApi);
|
|
813
871
|
const abortRef = useRef(null);
|
|
872
|
+
const generationRef = useRef(0);
|
|
814
873
|
const activeUploadRef = useRef(null);
|
|
815
874
|
const detachingRef = useRef(false);
|
|
875
|
+
const resettingRef = useRef(false);
|
|
816
876
|
const previewUrlRef = useRef(null);
|
|
817
877
|
const speedUpdaterRef = useRef(
|
|
818
878
|
createThrottledSpeedUpdater(createSpeedTracker())
|
|
@@ -825,9 +885,38 @@ function useFileUpload(options) {
|
|
|
825
885
|
revokeCurrentPreview();
|
|
826
886
|
replace(INITIAL_STATE);
|
|
827
887
|
}, [revokeCurrentPreview, replace]);
|
|
828
|
-
|
|
888
|
+
const abortMultipartSession = useCallback(
|
|
889
|
+
(active) => {
|
|
890
|
+
if (!active) return;
|
|
891
|
+
const opts = optsRef.current;
|
|
892
|
+
const api = opts.api ?? apiRef.current;
|
|
893
|
+
const storeOpt = opts.uploadStore;
|
|
894
|
+
if (storeOpt != null && storeOpt !== false) {
|
|
895
|
+
void Promise.resolve(storeOpt.delete(active.resumeKey)).catch(() => {
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
if (api && active.uploadId && active.serverKey) {
|
|
899
|
+
api.multipart.abort({
|
|
900
|
+
route: opts.route,
|
|
901
|
+
key: active.serverKey,
|
|
902
|
+
uploadId: active.uploadId
|
|
903
|
+
}).catch(() => {
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
},
|
|
907
|
+
[apiRef, optsRef]
|
|
908
|
+
);
|
|
909
|
+
useEffect(
|
|
910
|
+
() => () => {
|
|
911
|
+
generationRef.current += 1;
|
|
912
|
+
abortRef.current?.abort();
|
|
913
|
+
abortMultipartSession(activeUploadRef.current);
|
|
914
|
+
revokeCurrentPreview();
|
|
915
|
+
},
|
|
916
|
+
[abortMultipartSession, revokeCurrentPreview]
|
|
917
|
+
);
|
|
829
918
|
const upload = useCallback(
|
|
830
|
-
async (file,
|
|
919
|
+
async (file, requestOptions) => {
|
|
831
920
|
revokeCurrentPreview();
|
|
832
921
|
const previewUrl = createImagePreviewUrl(file);
|
|
833
922
|
previewUrlRef.current = previewUrl;
|
|
@@ -850,9 +939,15 @@ function useFileUpload(options) {
|
|
|
850
939
|
throw new Error(
|
|
851
940
|
"[dimah-s3] No S3Api found. Pass `api` to useFileUpload or wrap with <S3Provider>."
|
|
852
941
|
);
|
|
853
|
-
const
|
|
942
|
+
const policy = await resolveRouteUploadPolicy(api, opts.route, {
|
|
854
943
|
accept: opts.accept,
|
|
855
|
-
maxFileSize: opts.maxFileSize
|
|
944
|
+
maxFileSize: opts.maxFileSize,
|
|
945
|
+
multipart: opts.multipart,
|
|
946
|
+
checksum: opts.checksum
|
|
947
|
+
});
|
|
948
|
+
const validationError = validateFile(file, {
|
|
949
|
+
accept: policy.accept,
|
|
950
|
+
maxFileSize: policy.maxFileSize
|
|
856
951
|
});
|
|
857
952
|
if (validationError) {
|
|
858
953
|
const message = formatValidateFileError(validationError);
|
|
@@ -863,9 +958,36 @@ function useFileUpload(options) {
|
|
|
863
958
|
opts.onError?.(file, new Error(message), "validating");
|
|
864
959
|
return;
|
|
865
960
|
}
|
|
961
|
+
const mergedOptions = mergeRequestOptions(opts, file, requestOptions);
|
|
962
|
+
const previous = activeUploadRef.current;
|
|
963
|
+
abortRef.current?.abort();
|
|
964
|
+
abortMultipartSession(previous);
|
|
965
|
+
const generation = ++generationRef.current;
|
|
966
|
+
const controller = new AbortController();
|
|
967
|
+
abortRef.current = controller;
|
|
968
|
+
activeUploadRef.current = {
|
|
969
|
+
file,
|
|
970
|
+
resumeKey: multipartResumeKey(opts.route, file),
|
|
971
|
+
serverKey: "",
|
|
972
|
+
requestOptions: mergedOptions
|
|
973
|
+
};
|
|
974
|
+
const isCurrent = () => generation === generationRef.current;
|
|
975
|
+
const stopIfAborted = () => {
|
|
976
|
+
if (!controller.signal.aborted) return false;
|
|
977
|
+
if (!isCurrent()) return true;
|
|
978
|
+
abortRef.current = null;
|
|
979
|
+
activeUploadRef.current = null;
|
|
980
|
+
if (detachingRef.current) detachingRef.current = false;
|
|
981
|
+
else if (resettingRef.current) resettingRef.current = false;
|
|
982
|
+
else opts.onCancel?.(file);
|
|
983
|
+
return true;
|
|
984
|
+
};
|
|
866
985
|
if (opts.beforeUpload) {
|
|
867
986
|
const allowed = await opts.beforeUpload(file);
|
|
987
|
+
if (stopIfAborted()) return;
|
|
868
988
|
if (!allowed) {
|
|
989
|
+
abortRef.current = null;
|
|
990
|
+
activeUploadRef.current = null;
|
|
869
991
|
patch((draft) => {
|
|
870
992
|
draft.phase = "error";
|
|
871
993
|
draft.error = hookBlockedError(
|
|
@@ -876,48 +998,44 @@ function useFileUpload(options) {
|
|
|
876
998
|
return;
|
|
877
999
|
}
|
|
878
1000
|
}
|
|
1001
|
+
if (stopIfAborted()) return;
|
|
879
1002
|
speedUpdaterRef.current.reset();
|
|
880
1003
|
patch((draft) => {
|
|
881
1004
|
draft.phase = "presigning";
|
|
882
1005
|
});
|
|
883
|
-
opts.onUploadStart?.(file
|
|
884
|
-
|
|
885
|
-
const controller = new AbortController();
|
|
886
|
-
abortRef.current = controller;
|
|
887
|
-
activeUploadRef.current = {
|
|
888
|
-
file,
|
|
889
|
-
objectKey,
|
|
890
|
-
serverKey: objectKey,
|
|
891
|
-
bucket: mergedOptions?.bucket,
|
|
892
|
-
requestOptions: mergedOptions
|
|
893
|
-
};
|
|
1006
|
+
opts.onUploadStart?.(file);
|
|
1007
|
+
let errorPhase = "presigning";
|
|
894
1008
|
try {
|
|
895
1009
|
const result = await uploadFile(
|
|
896
1010
|
api,
|
|
897
1011
|
file,
|
|
898
|
-
objectKey,
|
|
899
1012
|
{
|
|
900
|
-
|
|
901
|
-
|
|
1013
|
+
route: opts.route,
|
|
1014
|
+
multipart: policy.multipart,
|
|
1015
|
+
checksum: policy.checksum,
|
|
902
1016
|
concurrentParts: opts.concurrentParts,
|
|
903
|
-
partSize: opts.partSize,
|
|
904
1017
|
retry: opts.retry,
|
|
905
1018
|
uploadStore: opts.uploadStore
|
|
906
1019
|
},
|
|
907
1020
|
{
|
|
908
1021
|
onProgress: (progress) => {
|
|
1022
|
+
if (!isCurrent()) return;
|
|
909
1023
|
const p = speedUpdaterRef.current.apply(progress);
|
|
910
1024
|
patch((draft) => {
|
|
911
1025
|
draft.progress = p;
|
|
912
1026
|
});
|
|
913
1027
|
opts.onProgress?.(file, p);
|
|
914
1028
|
},
|
|
915
|
-
onPhaseChange: (phase) =>
|
|
916
|
-
|
|
917
|
-
|
|
1029
|
+
onPhaseChange: (phase) => {
|
|
1030
|
+
if (!isCurrent()) return;
|
|
1031
|
+
errorPhase = phase;
|
|
1032
|
+
patch((draft) => {
|
|
1033
|
+
draft.phase = phase;
|
|
1034
|
+
});
|
|
1035
|
+
},
|
|
918
1036
|
onPartUpload: (partNumber, totalParts) => opts.onPartUpload?.(file, partNumber, totalParts),
|
|
919
1037
|
onMultipartInit: (uploadId, serverKey) => {
|
|
920
|
-
if (activeUploadRef.current) {
|
|
1038
|
+
if (activeUploadRef.current && isCurrent()) {
|
|
921
1039
|
activeUploadRef.current.uploadId = uploadId;
|
|
922
1040
|
activeUploadRef.current.serverKey = serverKey;
|
|
923
1041
|
}
|
|
@@ -927,6 +1045,7 @@ function useFileUpload(options) {
|
|
|
927
1045
|
controller.signal,
|
|
928
1046
|
mergedOptions
|
|
929
1047
|
);
|
|
1048
|
+
if (!isCurrent()) return;
|
|
930
1049
|
patch((draft) => {
|
|
931
1050
|
draft.phase = "success";
|
|
932
1051
|
draft.result = result;
|
|
@@ -936,13 +1055,22 @@ function useFileUpload(options) {
|
|
|
936
1055
|
percent: 100
|
|
937
1056
|
};
|
|
938
1057
|
});
|
|
939
|
-
|
|
1058
|
+
try {
|
|
1059
|
+
await opts.onSuccess?.(file, result);
|
|
1060
|
+
} catch (err) {
|
|
1061
|
+
opts.onError?.(file, err, "success");
|
|
1062
|
+
}
|
|
940
1063
|
} catch (err) {
|
|
941
|
-
if (
|
|
1064
|
+
if (!isCurrent()) return;
|
|
1065
|
+
if (isAbortError(err)) {
|
|
942
1066
|
if (detachingRef.current) {
|
|
943
1067
|
detachingRef.current = false;
|
|
944
1068
|
return;
|
|
945
1069
|
}
|
|
1070
|
+
if (resettingRef.current) {
|
|
1071
|
+
resettingRef.current = false;
|
|
1072
|
+
return;
|
|
1073
|
+
}
|
|
946
1074
|
opts.onCancel?.(file);
|
|
947
1075
|
clearToIdle();
|
|
948
1076
|
return;
|
|
@@ -952,13 +1080,16 @@ function useFileUpload(options) {
|
|
|
952
1080
|
draft.phase = "error";
|
|
953
1081
|
draft.error = toHookError(err, message);
|
|
954
1082
|
});
|
|
955
|
-
opts.onError?.(file, err,
|
|
1083
|
+
opts.onError?.(file, err, errorPhase);
|
|
956
1084
|
} finally {
|
|
957
|
-
|
|
958
|
-
|
|
1085
|
+
if (isCurrent()) {
|
|
1086
|
+
abortRef.current = null;
|
|
1087
|
+
activeUploadRef.current = null;
|
|
1088
|
+
}
|
|
959
1089
|
}
|
|
960
1090
|
},
|
|
961
1091
|
[
|
|
1092
|
+
abortMultipartSession,
|
|
962
1093
|
apiRef,
|
|
963
1094
|
optsRef,
|
|
964
1095
|
formatValidateFileError,
|
|
@@ -968,33 +1099,30 @@ function useFileUpload(options) {
|
|
|
968
1099
|
]
|
|
969
1100
|
);
|
|
970
1101
|
const cancel = useCallback(() => {
|
|
971
|
-
const opts = optsRef.current;
|
|
972
|
-
const api = opts.api ?? apiRef.current;
|
|
973
1102
|
const active = activeUploadRef.current;
|
|
1103
|
+
generationRef.current += 1;
|
|
974
1104
|
abortRef.current?.abort();
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
void Promise.resolve(storeOpt.delete(objectKey)).catch(() => {
|
|
980
|
-
});
|
|
981
|
-
}
|
|
982
|
-
if (uploadId) {
|
|
983
|
-
api.multipart.abort({ key: serverKey, uploadId, bucket }).catch(() => {
|
|
984
|
-
});
|
|
985
|
-
}
|
|
986
|
-
}
|
|
1105
|
+
abortMultipartSession(active);
|
|
1106
|
+
abortRef.current = null;
|
|
1107
|
+
activeUploadRef.current = null;
|
|
1108
|
+
if (active) optsRef.current.onCancel?.(active.file);
|
|
987
1109
|
clearToIdle();
|
|
988
|
-
}, [
|
|
1110
|
+
}, [abortMultipartSession, optsRef, clearToIdle]);
|
|
989
1111
|
const detach = useCallback(() => {
|
|
990
|
-
|
|
991
|
-
if (!active) return;
|
|
1112
|
+
if (!activeUploadRef.current) return;
|
|
992
1113
|
detachingRef.current = true;
|
|
1114
|
+
generationRef.current += 1;
|
|
993
1115
|
abortRef.current?.abort();
|
|
1116
|
+
abortRef.current = null;
|
|
1117
|
+
activeUploadRef.current = null;
|
|
994
1118
|
clearToIdle();
|
|
995
1119
|
}, [clearToIdle]);
|
|
996
1120
|
const reset = useCallback(() => {
|
|
1121
|
+
resettingRef.current = true;
|
|
1122
|
+
generationRef.current += 1;
|
|
997
1123
|
abortRef.current?.abort();
|
|
1124
|
+
abortRef.current = null;
|
|
1125
|
+
activeUploadRef.current = null;
|
|
998
1126
|
clearToIdle();
|
|
999
1127
|
}, [clearToIdle]);
|
|
1000
1128
|
return {
|
|
@@ -1028,6 +1156,7 @@ function useMultiFileUpload(options) {
|
|
|
1028
1156
|
const optsRef = useLiveRef(options);
|
|
1029
1157
|
const apiRef = useLiveRef(contextApi);
|
|
1030
1158
|
const abortRef = useRef(null);
|
|
1159
|
+
const generationRef = useRef(0);
|
|
1031
1160
|
const resettingRef = useRef(false);
|
|
1032
1161
|
const detachingRef = useRef(false);
|
|
1033
1162
|
const fileMapRef = useRef(/* @__PURE__ */ new Map());
|
|
@@ -1045,9 +1174,39 @@ function useMultiFileUpload(options) {
|
|
|
1045
1174
|
revokeAllPreviews();
|
|
1046
1175
|
replace(INITIAL_STATE2);
|
|
1047
1176
|
}, [revokeAllPreviews, replace]);
|
|
1048
|
-
|
|
1177
|
+
const abortMultipartSessions = useCallback(() => {
|
|
1178
|
+
const opts = optsRef.current;
|
|
1179
|
+
const api = opts.api ?? apiRef.current;
|
|
1180
|
+
const uploadStore = opts.uploadStore;
|
|
1181
|
+
for (const active of activeUploadsRef.current.values()) {
|
|
1182
|
+
if (uploadStore != null && uploadStore !== false) {
|
|
1183
|
+
void Promise.resolve(uploadStore.delete(active.resumeKey)).catch(
|
|
1184
|
+
() => {
|
|
1185
|
+
}
|
|
1186
|
+
);
|
|
1187
|
+
}
|
|
1188
|
+
if (api && active.uploadId && active.serverKey) {
|
|
1189
|
+
api.multipart.abort({
|
|
1190
|
+
route: opts.route,
|
|
1191
|
+
key: active.serverKey,
|
|
1192
|
+
uploadId: active.uploadId
|
|
1193
|
+
}).catch(() => {
|
|
1194
|
+
});
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
activeUploadsRef.current.clear();
|
|
1198
|
+
}, [apiRef, optsRef]);
|
|
1199
|
+
useEffect(
|
|
1200
|
+
() => () => {
|
|
1201
|
+
generationRef.current += 1;
|
|
1202
|
+
abortRef.current?.abort();
|
|
1203
|
+
abortMultipartSessions();
|
|
1204
|
+
revokeAllPreviews();
|
|
1205
|
+
},
|
|
1206
|
+
[abortMultipartSessions, revokeAllPreviews]
|
|
1207
|
+
);
|
|
1049
1208
|
const upload = useCallback(
|
|
1050
|
-
async (files
|
|
1209
|
+
async (files) => {
|
|
1051
1210
|
const opts = optsRef.current;
|
|
1052
1211
|
const api = opts.api ?? apiRef.current;
|
|
1053
1212
|
if (!api)
|
|
@@ -1061,6 +1220,12 @@ function useMultiFileUpload(options) {
|
|
|
1061
1220
|
draft.phase = "validating";
|
|
1062
1221
|
draft.error = null;
|
|
1063
1222
|
});
|
|
1223
|
+
const policy = await resolveRouteUploadPolicy(api, opts.route, {
|
|
1224
|
+
accept: opts.accept,
|
|
1225
|
+
maxFileSize: opts.maxFileSize,
|
|
1226
|
+
multipart: opts.multipart,
|
|
1227
|
+
checksum: opts.checksum
|
|
1228
|
+
});
|
|
1064
1229
|
if (opts.maxFiles && files.length > opts.maxFiles) {
|
|
1065
1230
|
const msg = `Too many files. Maximum is ${opts.maxFiles}.`;
|
|
1066
1231
|
patch((draft) => {
|
|
@@ -1072,8 +1237,8 @@ function useMultiFileUpload(options) {
|
|
|
1072
1237
|
}
|
|
1073
1238
|
for (const file of files) {
|
|
1074
1239
|
const validationError = validateFile(file, {
|
|
1075
|
-
accept:
|
|
1076
|
-
maxFileSize:
|
|
1240
|
+
accept: policy.accept,
|
|
1241
|
+
maxFileSize: policy.maxFileSize
|
|
1077
1242
|
});
|
|
1078
1243
|
if (validationError) {
|
|
1079
1244
|
const detail = formatValidateFileError(validationError);
|
|
@@ -1086,9 +1251,24 @@ function useMultiFileUpload(options) {
|
|
|
1086
1251
|
return;
|
|
1087
1252
|
}
|
|
1088
1253
|
}
|
|
1254
|
+
abortRef.current?.abort();
|
|
1255
|
+
abortMultipartSessions();
|
|
1256
|
+
const generation = ++generationRef.current;
|
|
1257
|
+
const controller = new AbortController();
|
|
1258
|
+
abortRef.current = controller;
|
|
1259
|
+
const isCurrent = () => generation === generationRef.current;
|
|
1089
1260
|
if (opts.beforeUpload) {
|
|
1090
1261
|
const allowed = await opts.beforeUpload(files);
|
|
1262
|
+
if (controller.signal.aborted) {
|
|
1263
|
+
if (!isCurrent()) return;
|
|
1264
|
+
abortRef.current = null;
|
|
1265
|
+
if (detachingRef.current) detachingRef.current = false;
|
|
1266
|
+
else if (resettingRef.current) resettingRef.current = false;
|
|
1267
|
+
else opts.onCancel?.();
|
|
1268
|
+
return;
|
|
1269
|
+
}
|
|
1091
1270
|
if (!allowed) {
|
|
1271
|
+
abortRef.current = null;
|
|
1092
1272
|
patch((draft) => {
|
|
1093
1273
|
draft.phase = "error";
|
|
1094
1274
|
draft.error = hookBlockedError(
|
|
@@ -1099,14 +1279,21 @@ function useMultiFileUpload(options) {
|
|
|
1099
1279
|
return;
|
|
1100
1280
|
}
|
|
1101
1281
|
}
|
|
1282
|
+
if (controller.signal.aborted) {
|
|
1283
|
+
if (!isCurrent()) return;
|
|
1284
|
+
abortRef.current = null;
|
|
1285
|
+
if (detachingRef.current) detachingRef.current = false;
|
|
1286
|
+
else if (resettingRef.current) resettingRef.current = false;
|
|
1287
|
+
else opts.onCancel?.();
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1102
1290
|
revokeAllPreviews();
|
|
1103
1291
|
const nextPreviewUrls = [];
|
|
1104
1292
|
for (const file of files) {
|
|
1105
1293
|
const id = generateId();
|
|
1106
|
-
const objectKey = resolveKey(file);
|
|
1107
1294
|
const previewUrl = createImagePreviewUrl(file);
|
|
1108
1295
|
if (previewUrl) nextPreviewUrls.push(previewUrl);
|
|
1109
|
-
items.push({ id, file
|
|
1296
|
+
items.push({ id, file });
|
|
1110
1297
|
fileMap.set(id, file);
|
|
1111
1298
|
fileStates.push({
|
|
1112
1299
|
id,
|
|
@@ -1116,7 +1303,8 @@ function useMultiFileUpload(options) {
|
|
|
1116
1303
|
previewUrl,
|
|
1117
1304
|
status: "pending",
|
|
1118
1305
|
progress: { loaded: 0, total: file.size, percent: 0 },
|
|
1119
|
-
error: null
|
|
1306
|
+
error: null,
|
|
1307
|
+
result: null
|
|
1120
1308
|
});
|
|
1121
1309
|
}
|
|
1122
1310
|
previewUrlsRef.current = nextPreviewUrls;
|
|
@@ -1125,9 +1313,8 @@ function useMultiFileUpload(options) {
|
|
|
1125
1313
|
items.map((item) => [
|
|
1126
1314
|
item.id,
|
|
1127
1315
|
{
|
|
1128
|
-
|
|
1129
|
-
serverKey:
|
|
1130
|
-
bucket: opts.getUploadOptions?.(item.file)?.bucket ?? opts.uploadOptions?.bucket
|
|
1316
|
+
resumeKey: multipartResumeKey(opts.route, item.file),
|
|
1317
|
+
serverKey: ""
|
|
1131
1318
|
}
|
|
1132
1319
|
])
|
|
1133
1320
|
);
|
|
@@ -1150,23 +1337,22 @@ function useMultiFileUpload(options) {
|
|
|
1150
1337
|
);
|
|
1151
1338
|
}
|
|
1152
1339
|
totalSpeedUpdaterRef.current.reset();
|
|
1153
|
-
const controller = new AbortController();
|
|
1154
|
-
abortRef.current = controller;
|
|
1155
1340
|
try {
|
|
1156
1341
|
const results = await uploadFiles(
|
|
1157
1342
|
api,
|
|
1158
1343
|
items,
|
|
1159
1344
|
{
|
|
1160
|
-
|
|
1161
|
-
|
|
1345
|
+
route: opts.route,
|
|
1346
|
+
multipart: policy.multipart,
|
|
1347
|
+
checksum: policy.checksum,
|
|
1162
1348
|
concurrentParts: opts.concurrentParts,
|
|
1163
1349
|
concurrentFiles: opts.concurrentFiles,
|
|
1164
|
-
partSize: opts.partSize,
|
|
1165
1350
|
retry: opts.retry,
|
|
1166
1351
|
uploadStore: opts.uploadStore
|
|
1167
1352
|
},
|
|
1168
1353
|
{
|
|
1169
1354
|
onFileProgress: (id, progress) => {
|
|
1355
|
+
if (!isCurrent()) return;
|
|
1170
1356
|
const updater = fileSpeedUpdatersRef.current.get(id);
|
|
1171
1357
|
const p = updater ? updater.apply(progress) : progress;
|
|
1172
1358
|
patch((draft) => {
|
|
@@ -1180,11 +1366,13 @@ function useMultiFileUpload(options) {
|
|
|
1180
1366
|
if (file) opts.onFileProgress?.(file, p);
|
|
1181
1367
|
},
|
|
1182
1368
|
onFileSuccess: (id, result) => {
|
|
1369
|
+
if (!isCurrent()) return;
|
|
1183
1370
|
activeUploadsRef.current.delete(id);
|
|
1184
1371
|
patch((draft) => {
|
|
1185
1372
|
const fileState = draft.files.find((f) => f.id === id);
|
|
1186
1373
|
if (fileState) {
|
|
1187
1374
|
fileState.status = "success";
|
|
1375
|
+
fileState.result = result;
|
|
1188
1376
|
fileState.progress = {
|
|
1189
1377
|
loaded: fileState.size,
|
|
1190
1378
|
total: fileState.size,
|
|
@@ -1196,6 +1384,7 @@ function useMultiFileUpload(options) {
|
|
|
1196
1384
|
if (file) opts.onFileSuccess?.(file, result);
|
|
1197
1385
|
},
|
|
1198
1386
|
onFileError: (id, error) => {
|
|
1387
|
+
if (!isCurrent()) return;
|
|
1199
1388
|
patch((draft) => {
|
|
1200
1389
|
const fileState = draft.files.find((f) => f.id === id);
|
|
1201
1390
|
if (fileState) {
|
|
@@ -1207,6 +1396,7 @@ function useMultiFileUpload(options) {
|
|
|
1207
1396
|
if (file) opts.onFileError?.(file, error);
|
|
1208
1397
|
},
|
|
1209
1398
|
onTotalProgress: (progress) => {
|
|
1399
|
+
if (!isCurrent()) return;
|
|
1210
1400
|
const p = totalSpeedUpdaterRef.current.apply(progress);
|
|
1211
1401
|
patch((draft) => {
|
|
1212
1402
|
draft.totalProgress = p;
|
|
@@ -1228,6 +1418,7 @@ function useMultiFileUpload(options) {
|
|
|
1228
1418
|
return { ...opts.uploadOptions, ...perFile };
|
|
1229
1419
|
}
|
|
1230
1420
|
);
|
|
1421
|
+
if (!isCurrent()) return;
|
|
1231
1422
|
const hasErrors = results.some((r) => r.status === "error");
|
|
1232
1423
|
const successResults = results.filter((r) => r.result !== null).map((r) => r.result);
|
|
1233
1424
|
patch((draft) => {
|
|
@@ -1244,10 +1435,15 @@ function useMultiFileUpload(options) {
|
|
|
1244
1435
|
}
|
|
1245
1436
|
});
|
|
1246
1437
|
if (!hasErrors) {
|
|
1247
|
-
|
|
1438
|
+
try {
|
|
1439
|
+
await opts.onSuccess?.(successResults);
|
|
1440
|
+
} catch (err) {
|
|
1441
|
+
opts.onError?.(err);
|
|
1442
|
+
}
|
|
1248
1443
|
}
|
|
1249
1444
|
} catch (err) {
|
|
1250
|
-
if (
|
|
1445
|
+
if (!isCurrent()) return;
|
|
1446
|
+
if (isAbortError(err)) {
|
|
1251
1447
|
if (detachingRef.current) {
|
|
1252
1448
|
detachingRef.current = false;
|
|
1253
1449
|
return;
|
|
@@ -1263,11 +1459,14 @@ function useMultiFileUpload(options) {
|
|
|
1263
1459
|
});
|
|
1264
1460
|
opts.onError?.(err);
|
|
1265
1461
|
} finally {
|
|
1266
|
-
|
|
1267
|
-
|
|
1462
|
+
if (isCurrent()) {
|
|
1463
|
+
abortRef.current = null;
|
|
1464
|
+
activeUploadsRef.current.clear();
|
|
1465
|
+
}
|
|
1268
1466
|
}
|
|
1269
1467
|
},
|
|
1270
1468
|
[
|
|
1469
|
+
abortMultipartSessions,
|
|
1271
1470
|
apiRef,
|
|
1272
1471
|
optsRef,
|
|
1273
1472
|
formatValidateFileError,
|
|
@@ -1277,40 +1476,29 @@ function useMultiFileUpload(options) {
|
|
|
1277
1476
|
]
|
|
1278
1477
|
);
|
|
1279
1478
|
const cancel = useCallback(() => {
|
|
1280
|
-
const
|
|
1281
|
-
|
|
1479
|
+
const hadWork = abortRef.current != null || activeUploadsRef.current.size > 0;
|
|
1480
|
+
generationRef.current += 1;
|
|
1282
1481
|
abortRef.current?.abort();
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
if (uploadStore != null && uploadStore !== false) {
|
|
1287
|
-
void Promise.resolve(uploadStore.delete(active.objectKey)).catch(
|
|
1288
|
-
() => {
|
|
1289
|
-
}
|
|
1290
|
-
);
|
|
1291
|
-
}
|
|
1292
|
-
if (active.uploadId) {
|
|
1293
|
-
api.multipart.abort({
|
|
1294
|
-
key: active.serverKey,
|
|
1295
|
-
uploadId: active.uploadId,
|
|
1296
|
-
bucket: active.bucket
|
|
1297
|
-
}).catch(() => {
|
|
1298
|
-
});
|
|
1299
|
-
}
|
|
1300
|
-
}
|
|
1301
|
-
}
|
|
1302
|
-
activeUploadsRef.current.clear();
|
|
1482
|
+
abortMultipartSessions();
|
|
1483
|
+
abortRef.current = null;
|
|
1484
|
+
if (hadWork) optsRef.current.onCancel?.();
|
|
1303
1485
|
clearToIdle();
|
|
1304
|
-
}, [
|
|
1486
|
+
}, [abortMultipartSessions, optsRef, clearToIdle]);
|
|
1305
1487
|
const detach = useCallback(() => {
|
|
1306
|
-
if (activeUploadsRef.current.size === 0) return;
|
|
1488
|
+
if (activeUploadsRef.current.size === 0 && !abortRef.current) return;
|
|
1307
1489
|
detachingRef.current = true;
|
|
1490
|
+
generationRef.current += 1;
|
|
1308
1491
|
abortRef.current?.abort();
|
|
1492
|
+
abortRef.current = null;
|
|
1493
|
+
activeUploadsRef.current.clear();
|
|
1309
1494
|
clearToIdle();
|
|
1310
1495
|
}, [clearToIdle]);
|
|
1311
1496
|
const reset = useCallback(() => {
|
|
1312
1497
|
resettingRef.current = true;
|
|
1498
|
+
generationRef.current += 1;
|
|
1313
1499
|
abortRef.current?.abort();
|
|
1500
|
+
abortRef.current = null;
|
|
1501
|
+
activeUploadsRef.current.clear();
|
|
1314
1502
|
clearToIdle();
|
|
1315
1503
|
}, [clearToIdle]);
|
|
1316
1504
|
return {
|
|
@@ -1383,33 +1571,54 @@ function useFileIntake(options) {
|
|
|
1383
1571
|
fileRejections
|
|
1384
1572
|
};
|
|
1385
1573
|
}
|
|
1574
|
+
function useRouteUploadPolicy(options) {
|
|
1575
|
+
const contextApi = useContext(S3Context);
|
|
1576
|
+
const api = options.api ?? contextApi;
|
|
1577
|
+
const optsRef = useLiveRef(options);
|
|
1578
|
+
const [catalogPolicy, setCatalogPolicy] = useState({});
|
|
1579
|
+
useEffect(() => {
|
|
1580
|
+
if (!api) return;
|
|
1581
|
+
let cancelled = false;
|
|
1582
|
+
void loadRouteCatalog(api).then((catalog) => {
|
|
1583
|
+
if (cancelled) return;
|
|
1584
|
+
setCatalogPolicy(
|
|
1585
|
+
mergeRouteUploadPolicy(catalog, optsRef.current.route, {})
|
|
1586
|
+
);
|
|
1587
|
+
}).catch(() => {
|
|
1588
|
+
});
|
|
1589
|
+
return () => {
|
|
1590
|
+
cancelled = true;
|
|
1591
|
+
};
|
|
1592
|
+
}, [api, options.route, optsRef]);
|
|
1593
|
+
return mergeRouteUploadPolicy(null, options.route, {
|
|
1594
|
+
accept: options.accept ?? catalogPolicy.accept,
|
|
1595
|
+
maxFileSize: options.maxFileSize ?? catalogPolicy.maxFileSize,
|
|
1596
|
+
multipart: options.multipart ?? catalogPolicy.multipart,
|
|
1597
|
+
checksum: options.checksum ?? catalogPolicy.checksum
|
|
1598
|
+
});
|
|
1599
|
+
}
|
|
1386
1600
|
|
|
1387
1601
|
// src/hooks/use-upload.ts
|
|
1388
1602
|
function useUpload(options) {
|
|
1389
|
-
const {
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
}
|
|
1603
|
+
const { disabled, noDrag, noClick, noKeyboard, onFileReject, ...uploadOpts } = options;
|
|
1604
|
+
const policy = useRouteUploadPolicy({
|
|
1605
|
+
api: options.api,
|
|
1606
|
+
route: options.route,
|
|
1607
|
+
accept: options.accept,
|
|
1608
|
+
maxFileSize: options.maxFileSize,
|
|
1609
|
+
multipart: options.multipart,
|
|
1610
|
+
checksum: options.checksum
|
|
1611
|
+
});
|
|
1398
1612
|
const single = useFileUpload(uploadOpts);
|
|
1399
|
-
const resolveKey = (file) => {
|
|
1400
|
-
if (typeof objectKey === "function") return objectKey(file);
|
|
1401
|
-
if (objectKey) return objectKey;
|
|
1402
|
-
return defaultObjectKey(file);
|
|
1403
|
-
};
|
|
1404
1613
|
const handleFiles = (files) => {
|
|
1405
1614
|
const list = files == null ? [] : Array.from(files);
|
|
1406
1615
|
const file = list[0];
|
|
1407
1616
|
if (!file) return;
|
|
1408
|
-
void single.upload(file
|
|
1617
|
+
void single.upload(file);
|
|
1409
1618
|
};
|
|
1410
1619
|
const intake = useFileIntake({
|
|
1411
|
-
accept:
|
|
1412
|
-
maxFileSize:
|
|
1620
|
+
accept: policy.accept,
|
|
1621
|
+
maxFileSize: policy.maxFileSize,
|
|
1413
1622
|
maxFiles: 1,
|
|
1414
1623
|
multiple: false,
|
|
1415
1624
|
disabled: Boolean(disabled) || single.isPending,
|
|
@@ -1424,6 +1633,7 @@ function useUpload(options) {
|
|
|
1424
1633
|
fileInfo: single.fileInfo,
|
|
1425
1634
|
progress: single.progress,
|
|
1426
1635
|
error: single.error,
|
|
1636
|
+
result: single.result,
|
|
1427
1637
|
isUploading: single.isUploading,
|
|
1428
1638
|
isPending: single.isPending,
|
|
1429
1639
|
handleFiles,
|
|
@@ -1439,30 +1649,28 @@ function useUpload(options) {
|
|
|
1439
1649
|
fileRejections: intake.fileRejections
|
|
1440
1650
|
};
|
|
1441
1651
|
}
|
|
1652
|
+
|
|
1653
|
+
// src/hooks/use-multi-upload.ts
|
|
1442
1654
|
function useMultiUpload(options) {
|
|
1443
|
-
const {
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
}
|
|
1655
|
+
const { disabled, noDrag, noClick, noKeyboard, onFileReject, ...multiOpts } = options;
|
|
1656
|
+
const policy = useRouteUploadPolicy({
|
|
1657
|
+
api: options.api,
|
|
1658
|
+
route: options.route,
|
|
1659
|
+
accept: options.accept,
|
|
1660
|
+
maxFileSize: options.maxFileSize,
|
|
1661
|
+
multipart: options.multipart,
|
|
1662
|
+
checksum: options.checksum
|
|
1663
|
+
});
|
|
1452
1664
|
const multi = useMultiFileUpload(multiOpts);
|
|
1453
|
-
const resolveKey = (file) => {
|
|
1454
|
-
if (objectKey) return objectKey(file);
|
|
1455
|
-
return defaultObjectKey(file);
|
|
1456
|
-
};
|
|
1457
1665
|
const handleFiles = (files) => {
|
|
1458
1666
|
if (files == null) return;
|
|
1459
1667
|
const list = Array.from(files);
|
|
1460
1668
|
if (list.length === 0) return;
|
|
1461
|
-
void multi.upload(list
|
|
1669
|
+
void multi.upload(list);
|
|
1462
1670
|
};
|
|
1463
1671
|
const intake = useFileIntake({
|
|
1464
|
-
accept:
|
|
1465
|
-
maxFileSize:
|
|
1672
|
+
accept: policy.accept,
|
|
1673
|
+
maxFileSize: policy.maxFileSize,
|
|
1466
1674
|
maxFiles: options.maxFiles,
|
|
1467
1675
|
multiple: true,
|
|
1468
1676
|
disabled: Boolean(disabled) || multi.isPending,
|
|
@@ -1505,12 +1713,14 @@ var INITIAL_STATE3 = {
|
|
|
1505
1713
|
function missingApiMessage(hook) {
|
|
1506
1714
|
return `[dimah-s3] No S3Api found. Pass \`api\` to ${hook} or wrap with <S3Provider>.`;
|
|
1507
1715
|
}
|
|
1508
|
-
function useDownload(options
|
|
1716
|
+
function useDownload(options) {
|
|
1509
1717
|
const [state, patch, replace] = useImmerState(INITIAL_STATE3);
|
|
1510
1718
|
const contextApi = useContext(S3Context);
|
|
1511
1719
|
const optsRef = useLiveRef(options);
|
|
1512
1720
|
const apiRef = useLiveRef(contextApi);
|
|
1513
1721
|
const abortRef = useRef(null);
|
|
1722
|
+
const generationRef = useRef(0);
|
|
1723
|
+
const downloadKeyRef = useRef(null);
|
|
1514
1724
|
const resettingRef = useRef(false);
|
|
1515
1725
|
const speedUpdaterRef = useRef(
|
|
1516
1726
|
createThrottledSpeedUpdater(createSpeedTracker())
|
|
@@ -1527,9 +1737,11 @@ function useDownload(options = {}) {
|
|
|
1527
1737
|
draft.expiresIn = null;
|
|
1528
1738
|
});
|
|
1529
1739
|
try {
|
|
1530
|
-
const result = await api.download(
|
|
1740
|
+
const result = await api.download({
|
|
1741
|
+
route: opts.route,
|
|
1742
|
+
key,
|
|
1531
1743
|
fileName: downloadName,
|
|
1532
|
-
|
|
1744
|
+
...opts.disposition ? { disposition: opts.disposition } : {}
|
|
1533
1745
|
});
|
|
1534
1746
|
patch((draft) => {
|
|
1535
1747
|
draft.phase = "idle";
|
|
@@ -1582,6 +1794,7 @@ function useDownload(options = {}) {
|
|
|
1582
1794
|
const opts = optsRef.current;
|
|
1583
1795
|
const api = opts.api ?? apiRef.current;
|
|
1584
1796
|
if (!api) throw new Error(missingApiMessage("useDownload"));
|
|
1797
|
+
downloadKeyRef.current = key;
|
|
1585
1798
|
if (opts.beforeDownload) {
|
|
1586
1799
|
const allowed = await opts.beforeDownload(key);
|
|
1587
1800
|
if (!allowed) {
|
|
@@ -1595,6 +1808,9 @@ function useDownload(options = {}) {
|
|
|
1595
1808
|
return;
|
|
1596
1809
|
}
|
|
1597
1810
|
}
|
|
1811
|
+
abortRef.current?.abort();
|
|
1812
|
+
const generation = ++generationRef.current;
|
|
1813
|
+
const isCurrent = () => generation === generationRef.current;
|
|
1598
1814
|
patch((draft) => {
|
|
1599
1815
|
draft.phase = "presigning";
|
|
1600
1816
|
draft.progress = { ...INITIAL_PROGRESS3 };
|
|
@@ -1603,10 +1819,13 @@ function useDownload(options = {}) {
|
|
|
1603
1819
|
draft.fileSize = null;
|
|
1604
1820
|
});
|
|
1605
1821
|
try {
|
|
1606
|
-
const { url } = await api.download(
|
|
1822
|
+
const { url } = await api.download({
|
|
1823
|
+
route: opts.route,
|
|
1824
|
+
key,
|
|
1607
1825
|
fileName: downloadName,
|
|
1608
|
-
|
|
1826
|
+
...opts.disposition ? { disposition: opts.disposition } : {}
|
|
1609
1827
|
});
|
|
1828
|
+
if (!isCurrent()) return;
|
|
1610
1829
|
patch((draft) => {
|
|
1611
1830
|
draft.phase = "downloading";
|
|
1612
1831
|
});
|
|
@@ -1641,6 +1860,7 @@ function useDownload(options = {}) {
|
|
|
1641
1860
|
total: contentLength,
|
|
1642
1861
|
percent
|
|
1643
1862
|
});
|
|
1863
|
+
if (!isCurrent()) return;
|
|
1644
1864
|
patch((draft) => {
|
|
1645
1865
|
draft.progress = progress;
|
|
1646
1866
|
});
|
|
@@ -1653,6 +1873,7 @@ function useDownload(options = {}) {
|
|
|
1653
1873
|
anchor.download = name ?? fallback;
|
|
1654
1874
|
anchor.click();
|
|
1655
1875
|
URL.revokeObjectURL(blobUrl);
|
|
1876
|
+
if (!isCurrent()) return;
|
|
1656
1877
|
patch((draft) => {
|
|
1657
1878
|
draft.phase = "success";
|
|
1658
1879
|
draft.fileSize = blob.size;
|
|
@@ -1662,9 +1883,14 @@ function useDownload(options = {}) {
|
|
|
1662
1883
|
percent: 100
|
|
1663
1884
|
};
|
|
1664
1885
|
});
|
|
1665
|
-
|
|
1886
|
+
try {
|
|
1887
|
+
await opts.onSuccess?.(key, name ?? fallback);
|
|
1888
|
+
} catch (err) {
|
|
1889
|
+
opts.onError?.(key, err, "success");
|
|
1890
|
+
}
|
|
1666
1891
|
} catch (err) {
|
|
1667
|
-
if (
|
|
1892
|
+
if (!isCurrent()) return;
|
|
1893
|
+
if (isAbortError(err)) {
|
|
1668
1894
|
if (!resettingRef.current) opts.onCancel?.(key);
|
|
1669
1895
|
resettingRef.current = false;
|
|
1670
1896
|
replace(INITIAL_STATE3);
|
|
@@ -1676,7 +1902,7 @@ function useDownload(options = {}) {
|
|
|
1676
1902
|
});
|
|
1677
1903
|
opts.onError?.(key, err, "downloading");
|
|
1678
1904
|
} finally {
|
|
1679
|
-
abortRef.current = null;
|
|
1905
|
+
if (isCurrent()) abortRef.current = null;
|
|
1680
1906
|
}
|
|
1681
1907
|
},
|
|
1682
1908
|
[apiRef, optsRef, patch, replace]
|
|
@@ -1692,12 +1918,20 @@ function useDownload(options = {}) {
|
|
|
1692
1918
|
[downloadFetch, downloadNavigate, optsRef]
|
|
1693
1919
|
);
|
|
1694
1920
|
const cancel = useCallback(() => {
|
|
1921
|
+
const key = downloadKeyRef.current;
|
|
1922
|
+
generationRef.current += 1;
|
|
1695
1923
|
abortRef.current?.abort();
|
|
1924
|
+
abortRef.current = null;
|
|
1925
|
+
downloadKeyRef.current = null;
|
|
1926
|
+
const opts = optsRef.current;
|
|
1927
|
+
if (key && opts.mode === "fetch") opts.onCancel?.(key);
|
|
1696
1928
|
replace(INITIAL_STATE3);
|
|
1697
|
-
}, [replace]);
|
|
1929
|
+
}, [optsRef, replace]);
|
|
1698
1930
|
const reset = useCallback(() => {
|
|
1699
1931
|
resettingRef.current = true;
|
|
1932
|
+
generationRef.current += 1;
|
|
1700
1933
|
abortRef.current?.abort();
|
|
1934
|
+
abortRef.current = null;
|
|
1701
1935
|
replace(INITIAL_STATE3);
|
|
1702
1936
|
}, [replace]);
|
|
1703
1937
|
if (options.mode === "fetch") {
|
|
@@ -1733,6 +1967,7 @@ function useDelete(options) {
|
|
|
1733
1967
|
const optsRef = useLiveRef(options);
|
|
1734
1968
|
const apiRef = useLiveRef(contextApi);
|
|
1735
1969
|
const pendingKeyRef = useRef(null);
|
|
1970
|
+
const inFlightRef = useRef(false);
|
|
1736
1971
|
const requestDelete = useCallback(
|
|
1737
1972
|
(key) => {
|
|
1738
1973
|
pendingKeyRef.current = key;
|
|
@@ -1744,50 +1979,140 @@ function useDelete(options) {
|
|
|
1744
1979
|
},
|
|
1745
1980
|
[patch]
|
|
1746
1981
|
);
|
|
1747
|
-
const
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1982
|
+
const executeDelete = useCallback(
|
|
1983
|
+
async (key) => {
|
|
1984
|
+
if (inFlightRef.current) return;
|
|
1985
|
+
const opts = optsRef.current;
|
|
1986
|
+
const api = opts.api ?? apiRef.current;
|
|
1987
|
+
if (!api)
|
|
1988
|
+
throw new Error(
|
|
1989
|
+
"[dimah-s3] No S3Api found. Pass `api` to useDelete or wrap with <S3Provider>."
|
|
1990
|
+
);
|
|
1991
|
+
if (opts.beforeDelete) {
|
|
1992
|
+
const allowed = await opts.beforeDelete(key);
|
|
1993
|
+
if (!allowed) {
|
|
1994
|
+
patch((draft) => {
|
|
1995
|
+
draft.phase = "error";
|
|
1996
|
+
draft.error = hookBlockedError(
|
|
1997
|
+
"Delete blocked by beforeDelete hook"
|
|
1998
|
+
);
|
|
1999
|
+
draft.pendingKey = null;
|
|
2000
|
+
});
|
|
2001
|
+
opts.onError?.(key, new Error("blocked"), "confirming");
|
|
2002
|
+
pendingKeyRef.current = null;
|
|
2003
|
+
return;
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
inFlightRef.current = true;
|
|
2007
|
+
patch((draft) => {
|
|
2008
|
+
draft.phase = "deleting";
|
|
2009
|
+
draft.error = null;
|
|
2010
|
+
});
|
|
2011
|
+
opts.onDeleteStart?.(key);
|
|
2012
|
+
try {
|
|
2013
|
+
await api.delete({ route: opts.route, key });
|
|
2014
|
+
pendingKeyRef.current = null;
|
|
1759
2015
|
patch((draft) => {
|
|
1760
|
-
draft.phase = "
|
|
1761
|
-
draft.error =
|
|
2016
|
+
draft.phase = "success";
|
|
2017
|
+
draft.error = null;
|
|
1762
2018
|
draft.pendingKey = null;
|
|
1763
2019
|
});
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
2020
|
+
try {
|
|
2021
|
+
await opts.onSuccess?.(key);
|
|
2022
|
+
} catch (err) {
|
|
2023
|
+
opts.onError?.(key, err, "success");
|
|
2024
|
+
}
|
|
2025
|
+
} catch (err) {
|
|
2026
|
+
patch((draft) => {
|
|
2027
|
+
draft.phase = "error";
|
|
2028
|
+
draft.error = toHookError(err, "Delete failed");
|
|
2029
|
+
});
|
|
2030
|
+
opts.onError?.(key, err, "deleting");
|
|
2031
|
+
} finally {
|
|
2032
|
+
inFlightRef.current = false;
|
|
1767
2033
|
}
|
|
1768
|
-
}
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
2034
|
+
},
|
|
2035
|
+
[apiRef, optsRef, patch]
|
|
2036
|
+
);
|
|
2037
|
+
const confirmDelete = useCallback(async () => {
|
|
2038
|
+
const key = pendingKeyRef.current;
|
|
2039
|
+
if (!key) return;
|
|
2040
|
+
await executeDelete(key);
|
|
2041
|
+
}, [executeDelete]);
|
|
2042
|
+
const remove = useCallback(
|
|
2043
|
+
async (key) => {
|
|
2044
|
+
if (inFlightRef.current) return;
|
|
2045
|
+
pendingKeyRef.current = key;
|
|
1777
2046
|
patch((draft) => {
|
|
1778
|
-
draft.
|
|
2047
|
+
draft.pendingKey = key;
|
|
1779
2048
|
draft.error = null;
|
|
1780
|
-
draft.pendingKey = null;
|
|
1781
2049
|
});
|
|
1782
|
-
await
|
|
1783
|
-
}
|
|
2050
|
+
await executeDelete(key);
|
|
2051
|
+
},
|
|
2052
|
+
[executeDelete, patch]
|
|
2053
|
+
);
|
|
2054
|
+
const removeMany = useCallback(
|
|
2055
|
+
async (keys) => {
|
|
2056
|
+
if (inFlightRef.current || keys.length === 0) return;
|
|
2057
|
+
const opts = optsRef.current;
|
|
2058
|
+
const api = opts.api ?? apiRef.current;
|
|
2059
|
+
if (!api)
|
|
2060
|
+
throw new Error(
|
|
2061
|
+
"[dimah-s3] No S3Api found. Pass `api` to useDelete or wrap with <S3Provider>."
|
|
2062
|
+
);
|
|
2063
|
+
inFlightRef.current = true;
|
|
1784
2064
|
patch((draft) => {
|
|
1785
|
-
draft.phase = "
|
|
1786
|
-
draft.error =
|
|
2065
|
+
draft.phase = "deleting";
|
|
2066
|
+
draft.error = null;
|
|
1787
2067
|
});
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
2068
|
+
try {
|
|
2069
|
+
const { results } = await api.deleteMany({
|
|
2070
|
+
route: opts.route,
|
|
2071
|
+
keys
|
|
2072
|
+
});
|
|
2073
|
+
const failed = results.filter((item) => !item.success);
|
|
2074
|
+
for (const item of results) {
|
|
2075
|
+
if (item.success) {
|
|
2076
|
+
try {
|
|
2077
|
+
await opts.onSuccess?.(item.key);
|
|
2078
|
+
} catch (err) {
|
|
2079
|
+
opts.onError?.(item.key, err, "success");
|
|
2080
|
+
}
|
|
2081
|
+
} else {
|
|
2082
|
+
opts.onError?.(
|
|
2083
|
+
item.key,
|
|
2084
|
+
new Error(item.error?.message ?? "Delete failed"),
|
|
2085
|
+
"deleting"
|
|
2086
|
+
);
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
if (failed.length > 0) {
|
|
2090
|
+
patch((draft) => {
|
|
2091
|
+
draft.phase = "error";
|
|
2092
|
+
draft.error = toHookError(
|
|
2093
|
+
new Error(failed[0]?.error?.message ?? "Delete failed"),
|
|
2094
|
+
"Delete failed"
|
|
2095
|
+
);
|
|
2096
|
+
});
|
|
2097
|
+
return;
|
|
2098
|
+
}
|
|
2099
|
+
patch((draft) => {
|
|
2100
|
+
draft.phase = "success";
|
|
2101
|
+
draft.error = null;
|
|
2102
|
+
draft.pendingKey = null;
|
|
2103
|
+
});
|
|
2104
|
+
} catch (err) {
|
|
2105
|
+
patch((draft) => {
|
|
2106
|
+
draft.phase = "error";
|
|
2107
|
+
draft.error = toHookError(err, "Delete failed");
|
|
2108
|
+
});
|
|
2109
|
+
opts.onError?.(keys[0] ?? "", err, "deleting");
|
|
2110
|
+
} finally {
|
|
2111
|
+
inFlightRef.current = false;
|
|
2112
|
+
}
|
|
2113
|
+
},
|
|
2114
|
+
[apiRef, optsRef, patch]
|
|
2115
|
+
);
|
|
1791
2116
|
const cancelDelete = useCallback(() => {
|
|
1792
2117
|
pendingKeyRef.current = null;
|
|
1793
2118
|
replace(INITIAL_STATE4);
|
|
@@ -1802,11 +2127,110 @@ function useDelete(options) {
|
|
|
1802
2127
|
pendingKey: state.pendingKey,
|
|
1803
2128
|
requestDelete,
|
|
1804
2129
|
confirmDelete,
|
|
2130
|
+
remove,
|
|
2131
|
+
removeMany,
|
|
1805
2132
|
cancelDelete,
|
|
1806
2133
|
reset
|
|
1807
2134
|
};
|
|
1808
2135
|
}
|
|
2136
|
+
var cache = /* @__PURE__ */ new Map();
|
|
2137
|
+
var REFRESH_SKEW_MS = 15e3;
|
|
2138
|
+
function cacheKey(route, objectKey, disposition, fileName) {
|
|
2139
|
+
return `${route}\0${objectKey}\0${disposition}\0${fileName ?? ""}`;
|
|
2140
|
+
}
|
|
2141
|
+
function readFresh(key) {
|
|
2142
|
+
const entry = cache.get(key);
|
|
2143
|
+
if (!entry) return void 0;
|
|
2144
|
+
if (entry.expiresAt - REFRESH_SKEW_MS <= Date.now()) {
|
|
2145
|
+
cache.delete(key);
|
|
2146
|
+
return void 0;
|
|
2147
|
+
}
|
|
2148
|
+
return entry;
|
|
2149
|
+
}
|
|
2150
|
+
function useObjectUrl(options) {
|
|
2151
|
+
const contextApi = useContext(S3Context);
|
|
2152
|
+
const optsRef = useLiveRef(options);
|
|
2153
|
+
const apiRef = useLiveRef(contextApi);
|
|
2154
|
+
const generationRef = useRef(0);
|
|
2155
|
+
const [url, setUrl] = useState(null);
|
|
2156
|
+
const [expiresIn, setExpiresIn] = useState(null);
|
|
2157
|
+
const [error, setError] = useState(null);
|
|
2158
|
+
const [isLoading, setIsLoading] = useState(false);
|
|
2159
|
+
const [tick, setTick] = useState(0);
|
|
2160
|
+
const objectKey = options.objectKey ?? null;
|
|
2161
|
+
const disposition = options.disposition ?? "inline";
|
|
2162
|
+
const fileName = options.fileName;
|
|
2163
|
+
const route = options.route;
|
|
2164
|
+
const load = useCallback(async () => {
|
|
2165
|
+
const opts = optsRef.current;
|
|
2166
|
+
const key = opts.objectKey;
|
|
2167
|
+
if (!key) {
|
|
2168
|
+
setUrl(null);
|
|
2169
|
+
setExpiresIn(null);
|
|
2170
|
+
setError(null);
|
|
2171
|
+
setIsLoading(false);
|
|
2172
|
+
return;
|
|
2173
|
+
}
|
|
2174
|
+
const api = opts.api ?? apiRef.current;
|
|
2175
|
+
if (!api) {
|
|
2176
|
+
throw new Error(
|
|
2177
|
+
"[dimah-s3] No S3Api found. Pass `api` to useObjectUrl or wrap with <S3Provider>."
|
|
2178
|
+
);
|
|
2179
|
+
}
|
|
2180
|
+
const id = cacheKey(
|
|
2181
|
+
opts.route,
|
|
2182
|
+
key,
|
|
2183
|
+
opts.disposition ?? "inline",
|
|
2184
|
+
opts.fileName
|
|
2185
|
+
);
|
|
2186
|
+
const cached = readFresh(id);
|
|
2187
|
+
if (cached) {
|
|
2188
|
+
setUrl(cached.url);
|
|
2189
|
+
setExpiresIn(cached.expiresIn);
|
|
2190
|
+
setError(null);
|
|
2191
|
+
setIsLoading(false);
|
|
2192
|
+
return;
|
|
2193
|
+
}
|
|
2194
|
+
const generation = ++generationRef.current;
|
|
2195
|
+
setIsLoading(true);
|
|
2196
|
+
try {
|
|
2197
|
+
const result = await api.download({
|
|
2198
|
+
route: opts.route,
|
|
2199
|
+
key,
|
|
2200
|
+
fileName: opts.fileName,
|
|
2201
|
+
disposition: opts.disposition ?? "inline"
|
|
2202
|
+
});
|
|
2203
|
+
if (generation !== generationRef.current) return;
|
|
2204
|
+
const ttlMs = result.expiresIn > 0 ? result.expiresIn * 1e3 : 24 * 60 * 60 * 1e3;
|
|
2205
|
+
cache.set(id, {
|
|
2206
|
+
url: result.url,
|
|
2207
|
+
expiresIn: result.expiresIn,
|
|
2208
|
+
expiresAt: Date.now() + ttlMs
|
|
2209
|
+
});
|
|
2210
|
+
setUrl(result.url);
|
|
2211
|
+
setExpiresIn(result.expiresIn);
|
|
2212
|
+
setError(null);
|
|
2213
|
+
} catch (err) {
|
|
2214
|
+
if (generation !== generationRef.current) return;
|
|
2215
|
+
setUrl(null);
|
|
2216
|
+
setExpiresIn(null);
|
|
2217
|
+
setError(toHookError(err, "Download failed"));
|
|
2218
|
+
} finally {
|
|
2219
|
+
if (generation === generationRef.current) setIsLoading(false);
|
|
2220
|
+
}
|
|
2221
|
+
}, [apiRef, optsRef]);
|
|
2222
|
+
useEffect(() => {
|
|
2223
|
+
void load();
|
|
2224
|
+
}, [load, objectKey, route, disposition, fileName, tick]);
|
|
2225
|
+
const refresh = useCallback(() => {
|
|
2226
|
+
if (objectKey) {
|
|
2227
|
+
cache.delete(cacheKey(route, objectKey, disposition, fileName));
|
|
2228
|
+
}
|
|
2229
|
+
setTick((n) => n + 1);
|
|
2230
|
+
}, [disposition, fileName, objectKey, route]);
|
|
2231
|
+
return { url, expiresIn, error, isLoading, refresh };
|
|
2232
|
+
}
|
|
1809
2233
|
|
|
1810
|
-
export { S3Provider, createLocalStorageStore, createMemoryStore, createS3Client, defineApi, formatAcceptLabels, formatEta, formatSpeed, formatUploadProgress, uploadFile, uploadFiles, useApi, useDelete, useDownload, useFileUpload, useFormatDimahError, useFormatValidateFileError, useMultiFileUpload, useMultiUpload, useUpload };
|
|
2234
|
+
export { DEFAULT_MULTIPART_THRESHOLD, S3Provider, S3UploadError, createLocalStorageStore, createMemoryStore, createS3Client, defineApi, formatAcceptLabels, formatEta, formatSpeed, formatUploadProgress, loadRouteCatalog, mergeRouteUploadPolicy, multipartResumeKey, resolveRouteUploadPolicy, uploadFile, uploadFiles, useApi, useDelete, useDownload, useFileUpload, useFormatDimahError, useFormatValidateFileError, useMultiFileUpload, useMultiUpload, useObjectUrl, useRouteUploadPolicy, useUpload };
|
|
1811
2235
|
//# sourceMappingURL=index.js.map
|
|
1812
2236
|
//# sourceMappingURL=index.js.map
|