@dimah-s3/react 1.1.1 → 1.2.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/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { DimahS3Error, createS3Client as createS3Client$1, sha256File, formatFileSize, isDimahS3Error, S3_ERROR_CODES, validateFile, parseFileName } from '@dimah-s3/core';
1
+ import { DimahS3Error, createS3Client as createS3Client$1, sha256File, formatFileSize, isDimahS3Error, S3_ERROR_CODES, parseFileName, validateFile } from '@dimah-s3/core';
2
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
- import { createContext, useContext, useCallback, useRef, useEffect, useState, useLayoutEffect } from 'react';
3
+ import { createContext, useContext, useCallback, useState, useEffect, useRef, 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';
@@ -134,6 +134,7 @@ var MAX_RETRIES = 3;
134
134
  var RETRY_BASE_DELAY = 1e3;
135
135
  var DEFAULT_CONCURRENT_PARTS = 2;
136
136
  var DEFAULT_CONCURRENT_FILES = 2;
137
+ var DEFAULT_MAX_FILES = 1;
137
138
 
138
139
  // src/upload/retry.ts
139
140
  async function withRetry(fn, retryConfig, signal) {
@@ -559,6 +560,12 @@ async function uploadFiles(api, items, config, callbacks = {}, signal, getReques
559
560
  callbacks.onFileProgress?.(item.id, progress);
560
561
  reportTotalProgress();
561
562
  },
563
+ onPhaseChange: (phase) => {
564
+ callbacks.onFilePhaseChange?.(item.id, phase);
565
+ },
566
+ onPartUpload: (partNumber, totalParts) => {
567
+ callbacks.onPartUpload?.(item.id, partNumber, totalParts);
568
+ },
562
569
  onMultipartInit: (uploadId, key) => {
563
570
  callbacks.onMultipartInit?.(item.id, uploadId, key);
564
571
  }
@@ -843,10 +850,9 @@ function useImmerState(initialState) {
843
850
  var INITIAL_PROGRESS = { loaded: 0, total: 0, percent: 0 };
844
851
  var INITIAL_STATE = {
845
852
  phase: "idle",
853
+ files: [],
846
854
  progress: INITIAL_PROGRESS,
847
- error: null,
848
- result: null,
849
- fileInfo: null
855
+ error: null
850
856
  };
851
857
  var PENDING_PHASES = /* @__PURE__ */ new Set([
852
858
  "validating",
@@ -854,303 +860,14 @@ var PENDING_PHASES = /* @__PURE__ */ new Set([
854
860
  "uploading",
855
861
  "finalizing"
856
862
  ]);
857
- function mergeRequestOptions(hook, file, requestOptions) {
858
- const merged = {
859
- ...hook.uploadOptions,
860
- ...hook.getUploadOptions?.(file),
861
- ...requestOptions
862
- };
863
- return Object.keys(merged).length > 0 ? merged : void 0;
864
- }
865
- function useFileUpload(options) {
866
- const [state, patch, replace] = useImmerState(INITIAL_STATE);
867
- const contextApi = useContext(S3Context);
868
- const formatValidateFileError = useFormatValidateFileError();
869
- const optsRef = useLiveRef(options);
870
- const apiRef = useLiveRef(contextApi);
871
- const abortRef = useRef(null);
872
- const generationRef = useRef(0);
873
- const activeUploadRef = useRef(null);
874
- const detachingRef = useRef(false);
875
- const resettingRef = useRef(false);
876
- const previewUrlRef = useRef(null);
877
- const speedUpdaterRef = useRef(
878
- createThrottledSpeedUpdater(createSpeedTracker())
879
- );
880
- const revokeCurrentPreview = useCallback(() => {
881
- revokePreviewUrl(previewUrlRef.current);
882
- previewUrlRef.current = null;
883
- }, []);
884
- const clearToIdle = useCallback(() => {
885
- revokeCurrentPreview();
886
- replace(INITIAL_STATE);
887
- }, [revokeCurrentPreview, replace]);
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
- );
918
- const upload = useCallback(
919
- async (file, requestOptions) => {
920
- revokeCurrentPreview();
921
- const previewUrl = createImagePreviewUrl(file);
922
- previewUrlRef.current = previewUrl;
923
- const fileInfo = {
924
- name: file.name,
925
- size: file.size,
926
- type: file.type,
927
- previewUrl
928
- };
929
- patch((draft) => {
930
- draft.phase = "validating";
931
- draft.progress = { ...INITIAL_PROGRESS };
932
- draft.error = null;
933
- draft.result = null;
934
- draft.fileInfo = fileInfo;
935
- });
936
- const opts = optsRef.current;
937
- const api = opts.api ?? apiRef.current;
938
- if (!api)
939
- throw new Error(
940
- "[dimah-s3] No S3Api found. Pass `api` to useFileUpload or wrap with <S3Provider>."
941
- );
942
- const policy = await resolveRouteUploadPolicy(api, opts.route, {
943
- accept: opts.accept,
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
951
- });
952
- if (validationError) {
953
- const message = formatValidateFileError(validationError);
954
- patch((draft) => {
955
- draft.phase = "error";
956
- draft.error = new DimahS3Error("BAD_REQUEST", { message });
957
- });
958
- opts.onError?.(file, new Error(message), "validating");
959
- return;
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
- };
985
- if (opts.beforeUpload) {
986
- const allowed = await opts.beforeUpload(file);
987
- if (stopIfAborted()) return;
988
- if (!allowed) {
989
- abortRef.current = null;
990
- activeUploadRef.current = null;
991
- patch((draft) => {
992
- draft.phase = "error";
993
- draft.error = hookBlockedError(
994
- "Upload blocked by beforeUpload hook"
995
- );
996
- });
997
- opts.onError?.(file, new Error("blocked"), "validating");
998
- return;
999
- }
1000
- }
1001
- if (stopIfAborted()) return;
1002
- speedUpdaterRef.current.reset();
1003
- patch((draft) => {
1004
- draft.phase = "presigning";
1005
- });
1006
- opts.onUploadStart?.(file);
1007
- let errorPhase = "presigning";
1008
- try {
1009
- const result = await uploadFile(
1010
- api,
1011
- file,
1012
- {
1013
- route: opts.route,
1014
- multipart: policy.multipart,
1015
- checksum: policy.checksum,
1016
- concurrentParts: opts.concurrentParts,
1017
- retry: opts.retry,
1018
- uploadStore: opts.uploadStore
1019
- },
1020
- {
1021
- onProgress: (progress) => {
1022
- if (!isCurrent()) return;
1023
- const p = speedUpdaterRef.current.apply(progress);
1024
- patch((draft) => {
1025
- draft.progress = p;
1026
- });
1027
- opts.onProgress?.(file, p);
1028
- },
1029
- onPhaseChange: (phase) => {
1030
- if (!isCurrent()) return;
1031
- errorPhase = phase;
1032
- patch((draft) => {
1033
- draft.phase = phase;
1034
- });
1035
- },
1036
- onPartUpload: (partNumber, totalParts) => opts.onPartUpload?.(file, partNumber, totalParts),
1037
- onMultipartInit: (uploadId, serverKey) => {
1038
- if (activeUploadRef.current && isCurrent()) {
1039
- activeUploadRef.current.uploadId = uploadId;
1040
- activeUploadRef.current.serverKey = serverKey;
1041
- }
1042
- opts.onMultipartInit?.(file, uploadId);
1043
- }
1044
- },
1045
- controller.signal,
1046
- mergedOptions
1047
- );
1048
- if (!isCurrent()) return;
1049
- patch((draft) => {
1050
- draft.phase = "success";
1051
- draft.result = result;
1052
- draft.progress = {
1053
- loaded: file.size,
1054
- total: file.size,
1055
- percent: 100
1056
- };
1057
- });
1058
- try {
1059
- await opts.onSuccess?.(file, result);
1060
- } catch (err) {
1061
- opts.onError?.(file, err, "success");
1062
- }
1063
- } catch (err) {
1064
- if (!isCurrent()) return;
1065
- if (isAbortError(err)) {
1066
- if (detachingRef.current) {
1067
- detachingRef.current = false;
1068
- return;
1069
- }
1070
- if (resettingRef.current) {
1071
- resettingRef.current = false;
1072
- return;
1073
- }
1074
- opts.onCancel?.(file);
1075
- clearToIdle();
1076
- return;
1077
- }
1078
- const message = err instanceof Error ? err.message : "Upload failed";
1079
- patch((draft) => {
1080
- draft.phase = "error";
1081
- draft.error = toHookError(err, message);
1082
- });
1083
- opts.onError?.(file, err, errorPhase);
1084
- } finally {
1085
- if (isCurrent()) {
1086
- abortRef.current = null;
1087
- activeUploadRef.current = null;
1088
- }
1089
- }
1090
- },
1091
- [
1092
- abortMultipartSession,
1093
- apiRef,
1094
- optsRef,
1095
- formatValidateFileError,
1096
- revokeCurrentPreview,
1097
- clearToIdle,
1098
- patch
1099
- ]
1100
- );
1101
- const cancel = useCallback(() => {
1102
- const active = activeUploadRef.current;
1103
- generationRef.current += 1;
1104
- abortRef.current?.abort();
1105
- abortMultipartSession(active);
1106
- abortRef.current = null;
1107
- activeUploadRef.current = null;
1108
- if (active) optsRef.current.onCancel?.(active.file);
1109
- clearToIdle();
1110
- }, [abortMultipartSession, optsRef, clearToIdle]);
1111
- const detach = useCallback(() => {
1112
- if (!activeUploadRef.current) return;
1113
- detachingRef.current = true;
1114
- generationRef.current += 1;
1115
- abortRef.current?.abort();
1116
- abortRef.current = null;
1117
- activeUploadRef.current = null;
1118
- clearToIdle();
1119
- }, [clearToIdle]);
1120
- const reset = useCallback(() => {
1121
- resettingRef.current = true;
1122
- generationRef.current += 1;
1123
- abortRef.current?.abort();
1124
- abortRef.current = null;
1125
- activeUploadRef.current = null;
1126
- clearToIdle();
1127
- }, [clearToIdle]);
1128
- return {
1129
- ...state,
1130
- isUploading: state.phase === "uploading",
1131
- isPending: PENDING_PHASES.has(state.phase),
1132
- upload,
1133
- cancel,
1134
- detach,
1135
- reset
1136
- };
1137
- }
1138
- var INITIAL_PROGRESS2 = { loaded: 0, total: 0, percent: 0 };
1139
- var INITIAL_STATE2 = {
1140
- phase: "idle",
1141
- files: [],
1142
- totalProgress: INITIAL_PROGRESS2,
1143
- error: null
1144
- };
1145
- var PENDING_PHASES2 = /* @__PURE__ */ new Set([
1146
- "validating",
1147
- "uploading"
1148
- ]);
1149
863
  function generateId() {
1150
864
  return crypto.randomUUID();
1151
865
  }
1152
- function useMultiFileUpload(options) {
1153
- const [state, patch, replace] = useImmerState(INITIAL_STATE2);
866
+ function normalizeFiles(files) {
867
+ return Array.isArray(files) ? files : [files];
868
+ }
869
+ function useFileUpload(options) {
870
+ const [state, patch, replace] = useImmerState(INITIAL_STATE);
1154
871
  const contextApi = useContext(S3Context);
1155
872
  const formatValidateFileError = useFormatValidateFileError();
1156
873
  const optsRef = useLiveRef(options);
@@ -1172,7 +889,7 @@ function useMultiFileUpload(options) {
1172
889
  }, []);
1173
890
  const clearToIdle = useCallback(() => {
1174
891
  revokeAllPreviews();
1175
- replace(INITIAL_STATE2);
892
+ replace(INITIAL_STATE);
1176
893
  }, [revokeAllPreviews, replace]);
1177
894
  const abortMultipartSessions = useCallback(() => {
1178
895
  const opts = optsRef.current;
@@ -1206,16 +923,15 @@ function useMultiFileUpload(options) {
1206
923
  [abortMultipartSessions, revokeAllPreviews]
1207
924
  );
1208
925
  const upload = useCallback(
1209
- async (files) => {
926
+ async (input) => {
927
+ const files = normalizeFiles(input);
1210
928
  const opts = optsRef.current;
1211
929
  const api = opts.api ?? apiRef.current;
1212
930
  if (!api)
1213
931
  throw new Error(
1214
- "[dimah-s3] No S3Api found. Pass `api` to useMultiFileUpload or wrap with <S3Provider>."
932
+ "[dimah-s3] No S3Api found. Pass `api` to useUpload or wrap with <S3Provider>."
1215
933
  );
1216
- const items = [];
1217
- const fileStates = [];
1218
- const fileMap = /* @__PURE__ */ new Map();
934
+ const maxFiles = opts.maxFiles ?? DEFAULT_MAX_FILES;
1219
935
  patch((draft) => {
1220
936
  draft.phase = "validating";
1221
937
  draft.error = null;
@@ -1226,13 +942,13 @@ function useMultiFileUpload(options) {
1226
942
  multipart: opts.multipart,
1227
943
  checksum: opts.checksum
1228
944
  });
1229
- if (opts.maxFiles && files.length > opts.maxFiles) {
1230
- const msg = `Too many files. Maximum is ${opts.maxFiles}.`;
945
+ if (maxFiles > 0 && files.length > maxFiles) {
946
+ const msg = `Too many files. Maximum is ${maxFiles}.`;
1231
947
  patch((draft) => {
1232
948
  draft.phase = "error";
1233
949
  draft.error = new DimahS3Error("BAD_REQUEST", { message: msg });
1234
950
  });
1235
- opts.onError?.(new Error(msg));
951
+ opts.onError?.(new Error(msg), "validating");
1236
952
  return;
1237
953
  }
1238
954
  for (const file of files) {
@@ -1243,11 +959,28 @@ function useMultiFileUpload(options) {
1243
959
  if (validationError) {
1244
960
  const detail = formatValidateFileError(validationError);
1245
961
  const msg = `${file.name}: ${detail}`;
962
+ const error = new DimahS3Error("BAD_REQUEST", { message: msg });
963
+ revokeAllPreviews();
964
+ const previewUrl = createImagePreviewUrl(file);
965
+ if (previewUrl) previewUrlsRef.current = [previewUrl];
1246
966
  patch((draft) => {
1247
967
  draft.phase = "error";
1248
- draft.error = new DimahS3Error("BAD_REQUEST", { message: msg });
968
+ draft.error = error;
969
+ draft.files = [
970
+ {
971
+ id: generateId(),
972
+ name: file.name,
973
+ size: file.size,
974
+ type: file.type,
975
+ previewUrl,
976
+ status: "error",
977
+ progress: { loaded: 0, total: file.size, percent: 0 },
978
+ error,
979
+ result: null
980
+ }
981
+ ];
1249
982
  });
1250
- opts.onError?.(new Error(msg));
983
+ opts.onError?.(new Error(msg), "validating");
1251
984
  return;
1252
985
  }
1253
986
  }
@@ -1275,7 +1008,7 @@ function useMultiFileUpload(options) {
1275
1008
  "Upload blocked by beforeUpload hook"
1276
1009
  );
1277
1010
  });
1278
- opts.onError?.(new Error("blocked"));
1011
+ opts.onError?.(new Error("blocked"), "validating");
1279
1012
  return;
1280
1013
  }
1281
1014
  }
@@ -1289,6 +1022,9 @@ function useMultiFileUpload(options) {
1289
1022
  }
1290
1023
  revokeAllPreviews();
1291
1024
  const nextPreviewUrls = [];
1025
+ const items = [];
1026
+ const fileStates = [];
1027
+ const fileMap = /* @__PURE__ */ new Map();
1292
1028
  for (const file of files) {
1293
1029
  const id = generateId();
1294
1030
  const previewUrl = createImagePreviewUrl(file);
@@ -1318,10 +1054,11 @@ function useMultiFileUpload(options) {
1318
1054
  }
1319
1055
  ])
1320
1056
  );
1057
+ const singleFile = items.length === 1;
1321
1058
  patch((draft) => {
1322
- draft.phase = "uploading";
1059
+ draft.phase = singleFile ? "presigning" : "uploading";
1323
1060
  draft.files = fileStates;
1324
- draft.totalProgress = {
1061
+ draft.progress = {
1325
1062
  loaded: 0,
1326
1063
  total: files.reduce((s, f) => s + f.size, 0),
1327
1064
  percent: 0
@@ -1337,6 +1074,7 @@ function useMultiFileUpload(options) {
1337
1074
  );
1338
1075
  }
1339
1076
  totalSpeedUpdaterRef.current.reset();
1077
+ let errorPhase = singleFile ? "presigning" : "uploading";
1340
1078
  try {
1341
1079
  const results = await uploadFiles(
1342
1080
  api,
@@ -1365,6 +1103,19 @@ function useMultiFileUpload(options) {
1365
1103
  const file = fileMap.get(id);
1366
1104
  if (file) opts.onFileProgress?.(file, p);
1367
1105
  },
1106
+ onFilePhaseChange: (_id, phase) => {
1107
+ if (!isCurrent()) return;
1108
+ errorPhase = phase;
1109
+ if (singleFile) {
1110
+ patch((draft) => {
1111
+ draft.phase = phase;
1112
+ });
1113
+ }
1114
+ },
1115
+ onPartUpload: (id, partNumber, totalParts) => {
1116
+ const file = fileMap.get(id);
1117
+ if (file) opts.onPartUpload?.(file, partNumber, totalParts);
1118
+ },
1368
1119
  onFileSuccess: (id, result) => {
1369
1120
  if (!isCurrent()) return;
1370
1121
  activeUploadsRef.current.delete(id);
@@ -1399,7 +1150,7 @@ function useMultiFileUpload(options) {
1399
1150
  if (!isCurrent()) return;
1400
1151
  const p = totalSpeedUpdaterRef.current.apply(progress);
1401
1152
  patch((draft) => {
1402
- draft.totalProgress = p;
1153
+ draft.progress = p;
1403
1154
  });
1404
1155
  opts.onProgress?.(p);
1405
1156
  },
@@ -1409,6 +1160,8 @@ function useMultiFileUpload(options) {
1409
1160
  active.uploadId = uploadId;
1410
1161
  active.serverKey = serverKey;
1411
1162
  }
1163
+ const file = fileMap.get(id);
1164
+ if (file) opts.onMultipartInit?.(file, uploadId);
1412
1165
  }
1413
1166
  },
1414
1167
  controller.signal,
@@ -1427,18 +1180,25 @@ function useMultiFileUpload(options) {
1427
1180
  message: `${results.filter((r) => r.status === "error").length} file(s) failed`
1428
1181
  }) : null;
1429
1182
  if (!hasErrors) {
1430
- draft.totalProgress = {
1431
- loaded: draft.totalProgress.total,
1432
- total: draft.totalProgress.total,
1183
+ draft.progress = {
1184
+ loaded: draft.progress.total,
1185
+ total: draft.progress.total,
1433
1186
  percent: 100
1434
1187
  };
1435
1188
  }
1436
1189
  });
1437
- if (!hasErrors) {
1190
+ if (hasErrors) {
1191
+ opts.onError?.(
1192
+ new Error(
1193
+ `${results.filter((r) => r.status === "error").length} file(s) failed`
1194
+ ),
1195
+ errorPhase
1196
+ );
1197
+ } else {
1438
1198
  try {
1439
1199
  await opts.onSuccess?.(successResults);
1440
1200
  } catch (err) {
1441
- opts.onError?.(err);
1201
+ opts.onError?.(err, "success");
1442
1202
  }
1443
1203
  }
1444
1204
  } catch (err) {
@@ -1457,7 +1217,7 @@ function useMultiFileUpload(options) {
1457
1217
  draft.phase = "error";
1458
1218
  draft.error = toHookError(err, "Upload failed");
1459
1219
  });
1460
- opts.onError?.(err);
1220
+ opts.onError?.(err, errorPhase);
1461
1221
  } finally {
1462
1222
  if (isCurrent()) {
1463
1223
  abortRef.current = null;
@@ -1503,8 +1263,9 @@ function useMultiFileUpload(options) {
1503
1263
  }, [clearToIdle]);
1504
1264
  return {
1505
1265
  ...state,
1266
+ file: state.files[0] ?? null,
1506
1267
  isUploading: state.phase === "uploading",
1507
- isPending: PENDING_PHASES2.has(state.phase),
1268
+ isPending: PENDING_PHASES.has(state.phase),
1508
1269
  upload,
1509
1270
  cancel,
1510
1271
  detach,
@@ -1599,9 +1360,16 @@ function useRouteUploadPolicy(options) {
1599
1360
  }
1600
1361
 
1601
1362
  // src/hooks/use-upload.ts
1363
+ function toFileArray(files) {
1364
+ if (files == null) return [];
1365
+ if (files instanceof File) return [files];
1366
+ return Array.from(files);
1367
+ }
1602
1368
  function useUpload(options) {
1603
1369
  const { disabled, noDrag, noClick, noKeyboard, onFileReject, ...uploadOpts } = options;
1604
- const policy = useRouteUploadPolicy({
1370
+ const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
1371
+ const resumable = options.uploadStore != null && options.uploadStore !== false;
1372
+ const catalogPolicy = useRouteUploadPolicy({
1605
1373
  api: options.api,
1606
1374
  route: options.route,
1607
1375
  accept: options.accept,
@@ -1609,38 +1377,41 @@ function useUpload(options) {
1609
1377
  multipart: options.multipart,
1610
1378
  checksum: options.checksum
1611
1379
  });
1612
- const single = useFileUpload(uploadOpts);
1380
+ const engine = useFileUpload(uploadOpts);
1613
1381
  const handleFiles = (files) => {
1614
- const list = files == null ? [] : Array.from(files);
1615
- const file = list[0];
1616
- if (!file) return;
1617
- void single.upload(file);
1382
+ const list = toFileArray(files);
1383
+ if (list.length === 0) return Promise.resolve();
1384
+ return engine.upload(list);
1618
1385
  };
1619
1386
  const intake = useFileIntake({
1620
- accept: policy.accept,
1621
- maxFileSize: policy.maxFileSize,
1622
- maxFiles: 1,
1623
- multiple: false,
1624
- disabled: Boolean(disabled) || single.isPending,
1387
+ accept: catalogPolicy.accept,
1388
+ maxFileSize: catalogPolicy.maxFileSize,
1389
+ maxFiles,
1390
+ multiple: maxFiles > 1,
1391
+ disabled: Boolean(disabled) || engine.isPending,
1625
1392
  noDrag,
1626
1393
  noClick,
1627
1394
  noKeyboard,
1628
- onAccept: (files) => handleFiles(files),
1395
+ onAccept: (files) => {
1396
+ void handleFiles(files);
1397
+ },
1629
1398
  onReject: onFileReject
1630
1399
  });
1631
1400
  return {
1632
- phase: single.phase,
1633
- fileInfo: single.fileInfo,
1634
- progress: single.progress,
1635
- error: single.error,
1636
- result: single.result,
1637
- isUploading: single.isUploading,
1638
- isPending: single.isPending,
1401
+ files: engine.files,
1402
+ file: engine.file,
1403
+ phase: engine.phase,
1404
+ progress: engine.progress,
1405
+ error: engine.error,
1406
+ isUploading: engine.isUploading,
1407
+ isPending: engine.isPending,
1408
+ policy: { ...catalogPolicy, maxFiles },
1409
+ resumable,
1639
1410
  handleFiles,
1640
1411
  open: intake.open,
1641
- cancel: single.cancel,
1642
- detach: single.detach,
1643
- reset: single.reset,
1412
+ cancel: engine.cancel,
1413
+ detach: engine.detach,
1414
+ reset: engine.reset,
1644
1415
  getRootProps: intake.getRootProps,
1645
1416
  getInputProps: intake.getInputProps,
1646
1417
  isDragActive: intake.isDragActive,
@@ -1649,72 +1420,28 @@ function useUpload(options) {
1649
1420
  fileRejections: intake.fileRejections
1650
1421
  };
1651
1422
  }
1652
-
1653
- // src/hooks/use-multi-upload.ts
1654
- function useMultiUpload(options) {
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
- });
1664
- const multi = useMultiFileUpload(multiOpts);
1665
- const handleFiles = (files) => {
1666
- if (files == null) return;
1667
- const list = Array.from(files);
1668
- if (list.length === 0) return;
1669
- void multi.upload(list);
1670
- };
1671
- const intake = useFileIntake({
1672
- accept: policy.accept,
1673
- maxFileSize: policy.maxFileSize,
1674
- maxFiles: options.maxFiles,
1675
- multiple: true,
1676
- disabled: Boolean(disabled) || multi.isPending,
1677
- noDrag,
1678
- noClick,
1679
- noKeyboard,
1680
- onAccept: (files) => handleFiles(files),
1681
- onReject: onFileReject
1682
- });
1683
- return {
1684
- phase: multi.phase,
1685
- files: multi.files,
1686
- totalProgress: multi.totalProgress,
1687
- error: multi.error,
1688
- isUploading: multi.isUploading,
1689
- isPending: multi.isPending,
1690
- handleFiles,
1691
- open: intake.open,
1692
- cancel: multi.cancel,
1693
- detach: multi.detach,
1694
- reset: multi.reset,
1695
- getRootProps: intake.getRootProps,
1696
- getInputProps: intake.getInputProps,
1697
- isDragActive: intake.isDragActive,
1698
- isDragAccept: intake.isDragAccept,
1699
- isDragReject: intake.isDragReject,
1700
- fileRejections: intake.fileRejections
1701
- };
1423
+ function isFetchDownload(download) {
1424
+ return download.mode === "fetch";
1702
1425
  }
1703
- var INITIAL_PROGRESS3 = { loaded: 0, total: 0, percent: 0 };
1704
- var INITIAL_STATE3 = {
1426
+ var INITIAL_PROGRESS2 = { loaded: 0, total: 0, percent: 0 };
1427
+ var INITIAL_STATE2 = {
1705
1428
  phase: "idle",
1429
+ objectKey: null,
1706
1430
  error: null,
1707
1431
  url: null,
1708
1432
  expiresIn: null,
1709
- progress: INITIAL_PROGRESS3,
1433
+ progress: INITIAL_PROGRESS2,
1710
1434
  fileName: null,
1711
1435
  fileSize: null
1712
1436
  };
1437
+ function idleKeepingKey(objectKey) {
1438
+ return { ...INITIAL_STATE2, objectKey };
1439
+ }
1713
1440
  function missingApiMessage(hook) {
1714
1441
  return `[dimah-s3] No S3Api found. Pass \`api\` to ${hook} or wrap with <S3Provider>.`;
1715
1442
  }
1716
1443
  function useDownload(options) {
1717
- const [state, patch, replace] = useImmerState(INITIAL_STATE3);
1444
+ const [state, patch, replace] = useImmerState(INITIAL_STATE2);
1718
1445
  const contextApi = useContext(S3Context);
1719
1446
  const optsRef = useLiveRef(options);
1720
1447
  const apiRef = useLiveRef(contextApi);
@@ -1732,6 +1459,7 @@ function useDownload(options) {
1732
1459
  if (!api) throw new Error(missingApiMessage("useDownload"));
1733
1460
  patch((draft) => {
1734
1461
  draft.phase = "presigning";
1462
+ draft.objectKey = key;
1735
1463
  draft.error = null;
1736
1464
  draft.url = null;
1737
1465
  draft.expiresIn = null;
@@ -1771,6 +1499,7 @@ function useDownload(options) {
1771
1499
  if (!allowed) {
1772
1500
  patch((draft) => {
1773
1501
  draft.phase = "error";
1502
+ draft.objectKey = key;
1774
1503
  draft.error = hookBlockedError(
1775
1504
  "Download blocked by beforeDownload hook"
1776
1505
  );
@@ -1800,6 +1529,7 @@ function useDownload(options) {
1800
1529
  if (!allowed) {
1801
1530
  patch((draft) => {
1802
1531
  draft.phase = "error";
1532
+ draft.objectKey = key;
1803
1533
  draft.error = hookBlockedError(
1804
1534
  "Download blocked by beforeDownload hook"
1805
1535
  );
@@ -1813,7 +1543,8 @@ function useDownload(options) {
1813
1543
  const isCurrent = () => generation === generationRef.current;
1814
1544
  patch((draft) => {
1815
1545
  draft.phase = "presigning";
1816
- draft.progress = { ...INITIAL_PROGRESS3 };
1546
+ draft.objectKey = key;
1547
+ draft.progress = { ...INITIAL_PROGRESS2 };
1817
1548
  draft.error = null;
1818
1549
  draft.fileName = downloadName ?? null;
1819
1550
  draft.fileSize = null;
@@ -1893,7 +1624,7 @@ function useDownload(options) {
1893
1624
  if (isAbortError(err)) {
1894
1625
  if (!resettingRef.current) opts.onCancel?.(key);
1895
1626
  resettingRef.current = false;
1896
- replace(INITIAL_STATE3);
1627
+ replace(idleKeepingKey(key));
1897
1628
  return;
1898
1629
  }
1899
1630
  patch((draft) => {
@@ -1925,56 +1656,65 @@ function useDownload(options) {
1925
1656
  downloadKeyRef.current = null;
1926
1657
  const opts = optsRef.current;
1927
1658
  if (key && opts.mode === "fetch") opts.onCancel?.(key);
1928
- replace(INITIAL_STATE3);
1659
+ replace(idleKeepingKey(key));
1929
1660
  }, [optsRef, replace]);
1930
1661
  const reset = useCallback(() => {
1931
1662
  resettingRef.current = true;
1932
1663
  generationRef.current += 1;
1933
1664
  abortRef.current?.abort();
1934
1665
  abortRef.current = null;
1935
- replace(INITIAL_STATE3);
1666
+ replace(INITIAL_STATE2);
1936
1667
  }, [replace]);
1937
1668
  if (options.mode === "fetch") {
1669
+ const isDownloading = state.phase === "downloading";
1670
+ const isPending = state.phase === "presigning" || state.phase === "downloading";
1938
1671
  return {
1672
+ mode: "fetch",
1939
1673
  phase: state.phase,
1674
+ objectKey: state.objectKey,
1940
1675
  progress: state.progress,
1941
1676
  error: state.error,
1942
1677
  fileName: state.fileName,
1943
1678
  fileSize: state.fileSize,
1679
+ isDownloading,
1680
+ isPending,
1944
1681
  download,
1945
1682
  cancel,
1946
1683
  reset
1947
1684
  };
1948
1685
  }
1949
1686
  return {
1687
+ mode: "navigate",
1950
1688
  phase: state.phase,
1689
+ objectKey: state.objectKey,
1951
1690
  error: state.error,
1952
1691
  url: state.url,
1953
1692
  expiresIn: state.expiresIn,
1693
+ isPending: state.phase === "presigning",
1954
1694
  download,
1955
1695
  presign,
1956
1696
  reset
1957
1697
  };
1958
1698
  }
1959
- var INITIAL_STATE4 = {
1699
+ var INITIAL_STATE3 = {
1960
1700
  phase: "idle",
1961
1701
  error: null,
1962
- pendingKey: null
1702
+ objectKey: null
1963
1703
  };
1964
1704
  function useDelete(options) {
1965
- const [state, patch, replace] = useImmerState(INITIAL_STATE4);
1705
+ const [state, patch, replace] = useImmerState(INITIAL_STATE3);
1966
1706
  const contextApi = useContext(S3Context);
1967
1707
  const optsRef = useLiveRef(options);
1968
1708
  const apiRef = useLiveRef(contextApi);
1969
- const pendingKeyRef = useRef(null);
1709
+ const objectKeyRef = useRef(null);
1970
1710
  const inFlightRef = useRef(false);
1971
1711
  const requestDelete = useCallback(
1972
1712
  (key) => {
1973
- pendingKeyRef.current = key;
1713
+ objectKeyRef.current = key;
1974
1714
  patch((draft) => {
1975
1715
  draft.phase = "confirming";
1976
1716
  draft.error = null;
1977
- draft.pendingKey = key;
1717
+ draft.objectKey = key;
1978
1718
  });
1979
1719
  },
1980
1720
  [patch]
@@ -1991,15 +1731,15 @@ function useDelete(options) {
1991
1731
  if (opts.beforeDelete) {
1992
1732
  const allowed = await opts.beforeDelete(key);
1993
1733
  if (!allowed) {
1734
+ objectKeyRef.current = null;
1994
1735
  patch((draft) => {
1995
1736
  draft.phase = "error";
1996
1737
  draft.error = hookBlockedError(
1997
1738
  "Delete blocked by beforeDelete hook"
1998
1739
  );
1999
- draft.pendingKey = null;
1740
+ draft.objectKey = key;
2000
1741
  });
2001
1742
  opts.onError?.(key, new Error("blocked"), "confirming");
2002
- pendingKeyRef.current = null;
2003
1743
  return;
2004
1744
  }
2005
1745
  }
@@ -2007,15 +1747,16 @@ function useDelete(options) {
2007
1747
  patch((draft) => {
2008
1748
  draft.phase = "deleting";
2009
1749
  draft.error = null;
1750
+ draft.objectKey = key;
2010
1751
  });
2011
1752
  opts.onDeleteStart?.(key);
2012
1753
  try {
2013
1754
  await api.delete({ route: opts.route, key });
2014
- pendingKeyRef.current = null;
1755
+ objectKeyRef.current = null;
2015
1756
  patch((draft) => {
2016
1757
  draft.phase = "success";
2017
1758
  draft.error = null;
2018
- draft.pendingKey = null;
1759
+ draft.objectKey = key;
2019
1760
  });
2020
1761
  try {
2021
1762
  await opts.onSuccess?.(key);
@@ -2026,6 +1767,7 @@ function useDelete(options) {
2026
1767
  patch((draft) => {
2027
1768
  draft.phase = "error";
2028
1769
  draft.error = toHookError(err, "Delete failed");
1770
+ draft.objectKey = key;
2029
1771
  });
2030
1772
  opts.onError?.(key, err, "deleting");
2031
1773
  } finally {
@@ -2035,16 +1777,16 @@ function useDelete(options) {
2035
1777
  [apiRef, optsRef, patch]
2036
1778
  );
2037
1779
  const confirmDelete = useCallback(async () => {
2038
- const key = pendingKeyRef.current;
1780
+ const key = objectKeyRef.current;
2039
1781
  if (!key) return;
2040
1782
  await executeDelete(key);
2041
1783
  }, [executeDelete]);
2042
1784
  const remove = useCallback(
2043
1785
  async (key) => {
2044
1786
  if (inFlightRef.current) return;
2045
- pendingKeyRef.current = key;
1787
+ objectKeyRef.current = key;
2046
1788
  patch((draft) => {
2047
- draft.pendingKey = key;
1789
+ draft.objectKey = key;
2048
1790
  draft.error = null;
2049
1791
  });
2050
1792
  await executeDelete(key);
@@ -2099,7 +1841,6 @@ function useDelete(options) {
2099
1841
  patch((draft) => {
2100
1842
  draft.phase = "success";
2101
1843
  draft.error = null;
2102
- draft.pendingKey = null;
2103
1844
  });
2104
1845
  } catch (err) {
2105
1846
  patch((draft) => {
@@ -2114,17 +1855,22 @@ function useDelete(options) {
2114
1855
  [apiRef, optsRef, patch]
2115
1856
  );
2116
1857
  const cancelDelete = useCallback(() => {
2117
- pendingKeyRef.current = null;
2118
- replace(INITIAL_STATE4);
1858
+ objectKeyRef.current = null;
1859
+ replace(INITIAL_STATE3);
2119
1860
  }, [replace]);
2120
1861
  const reset = useCallback(() => {
2121
- pendingKeyRef.current = null;
2122
- replace(INITIAL_STATE4);
1862
+ objectKeyRef.current = null;
1863
+ replace(INITIAL_STATE3);
2123
1864
  }, [replace]);
1865
+ const isConfirming = state.phase === "confirming";
1866
+ const isDeleting = state.phase === "deleting";
2124
1867
  return {
2125
1868
  phase: state.phase,
1869
+ objectKey: state.objectKey,
2126
1870
  error: state.error,
2127
- pendingKey: state.pendingKey,
1871
+ isConfirming,
1872
+ isDeleting,
1873
+ isPending: isConfirming || isDeleting,
2128
1874
  requestDelete,
2129
1875
  confirmDelete,
2130
1876
  remove,
@@ -2231,6 +1977,6 @@ function useObjectUrl(options) {
2231
1977
  return { url, expiresIn, error, isLoading, refresh };
2232
1978
  }
2233
1979
 
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 };
1980
+ export { DEFAULT_MULTIPART_THRESHOLD, S3Provider, S3UploadError, createLocalStorageStore, createMemoryStore, createS3Client, defineApi, formatAcceptLabels, formatEta, formatSpeed, formatUploadProgress, isFetchDownload, loadRouteCatalog, mergeRouteUploadPolicy, multipartResumeKey, resolveRouteUploadPolicy, uploadFile, uploadFiles, useApi, useDelete, useDownload, useFormatDimahError, useFormatValidateFileError, useObjectUrl, useRouteUploadPolicy, useUpload };
2235
1981
  //# sourceMappingURL=index.js.map
2236
1982
  //# sourceMappingURL=index.js.map