@dimah-s3/react 1.7.1 → 2.0.0-beta.1

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.
Files changed (148) hide show
  1. package/README.md +53 -13
  2. package/dist/api.d.ts +24 -15
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/chunk-SPUUNLXI.js +824 -0
  5. package/dist/chunk-SPUUNLXI.js.map +1 -0
  6. package/dist/create-s3-client.d.ts +1 -1
  7. package/dist/create-s3-client.d.ts.map +1 -1
  8. package/dist/engine.d.ts +15 -1
  9. package/dist/engine.d.ts.map +1 -1
  10. package/dist/engine.js +204 -512
  11. package/dist/engine.js.map +1 -1
  12. package/dist/helpers/format-accept-labels.d.ts +15 -2
  13. package/dist/helpers/format-accept-labels.d.ts.map +1 -1
  14. package/dist/helpers/format-date.d.ts +7 -0
  15. package/dist/helpers/format-date.d.ts.map +1 -0
  16. package/dist/helpers/format-dimah-error.d.ts +12 -2
  17. package/dist/helpers/format-dimah-error.d.ts.map +1 -1
  18. package/dist/helpers/format-file-size.d.ts +20 -0
  19. package/dist/helpers/format-file-size.d.ts.map +1 -0
  20. package/dist/helpers/format-speed.d.ts +1 -1
  21. package/dist/helpers/format-speed.d.ts.map +1 -1
  22. package/dist/helpers/format-upload-progress.d.ts +1 -1
  23. package/dist/helpers/format-upload-progress.d.ts.map +1 -1
  24. package/dist/helpers/index.d.ts +5 -8
  25. package/dist/helpers/index.d.ts.map +1 -1
  26. package/dist/helpers/load-route-catalog.d.ts +32 -8
  27. package/dist/helpers/load-route-catalog.d.ts.map +1 -1
  28. package/dist/helpers/throttled-speed.d.ts +2 -2
  29. package/dist/helpers/throttled-speed.d.ts.map +1 -1
  30. package/dist/helpers/to-timestamp.d.ts +5 -0
  31. package/dist/helpers/to-timestamp.d.ts.map +1 -0
  32. package/dist/helpers/truncate-file-name.d.ts +8 -0
  33. package/dist/helpers/truncate-file-name.d.ts.map +1 -0
  34. package/dist/helpers/use-format-accept-labels.d.ts +12 -0
  35. package/dist/helpers/use-format-accept-labels.d.ts.map +1 -0
  36. package/dist/helpers/use-format-eta.d.ts +14 -0
  37. package/dist/helpers/use-format-eta.d.ts.map +1 -0
  38. package/dist/helpers/use-format-speed.d.ts +12 -0
  39. package/dist/helpers/use-format-speed.d.ts.map +1 -0
  40. package/dist/hooks/use-delete.d.ts +6 -44
  41. package/dist/hooks/use-delete.d.ts.map +1 -1
  42. package/dist/hooks/use-download.d.ts +7 -117
  43. package/dist/hooks/use-download.d.ts.map +1 -1
  44. package/dist/hooks/use-fetch-download.d.ts +8 -0
  45. package/dist/hooks/use-fetch-download.d.ts.map +1 -0
  46. package/dist/hooks/use-file-intake.d.ts +43 -29
  47. package/dist/hooks/use-file-intake.d.ts.map +1 -1
  48. package/dist/hooks/use-file-upload.d.ts +38 -34
  49. package/dist/hooks/use-file-upload.d.ts.map +1 -1
  50. package/dist/hooks/use-object-list-selection.d.ts +78 -0
  51. package/dist/hooks/use-object-list-selection.d.ts.map +1 -0
  52. package/dist/hooks/use-object-list.d.ts +66 -16
  53. package/dist/hooks/use-object-list.d.ts.map +1 -1
  54. package/dist/hooks/use-object-url.d.ts +27 -10
  55. package/dist/hooks/use-object-url.d.ts.map +1 -1
  56. package/dist/hooks/use-route-upload-policy.d.ts +22 -14
  57. package/dist/hooks/use-route-upload-policy.d.ts.map +1 -1
  58. package/dist/hooks/use-upload.d.ts +72 -65
  59. package/dist/hooks/use-upload.d.ts.map +1 -1
  60. package/dist/index.d.ts +15 -19
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +2420 -2164
  63. package/dist/index.js.map +1 -1
  64. package/dist/internal/abortable.d.ts +9 -0
  65. package/dist/internal/abortable.d.ts.map +1 -0
  66. package/dist/internal/browser-download.d.ts +15 -0
  67. package/dist/internal/browser-download.d.ts.map +1 -0
  68. package/dist/internal/callbacks.d.ts +54 -0
  69. package/dist/internal/callbacks.d.ts.map +1 -0
  70. package/dist/internal/client-error.d.ts +15 -0
  71. package/dist/internal/client-error.d.ts.map +1 -0
  72. package/dist/internal/hooks.d.ts +27 -0
  73. package/dist/internal/hooks.d.ts.map +1 -0
  74. package/dist/internal/lru.d.ts +13 -0
  75. package/dist/internal/lru.d.ts.map +1 -0
  76. package/dist/internal/operations.d.ts +74 -0
  77. package/dist/internal/operations.d.ts.map +1 -0
  78. package/dist/internal/pool.d.ts +8 -0
  79. package/dist/internal/pool.d.ts.map +1 -0
  80. package/dist/list/entries.d.ts +14 -0
  81. package/dist/list/entries.d.ts.map +1 -0
  82. package/dist/list/memory-object-source.d.ts +60 -0
  83. package/dist/list/memory-object-source.d.ts.map +1 -0
  84. package/dist/list/types.d.ts +123 -11
  85. package/dist/list/types.d.ts.map +1 -1
  86. package/dist/s3-provider.d.ts +3 -2
  87. package/dist/s3-provider.d.ts.map +1 -1
  88. package/dist/store/local-storage-store.d.ts +5 -4
  89. package/dist/store/local-storage-store.d.ts.map +1 -1
  90. package/dist/store/memory-store.d.ts +3 -4
  91. package/dist/store/memory-store.d.ts.map +1 -1
  92. package/dist/translations/types.d.ts +105 -23
  93. package/dist/translations/types.d.ts.map +1 -1
  94. package/dist/types/delete.d.ts +98 -9
  95. package/dist/types/delete.d.ts.map +1 -1
  96. package/dist/types/download.d.ts +152 -23
  97. package/dist/types/download.d.ts.map +1 -1
  98. package/dist/types/index.d.ts +1 -1
  99. package/dist/types/index.d.ts.map +1 -1
  100. package/dist/types/operation.d.ts +38 -0
  101. package/dist/types/operation.d.ts.map +1 -0
  102. package/dist/types/upload-store.d.ts +30 -40
  103. package/dist/types/upload-store.d.ts.map +1 -1
  104. package/dist/types/upload.d.ts +177 -130
  105. package/dist/types/upload.d.ts.map +1 -1
  106. package/dist/upload/abort.d.ts +10 -0
  107. package/dist/upload/abort.d.ts.map +1 -0
  108. package/dist/upload/constants.d.ts +8 -3
  109. package/dist/upload/constants.d.ts.map +1 -1
  110. package/dist/upload/index.d.ts +3 -2
  111. package/dist/upload/index.d.ts.map +1 -1
  112. package/dist/upload/multipart.d.ts +14 -4
  113. package/dist/upload/multipart.d.ts.map +1 -1
  114. package/dist/upload/part-pool.d.ts +16 -0
  115. package/dist/upload/part-pool.d.ts.map +1 -0
  116. package/dist/upload/presigned-http.d.ts +5 -14
  117. package/dist/upload/presigned-http.d.ts.map +1 -1
  118. package/dist/upload/progress.d.ts +7 -0
  119. package/dist/upload/progress.d.ts.map +1 -0
  120. package/dist/upload/request.d.ts +9 -0
  121. package/dist/upload/request.d.ts.map +1 -0
  122. package/dist/upload/resume-key.d.ts +7 -3
  123. package/dist/upload/resume-key.d.ts.map +1 -1
  124. package/dist/upload/retry.d.ts +27 -2
  125. package/dist/upload/retry.d.ts.map +1 -1
  126. package/dist/upload/stored-upload.d.ts +7 -0
  127. package/dist/upload/stored-upload.d.ts.map +1 -0
  128. package/dist/upload/upload-file.d.ts +10 -11
  129. package/dist/upload/upload-file.d.ts.map +1 -1
  130. package/dist/upload/upload-part.d.ts +6 -3
  131. package/dist/upload/upload-part.d.ts.map +1 -1
  132. package/dist/upload/xhr-upload.d.ts +10 -2
  133. package/dist/upload/xhr-upload.d.ts.map +1 -1
  134. package/package.json +7 -8
  135. package/dist/helpers/format-eta.d.ts +0 -13
  136. package/dist/helpers/format-eta.d.ts.map +0 -1
  137. package/dist/helpers/format-validate-file-error.d.ts +0 -9
  138. package/dist/helpers/format-validate-file-error.d.ts.map +0 -1
  139. package/dist/hooks/index.d.ts +0 -7
  140. package/dist/hooks/index.d.ts.map +0 -1
  141. package/dist/internal-helpers.d.ts +0 -10
  142. package/dist/internal-helpers.d.ts.map +0 -1
  143. package/dist/store/use-immer-state.d.ts +0 -8
  144. package/dist/store/use-immer-state.d.ts.map +0 -1
  145. package/dist/types/error.d.ts +0 -27
  146. package/dist/types/error.d.ts.map +0 -1
  147. package/dist/upload/upload-files.d.ts +0 -26
  148. package/dist/upload/upload-files.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,76 +1,27 @@
1
- import { createS3Client as createS3Client$1, sha256File, formatFileSize, isAPIError, S3_ERROR_CODES, parseFileName, DELETE_BATCH_MAX_KEYS, isS3ErrorCode, APIError, validateFile } from '@dimah-s3/core';
2
- export { APIError, S3_ERROR_CODES, buildContentDisposition, buildObjectKey, buildPublicObjectUrl, fileNameFromKey, formatFileSize, isAPIError, isS3ErrorCode, matchesMagicBytes, resolveInlineDisposition, sanitizeFileName, sha256Base64, sha256File, sniffContentType, validateFile } from '@dimah-s3/core';
3
- import { createContext, useContext, useCallback, useMemo, useState, useEffect, useRef, useLayoutEffect } from 'react';
1
+ "use client";
2
+ import { requireApi, loadRouteCatalog, toClientError, mergeRouteUploadPolicy, resolveRouteUploadPolicy, DEFAULT_MAX_FILES, runBeforeCallback, mapWithConcurrency, abortable, reportOperationOutcome, transferProgress, runStartCallback, notify, runAfterCallback, createObjectListEntries, formatAcceptLabels, formatFileSize, isRawAPIError, toTimestamp, uploadAbortReason, DEFAULT_CONCURRENT_FILES, mergeUploadRequest, resolveUploadRequest, hookFailed, uploadFile } from './chunk-SPUUNLXI.js';
3
+ import { createContext, useContext, useState, useEffect, useCallback, useId, useRef, useMemo, useSyncExternalStore, useLayoutEffect } from 'react';
4
4
  import { TranslationProvider, useTranslations } from '@fuma-translate/react';
5
5
  import { jsx } from 'react/jsx-runtime';
6
- import { produce } from 'immer';
7
- import { ErrorCode, useDropzone } from 'react-dropzone';
6
+ import { createS3Client as createS3Client$1, parseFileName, fileNameFromKey, s3Error, DELETE_MANY_MAX_KEYS, APIError, normalizeObjectKey, isAPIError, S3_ERROR_CODES, validateFile } from '@dimah-s3/core';
7
+ import { useDropzone } from 'react-dropzone';
8
8
 
9
- var S3UploadError = class extends Error {
10
- name = "S3UploadError";
11
- code;
12
- status;
13
- phase;
14
- constructor(message, code, status = 400, phase, options) {
15
- super(message, options);
16
- this.code = code;
17
- this.status = status;
18
- this.phase = phase;
19
- }
20
- get statusCode() {
21
- return this.status;
22
- }
23
- };
24
- function toUploadError(err, phase) {
25
- if (err instanceof S3UploadError) {
26
- if (err.phase == null) {
27
- return new S3UploadError(err.message, err.code, err.statusCode, phase, {
28
- cause: err
29
- });
30
- }
31
- return err;
32
- }
33
- if (isAbortError(err)) {
34
- throw err;
35
- }
36
- if (isAPIError(err)) return err;
37
- const message = err instanceof Error ? err.message : "Upload failed";
38
- return new S3UploadError(message, "UPLOAD_ERROR", 500, phase, {
39
- cause: err
40
- });
41
- }
42
- function toHookError(err, fallback = "Request failed") {
43
- if (isAPIError(err)) return err;
44
- const message = err instanceof Error ? err.message : fallback;
45
- return new APIError("BAD_REQUEST", { message, cause: err });
46
- }
47
- function isAbortError(err) {
48
- if (err instanceof Error && err.name === "AbortError") return true;
49
- return typeof err === "object" && err !== null && err.name === "AbortError";
50
- }
51
- function hookBlockedError(message) {
52
- return new APIError("BAD_REQUEST", { message });
53
- }
54
-
55
- // src/api.ts
56
- function defineApi(input) {
57
- return input;
58
- }
59
9
  var S3Context = createContext(null);
60
10
  var S3LocaleContext = createContext(void 0);
11
+ var NO_TRANSLATIONS = {};
61
12
  function S3Provider({
62
13
  api,
63
14
  translations,
64
15
  locale,
65
16
  children
66
17
  }) {
67
- return /* @__PURE__ */ jsx(S3Context.Provider, { value: api, children: /* @__PURE__ */ jsx(S3LocaleContext.Provider, { value: locale, children: translations ? /* @__PURE__ */ jsx(TranslationProvider, { translations, children }) : children }) });
18
+ return /* @__PURE__ */ jsx(S3Context.Provider, { value: api, children: /* @__PURE__ */ jsx(S3LocaleContext.Provider, { value: locale, children: /* @__PURE__ */ jsx(TranslationProvider, { translations: translations ?? NO_TRANSLATIONS, children }) }) });
68
19
  }
69
20
  function useApi() {
70
21
  const ctx = useContext(S3Context);
71
22
  if (!ctx) {
72
23
  throw new Error(
73
- "[dimah-s3] No S3Api found. Either wrap your app with <S3Provider api={...}> or pass `api` directly to the hook."
24
+ "[dimah-s3] No S3Api found. Wrap your app with <S3Provider api={...}>."
74
25
  );
75
26
  }
76
27
  return ctx;
@@ -86,1300 +37,897 @@ function createS3Client(options) {
86
37
  return Object.assign(api, { Provider, useApi: useApi2 });
87
38
  }
88
39
 
89
- // src/store/local-storage-store.ts
90
- var STORAGE_PREFIX = "dimah-s3:upload:";
91
- function createLocalStorageStore() {
92
- return {
93
- get(resumeKey, fileSize) {
94
- try {
95
- const raw = localStorage.getItem(STORAGE_PREFIX + resumeKey);
96
- if (!raw) return null;
97
- const stored = JSON.parse(raw);
98
- if (stored.resumeKey !== resumeKey || stored.fileSize !== fileSize || !stored.uploadId || !stored.key) {
99
- return null;
40
+ // src/internal/operations.ts
41
+ function newestOperation(operations, key) {
42
+ return operations.findLast((operation) => operation.key === key);
43
+ }
44
+ async function runAfter(after, outcome) {
45
+ await after(outcome);
46
+ return outcome;
47
+ }
48
+ function createOperationStore() {
49
+ const running = /* @__PURE__ */ new Map();
50
+ const listeners = /* @__PURE__ */ new Set();
51
+ let nextId = 0;
52
+ let snapshot = { operations: [], pendingKeys: [] };
53
+ function commit(operations) {
54
+ snapshot = { operations, pendingKeys: [...running.keys()] };
55
+ for (const listener of listeners) listener();
56
+ }
57
+ function isRunning(operation) {
58
+ return running.get(operation.key)?.operationId === operation.id;
59
+ }
60
+ function claim2(key) {
61
+ if (running.has(key)) {
62
+ throw new Error(`[dimah-s3] Key "${key}" already has a running call.`);
63
+ }
64
+ const { promise, resolve, reject } = Promise.withResolvers();
65
+ const entry = {
66
+ controller: new AbortController(),
67
+ promise,
68
+ operationId: null
69
+ };
70
+ let settled = false;
71
+ running.set(key, entry);
72
+ commit(snapshot.operations);
73
+ const release = () => {
74
+ running.delete(key);
75
+ commit(snapshot.operations);
76
+ };
77
+ return {
78
+ key,
79
+ signal: entry.controller.signal,
80
+ promise,
81
+ get operation() {
82
+ return entry.operationId === null ? void 0 : snapshot.operations.find(({ id }) => id === entry.operationId);
83
+ },
84
+ publish(fields) {
85
+ if (entry.operationId !== null) {
86
+ throw new Error(
87
+ `[dimah-s3] The call for "${key}" already published an operation.`
88
+ );
100
89
  }
101
- return stored;
102
- } catch {
103
- return null;
104
- }
105
- },
106
- set(upload) {
107
- try {
108
- localStorage.setItem(
109
- STORAGE_PREFIX + upload.resumeKey,
110
- JSON.stringify(upload)
90
+ const operation = { ...fields, id: String(++nextId), key };
91
+ entry.operationId = operation.id;
92
+ commit([...snapshot.operations, operation]);
93
+ return operation;
94
+ },
95
+ update(patch) {
96
+ const id = entry.operationId;
97
+ if (id === null) return;
98
+ commit(
99
+ snapshot.operations.map(
100
+ (operation) => operation.id === id ? { ...operation, ...patch } : operation
101
+ )
111
102
  );
112
- } catch {
113
- }
114
- },
115
- delete(resumeKey) {
116
- try {
117
- localStorage.removeItem(STORAGE_PREFIX + resumeKey);
118
- } catch {
103
+ },
104
+ settle(outcome, after) {
105
+ if (settled) return promise;
106
+ settled = true;
107
+ Promise.resolve(outcome).then(
108
+ (value) => {
109
+ release();
110
+ resolve(after ? runAfter(after, value) : value);
111
+ },
112
+ (error) => {
113
+ release();
114
+ reject(error);
115
+ }
116
+ );
117
+ return promise;
119
118
  }
120
- }
121
- };
122
- }
123
-
124
- // src/store/memory-store.ts
125
- function createMemoryStore() {
126
- const map = /* @__PURE__ */ new Map();
119
+ };
120
+ }
127
121
  return {
128
- get(resumeKey, fileSize) {
129
- const stored = map.get(resumeKey);
130
- if (!stored) return null;
131
- return stored.fileSize === fileSize ? stored : null;
122
+ subscribe(listener) {
123
+ listeners.add(listener);
124
+ return () => {
125
+ listeners.delete(listener);
126
+ };
132
127
  },
133
- set(upload) {
134
- map.set(upload.resumeKey, upload);
128
+ getSnapshot: () => snapshot,
129
+ get: (key) => newestOperation(snapshot.operations, key),
130
+ join: (key) => running.get(key)?.promise,
131
+ claim: claim2,
132
+ run(key, task, after) {
133
+ const joined = running.get(key)?.promise;
134
+ if (joined) return joined;
135
+ const call = claim2(key);
136
+ const start = async () => task(call);
137
+ return call.settle(start(), after);
135
138
  },
136
- delete(resumeKey) {
137
- map.delete(resumeKey);
139
+ cancel(key, reason) {
140
+ const entries = key === void 0 ? [...running.values()] : [running.get(key)];
141
+ for (const entry of entries) entry?.controller.abort(reason);
142
+ },
143
+ reset(key) {
144
+ const operations = snapshot.operations.filter(
145
+ (operation) => isRunning(operation) || key !== void 0 && operation.key !== key
146
+ );
147
+ if (operations.length !== snapshot.operations.length) commit(operations);
138
148
  }
139
149
  };
140
150
  }
141
151
 
142
- // src/upload/constants.ts
143
- var DEFAULT_MULTIPART_THRESHOLD = 50 * 1024 * 1024;
144
- var DEFAULT_PART_SIZE = 5 * 1024 * 1024;
145
- var MAX_RETRIES = 3;
146
- var RETRY_BASE_DELAY = 1e3;
147
- var DEFAULT_CONCURRENT_PARTS = 2;
148
- var DEFAULT_CONCURRENT_FILES = 2;
149
- var DEFAULT_MAX_FILES = 1;
150
- function httpStatus(err) {
151
- if (err instanceof S3UploadError) return err.statusCode;
152
- if (isAPIError(err)) return err.statusCode;
153
- return void 0;
154
- }
155
- function isNonRetryable(err) {
156
- if (isAbortError(err)) return true;
157
- const status = httpStatus(err);
158
- return typeof status === "number" && status >= 400 && status < 500 && status !== 429;
159
- }
160
- function waitForRetry(delay, signal) {
161
- if (signal?.aborted) {
162
- return Promise.reject(new DOMException("Upload aborted", "AbortError"));
163
- }
164
- const timeout = AbortSignal.timeout(delay);
165
- const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
166
- return new Promise((resolve, reject) => {
167
- const onAbort = () => {
168
- if (signal?.aborted) {
169
- reject(new DOMException("Upload aborted", "AbortError"));
170
- return;
171
- }
172
- resolve();
173
- };
174
- if (combined.aborted) {
175
- onAbort();
176
- return;
177
- }
178
- combined.addEventListener("abort", onAbort, { once: true });
152
+ // src/internal/hooks.ts
153
+ function useLiveRef(value) {
154
+ const ref = useRef(value);
155
+ useLayoutEffect(() => {
156
+ ref.current = value;
179
157
  });
158
+ return ref;
180
159
  }
181
- async function withRetry(fn, retryConfig, signal) {
182
- const maxRetries = retryConfig?.maxRetries ?? MAX_RETRIES;
183
- const baseDelay = retryConfig?.baseDelay ?? RETRY_BASE_DELAY;
184
- let lastError;
185
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
186
- try {
187
- return await fn();
188
- } catch (err) {
189
- if (isNonRetryable(err)) throw err;
190
- lastError = err;
191
- if (attempt < maxRetries) {
192
- const delay = baseDelay * 2 ** attempt;
193
- await waitForRetry(delay, signal);
194
- }
195
- }
196
- }
197
- throw lastError;
160
+ function useControllableState(value, defaultValue, onChange, isEqual = Object.is) {
161
+ const [local, setLocal] = useState(defaultValue);
162
+ const controlled = value !== void 0;
163
+ const current = controlled ? value : local;
164
+ const currentRef = useLiveRef(current);
165
+ const controlledRef = useLiveRef(controlled);
166
+ const onChangeRef = useLiveRef(onChange);
167
+ const isEqualRef = useLiveRef(isEqual);
168
+ const set = useCallback(
169
+ (next) => {
170
+ if (isEqualRef.current(currentRef.current, next)) return;
171
+ currentRef.current = next;
172
+ if (!controlledRef.current) setLocal(() => next);
173
+ onChangeRef.current?.(next);
174
+ },
175
+ [controlledRef, currentRef, isEqualRef, onChangeRef]
176
+ );
177
+ return [current, set];
178
+ }
179
+ function useOperationStore() {
180
+ const [store] = useState(() => createOperationStore());
181
+ const { operations, pendingKeys } = useSyncExternalStore(
182
+ store.subscribe,
183
+ store.getSnapshot,
184
+ store.getSnapshot
185
+ );
186
+ const get = useCallback(
187
+ (key) => newestOperation(operations, key),
188
+ [operations]
189
+ );
190
+ return { store, operations, pendingKeys, get };
198
191
  }
199
192
 
200
- // src/upload/xhr-upload.ts
201
- function sendXhrUpload(options) {
202
- const {
203
- method,
204
- url,
205
- body,
206
- headers,
207
- signal,
208
- errorLabel = "Upload",
209
- onProgress
210
- } = options;
211
- return new Promise((resolve, reject) => {
212
- if (signal?.aborted) {
213
- reject(new DOMException("Upload aborted", "AbortError"));
214
- return;
215
- }
216
- const xhr = new XMLHttpRequest();
217
- const onAbort = () => {
218
- xhr.abort();
219
- reject(new DOMException("Upload aborted", "AbortError"));
220
- };
221
- signal?.addEventListener("abort", onAbort, { once: true });
222
- xhr.upload.addEventListener("progress", (e) => {
223
- if (e.lengthComputable) {
224
- onProgress?.(e.loaded, e.total);
225
- }
226
- });
227
- xhr.addEventListener("load", () => {
228
- signal?.removeEventListener("abort", onAbort);
229
- if (xhr.status >= 200 && xhr.status < 300) {
230
- resolve();
231
- } else {
232
- reject(
233
- new S3UploadError(
234
- `${errorLabel} failed: ${xhr.status} ${xhr.statusText}`,
235
- "HTTP_ERROR",
236
- xhr.status,
237
- "uploading"
238
- )
239
- );
240
- }
241
- });
242
- xhr.addEventListener("error", () => {
243
- signal?.removeEventListener("abort", onAbort);
244
- reject(
245
- new S3UploadError(
246
- `${errorLabel} failed: network error`,
247
- "NETWORK_ERROR",
248
- 0,
249
- "uploading"
250
- )
251
- );
252
- });
253
- xhr.addEventListener("abort", () => {
254
- signal?.removeEventListener("abort", onAbort);
255
- reject(new DOMException("Upload aborted", "AbortError"));
256
- });
257
- xhr.open(method, url);
258
- if (headers) {
259
- for (const [k, v] of Object.entries(headers)) {
260
- xhr.setRequestHeader(k, v);
261
- }
262
- }
263
- xhr.send(body);
264
- });
193
+ // src/helpers/file-preview.ts
194
+ function createImagePreviewUrl(file) {
195
+ if (!file.type.startsWith("image/")) return null;
196
+ return URL.createObjectURL(file);
197
+ }
198
+ function revokePreviewUrl(url) {
199
+ if (!url) return;
200
+ URL.revokeObjectURL(url);
265
201
  }
266
202
 
267
- // src/upload/presigned-http.ts
268
- function reportByteProgress(onProgress) {
269
- return (loaded, total) => {
270
- onProgress?.({
271
- loaded,
272
- total,
273
- percent: total > 0 ? Math.round(loaded / total * 100) : 0
274
- });
203
+ // src/helpers/speed-tracker.ts
204
+ function createSpeedTracker(windowMs = 3e3) {
205
+ const samples = [];
206
+ return {
207
+ /**
208
+ * Record the latest cumulative `loaded` byte count.
209
+ * Returns the current speed in bytes/second (0 until at least 2 samples exist).
210
+ */
211
+ update(loaded) {
212
+ const now = Date.now();
213
+ samples.push({ t: now, loaded });
214
+ const cutoff = now - windowMs;
215
+ while (samples.length > 1 && samples[0].t < cutoff) {
216
+ samples.shift();
217
+ }
218
+ const oldest = samples[0];
219
+ const newest = samples.at(-1);
220
+ if (oldest == null || newest == null) return 0;
221
+ const deltaMs = newest.t - oldest.t;
222
+ const deltaBytes = newest.loaded - oldest.loaded;
223
+ return deltaMs > 0 ? Math.round(deltaBytes / deltaMs * 1e3) : 0;
224
+ },
225
+ reset() {
226
+ samples.length = 0;
227
+ }
275
228
  };
276
229
  }
277
- function uploadSimple(file, url, fields, onProgress, signal) {
278
- const formData = new FormData();
279
- for (const [k, v] of Object.entries(fields)) {
280
- formData.append(k, v);
281
- }
282
- formData.append("file", file);
283
- return sendXhrUpload({
284
- method: "POST",
285
- url,
286
- body: formData,
287
- signal,
288
- onProgress: reportByteProgress(onProgress)
289
- }).then(() => {
290
- onProgress?.({ loaded: file.size, total: file.size, percent: 100 });
291
- });
292
- }
293
- function uploadPut(file, url, headers, onProgress, signal) {
294
- return sendXhrUpload({
295
- method: "PUT",
296
- url,
297
- body: file,
298
- headers,
299
- signal,
300
- onProgress: reportByteProgress(onProgress)
301
- }).then(() => {
302
- onProgress?.({ loaded: file.size, total: file.size, percent: 100 });
303
- });
304
- }
305
230
 
306
- // src/upload/upload-part.ts
307
- function uploadPart(blob, url, partLoaded, reportProgress, signal) {
308
- return sendXhrUpload({
309
- method: "PUT",
310
- url,
311
- body: blob,
312
- signal,
313
- errorLabel: "Part upload",
314
- onProgress: (loaded) => {
315
- partLoaded.bytes = loaded;
316
- reportProgress();
231
+ // src/helpers/throttled-speed.ts
232
+ function createThrottledSpeedUpdater(tracker, intervalMs = 500) {
233
+ let lastSpeed;
234
+ let lastUpdate = 0;
235
+ return {
236
+ reset() {
237
+ tracker.reset();
238
+ lastSpeed = void 0;
239
+ lastUpdate = 0;
240
+ },
241
+ apply(progress) {
242
+ const rawSpeed = tracker.update(progress.loaded);
243
+ const now = Date.now();
244
+ if (rawSpeed > 0 && now - lastUpdate >= intervalMs) {
245
+ lastSpeed = rawSpeed;
246
+ lastUpdate = now;
247
+ }
248
+ return lastSpeed ? { ...progress, speed: lastSpeed } : progress;
317
249
  }
318
- }).then(() => {
319
- partLoaded.bytes = blob.size;
320
- reportProgress();
321
- });
250
+ };
322
251
  }
323
252
 
324
- // src/upload/resume-key.ts
325
- function multipartResumeKey(route, file) {
326
- return `${route}:${file.name}:${file.size}:${file.lastModified}`;
253
+ // src/hooks/use-file-upload.ts
254
+ function useFileUpload(options) {
255
+ const contextApi = useContext(S3Context);
256
+ const [queue] = useState(() => createUploadQueue(options, contextApi));
257
+ const snapshot = useSyncExternalStore(
258
+ queue.subscribe,
259
+ queue.getSnapshot,
260
+ queue.getSnapshot
261
+ );
262
+ useLayoutEffect(() => {
263
+ queue.configure(options, contextApi);
264
+ });
265
+ useEffect(() => queue.dispose, [queue]);
266
+ const { files, fileRejections, preparing } = snapshot;
267
+ const summary = useMemo(() => summarize(files), [files]);
268
+ const isPending = preparing > 0 || summary.active;
269
+ return {
270
+ files,
271
+ file: files[0] ?? null,
272
+ phase: isPending ? "uploading" : summary.phase,
273
+ progress: summary.progress,
274
+ error: summary.error,
275
+ isPending,
276
+ fileRejections,
277
+ upload: queue.upload,
278
+ retry: queue.retry,
279
+ cancel: queue.cancel,
280
+ detach: queue.detach,
281
+ reset: queue.reset
282
+ };
327
283
  }
328
-
329
- // src/upload/multipart.ts
330
- function resolvePartSize(partIndex, totalParts, partSize, fileSize) {
331
- return partIndex === totalParts - 1 ? fileSize - partIndex * partSize : partSize;
332
- }
333
- async function uploadMultipart(api, file, route, partSize, concurrentParts, onProgress, signal, requestOptions, retryConfig, uploadStore, onPartUpload, onMultipartInit) {
334
- const rawContentType = requestOptions?.contentType ?? file.type;
335
- const contentType = rawContentType.trim() === "" ? void 0 : rawContentType;
336
- const fileName = requestOptions?.fileName || file.name;
337
- const resumeKey = multipartResumeKey(route, file);
338
- const store = uploadStore != null && uploadStore !== false ? uploadStore : null;
339
- const completedPartNumbers = /* @__PURE__ */ new Set();
340
- const initUpload = async () => {
341
- const result = await api.multipart.init({
342
- route,
343
- contentType,
344
- fileSize: file.size,
345
- fileName,
346
- metadata: requestOptions?.metadata,
347
- checksum: requestOptions?.checksum
348
- });
349
- await store?.set({
350
- resumeKey,
351
- uploadId: result.uploadId,
352
- key: result.key,
353
- fileSize: file.size
354
- });
355
- onMultipartInit?.(result.uploadId, result.key);
356
- return { uploadId: result.uploadId, key: result.key };
284
+ var ACTIVE_PHASES = /* @__PURE__ */ new Set([
285
+ "queued",
286
+ "preparing",
287
+ "presigning",
288
+ "uploading",
289
+ "finalizing"
290
+ ]);
291
+ function createUploadQueue(initialOptions, initialContextApi) {
292
+ const listeners = /* @__PURE__ */ new Set();
293
+ const tasks = /* @__PURE__ */ new Map();
294
+ const waiting = [];
295
+ const preparingCalls = /* @__PURE__ */ new Set();
296
+ const entryCalls = /* @__PURE__ */ new Map();
297
+ const retrying = /* @__PURE__ */ new Map();
298
+ let running = 0;
299
+ let latest = { options: initialOptions, contextApi: initialContextApi };
300
+ let snapshot = {
301
+ files: [],
302
+ fileRejections: [],
303
+ preparing: 0
357
304
  };
358
- const existing = store ? await store.get(resumeKey, file.size) : null;
359
- let uploadId;
360
- let key;
361
- if (existing) {
362
- try {
363
- const { parts: parts2 } = await api.multipart.listParts({
364
- route,
365
- key: existing.key,
366
- uploadId: existing.uploadId
367
- });
368
- uploadId = existing.uploadId;
369
- key = existing.key;
370
- for (const p of parts2) completedPartNumbers.add(p.partNumber);
371
- onMultipartInit?.(uploadId, key);
372
- } catch (err) {
373
- if (!isS3ErrorCode(err, "OBJECT_NOT_FOUND")) throw err;
374
- await store?.delete(resumeKey);
375
- ({ uploadId, key } = await initUpload());
376
- }
377
- } else {
378
- ({ uploadId, key } = await initUpload());
305
+ function commit(patch) {
306
+ snapshot = { ...snapshot, ...patch };
307
+ for (const listener of listeners) listener();
379
308
  }
380
- const totalParts = Math.ceil(file.size / partSize);
381
- const partProgress = Array.from(
382
- { length: totalParts },
383
- (_, i) => ({
384
- bytes: completedPartNumbers.has(i + 1) ? resolvePartSize(i, totalParts, partSize, file.size) : 0
385
- })
386
- );
387
- const parts = Array.from(
388
- completedPartNumbers,
389
- (n) => ({ partNumber: n })
390
- );
391
- const reportProgress = () => {
392
- const loaded = partProgress.reduce((sum, p) => sum + p.bytes, 0);
393
- onProgress?.({
394
- loaded,
395
- total: file.size,
396
- percent: Math.round(loaded / file.size * 100)
309
+ function hasFile(id) {
310
+ return snapshot.files.some((entry) => entry.id === id);
311
+ }
312
+ function patchFile(id, patch) {
313
+ if (!hasFile(id)) return;
314
+ commit({
315
+ files: snapshot.files.map(
316
+ (entry) => entry.id === id ? { ...entry, ...patch } : entry
317
+ )
397
318
  });
398
- };
399
- if (completedPartNumbers.size > 0) {
400
- reportProgress();
401
319
  }
402
- try {
403
- for (let batchStart = 0; batchStart < totalParts; batchStart += concurrentParts) {
404
- if (signal?.aborted) {
405
- throw new DOMException("Upload aborted", "AbortError");
406
- }
407
- const batchEnd = Math.min(batchStart + concurrentParts, totalParts);
408
- const batch = [];
409
- for (let i = batchStart; i < batchEnd; i++) {
410
- const partNumber = i + 1;
411
- if (completedPartNumbers.has(partNumber)) continue;
412
- const start = i * partSize;
413
- const end = Math.min(start + partSize, file.size);
414
- const blob = file.slice(start, end);
415
- batch.push(
416
- withRetry(
417
- async () => {
418
- const { url } = await api.multipart.signPart({
419
- route,
420
- key,
421
- uploadId,
422
- partNumber,
423
- partSize: blob.size
424
- });
425
- partProgress[i].bytes = 0;
426
- await uploadPart(
427
- blob,
428
- url,
429
- partProgress[i],
430
- reportProgress,
431
- signal
432
- );
433
- onPartUpload?.(partNumber, totalParts);
434
- return { partNumber };
435
- },
436
- retryConfig,
437
- signal
438
- )
439
- );
320
+ function replaceFiles(replace) {
321
+ let changed = false;
322
+ const files = snapshot.files.map((entry) => {
323
+ const next = replace(entry) ?? entry;
324
+ if (next !== entry) changed = true;
325
+ return next;
326
+ });
327
+ if (changed) commit({ files });
328
+ }
329
+ function removeFiles(shouldRemove) {
330
+ const kept = [];
331
+ for (const entry of snapshot.files) {
332
+ if (shouldRemove(entry)) {
333
+ revokePreviewUrl(entry.previewUrl);
334
+ entryCalls.delete(entry.id);
335
+ } else {
336
+ kept.push(entry);
440
337
  }
441
- const batchResults = await Promise.all(batch);
442
- parts.push(...batchResults);
443
338
  }
444
- const result = await api.multipart.complete({
445
- route,
446
- key,
447
- uploadId,
448
- parts: parts.toSorted((a, b) => a.partNumber - b.partNumber)
449
- });
450
- await store?.delete(resumeKey);
451
- onProgress?.({ loaded: file.size, total: file.size, percent: 100 });
452
- return {
453
- key,
454
- eTag: result.eTag,
455
- contentLength: result.contentLength,
456
- contentType: result.contentType,
457
- fileName: result.fileName
339
+ if (kept.length !== snapshot.files.length) commit({ files: kept });
340
+ }
341
+ function abortTask(task, reason) {
342
+ if (task.running) {
343
+ task.controller.abort(reason);
344
+ return;
345
+ }
346
+ waiting.splice(waiting.indexOf(task), 1);
347
+ tasks.delete(task.id);
348
+ removeFiles((entry) => entry.id === task.id);
349
+ task.resolve({ status: "aborted", file: task.file });
350
+ }
351
+ function abortAll(reason) {
352
+ for (const controller of preparingCalls) controller.abort(reason);
353
+ for (const task of tasks.values()) abortTask(task, reason);
354
+ }
355
+ function schedule(entry, config) {
356
+ const { promise, resolve } = Promise.withResolvers();
357
+ const task = {
358
+ id: entry.id,
359
+ file: entry.file,
360
+ config,
361
+ controller: new AbortController(),
362
+ running: false,
363
+ resolve
458
364
  };
459
- } catch (err) {
460
- if (store === null) {
461
- api.multipart.abort({ route, key, uploadId }).catch(() => {
365
+ tasks.set(task.id, task);
366
+ waiting.push(task);
367
+ pump();
368
+ return promise;
369
+ }
370
+ function pump() {
371
+ const limit = Math.max(
372
+ 1,
373
+ latest.options.concurrentFiles ?? DEFAULT_CONCURRENT_FILES
374
+ );
375
+ while (running < limit && waiting.length > 0) {
376
+ const task = waiting.shift();
377
+ if (task) void run(task);
378
+ }
379
+ }
380
+ async function run(task) {
381
+ running += 1;
382
+ task.running = true;
383
+ const outcome = await execute(task);
384
+ running -= 1;
385
+ tasks.delete(task.id);
386
+ if (outcome.status === "success") {
387
+ patchFile(task.id, {
388
+ phase: "success",
389
+ result: outcome.result,
390
+ progress: transferProgress(task.file.size, task.file.size)
462
391
  });
392
+ } else if (outcome.status === "error") {
393
+ patchFile(task.id, { phase: "error", error: outcome.error });
394
+ } else {
395
+ removeFiles((entry) => entry.id === task.id);
463
396
  }
464
- throw err;
397
+ pump();
398
+ task.resolve(outcome);
465
399
  }
466
- }
467
-
468
- // src/upload/upload-file.ts
469
- function getUploadTransport(api) {
470
- const transport = api.uploadTransport;
471
- return typeof transport === "function" ? transport : void 0;
472
- }
473
- async function uploadFile(api, file, config, callbacks = {}, signal, requestOptions) {
474
- const { route } = config;
475
- const useMultipart = config.multipart === true && file.size >= DEFAULT_MULTIPART_THRESHOLD;
476
- const concurrentParts = config.concurrentParts ?? DEFAULT_CONCURRENT_PARTS;
477
- const rawContentType = requestOptions?.contentType ?? file.type;
478
- const contentType = rawContentType.trim() === "" ? void 0 : rawContentType;
479
- const fileName = requestOptions?.fileName || file.name;
480
- const checksum = requestOptions?.checksum ?? (config.checksum ? await sha256File(file) : void 0);
481
- try {
482
- if (useMultipart) {
483
- callbacks.onPhaseChange?.("presigning");
484
- return await uploadMultipart(
485
- api,
400
+ async function execute(task) {
401
+ const { id, file, config } = task;
402
+ const { options, call, api, policy } = config;
403
+ const { signal } = task.controller;
404
+ const speed = createThrottledSpeedUpdater(createSpeedTracker());
405
+ let request;
406
+ try {
407
+ request = mergeUploadRequest(
408
+ resolveUploadRequest(options.uploadOptions, file),
409
+ resolveUploadRequest(call.uploadOptions, file)
410
+ );
411
+ } catch (error) {
412
+ return {
413
+ status: "error",
486
414
  file,
487
- route,
488
- DEFAULT_PART_SIZE,
489
- concurrentParts,
490
- callbacks.onProgress,
415
+ error: hookFailed("uploadOptions", error)
416
+ };
417
+ }
418
+ try {
419
+ const result = await uploadFile(api, file, {
420
+ route: options.route,
421
+ policy,
422
+ concurrentParts: options.concurrentParts,
423
+ retry: options.retry,
424
+ uploadStore: options.uploadStore,
425
+ request,
491
426
  signal,
492
- { ...requestOptions, checksum },
493
- config.retry,
494
- config.uploadStore,
495
- callbacks.onPartUpload,
496
- (uploadId, serverKey) => {
497
- callbacks.onPhaseChange?.("uploading");
498
- callbacks.onMultipartInit?.(uploadId, serverKey);
427
+ onPhaseChange: (phase) => {
428
+ if (!signal.aborted) patchFile(id, { phase });
429
+ },
430
+ onProgress: (raw) => {
431
+ if (signal.aborted) return;
432
+ const progress = speed.apply(raw);
433
+ patchFile(id, { progress });
434
+ notify(latest.options.onProgress, progress, file);
435
+ },
436
+ onPartUpload: (part) => {
437
+ if (!signal.aborted) notify(latest.options.onPartUpload, part, file);
438
+ },
439
+ onMultipartInit: (session) => {
440
+ if (!signal.aborted) {
441
+ notify(latest.options.onMultipartInit, session, file);
442
+ }
443
+ }
444
+ });
445
+ return { status: "success", file, result };
446
+ } catch (error) {
447
+ if (signal.aborted) return { status: "aborted", file };
448
+ return { status: "error", file, error: toClientError(error) };
449
+ }
450
+ }
451
+ async function prepare(api, files, options, call, signal) {
452
+ let pending = files;
453
+ try {
454
+ let catalog;
455
+ try {
456
+ catalog = await abortable(loadRouteCatalog(api), signal);
457
+ } catch (error2) {
458
+ if (signal.aborted) throw error2;
459
+ commit({ fileRejections: [] });
460
+ return { status: "error", files, error: toClientError(error2) };
461
+ }
462
+ const policy = mergeRouteUploadPolicy(
463
+ resolveRouteUploadPolicy(catalog, options.route),
464
+ {
465
+ accept: options.accept,
466
+ maxFileSize: options.maxFileSize,
467
+ multipart: options.multipart
499
468
  }
500
469
  );
470
+ const maxFiles = Math.min(
471
+ options.maxFiles ?? DEFAULT_MAX_FILES,
472
+ call.maxFiles ?? Number.POSITIVE_INFINITY
473
+ );
474
+ const accepted = [];
475
+ const rejected = [];
476
+ for (const file of files) {
477
+ const error2 = validateFile(file, policy) ?? (accepted.length < maxFiles ? null : s3Error("TOO_MANY_FILES", { maxFiles }));
478
+ if (error2) rejected.push({ file, errors: [error2] });
479
+ else accepted.push(file);
480
+ }
481
+ commit({ fileRejections: rejected });
482
+ if (rejected.length > 0) notify(latest.options.onFileReject, rejected);
483
+ if (accepted.length === 0) return { status: "rejected" };
484
+ pending = accepted;
485
+ const before = await abortable(
486
+ runBeforeCallback(
487
+ "beforeUpload",
488
+ latest.options.beforeUpload,
489
+ accepted
490
+ ),
491
+ signal
492
+ );
493
+ if (before.status === "blocked") {
494
+ return { status: "blocked", files: accepted };
495
+ }
496
+ const error = before.status === "error" ? before.error : runStartCallback(
497
+ "onUploadStart",
498
+ latest.options.onUploadStart,
499
+ accepted
500
+ );
501
+ if (error) return { status: "error", files: accepted, error };
502
+ return {
503
+ status: "ready",
504
+ files: accepted,
505
+ policy: { multipart: policy.multipart, checksum: policy.checksum }
506
+ };
507
+ } catch (error) {
508
+ if (signal.aborted) return { status: "aborted", files: pending };
509
+ throw error;
501
510
  }
502
- callbacks.onPhaseChange?.("presigning");
503
- const presign = await withRetry(
504
- async () => api.upload({
505
- route,
506
- contentType,
507
- fileSize: file.size,
508
- fileName,
509
- metadata: requestOptions?.metadata,
510
- checksum
511
- }),
512
- config.retry,
513
- signal
511
+ }
512
+ function enqueue(entries, call, options, replace) {
513
+ if (replace && !options.queue) {
514
+ for (const task of tasks.values()) {
515
+ abortTask(task, uploadAbortReason("cancel"));
516
+ }
517
+ removeFiles(() => true);
518
+ }
519
+ for (const entry of entries) entryCalls.set(entry.id, call);
520
+ commit({ files: [...snapshot.files, ...entries] });
521
+ }
522
+ function upload(input, call = {}) {
523
+ return startCall([...input], call, []);
524
+ }
525
+ function retry(id) {
526
+ const failed = snapshot.files.filter(
527
+ (entry) => entry.phase === "error" && (id === void 0 || entry.id === id)
514
528
  );
515
- callbacks.onPhaseChange?.("uploading");
516
- await withRetry(
517
- async () => {
518
- const transport = getUploadTransport(api);
519
- if (transport) {
520
- await transport(file, presign, {
521
- onProgress: callbacks.onProgress,
522
- signal
523
- });
524
- } else if (presign.method === "PUT") {
525
- await uploadPut(
526
- file,
527
- presign.url,
528
- presign.headers,
529
- callbacks.onProgress,
530
- signal
531
- );
532
- } else {
533
- await uploadSimple(
534
- file,
535
- presign.url,
536
- presign.fields,
537
- callbacks.onProgress,
538
- signal
539
- );
540
- }
541
- },
542
- config.retry,
543
- signal
529
+ if (failed.length === 0) return Promise.resolve(batchResult([]));
530
+ const calls = Map.groupBy(
531
+ failed,
532
+ (entry) => entryCalls.get(entry.id) ?? {}
544
533
  );
545
- callbacks.onPhaseChange?.("finalizing");
546
- const confirmed = await withRetry(
547
- async () => api.confirm({
548
- route,
549
- key: presign.key
550
- }),
551
- config.retry,
552
- signal
534
+ return Promise.all(
535
+ [...calls].map(
536
+ ([call, entries]) => startCall(
537
+ entries.map((entry) => entry.file),
538
+ call,
539
+ entries
540
+ )
541
+ )
542
+ ).then(mergeBatchResults);
543
+ }
544
+ async function startCall(files, call, retried) {
545
+ const { options } = latest;
546
+ const api = requireApi(options.api ?? latest.contextApi, "useUpload");
547
+ if (files.length === 0) return settle(batchResult([]));
548
+ const controller = new AbortController();
549
+ if (!options.queue && retried.length === 0) {
550
+ const reason = uploadAbortReason("cancel");
551
+ for (const pending of preparingCalls) pending.abort(reason);
552
+ }
553
+ const previous = new Map(retried.map((entry) => [entry.id, entry]));
554
+ for (const id of previous.keys()) retrying.set(id, controller);
555
+ replaceFiles(
556
+ (entry) => previous.has(entry.id) ? requeued(entry) : void 0
553
557
  );
554
- return {
555
- key: confirmed.key,
556
- eTag: confirmed.eTag,
557
- contentLength: confirmed.contentLength,
558
- contentType: confirmed.contentType,
559
- fileName: confirmed.fileName
558
+ preparingCalls.add(controller);
559
+ commit({ preparing: snapshot.preparing + 1 });
560
+ let prepared;
561
+ try {
562
+ prepared = await prepare(api, files, options, call, controller.signal);
563
+ } finally {
564
+ preparingCalls.delete(controller);
565
+ for (const id of previous.keys()) retrying.delete(id);
566
+ commit({ preparing: snapshot.preparing - 1 });
567
+ }
568
+ const unclaimed = retried.filter((entry) => hasFile(entry.id));
569
+ const entryOf = (file) => {
570
+ const index = unclaimed.findIndex((entry) => entry.file === file);
571
+ return index < 0 ? null : unclaimed.splice(index, 1)[0];
560
572
  };
561
- } catch (err) {
562
- throw toUploadError(err, "uploading");
563
- }
564
- }
565
-
566
- // src/upload/upload-files.ts
567
- async function uploadFiles(api, items, config, callbacks = {}, signal, getRequestOptions) {
568
- const results = items.map((item) => ({
569
- ...item,
570
- status: "pending",
571
- progress: { loaded: 0, total: item.file.size, percent: 0 },
572
- result: null,
573
- error: null
574
- }));
575
- const reportTotalProgress = () => {
576
- const loaded = results.reduce((sum, r) => sum + r.progress.loaded, 0);
577
- const total = results.reduce((sum, r) => sum + r.progress.total, 0);
578
- callbacks.onTotalProgress?.({
579
- loaded,
580
- total,
581
- percent: total > 0 ? Math.round(loaded / total * 100) : 0
582
- });
583
- };
584
- let nextIndex = 0;
585
- const processNext = async () => {
586
- while (nextIndex < results.length) {
587
- if (signal?.aborted) return;
588
- const idx = nextIndex++;
589
- const item = results[idx];
590
- item.status = "uploading";
591
- try {
592
- const result = await uploadFile(
593
- api,
594
- item.file,
595
- config,
596
- {
597
- onProgress: (progress) => {
598
- item.progress = progress;
599
- callbacks.onFileProgress?.(item.id, progress);
600
- reportTotalProgress();
601
- },
602
- onPhaseChange: (phase) => {
603
- callbacks.onFilePhaseChange?.(item.id, phase);
604
- },
605
- onPartUpload: (partNumber, totalParts) => {
606
- callbacks.onPartUpload?.(item.id, partNumber, totalParts);
607
- },
608
- onMultipartInit: (uploadId, key) => {
609
- callbacks.onMultipartInit?.(item.id, uploadId, key);
610
- }
611
- },
612
- signal,
613
- getRequestOptions?.(item.file)
573
+ const dropRetried = (kept = /* @__PURE__ */ new Set()) => {
574
+ removeFiles((entry) => previous.has(entry.id) && !kept.has(entry.id));
575
+ };
576
+ let outcomes;
577
+ switch (prepared.status) {
578
+ case "rejected":
579
+ dropRetried();
580
+ return settle(batchResult([]));
581
+ case "blocked": {
582
+ const restored = /* @__PURE__ */ new Set();
583
+ for (const file of prepared.files) {
584
+ const entry = entryOf(file);
585
+ if (entry) restored.add(entry.id);
586
+ }
587
+ replaceFiles(
588
+ (entry) => restored.has(entry.id) ? previous.get(entry.id) : void 0
614
589
  );
615
- item.status = "success";
616
- item.result = result;
617
- item.progress = {
618
- loaded: item.file.size,
619
- total: item.file.size,
620
- percent: 100
621
- };
622
- callbacks.onFileSuccess?.(item.id, result);
623
- reportTotalProgress();
624
- } catch (err) {
625
- if (isAbortError(err)) throw err;
626
- const error = toHookError(err, "Upload failed");
627
- item.status = "error";
628
- item.error = error;
629
- callbacks.onFileError?.(item.id, error);
630
- reportTotalProgress();
590
+ dropRetried(restored);
591
+ return settle(batchResult([], prepared.files));
631
592
  }
632
- }
633
- };
634
- const concurrentFiles = config.concurrentFiles ?? DEFAULT_CONCURRENT_FILES;
635
- const workers = Array.from(
636
- { length: Math.min(concurrentFiles, items.length) },
637
- () => processNext()
638
- );
639
- await Promise.all(workers);
640
- return results;
641
- }
642
-
643
- // src/helpers/format-accept-labels.ts
644
- function formatAcceptLabel(type) {
645
- if (type.startsWith(".")) {
646
- const ext = type.slice(1).toLowerCase();
647
- return ext === "jpg" || ext === "jpeg" ? "JPEG" : ext.toUpperCase();
648
- }
649
- if (type.endsWith("/*")) {
650
- const base = type.slice(0, -2);
651
- return base.charAt(0).toUpperCase() + base.slice(1) + "s";
652
- }
653
- const sub = type.split("/")[1];
654
- return sub ? sub.toUpperCase() : type;
655
- }
656
- function formatAcceptLabels(accept) {
657
- if (!accept?.length) return [];
658
- return [...new Set(accept.map(formatAcceptLabel))];
659
- }
660
- function formatUploadProgress(loaded, total, percent, options) {
661
- const loadedStr = formatFileSize(loaded, options);
662
- if (!total) return loadedStr;
663
- return `${loadedStr} / ${formatFileSize(total, options)} (${Math.round(percent)}%)`;
664
- }
665
- function formatSpeed(bytesPerSecond, options) {
666
- return `${formatFileSize(bytesPerSecond, options)}/s`;
667
- }
668
-
669
- // src/helpers/format-eta.ts
670
- function formatEta(remainingBytes, bytesPerSecond) {
671
- if (bytesPerSecond <= 0 || remainingBytes <= 0) return null;
672
- const totalSeconds = remainingBytes / bytesPerSecond;
673
- if (totalSeconds < 60) return `${Math.ceil(totalSeconds)}s`;
674
- const totalMinutes = totalSeconds / 60;
675
- if (totalMinutes < 60) return `${Math.ceil(totalMinutes)}m`;
676
- const hours = Math.floor(totalMinutes / 60);
677
- const mins = Math.ceil(totalMinutes % 60);
678
- return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
679
- }
680
- function useFormatValidateFileError() {
681
- const t = useTranslations();
682
- return useCallback(
683
- (error) => {
684
- switch (error.code) {
685
- case "FILE_TYPE_NOT_ALLOWED":
686
- return t('File type "{type}" is not allowed', {
687
- note: "file validation",
688
- variables: { type: String(error.params?.type ?? "") }
689
- });
690
- case "FILE_EMPTY":
691
- return t("File is empty", { note: "file validation" });
692
- case "FILE_TOO_LARGE":
693
- return t("File size exceeds {size} limit", {
694
- note: "file validation",
695
- variables: { size: String(error.params?.size ?? "") }
696
- });
697
- default:
698
- return error.message;
699
- }
700
- },
701
- [t]
702
- );
703
- }
704
- function param(params, key, fallback = "") {
705
- const value = params?.[key];
706
- return value === void 0 ? fallback : String(value);
707
- }
708
- function useFormatDimahError() {
709
- const t = useTranslations();
710
- return useCallback(
711
- (err) => {
712
- if (!isAPIError(err) || err.code === void 0) {
713
- return err instanceof Error ? err.message : t("Unknown error", { note: "fallback" });
593
+ case "aborted":
594
+ dropRetried();
595
+ return settle(
596
+ batchResult(
597
+ prepared.files.map((file) => ({ status: "aborted", file }))
598
+ )
599
+ );
600
+ case "error": {
601
+ const { error } = prepared;
602
+ outcomes = [];
603
+ if (retried.length === 0) {
604
+ enqueue(
605
+ prepared.files.map((file) => ({
606
+ ...createEntry(file),
607
+ phase: "error",
608
+ error
609
+ })),
610
+ call,
611
+ options,
612
+ false
613
+ );
614
+ outcomes = prepared.files.map((file) => ({
615
+ status: "error",
616
+ file,
617
+ error
618
+ }));
619
+ } else {
620
+ const failed = /* @__PURE__ */ new Set();
621
+ for (const file of prepared.files) {
622
+ const entry = entryOf(file);
623
+ if (entry) failed.add(entry.id);
624
+ outcomes.push(
625
+ entry ? { status: "error", file, error } : { status: "aborted", file }
626
+ );
627
+ }
628
+ replaceFiles(
629
+ (entry) => failed.has(entry.id) ? { ...entry, phase: "error", error } : void 0
630
+ );
631
+ dropRetried(failed);
632
+ }
633
+ for (const outcome of outcomes) {
634
+ if (outcome.status === "error") {
635
+ await runAfterCallback(latest.options.onError, error, outcome.file);
636
+ }
637
+ }
638
+ break;
714
639
  }
715
- switch (err.code) {
716
- case S3_ERROR_CODES.NOT_FOUND.code:
717
- return t("Not found", { note: "API error" });
718
- case S3_ERROR_CODES.UNAUTHORIZED.code:
719
- return t("Unauthorized", { note: "API error" });
720
- case S3_ERROR_CODES.FORBIDDEN.code:
721
- return t("Access denied", { note: "API error" });
722
- case S3_ERROR_CODES.CONFLICT.code:
723
- return t("Conflict", { note: "API error" });
724
- case S3_ERROR_CODES.INTERNAL_ERROR.code:
725
- return t("Something went wrong", { note: "API error" });
726
- case S3_ERROR_CODES.OBJECT_NOT_FOUND.code:
727
- return t("File not found", { note: "API error" });
728
- case S3_ERROR_CODES.FEATURE_DISABLED.code:
729
- return t("{feature} is disabled", {
730
- note: "API error",
731
- variables: {
732
- feature: param(err.params, "feature", "This feature")
733
- }
734
- });
735
- case S3_ERROR_CODES.INVALID_KEY.code:
736
- return t("Object key is invalid", { note: "API error" });
737
- case S3_ERROR_CODES.UNKNOWN_ROUTE.code:
738
- return t("Unknown file route", { note: "API error" });
739
- case S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.code:
740
- return t("File type is not allowed", { note: "API error" });
741
- case S3_ERROR_CODES.S3_NETWORK_ERROR.code:
742
- return t("Could not reach storage ({code})", {
743
- note: "API error",
744
- variables: { code: param(err.params, "code", "UNKNOWN") }
745
- });
746
- case S3_ERROR_CODES.MULTIPART_PART_MISSING.code:
747
- return t("Uploaded part {partNumber} was not found", {
748
- note: "API error",
749
- variables: {
750
- partNumber: param(err.params, "partNumber", "?")
640
+ case "ready": {
641
+ const config = {
642
+ api,
643
+ options,
644
+ call,
645
+ policy: prepared.policy
646
+ };
647
+ let scheduled;
648
+ if (retried.length === 0) {
649
+ const entries = prepared.files.map(createEntry);
650
+ enqueue(entries, call, options, true);
651
+ scheduled = entries.map((entry) => schedule(entry, config));
652
+ } else {
653
+ const kept = /* @__PURE__ */ new Set();
654
+ scheduled = prepared.files.map((file) => {
655
+ const entry = entryOf(file);
656
+ if (!entry) {
657
+ return Promise.resolve({ status: "aborted", file });
751
658
  }
659
+ kept.add(entry.id);
660
+ return schedule(entry, config);
752
661
  });
753
- case S3_ERROR_CODES.PAYLOAD_TOO_LARGE.code:
754
- return t("File is too large", { note: "API error" });
755
- case S3_ERROR_CODES.VALIDATION_ERROR.code:
756
- return t("Invalid request", { note: "API error" });
757
- default:
758
- return err.message;
662
+ dropRetried(kept);
663
+ }
664
+ outcomes = await Promise.all(scheduled);
665
+ for (const outcome of outcomes) {
666
+ if (outcome.status === "error") {
667
+ await runAfterCallback(
668
+ latest.options.onError,
669
+ outcome.error,
670
+ outcome.file
671
+ );
672
+ }
673
+ }
674
+ for (const outcome of outcomes) {
675
+ if (outcome.status === "success") {
676
+ await runAfterCallback(
677
+ latest.options.onSuccess,
678
+ outcome.result,
679
+ outcome.file
680
+ );
681
+ }
682
+ }
683
+ break;
759
684
  }
760
- },
761
- [t]
762
- );
763
- }
764
- function useFormatFileSize() {
765
- const locale = useContext(S3LocaleContext);
766
- const t = useTranslations();
767
- return useMemo(() => {
768
- const units = {
769
- B: t("B", { note: "file size unit" }),
770
- KB: t("KB", { note: "file size unit" }),
771
- MB: t("MB", { note: "file size unit" }),
772
- GB: t("GB", { note: "file size unit" }),
773
- TB: t("TB", { note: "file size unit" }),
774
- PB: t("PB", { note: "file size unit" }),
775
- EB: t("EB", { note: "file size unit" })
685
+ }
686
+ return settle(batchResult(outcomes));
687
+ }
688
+ async function settle(result) {
689
+ await runAfterCallback(latest.options.onSettled, result);
690
+ return result;
691
+ }
692
+ function subscribe(listener) {
693
+ listeners.add(listener);
694
+ return () => {
695
+ listeners.delete(listener);
776
696
  };
777
- return (bytes) => formatFileSize(bytes, { locale, units });
778
- }, [locale, t]);
779
- }
780
- function useFormatNumber() {
781
- const locale = useContext(S3LocaleContext);
782
- return useCallback(
783
- (value) => locale ? numberFormat(locale).format(value) : String(value),
784
- [locale]
785
- );
786
- }
787
- var numberFormats = /* @__PURE__ */ new Map();
788
- function numberFormat(locale) {
789
- let format = numberFormats.get(locale);
790
- if (!format) {
791
- format = new Intl.NumberFormat(locale);
792
- numberFormats.set(locale, format);
793
697
  }
794
- return format;
698
+ function configure(options, contextApi) {
699
+ latest = { options, contextApi };
700
+ }
701
+ function getSnapshot() {
702
+ return snapshot;
703
+ }
704
+ function cancel(id) {
705
+ const reason = uploadAbortReason("cancel");
706
+ if (id === void 0) {
707
+ abortAll(reason);
708
+ return;
709
+ }
710
+ const task = tasks.get(id);
711
+ if (task) {
712
+ abortTask(task, reason);
713
+ return;
714
+ }
715
+ const controller = retrying.get(id);
716
+ if (!controller) return;
717
+ retrying.delete(id);
718
+ removeFiles((entry) => entry.id === id);
719
+ if (![...retrying.values()].includes(controller)) controller.abort(reason);
720
+ }
721
+ function detach() {
722
+ abortAll(uploadAbortReason("detach"));
723
+ }
724
+ function reset() {
725
+ removeFiles((entry) => !ACTIVE_PHASES.has(entry.phase));
726
+ if (snapshot.fileRejections.length > 0) commit({ fileRejections: [] });
727
+ }
728
+ function dispose() {
729
+ const cancelReason = uploadAbortReason("cancel");
730
+ const detachReason = uploadAbortReason("detach");
731
+ for (const controller of preparingCalls) controller.abort(cancelReason);
732
+ for (const task of tasks.values()) {
733
+ const resumable = task.config.options.uploadStore != null;
734
+ abortTask(task, resumable ? detachReason : cancelReason);
735
+ }
736
+ removeFiles(() => true);
737
+ }
738
+ return {
739
+ subscribe,
740
+ getSnapshot,
741
+ configure,
742
+ upload,
743
+ retry,
744
+ cancel,
745
+ detach,
746
+ reset,
747
+ dispose
748
+ };
795
749
  }
796
-
797
- // src/helpers/throttled-speed.ts
798
- function createThrottledSpeedUpdater(tracker, intervalMs = 500) {
799
- let lastSpeed;
800
- let lastUpdate = 0;
750
+ function createEntry(file) {
801
751
  return {
802
- reset() {
803
- tracker.reset();
804
- lastSpeed = void 0;
805
- lastUpdate = 0;
806
- },
807
- apply(progress) {
808
- const rawSpeed = tracker.update(progress.loaded);
809
- const now = Date.now();
810
- if (rawSpeed > 0 && now - lastUpdate >= intervalMs) {
811
- lastSpeed = rawSpeed;
812
- lastUpdate = now;
813
- }
814
- return lastSpeed ? { ...progress, speed: lastSpeed } : progress;
815
- }
752
+ id: crypto.randomUUID(),
753
+ file,
754
+ fileName: file.name,
755
+ fileSize: file.size,
756
+ contentType: file.type,
757
+ previewUrl: createImagePreviewUrl(file),
758
+ phase: "queued",
759
+ progress: transferProgress(0, file.size),
760
+ error: null,
761
+ result: null
816
762
  };
817
763
  }
818
-
819
- // src/helpers/load-route-catalog.ts
820
- var catalogByApi = /* @__PURE__ */ new WeakMap();
821
- function loadRouteCatalog(api) {
822
- const cached = catalogByApi.get(api);
823
- if (cached) return cached;
824
- const pending = api.catalog().catch((err) => {
825
- catalogByApi.delete(api);
826
- throw err;
827
- });
828
- catalogByApi.set(api, pending);
829
- return pending;
830
- }
831
- function mergeRouteUploadPolicy(catalog, route, overrides) {
832
- const upload = catalog?.routes[route]?.upload;
833
- const fromCatalog = upload?.enabled === true ? {
834
- accept: upload.fileTypes,
835
- maxFileSize: upload.maxFileSize,
836
- multipart: upload.multipart ? true : void 0,
837
- checksum: upload.checksum
838
- } : {};
764
+ function requeued(entry) {
839
765
  return {
840
- accept: overrides.accept ?? fromCatalog.accept,
841
- maxFileSize: overrides.maxFileSize ?? fromCatalog.maxFileSize,
842
- multipart: overrides.multipart ?? fromCatalog.multipart,
843
- checksum: overrides.checksum ?? fromCatalog.checksum
766
+ ...entry,
767
+ phase: "queued",
768
+ progress: transferProgress(0, entry.file.size),
769
+ error: null,
770
+ result: null
844
771
  };
845
772
  }
846
- async function resolveRouteUploadPolicy(api, route, overrides) {
847
- if (!api) return overrides;
848
- try {
849
- const catalog = await loadRouteCatalog(api);
850
- return mergeRouteUploadPolicy(catalog, route, overrides);
851
- } catch {
852
- return overrides;
773
+ function batchResult(outcomes, blocked = []) {
774
+ const result = {
775
+ uploaded: [],
776
+ failed: [],
777
+ blocked,
778
+ aborted: []
779
+ };
780
+ for (const outcome of outcomes) {
781
+ if (outcome.status === "success") {
782
+ result.uploaded.push({ file: outcome.file, result: outcome.result });
783
+ } else if (outcome.status === "error") {
784
+ result.failed.push({ file: outcome.file, error: outcome.error });
785
+ } else {
786
+ result.aborted.push(outcome.file);
787
+ }
853
788
  }
789
+ return result;
854
790
  }
855
-
856
- // src/helpers/speed-tracker.ts
857
- function createSpeedTracker(windowMs = 3e3) {
858
- const samples = [];
791
+ function mergeBatchResults(results) {
859
792
  return {
860
- /**
861
- * Record the latest cumulative `loaded` byte count.
862
- * Returns the current speed in bytes/second (0 until at least 2 samples exist).
863
- */
864
- update(loaded) {
865
- const now = Date.now();
866
- samples.push({ t: now, loaded });
867
- const cutoff = now - windowMs;
868
- while (samples.length > 1 && samples[0].t < cutoff) {
869
- samples.shift();
870
- }
871
- const oldest = samples[0];
872
- const newest = samples.at(-1);
873
- if (oldest == null || newest == null) return 0;
874
- const deltaMs = newest.t - oldest.t;
875
- const deltaBytes = newest.loaded - oldest.loaded;
876
- return deltaMs > 0 ? Math.round(deltaBytes / deltaMs * 1e3) : 0;
877
- },
878
- reset() {
879
- samples.length = 0;
880
- }
793
+ uploaded: results.flatMap((result) => result.uploaded),
794
+ failed: results.flatMap((result) => result.failed),
795
+ blocked: results.flatMap((result) => result.blocked),
796
+ aborted: results.flatMap((result) => result.aborted)
881
797
  };
882
798
  }
883
-
884
- // src/helpers/file-preview.ts
885
- function createImagePreviewUrl(file) {
886
- if (!file.type.startsWith("image/")) return null;
887
- return URL.createObjectURL(file);
888
- }
889
- function revokePreviewUrl(url) {
890
- if (!url) return;
891
- URL.revokeObjectURL(url);
892
- }
893
- function useLiveRef(value) {
894
- const ref = useRef(value);
895
- useLayoutEffect(() => {
896
- ref.current = value;
897
- });
898
- return ref;
899
- }
900
- function useImmerState(initialState) {
901
- const [state, setState] = useState(() => structuredClone(initialState));
902
- const patch = useCallback((recipe) => {
903
- setState(produce(recipe));
904
- }, []);
905
- const replace = useCallback((next) => {
906
- setState(structuredClone(next));
907
- }, []);
908
- return [state, patch, replace];
909
- }
910
-
911
- // src/hooks/use-file-upload.ts
912
- var INITIAL_PROGRESS = { loaded: 0, total: 0, percent: 0 };
913
- var INITIAL_STATE = {
914
- phase: "idle",
915
- files: [],
916
- progress: INITIAL_PROGRESS,
917
- error: null
918
- };
919
- var PENDING_PHASES = /* @__PURE__ */ new Set([
920
- "validating",
921
- "presigning",
922
- "uploading",
923
- "finalizing"
924
- ]);
925
- function generateId() {
926
- return crypto.randomUUID();
927
- }
928
- function normalizeFiles(files) {
929
- return Array.isArray(files) ? files : [files];
930
- }
931
- function useFileUpload(options) {
932
- const [state, patch, replace] = useImmerState(INITIAL_STATE);
933
- const contextApi = useContext(S3Context);
934
- const formatValidateFileError = useFormatValidateFileError();
935
- const optsRef = useLiveRef(options);
936
- const apiRef = useLiveRef(contextApi);
937
- const abortRef = useRef(null);
938
- const generationRef = useRef(0);
939
- const resettingRef = useRef(false);
940
- const detachingRef = useRef(false);
941
- const fileMapRef = useRef(/* @__PURE__ */ new Map());
942
- const activeUploadsRef = useRef(/* @__PURE__ */ new Map());
943
- const previewUrlsRef = useRef([]);
944
- const fileSpeedUpdatersRef = useRef(/* @__PURE__ */ new Map());
945
- const totalSpeedUpdaterRef = useRef(
946
- createThrottledSpeedUpdater(createSpeedTracker(), 1e3)
947
- );
948
- const revokeAllPreviews = useCallback(() => {
949
- for (const url of previewUrlsRef.current) revokePreviewUrl(url);
950
- previewUrlsRef.current = [];
951
- }, []);
952
- const clearToIdle = useCallback(() => {
953
- revokeAllPreviews();
954
- replace(INITIAL_STATE);
955
- }, [revokeAllPreviews, replace]);
956
- const abortMultipartSessions = useCallback(() => {
957
- const opts = optsRef.current;
958
- const api = opts.api ?? apiRef.current;
959
- const uploadStore = opts.uploadStore;
960
- for (const active of activeUploadsRef.current.values()) {
961
- if (uploadStore != null && uploadStore !== false) {
962
- void Promise.resolve(uploadStore.delete(active.resumeKey)).catch(
963
- () => {
964
- }
965
- );
966
- }
967
- if (api && active.uploadId && active.serverKey) {
968
- api.multipart.abort({
969
- route: opts.route,
970
- key: active.serverKey,
971
- uploadId: active.uploadId
972
- }).catch(() => {
973
- });
799
+ function summarize(files) {
800
+ let loaded = 0;
801
+ let total = 0;
802
+ let speed;
803
+ let active = false;
804
+ const failed = [];
805
+ for (const entry of files) {
806
+ loaded += entry.progress.loaded;
807
+ total += entry.progress.total;
808
+ if (ACTIVE_PHASES.has(entry.phase)) {
809
+ active = true;
810
+ if (entry.progress.speed !== void 0) {
811
+ speed = (speed ?? 0) + entry.progress.speed;
974
812
  }
975
813
  }
976
- activeUploadsRef.current.clear();
977
- }, [apiRef, optsRef]);
978
- useEffect(
979
- () => () => {
980
- generationRef.current += 1;
981
- abortRef.current?.abort();
982
- abortMultipartSessions();
983
- revokeAllPreviews();
984
- },
985
- [abortMultipartSessions, revokeAllPreviews]
986
- );
987
- const upload = useCallback(
988
- async (input) => {
989
- const files = normalizeFiles(input);
990
- const opts = optsRef.current;
991
- const api = opts.api ?? apiRef.current;
992
- if (!api)
993
- throw new Error(
994
- "[dimah-s3] No S3Api found. Pass `api` to useUpload or wrap with <S3Provider>."
995
- );
996
- const maxFiles = opts.maxFiles ?? DEFAULT_MAX_FILES;
997
- patch((draft) => {
998
- draft.phase = "validating";
999
- draft.error = null;
1000
- });
1001
- const policy = await resolveRouteUploadPolicy(api, opts.route, {
1002
- accept: opts.accept,
1003
- maxFileSize: opts.maxFileSize,
1004
- multipart: opts.multipart,
1005
- checksum: opts.checksum
1006
- });
1007
- if (maxFiles > 0 && files.length > maxFiles) {
1008
- const msg = `Too many files. Maximum is ${maxFiles}.`;
1009
- patch((draft) => {
1010
- draft.phase = "error";
1011
- draft.error = new APIError("BAD_REQUEST", { message: msg });
1012
- });
1013
- opts.onError?.(new Error(msg), "validating");
1014
- return;
1015
- }
1016
- for (const file of files) {
1017
- const validationError = validateFile(file, {
1018
- accept: policy.accept,
1019
- maxFileSize: policy.maxFileSize
1020
- });
1021
- if (validationError) {
1022
- const detail = formatValidateFileError(validationError);
1023
- const msg = `${file.name}: ${detail}`;
1024
- const error = new APIError("BAD_REQUEST", { message: msg });
1025
- revokeAllPreviews();
1026
- const previewUrl = createImagePreviewUrl(file);
1027
- if (previewUrl) previewUrlsRef.current = [previewUrl];
1028
- patch((draft) => {
1029
- draft.phase = "error";
1030
- draft.error = error;
1031
- draft.files = [
1032
- {
1033
- id: generateId(),
1034
- name: file.name,
1035
- size: file.size,
1036
- type: file.type,
1037
- previewUrl,
1038
- status: "error",
1039
- progress: { loaded: 0, total: file.size, percent: 0 },
1040
- error,
1041
- result: null
1042
- }
1043
- ];
1044
- });
1045
- opts.onError?.(new Error(msg), "validating");
1046
- return;
1047
- }
1048
- }
1049
- abortRef.current?.abort();
1050
- abortMultipartSessions();
1051
- const generation = ++generationRef.current;
1052
- const controller = new AbortController();
1053
- abortRef.current = controller;
1054
- const isCurrent = () => generation === generationRef.current;
1055
- if (opts.beforeUpload) {
1056
- const allowed = await opts.beforeUpload(files);
1057
- if (controller.signal.aborted) {
1058
- if (!isCurrent()) return;
1059
- abortRef.current = null;
1060
- if (detachingRef.current) detachingRef.current = false;
1061
- else if (resettingRef.current) resettingRef.current = false;
1062
- else opts.onCancel?.();
1063
- return;
1064
- }
1065
- if (!allowed) {
1066
- abortRef.current = null;
1067
- patch((draft) => {
1068
- draft.phase = "error";
1069
- draft.error = hookBlockedError(
1070
- "Upload blocked by beforeUpload hook"
1071
- );
1072
- });
1073
- opts.onError?.(new Error("blocked"), "validating");
1074
- return;
1075
- }
1076
- }
1077
- if (controller.signal.aborted) {
1078
- if (!isCurrent()) return;
1079
- abortRef.current = null;
1080
- if (detachingRef.current) detachingRef.current = false;
1081
- else if (resettingRef.current) resettingRef.current = false;
1082
- else opts.onCancel?.();
1083
- return;
1084
- }
1085
- revokeAllPreviews();
1086
- const nextPreviewUrls = [];
1087
- const items = [];
1088
- const fileStates = [];
1089
- const fileMap = /* @__PURE__ */ new Map();
1090
- for (const file of files) {
1091
- const id = generateId();
1092
- const previewUrl = createImagePreviewUrl(file);
1093
- if (previewUrl) nextPreviewUrls.push(previewUrl);
1094
- items.push({ id, file });
1095
- fileMap.set(id, file);
1096
- fileStates.push({
1097
- id,
1098
- name: file.name,
1099
- size: file.size,
1100
- type: file.type,
1101
- previewUrl,
1102
- status: "pending",
1103
- progress: { loaded: 0, total: file.size, percent: 0 },
1104
- error: null,
1105
- result: null
1106
- });
1107
- }
1108
- previewUrlsRef.current = nextPreviewUrls;
1109
- fileMapRef.current = fileMap;
1110
- activeUploadsRef.current = new Map(
1111
- items.map((item) => [
1112
- item.id,
1113
- {
1114
- resumeKey: multipartResumeKey(opts.route, item.file),
1115
- serverKey: ""
1116
- }
1117
- ])
1118
- );
1119
- const singleFile = items.length === 1;
1120
- patch((draft) => {
1121
- draft.phase = singleFile ? "presigning" : "uploading";
1122
- draft.files = fileStates;
1123
- draft.progress = {
1124
- loaded: 0,
1125
- total: files.reduce((s, f) => s + f.size, 0),
1126
- percent: 0
1127
- };
1128
- draft.error = null;
1129
- });
1130
- opts.onUploadStart?.(files);
1131
- fileSpeedUpdatersRef.current.clear();
1132
- for (const item of items) {
1133
- fileSpeedUpdatersRef.current.set(
1134
- item.id,
1135
- createThrottledSpeedUpdater(createSpeedTracker())
1136
- );
1137
- }
1138
- totalSpeedUpdaterRef.current.reset();
1139
- let errorPhase = singleFile ? "presigning" : "uploading";
1140
- try {
1141
- const results = await uploadFiles(
1142
- api,
1143
- items,
1144
- {
1145
- route: opts.route,
1146
- multipart: policy.multipart,
1147
- checksum: policy.checksum,
1148
- concurrentParts: opts.concurrentParts,
1149
- concurrentFiles: opts.concurrentFiles,
1150
- retry: opts.retry,
1151
- uploadStore: opts.uploadStore
1152
- },
1153
- {
1154
- onFileProgress: (id, progress) => {
1155
- if (!isCurrent()) return;
1156
- const updater = fileSpeedUpdatersRef.current.get(id);
1157
- const p = updater ? updater.apply(progress) : progress;
1158
- patch((draft) => {
1159
- const fileState = draft.files.find((f) => f.id === id);
1160
- if (fileState) {
1161
- fileState.status = "uploading";
1162
- fileState.progress = p;
1163
- }
1164
- });
1165
- const file = fileMap.get(id);
1166
- if (file) opts.onFileProgress?.(file, p);
1167
- },
1168
- onFilePhaseChange: (_id, phase) => {
1169
- if (!isCurrent()) return;
1170
- errorPhase = phase;
1171
- if (singleFile) {
1172
- patch((draft) => {
1173
- draft.phase = phase;
1174
- });
1175
- }
1176
- },
1177
- onPartUpload: (id, partNumber, totalParts) => {
1178
- const file = fileMap.get(id);
1179
- if (file) opts.onPartUpload?.(file, partNumber, totalParts);
1180
- },
1181
- onFileSuccess: (id, result) => {
1182
- if (!isCurrent()) return;
1183
- activeUploadsRef.current.delete(id);
1184
- patch((draft) => {
1185
- const fileState = draft.files.find((f) => f.id === id);
1186
- if (fileState) {
1187
- fileState.status = "success";
1188
- fileState.result = result;
1189
- fileState.progress = {
1190
- loaded: fileState.size,
1191
- total: fileState.size,
1192
- percent: 100
1193
- };
1194
- }
1195
- });
1196
- const file = fileMap.get(id);
1197
- if (file) opts.onFileSuccess?.(file, result);
1198
- },
1199
- onFileError: (id, error) => {
1200
- if (!isCurrent()) return;
1201
- patch((draft) => {
1202
- const fileState = draft.files.find((f) => f.id === id);
1203
- if (fileState) {
1204
- fileState.status = "error";
1205
- fileState.error = error;
1206
- }
1207
- });
1208
- const file = fileMap.get(id);
1209
- if (file) opts.onFileError?.(file, error);
1210
- },
1211
- onTotalProgress: (progress) => {
1212
- if (!isCurrent()) return;
1213
- const p = totalSpeedUpdaterRef.current.apply(progress);
1214
- patch((draft) => {
1215
- draft.progress = p;
1216
- });
1217
- opts.onProgress?.(p);
1218
- },
1219
- onMultipartInit: (id, uploadId, serverKey) => {
1220
- const active = activeUploadsRef.current.get(id);
1221
- if (active) {
1222
- active.uploadId = uploadId;
1223
- active.serverKey = serverKey;
1224
- }
1225
- const file = fileMap.get(id);
1226
- if (file) opts.onMultipartInit?.(file, uploadId);
1227
- }
1228
- },
1229
- controller.signal,
1230
- (file) => {
1231
- const perFile = opts.getUploadOptions?.(file);
1232
- if (!opts.uploadOptions) return perFile ?? {};
1233
- return { ...opts.uploadOptions, ...perFile };
1234
- }
1235
- );
1236
- if (!isCurrent()) return;
1237
- const hasErrors = results.some((r) => r.status === "error");
1238
- const successResults = results.flatMap(
1239
- (r) => r.result === null ? [] : [r.result]
1240
- );
1241
- patch((draft) => {
1242
- draft.phase = hasErrors ? "error" : "success";
1243
- draft.error = hasErrors ? new APIError("BAD_REQUEST", {
1244
- message: `${results.filter((r) => r.status === "error").length} file(s) failed`
1245
- }) : null;
1246
- if (!hasErrors) {
1247
- draft.progress = {
1248
- loaded: draft.progress.total,
1249
- total: draft.progress.total,
1250
- percent: 100
1251
- };
1252
- }
1253
- });
1254
- if (hasErrors) {
1255
- opts.onError?.(
1256
- new Error(
1257
- `${results.filter((r) => r.status === "error").length} file(s) failed`
1258
- ),
1259
- errorPhase
1260
- );
1261
- } else {
1262
- try {
1263
- await opts.onSuccess?.(successResults);
1264
- } catch (err) {
1265
- opts.onError?.(err, "success");
1266
- }
1267
- }
1268
- } catch (err) {
1269
- if (!isCurrent()) return;
1270
- if (isAbortError(err)) {
1271
- if (detachingRef.current) {
1272
- detachingRef.current = false;
1273
- return;
1274
- }
1275
- if (!resettingRef.current) opts.onCancel?.();
1276
- resettingRef.current = false;
1277
- clearToIdle();
1278
- return;
1279
- }
1280
- patch((draft) => {
1281
- draft.phase = "error";
1282
- draft.error = toHookError(err, "Upload failed");
1283
- });
1284
- opts.onError?.(err, errorPhase);
1285
- } finally {
1286
- if (isCurrent()) {
1287
- abortRef.current = null;
1288
- activeUploadsRef.current.clear();
1289
- }
1290
- }
1291
- },
1292
- [
1293
- abortMultipartSessions,
1294
- apiRef,
1295
- optsRef,
1296
- formatValidateFileError,
1297
- revokeAllPreviews,
1298
- clearToIdle,
1299
- patch
1300
- ]
1301
- );
1302
- const cancel = useCallback(() => {
1303
- const hadWork = abortRef.current != null || activeUploadsRef.current.size > 0;
1304
- generationRef.current += 1;
1305
- abortRef.current?.abort();
1306
- abortMultipartSessions();
1307
- abortRef.current = null;
1308
- if (hadWork) optsRef.current.onCancel?.();
1309
- clearToIdle();
1310
- }, [abortMultipartSessions, optsRef, clearToIdle]);
1311
- const detach = useCallback(() => {
1312
- if (activeUploadsRef.current.size === 0 && !abortRef.current) return;
1313
- detachingRef.current = true;
1314
- generationRef.current += 1;
1315
- abortRef.current?.abort();
1316
- abortRef.current = null;
1317
- activeUploadsRef.current.clear();
1318
- clearToIdle();
1319
- }, [clearToIdle]);
1320
- const reset = useCallback(() => {
1321
- resettingRef.current = true;
1322
- generationRef.current += 1;
1323
- abortRef.current?.abort();
1324
- abortRef.current = null;
1325
- activeUploadsRef.current.clear();
1326
- clearToIdle();
1327
- }, [clearToIdle]);
814
+ if (entry.error) failed.push(entry.error);
815
+ }
816
+ const progress = transferProgress(loaded, total);
817
+ const phase = files.length === 0 ? "idle" : failed.length > 0 ? "error" : "success";
818
+ const error = failed.length === 0 ? null : failed.length === 1 ? failed[0] : s3Error("PARTIAL_FAILURE", {
819
+ failed: failed.length,
820
+ total: files.length
821
+ });
1328
822
  return {
1329
- ...state,
1330
- file: state.files[0] ?? null,
1331
- isUploading: state.phase === "uploading",
1332
- isPending: PENDING_PHASES.has(state.phase),
1333
- upload,
1334
- cancel,
1335
- detach,
1336
- reset
823
+ active,
824
+ phase,
825
+ progress: speed === void 0 ? progress : { ...progress, speed },
826
+ error
1337
827
  };
1338
828
  }
829
+ var DRAG_HANDLERS = [
830
+ "onDragEnter",
831
+ "onDragOver",
832
+ "onDragLeave",
833
+ "onDrop"
834
+ ];
835
+ var claimedEvents = /* @__PURE__ */ new WeakSet();
836
+ var enteredTargets = /* @__PURE__ */ new WeakMap();
837
+ var acceptAll = () => null;
1339
838
  function useFileIntake(options) {
1340
- const optsRef = useLiveRef(options);
1341
- const onDropAccepted = useCallback(
1342
- (files) => {
1343
- optsRef.current.onAccept(files);
1344
- },
1345
- [optsRef]
1346
- );
1347
- const onDropRejected = useCallback(
1348
- (rejections) => {
1349
- optsRef.current.onReject?.(rejections);
839
+ const { accept, maxFiles } = options;
840
+ const onFilesRef = useLiveRef(options.onFiles);
841
+ const eventCalls = useRef(/* @__PURE__ */ new WeakMap());
842
+ const pickerCall = useRef(void 0);
843
+ const onDrop = useCallback(
844
+ (accepted, rejections, event) => {
845
+ const native = Array.isArray(event) ? null : nativeEventOf(event);
846
+ const call = native !== null && eventCalls.current.has(native) ? eventCalls.current.get(native) : pickerCall.current;
847
+ const files = [...accepted, ...rejections.map(({ file }) => file)];
848
+ onFilesRef.current(files, resolveCall(call));
1350
849
  },
1351
- [optsRef]
850
+ [onFilesRef]
1352
851
  );
1353
- const validator = useCallback(
1354
- (file) => {
1355
- const error = validateFile(file, { accept: optsRef.current.accept });
1356
- if (error?.code !== "FILE_TYPE_NOT_ALLOWED") return null;
1357
- return { code: ErrorCode.FileInvalidType, message: error.message };
1358
- },
1359
- [optsRef]
1360
- );
1361
- const htmlAccept = options.accept?.map((token) => token.trim()).filter(Boolean).join(",") || void 0;
1362
- const {
1363
- getRootProps,
1364
- getInputProps: getDropzoneInputProps,
1365
- inputRef,
1366
- open: openDropzone,
1367
- isDragActive,
1368
- isDragAccept,
1369
- isDragReject,
1370
- fileRejections
1371
- } = useDropzone({
1372
- maxSize: options.maxFileSize,
1373
- maxFiles: options.maxFiles,
1374
- multiple: options.multiple ?? false,
852
+ const mimeAccept = toMimeAccept(accept);
853
+ const dropzone = useDropzone({
854
+ // During a drag the browser exposes MIME types but no file names, so
855
+ // only a MIME-only list can be checked. Otherwise the validator makes
856
+ // the drag verdict unknown instead of a false reject.
857
+ accept: mimeAccept,
858
+ validator: accept?.length && !mimeAccept ? acceptAll : void 0,
859
+ maxFiles,
860
+ multiple: maxFiles > 1,
1375
861
  disabled: options.disabled,
1376
862
  noClick: options.noClick,
1377
863
  noDrag: options.noDrag,
1378
864
  noKeyboard: options.noKeyboard,
1379
- validator,
1380
- onDropAccepted,
1381
- onDropRejected
865
+ onDrop
1382
866
  });
867
+ const {
868
+ getRootProps: getDropzoneRootProps,
869
+ getInputProps: getDropzoneInputProps,
870
+ inputRef,
871
+ open: openDropzone
872
+ } = dropzone;
873
+ const htmlAccept = accept?.map((token) => token.trim()).filter(Boolean).join(",") || void 0;
874
+ const getRootProps = useCallback(
875
+ (props, call) => {
876
+ const {
877
+ onClick,
878
+ onKeyDown,
879
+ onPaste,
880
+ onDragEnter,
881
+ onDragOver,
882
+ onDragLeave,
883
+ onDrop: onRootDrop,
884
+ ...rest
885
+ } = props ?? {};
886
+ const root = getDropzoneRootProps({
887
+ ...rest,
888
+ onClick: (event) => {
889
+ onClick?.(event);
890
+ pickerCall.current = call;
891
+ },
892
+ onKeyDown: (event) => {
893
+ onKeyDown?.(event);
894
+ pickerCall.current = call;
895
+ }
896
+ });
897
+ const dropzonePaste = root.onPaste;
898
+ return {
899
+ ...root,
900
+ ...dragHandlers(
901
+ { onDragEnter, onDragOver, onDragLeave, onDrop: onRootDrop },
902
+ root,
903
+ (event) => eventCalls.current.set(event.nativeEvent, call),
904
+ false
905
+ ),
906
+ // A paste whose default the consumer's handler prevented is theirs.
907
+ onPaste: (event) => {
908
+ onPaste?.(event);
909
+ if (!dropzonePaste || event.defaultPrevented) return;
910
+ if (!claim(event.nativeEvent)) return;
911
+ eventCalls.current.set(event.nativeEvent, call);
912
+ dropzonePaste(event);
913
+ }
914
+ };
915
+ },
916
+ [getDropzoneRootProps]
917
+ );
918
+ const getDropTargetProps = useCallback(
919
+ (props, call) => ({
920
+ ...props,
921
+ // Only the drag handlers are used: no ref, role, tabIndex or click.
922
+ ...dragHandlers(
923
+ props ?? {},
924
+ getDropzoneRootProps(),
925
+ (event) => eventCalls.current.set(event.nativeEvent, call),
926
+ true
927
+ )
928
+ }),
929
+ [getDropzoneRootProps]
930
+ );
1383
931
  const inputsRef = useRef(/* @__PURE__ */ new Set());
1384
932
  const attachInput = useCallback(
1385
933
  (node) => {
@@ -1399,1068 +947,1776 @@ function useFileIntake(options) {
1399
947
  }),
1400
948
  [attachInput, getDropzoneInputProps, htmlAccept]
1401
949
  );
1402
- const open = useCallback(() => {
1403
- const inputs = inputsRef.current;
1404
- for (const node of inputs) {
1405
- if (!node.isConnected) inputs.delete(node);
1406
- }
1407
- const ref = inputRef;
1408
- if (!ref.current?.isConnected) ref.current = [...inputs].at(-1) ?? null;
1409
- openDropzone();
1410
- }, [inputRef, openDropzone]);
950
+ const { disabled } = options;
951
+ const open = useCallback(
952
+ (call) => {
953
+ const openPicker = openDropzone;
954
+ if (disabled || !openPicker) return;
955
+ pickerCall.current = call;
956
+ const inputs = inputsRef.current;
957
+ for (const node of inputs) {
958
+ if (!node.isConnected) inputs.delete(node);
959
+ }
960
+ const ref = inputRef;
961
+ if (!ref.current?.isConnected) ref.current = [...inputs].at(-1) ?? null;
962
+ openPicker();
963
+ },
964
+ [disabled, inputRef, openDropzone]
965
+ );
1411
966
  return {
1412
967
  getRootProps,
968
+ getDropTargetProps,
1413
969
  getInputProps,
1414
970
  open,
1415
- isDragActive,
1416
- isDragAccept,
1417
- isDragReject,
1418
- fileRejections
971
+ isDragActive: dropzone.isDragActive,
972
+ isDragAccept: dropzone.isDragAccept,
973
+ isDragReject: dropzone.isDragReject
1419
974
  };
1420
975
  }
1421
- var warnedCatalogKeys = /* @__PURE__ */ new Set();
1422
- function toError(cause) {
1423
- return cause instanceof Error ? cause : new Error(String(cause), { cause });
1424
- }
1425
- function isDevelopment() {
1426
- const env = globalThis.process?.env?.NODE_ENV;
1427
- return env === "development";
1428
- }
1429
- function warnCatalogFailure(route, hasExplicitConstraints2, cause) {
1430
- if (!isDevelopment()) return;
1431
- if (hasExplicitConstraints2) return;
1432
- const key = String(route);
1433
- if (warnedCatalogKeys.has(key)) return;
1434
- warnedCatalogKeys.add(key);
1435
- console.warn(
1436
- `[@dimah-s3/react] Route catalog failed for "${key}". Pass accept/maxFileSize on useUpload, or check GET /routes. Client-side constraints will not come from the server.`,
1437
- cause
1438
- );
976
+ function dragHandlers(user, dropzone, onClaimDrop, trackTarget) {
977
+ const handlers = {};
978
+ for (const name of DRAG_HANDLERS) {
979
+ const own = user[name];
980
+ const dropzoneHandler = dropzone[name] ?? null;
981
+ handlers[name] = dropzoneHandler ? (event) => {
982
+ own?.(event);
983
+ if (!claim(event.nativeEvent)) return;
984
+ if (trackTarget) trackDragTarget(name, event);
985
+ if (name === "onDrop") onClaimDrop(event);
986
+ dropzoneHandler(event);
987
+ } : own;
988
+ }
989
+ return handlers;
990
+ }
991
+ function claim(event) {
992
+ if (claimedEvents.has(event)) return false;
993
+ claimedEvents.add(event);
994
+ return true;
995
+ }
996
+ function trackDragTarget(name, event) {
997
+ if (!hasFiles(event)) return;
998
+ const element = event.currentTarget;
999
+ const entered = enteredTargets.get(element) ?? /* @__PURE__ */ new Set();
1000
+ if (name === "onDragEnter") entered.add(event.target);
1001
+ if (name === "onDragLeave") entered.delete(event.target);
1002
+ if (name === "onDrop") entered.clear();
1003
+ if (entered.size > 0) {
1004
+ enteredTargets.set(element, entered);
1005
+ element.setAttribute("data-drag-active", "true");
1006
+ } else {
1007
+ enteredTargets.delete(element);
1008
+ element.removeAttribute("data-drag-active");
1009
+ }
1010
+ }
1011
+ function hasFiles({ dataTransfer }) {
1012
+ return Array.from(dataTransfer.types).includes("Files") || Array.from(dataTransfer.items).some((item) => item.kind === "file");
1013
+ }
1014
+ function nativeEventOf(event) {
1015
+ return "nativeEvent" in event ? event.nativeEvent : event;
1016
+ }
1017
+ function resolveCall(call) {
1018
+ return typeof call === "function" ? call() : call;
1439
1019
  }
1440
- function hasExplicitConstraints(options) {
1441
- return options.accept != null || options.maxFileSize != null;
1020
+ function toMimeAccept(accept) {
1021
+ const tokens = accept?.map((token) => token.trim()).filter(Boolean);
1022
+ if (!tokens?.length || tokens.some((token) => !token.includes("/"))) {
1023
+ return void 0;
1024
+ }
1025
+ return Object.fromEntries(tokens.map((token) => [token, []]));
1442
1026
  }
1443
1027
  function useRouteUploadPolicy(options) {
1028
+ return useRouteUploadPolicyState(options)[0];
1029
+ }
1030
+ function useRouteUploadPolicyState(options) {
1444
1031
  const contextApi = useContext(S3Context);
1445
- const api = options.api ?? contextApi;
1446
- const optsRef = useLiveRef(options);
1447
- const [snapshot, setSnapshot] = useState(null);
1448
- const snapshotMatches = snapshot !== null && snapshot.api === api && snapshot.route === options.route;
1449
- const catalogPolicy = snapshotMatches ? snapshot.policy : {};
1450
- const catalogStatus = !api ? "idle" : snapshotMatches ? snapshot.status : "loading";
1451
- const catalogError = snapshotMatches ? snapshot.error : null;
1032
+ const api = requireApi(options.api ?? contextApi, "useRouteUploadPolicy");
1033
+ const [attempt, setAttempt] = useState(0);
1034
+ const [state, setState] = useState(null);
1452
1035
  useEffect(() => {
1453
- if (!api) return;
1454
- let cancelled = false;
1455
- void loadRouteCatalog(api).then((catalog) => {
1456
- if (cancelled) return;
1457
- setSnapshot({
1458
- api,
1459
- route: options.route,
1460
- policy: mergeRouteUploadPolicy(catalog, options.route, {}),
1461
- status: "ready",
1462
- error: null
1463
- });
1464
- }).catch((cause) => {
1465
- if (cancelled) return;
1466
- setSnapshot({
1467
- api,
1468
- route: options.route,
1469
- policy: {},
1470
- status: "error",
1471
- error: toError(cause)
1472
- });
1473
- warnCatalogFailure(
1474
- optsRef.current.route,
1475
- hasExplicitConstraints(optsRef.current),
1476
- cause
1477
- );
1478
- });
1036
+ let active = true;
1037
+ loadRouteCatalog(api).then(
1038
+ (catalog) => {
1039
+ if (active) setState({ api, attempt, catalog, error: null });
1040
+ },
1041
+ (error) => {
1042
+ if (active) {
1043
+ setState({
1044
+ api,
1045
+ attempt,
1046
+ catalog: null,
1047
+ error: toClientError(error)
1048
+ });
1049
+ }
1050
+ }
1051
+ );
1479
1052
  return () => {
1480
- cancelled = true;
1053
+ active = false;
1481
1054
  };
1482
- }, [api, options.route, optsRef]);
1483
- return {
1484
- ...mergeRouteUploadPolicy(null, options.route, {
1485
- accept: options.accept ?? catalogPolicy.accept,
1486
- maxFileSize: options.maxFileSize ?? catalogPolicy.maxFileSize,
1487
- multipart: options.multipart ?? catalogPolicy.multipart,
1488
- checksum: options.checksum ?? catalogPolicy.checksum
1489
- }),
1490
- catalogStatus,
1491
- catalogError
1492
- };
1055
+ }, [api, attempt]);
1056
+ const reload = useCallback(() => {
1057
+ setAttempt((current) => current + 1);
1058
+ }, []);
1059
+ const settled = state !== null && state.api === api && state.attempt === attempt ? state : null;
1060
+ const policy = mergeRouteUploadPolicy(
1061
+ resolveRouteUploadPolicy(settled?.catalog, options.route),
1062
+ {
1063
+ accept: options.accept,
1064
+ maxFileSize: options.maxFileSize,
1065
+ multipart: options.multipart
1066
+ }
1067
+ );
1068
+ const status = settled === null ? "loading" : settled.error ? "error" : "ready";
1069
+ return [{ ...policy, status, error: settled?.error ?? null }, reload];
1493
1070
  }
1494
1071
 
1495
- // src/hooks/use-upload.ts
1496
- function toFileArray(files) {
1497
- if (files == null) return [];
1498
- if (files instanceof File) return [files];
1499
- return Array.from(files);
1500
- }
1072
+ // src/hooks/use-upload.ts
1501
1073
  function useUpload(options) {
1502
- const { disabled, noDrag, noClick, noKeyboard, onFileReject, ...uploadOpts } = options;
1074
+ const instanceId = useId();
1075
+ const contextApi = useContext(S3Context);
1076
+ const api = requireApi(options.api ?? contextApi, "useUpload");
1503
1077
  const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
1504
- const resumable = options.uploadStore != null && options.uploadStore !== false;
1505
- const catalogPolicy = useRouteUploadPolicy({
1506
- api: options.api,
1078
+ const [routePolicy, reloadCatalog] = useRouteUploadPolicyState({
1079
+ api,
1507
1080
  route: options.route,
1508
1081
  accept: options.accept,
1509
1082
  maxFileSize: options.maxFileSize,
1510
- multipart: options.multipart,
1511
- checksum: options.checksum
1083
+ multipart: options.multipart
1512
1084
  });
1513
- const engine = useFileUpload(uploadOpts);
1514
- const handleFiles = (files) => {
1515
- const list = toFileArray(files);
1516
- if (list.length === 0) return Promise.resolve();
1517
- return engine.upload(list);
1518
- };
1085
+ const engine = useFileUpload(options);
1086
+ const { upload, retry: retryFiles } = engine;
1087
+ const catalogStatusRef = useLiveRef(routePolicy.status);
1088
+ const handleFiles = useCallback(
1089
+ (files, call) => {
1090
+ if (catalogStatusRef.current === "error") reloadCatalog();
1091
+ return upload(toFileArray(files), call);
1092
+ },
1093
+ [catalogStatusRef, reloadCatalog, upload]
1094
+ );
1095
+ const retry = useCallback(
1096
+ (id) => {
1097
+ if (catalogStatusRef.current === "error") reloadCatalog();
1098
+ return retryFiles(id);
1099
+ },
1100
+ [catalogStatusRef, reloadCatalog, retryFiles]
1101
+ );
1519
1102
  const intake = useFileIntake({
1520
- accept: catalogPolicy.accept,
1521
- maxFileSize: catalogPolicy.maxFileSize,
1103
+ accept: routePolicy.accept,
1522
1104
  maxFiles,
1523
- multiple: maxFiles > 1,
1524
- disabled: Boolean(disabled) || engine.isPending,
1525
- noDrag,
1526
- noClick,
1527
- noKeyboard,
1528
- onAccept: (files) => {
1529
- void handleFiles(files);
1530
- },
1531
- onReject: onFileReject
1105
+ disabled: options.disabled,
1106
+ noDrag: options.noDrag,
1107
+ noClick: options.noClick,
1108
+ noKeyboard: options.noKeyboard,
1109
+ onFiles: (files, call) => {
1110
+ void handleFiles(files, call);
1111
+ }
1532
1112
  });
1533
1113
  return {
1114
+ instanceId,
1534
1115
  files: engine.files,
1535
1116
  file: engine.file,
1536
1117
  phase: engine.phase,
1537
1118
  progress: engine.progress,
1538
1119
  error: engine.error,
1539
- isUploading: engine.isUploading,
1540
1120
  isPending: engine.isPending,
1541
- policy: { ...catalogPolicy, maxFiles },
1542
- resumable,
1121
+ policy: { ...routePolicy, maxFiles },
1122
+ resumable: options.uploadStore != null,
1123
+ disabled: options.disabled ?? false,
1543
1124
  handleFiles,
1544
1125
  open: intake.open,
1126
+ retry,
1545
1127
  cancel: engine.cancel,
1546
1128
  detach: engine.detach,
1547
1129
  reset: engine.reset,
1548
1130
  getRootProps: intake.getRootProps,
1131
+ getDropTargetProps: intake.getDropTargetProps,
1549
1132
  getInputProps: intake.getInputProps,
1550
1133
  isDragActive: intake.isDragActive,
1551
1134
  isDragAccept: intake.isDragAccept,
1552
1135
  isDragReject: intake.isDragReject,
1553
- fileRejections: intake.fileRejections
1136
+ fileRejections: engine.fileRejections
1554
1137
  };
1555
1138
  }
1556
- function isFetchDownload(download) {
1557
- return download.mode === "fetch";
1558
- }
1559
- var INITIAL_PROGRESS2 = { loaded: 0, total: 0, percent: 0 };
1560
- var INITIAL_STATE2 = {
1561
- phase: "idle",
1562
- objectKey: null,
1563
- error: null,
1564
- url: null,
1565
- expiresIn: null,
1566
- progress: INITIAL_PROGRESS2,
1567
- fileName: null,
1568
- fileSize: null
1569
- };
1570
- function idleKeepingKey(objectKey) {
1571
- return { ...INITIAL_STATE2, objectKey };
1139
+ function toFileArray(files) {
1140
+ if (files == null) return [];
1141
+ if (files instanceof File) return [files];
1142
+ return Array.from(files);
1143
+ }
1144
+ var REVOKE_DELAY_MS = 3e4;
1145
+ function startBrowserDownload(url) {
1146
+ clickLink(url);
1572
1147
  }
1573
- function missingApiMessage(hook) {
1574
- return `[dimah-s3] No S3Api found. Pass \`api\` to ${hook} or wrap with <S3Provider>.`;
1148
+ function saveBlob(blob, fileName) {
1149
+ const url = URL.createObjectURL(blob);
1150
+ clickLink(url, fileName);
1151
+ setTimeout(() => URL.revokeObjectURL(url), REVOKE_DELAY_MS);
1152
+ }
1153
+ async function readResponseBlob(response, signal, onChunk) {
1154
+ const readBytes = async (read) => {
1155
+ try {
1156
+ return await read();
1157
+ } catch (error) {
1158
+ signal.throwIfAborted();
1159
+ throw s3Error("NETWORK_ERROR", void 0, { cause: error });
1160
+ }
1161
+ };
1162
+ if (!response.body) {
1163
+ const blob = await readBytes(() => response.blob());
1164
+ onChunk?.(blob.size);
1165
+ return blob;
1166
+ }
1167
+ const type = response.headers.get("content-type") ?? "";
1168
+ const reader = response.body.getReader();
1169
+ const chunks = [];
1170
+ let loaded = 0;
1171
+ for (; ; ) {
1172
+ const { done, value } = await readBytes(() => reader.read());
1173
+ if (done) break;
1174
+ chunks.push(value);
1175
+ loaded += value.byteLength;
1176
+ onChunk?.(loaded);
1177
+ }
1178
+ return new Blob(chunks, { type });
1179
+ }
1180
+ function clickLink(href, fileName) {
1181
+ const link = document.createElement("a");
1182
+ link.href = href;
1183
+ if (fileName !== void 0) link.download = fileName;
1184
+ link.style.display = "none";
1185
+ document.body.append(link);
1186
+ try {
1187
+ link.click();
1188
+ } finally {
1189
+ link.remove();
1190
+ }
1575
1191
  }
1192
+
1193
+ // src/hooks/use-download.ts
1194
+ var PRESIGN_MANY_CONCURRENCY = 4;
1576
1195
  function useDownload(options) {
1577
- const [state, patch, replace] = useImmerState(INITIAL_STATE2);
1196
+ const instanceId = useId();
1578
1197
  const contextApi = useContext(S3Context);
1579
- const optsRef = useLiveRef(options);
1198
+ const optionsRef = useLiveRef(options);
1580
1199
  const apiRef = useLiveRef(contextApi);
1581
- const abortRef = useRef(null);
1582
- const generationRef = useRef(0);
1583
- const downloadKeyRef = useRef(null);
1584
- const resettingRef = useRef(false);
1585
- const speedUpdaterRef = useRef(
1586
- createThrottledSpeedUpdater(createSpeedTracker())
1200
+ const { store, operations, pendingKeys, get } = useOperationStore();
1201
+ const resolveApi = useCallback(
1202
+ () => requireApi(optionsRef.current.api ?? apiRef.current, "useDownload"),
1203
+ [apiRef, optionsRef]
1587
1204
  );
1588
- const requestDownloadUrl = useCallback(
1589
- async (key, downloadName, generation, expiresIn) => {
1590
- const opts = optsRef.current;
1591
- const api = opts.api ?? apiRef.current;
1592
- if (!api) throw new Error(missingApiMessage("useDownload"));
1593
- patch((draft) => {
1594
- draft.phase = "presigning";
1595
- draft.objectKey = key;
1596
- draft.error = null;
1597
- draft.url = null;
1598
- draft.expiresIn = null;
1599
- });
1600
- try {
1601
- const result = await api.download({
1602
- route: opts.route,
1205
+ const sign = useCallback(
1206
+ (api, key, request, signal) => {
1207
+ const { route, disposition } = optionsRef.current;
1208
+ return api.download(
1209
+ {
1210
+ route,
1603
1211
  key,
1604
- fileName: downloadName,
1605
- ...opts.disposition ? { disposition: opts.disposition } : {},
1606
- ...expiresIn != null ? { expiresIn } : {}
1607
- });
1608
- if (generation !== generationRef.current) {
1609
- return { url: result.url, expiresIn: result.expiresIn };
1610
- }
1611
- patch((draft) => {
1612
- draft.phase = "idle";
1613
- draft.error = null;
1614
- draft.url = result.url;
1615
- draft.expiresIn = result.expiresIn;
1616
- });
1617
- return { url: result.url, expiresIn: result.expiresIn };
1618
- } catch (err) {
1619
- if (generation !== generationRef.current) return null;
1620
- patch((draft) => {
1621
- draft.phase = "error";
1622
- draft.error = toHookError(err, "Download failed");
1623
- draft.url = null;
1624
- draft.expiresIn = null;
1625
- });
1626
- opts.onError?.(key, err);
1627
- return null;
1628
- }
1212
+ name: request.fileName,
1213
+ disposition,
1214
+ expiresIn: request.expiresIn
1215
+ },
1216
+ { signal }
1217
+ );
1629
1218
  },
1630
- [apiRef, optsRef, patch]
1219
+ [optionsRef]
1631
1220
  );
1632
- const presign = useCallback(
1633
- async (key, downloadName, expiresIn) => {
1634
- const generation = ++generationRef.current;
1635
- return requestDownloadUrl(key, downloadName, generation, expiresIn);
1221
+ const presign2 = useCallback(
1222
+ async (key, request = {}) => {
1223
+ const api = resolveApi();
1224
+ const before = await runBeforeCallback(
1225
+ "beforeDownload",
1226
+ optionsRef.current.beforeDownload,
1227
+ key
1228
+ );
1229
+ if (before.status !== "allowed") return { key, ...before };
1230
+ try {
1231
+ return { status: "success", key, data: await sign(api, key, request) };
1232
+ } catch (error) {
1233
+ return { status: "error", key, error: toClientError(error) };
1234
+ }
1636
1235
  },
1637
- [requestDownloadUrl]
1236
+ [optionsRef, resolveApi, sign]
1638
1237
  );
1639
1238
  const presignMany = useCallback(
1640
1239
  async (files) => {
1641
- const signed = [];
1642
- const failed = [];
1643
- if (files.length === 0) return { signed, failed };
1644
- const opts = optsRef.current;
1645
- const api = opts.api ?? apiRef.current;
1646
- if (!api) throw new Error(missingApiMessage("useDownload"));
1647
- for (const file of files) {
1648
- if (opts.beforeDownload) {
1649
- const allowed = await opts.beforeDownload(file.key);
1650
- if (!allowed) {
1651
- failed.push(file.key);
1652
- opts.onError?.(file.key, new Error("blocked"));
1653
- continue;
1654
- }
1655
- }
1656
- try {
1657
- const result = await api.download({
1658
- route: opts.route,
1659
- key: file.key,
1660
- fileName: file.fileName,
1661
- ...opts.disposition ? { disposition: opts.disposition } : {},
1662
- ...file.expiresIn != null ? { expiresIn: file.expiresIn } : {}
1663
- });
1664
- signed.push({
1665
- key: file.key,
1666
- url: result.url,
1667
- expiresIn: result.expiresIn
1668
- });
1669
- } catch (err) {
1670
- failed.push(file.key);
1671
- opts.onError?.(file.key, err);
1672
- }
1673
- }
1674
- return { signed, failed };
1675
- },
1676
- [apiRef, optsRef]
1677
- );
1678
- const downloadNavigate = useCallback(
1679
- async (key, downloadName) => {
1680
- const opts = optsRef.current;
1681
- const generation = ++generationRef.current;
1682
- if (opts.beforeDownload) {
1683
- const allowed = await opts.beforeDownload(key);
1684
- if (generation !== generationRef.current) return;
1685
- if (!allowed) {
1686
- patch((draft) => {
1687
- draft.phase = "error";
1688
- draft.objectKey = key;
1689
- draft.error = hookBlockedError(
1690
- "Download blocked by beforeDownload hook"
1691
- );
1692
- draft.url = null;
1693
- draft.expiresIn = null;
1694
- });
1695
- opts.onError?.(key, new Error("blocked"));
1696
- return;
1240
+ const outcomes = await mapWithConcurrency(
1241
+ files,
1242
+ PRESIGN_MANY_CONCURRENCY,
1243
+ ({ key, ...request }) => presign2(key, request)
1244
+ );
1245
+ const result = { signed: [], failed: [], blocked: [] };
1246
+ for (const outcome of outcomes) {
1247
+ if (outcome.status === "success") {
1248
+ result.signed.push(outcome.data);
1249
+ } else if (outcome.status === "error") {
1250
+ result.failed.push({ key: outcome.key, error: outcome.error });
1251
+ } else {
1252
+ result.blocked.push(outcome.key);
1697
1253
  }
1698
1254
  }
1699
- const result = await requestDownloadUrl(key, downloadName, generation);
1700
- if (!result || generation !== generationRef.current) return;
1701
- window.location.href = result.url;
1702
- opts.onInitiated?.(key);
1255
+ return result;
1703
1256
  },
1704
- [optsRef, requestDownloadUrl, patch]
1257
+ [presign2]
1705
1258
  );
1706
- const downloadFetch = useCallback(
1707
- async (key, downloadName) => {
1708
- const fallback = key.split("/").pop() ?? key;
1709
- const opts = optsRef.current;
1710
- const api = opts.api ?? apiRef.current;
1711
- if (!api) throw new Error(missingApiMessage("useDownload"));
1712
- downloadKeyRef.current = key;
1713
- if (opts.beforeDownload) {
1714
- const allowed = await opts.beforeDownload(key);
1715
- if (!allowed) {
1716
- patch((draft) => {
1717
- draft.phase = "error";
1718
- draft.objectKey = key;
1719
- draft.error = hookBlockedError(
1720
- "Download blocked by beforeDownload hook"
1721
- );
1722
- });
1723
- opts.onError?.(key, new Error("blocked"), "presigning");
1724
- return;
1725
- }
1726
- }
1727
- abortRef.current?.abort();
1728
- const generation = ++generationRef.current;
1729
- const isCurrent = () => generation === generationRef.current;
1730
- patch((draft) => {
1731
- draft.phase = "presigning";
1732
- draft.objectKey = key;
1733
- draft.progress = { ...INITIAL_PROGRESS2 };
1734
- draft.error = null;
1735
- draft.fileName = downloadName ?? null;
1736
- draft.fileSize = null;
1737
- });
1259
+ const navigate = useCallback(
1260
+ async (call, fileName) => {
1261
+ const { key, signal } = call;
1262
+ const api = resolveApi();
1263
+ const base = { fileName: fileName ?? null, error: null, result: null };
1738
1264
  try {
1739
- const { url } = await api.download({
1740
- route: opts.route,
1741
- key,
1742
- fileName: downloadName,
1743
- ...opts.disposition ? { disposition: opts.disposition } : {}
1744
- });
1745
- if (!isCurrent()) return;
1746
- patch((draft) => {
1747
- draft.phase = "downloading";
1748
- });
1749
- opts.onDownloadStart?.(key);
1750
- speedUpdaterRef.current.reset();
1751
- const controller = new AbortController();
1752
- abortRef.current = controller;
1753
- const res = await fetch(url, { signal: controller.signal });
1754
- if (!res.ok) {
1755
- throw new Error(
1756
- res.status === 404 ? "File not found" : `Download failed (${res.status})`
1757
- );
1758
- }
1759
- const contentLength = Number(res.headers.get("content-length") || 0);
1760
- const name = downloadName ?? parseFileName(res.headers.get("content-disposition")) ?? fallback;
1761
- patch((draft) => {
1762
- draft.fileName = name;
1763
- draft.fileSize = contentLength || null;
1764
- });
1765
- const reader = res.body?.getReader();
1766
- if (!reader) throw new Error("ReadableStream not supported");
1767
- const chunks = [];
1768
- let loaded = 0;
1769
- while (true) {
1770
- const { done, value } = await reader.read();
1771
- if (done) break;
1772
- chunks.push(value);
1773
- loaded += value.byteLength;
1774
- const percent = contentLength > 0 ? Math.round(loaded / contentLength * 100) : 0;
1775
- const progress = speedUpdaterRef.current.apply({
1776
- loaded,
1777
- total: contentLength,
1778
- percent
1779
- });
1780
- if (!isCurrent()) return;
1781
- patch((draft) => {
1782
- draft.progress = progress;
1783
- });
1784
- opts.onProgress?.(key, progress);
1785
- }
1786
- const blob = new Blob(chunks);
1787
- const blobUrl = URL.createObjectURL(blob);
1788
- const anchor = document.createElement("a");
1789
- anchor.href = blobUrl;
1790
- anchor.download = name ?? fallback;
1791
- anchor.click();
1792
- URL.revokeObjectURL(blobUrl);
1793
- if (!isCurrent()) return;
1794
- patch((draft) => {
1795
- draft.phase = "success";
1796
- draft.fileSize = blob.size;
1797
- draft.progress = {
1798
- loaded: blob.size,
1799
- total: blob.size,
1800
- percent: 100
1801
- };
1802
- });
1803
- try {
1804
- await opts.onSuccess?.(key, name ?? fallback);
1805
- } catch (err) {
1806
- opts.onError?.(key, err, "success");
1265
+ const before = await abortable(
1266
+ runBeforeCallback(
1267
+ "beforeDownload",
1268
+ optionsRef.current.beforeDownload,
1269
+ key
1270
+ ),
1271
+ signal
1272
+ );
1273
+ if (before.status === "blocked") return { status: "blocked", key };
1274
+ if (before.status === "error") {
1275
+ call.publish({ ...base, phase: "error", error: before.error });
1276
+ return { status: "error", key, error: before.error };
1807
1277
  }
1808
- } catch (err) {
1809
- if (!isCurrent()) return;
1810
- if (isAbortError(err)) {
1811
- if (!resettingRef.current) opts.onCancel?.(key);
1812
- resettingRef.current = false;
1813
- replace(idleKeepingKey(key));
1814
- return;
1278
+ call.publish({ ...base, phase: "presigning" });
1279
+ const data = await sign(api, key, { fileName }, signal);
1280
+ signal.throwIfAborted();
1281
+ startBrowserDownload(data.url);
1282
+ call.update({ phase: "success", result: data });
1283
+ return { status: "success", key, data };
1284
+ } catch (error) {
1285
+ if (signal.aborted) {
1286
+ call.update({ phase: "aborted" });
1287
+ return { status: "aborted", key };
1815
1288
  }
1816
- patch((draft) => {
1817
- draft.phase = "error";
1818
- draft.error = toHookError(err, "Download failed");
1819
- });
1820
- opts.onError?.(key, err, "downloading");
1821
- } finally {
1822
- if (isCurrent()) abortRef.current = null;
1289
+ const apiError = toClientError(error);
1290
+ call.update({ phase: "error", error: apiError });
1291
+ return { status: "error", key, error: apiError };
1823
1292
  }
1824
1293
  },
1825
- [apiRef, optsRef, patch, replace]
1294
+ [optionsRef, resolveApi, sign]
1826
1295
  );
1827
1296
  const download = useCallback(
1828
- async (key, downloadName) => {
1829
- if (optsRef.current.mode === "fetch") {
1830
- await downloadFetch(key, downloadName);
1831
- return;
1832
- }
1833
- await downloadNavigate(key, downloadName);
1834
- },
1835
- [downloadFetch, downloadNavigate, optsRef]
1297
+ (key, { fileName } = {}) => store.run(
1298
+ key,
1299
+ (call) => navigate(call, fileName),
1300
+ (outcome) => reportOperationOutcome(optionsRef.current, outcome)
1301
+ ),
1302
+ [navigate, optionsRef, store]
1836
1303
  );
1837
- const cancel = useCallback(() => {
1838
- const key = downloadKeyRef.current;
1839
- generationRef.current += 1;
1840
- abortRef.current?.abort();
1841
- abortRef.current = null;
1842
- downloadKeyRef.current = null;
1843
- const opts = optsRef.current;
1844
- if (key && opts.mode === "fetch") opts.onCancel?.(key);
1845
- replace(idleKeepingKey(key));
1846
- }, [optsRef, replace]);
1847
- const reset = useCallback(() => {
1848
- resettingRef.current = true;
1849
- generationRef.current += 1;
1850
- abortRef.current?.abort();
1851
- abortRef.current = null;
1852
- replace(INITIAL_STATE2);
1853
- }, [replace]);
1854
- if (options.mode === "fetch") {
1855
- const isDownloading = state.phase === "downloading";
1856
- const isPending = state.phase === "presigning" || state.phase === "downloading";
1857
- return {
1858
- mode: "fetch",
1859
- phase: state.phase,
1860
- objectKey: state.objectKey,
1861
- progress: state.progress,
1862
- error: state.error,
1863
- fileName: state.fileName,
1864
- fileSize: state.fileSize,
1865
- isDownloading,
1866
- isPending,
1867
- download,
1868
- cancel,
1869
- reset
1870
- };
1871
- }
1304
+ const cancel = useCallback((key) => store.cancel(key), [store]);
1305
+ const reset = useCallback((key) => store.reset(key), [store]);
1872
1306
  return {
1873
1307
  mode: "navigate",
1874
- phase: state.phase,
1875
- objectKey: state.objectKey,
1876
- error: state.error,
1877
- url: state.url,
1878
- expiresIn: state.expiresIn,
1879
- isPending: state.phase === "presigning",
1308
+ instanceId,
1309
+ operations,
1310
+ get,
1311
+ pendingKeys,
1312
+ isPending: pendingKeys.length > 0,
1880
1313
  download,
1881
- presign,
1314
+ presign: presign2,
1882
1315
  presignMany,
1316
+ cancel,
1883
1317
  reset
1884
1318
  };
1885
1319
  }
1886
- var INITIAL_STATE3 = {
1887
- phase: "idle",
1888
- error: null,
1889
- objectKey: null
1890
- };
1891
- function useDelete(options) {
1892
- const [state, patch, replace] = useImmerState(INITIAL_STATE3);
1320
+ var PROGRESS_INTERVAL_MS = 100;
1321
+ function useFetchDownload(options) {
1322
+ const instanceId = useId();
1893
1323
  const contextApi = useContext(S3Context);
1894
- const optsRef = useLiveRef(options);
1324
+ const optionsRef = useLiveRef(options);
1895
1325
  const apiRef = useLiveRef(contextApi);
1896
- const objectKeyRef = useRef(null);
1897
- const inFlightRef = useRef(false);
1898
- const generationRef = useRef(0);
1899
- const requestDelete = useCallback(
1900
- (key) => {
1901
- if (inFlightRef.current) return;
1902
- objectKeyRef.current = key;
1903
- patch((draft) => {
1904
- draft.phase = "confirming";
1905
- draft.error = null;
1906
- draft.objectKey = key;
1907
- });
1908
- },
1909
- [patch]
1910
- );
1911
- const executeDelete = useCallback(
1912
- async (key) => {
1913
- if (inFlightRef.current) return;
1914
- const opts = optsRef.current;
1915
- const api = opts.api ?? apiRef.current;
1916
- if (!api)
1917
- throw new Error(
1918
- "[dimah-s3] No S3Api found. Pass `api` to useDelete or wrap with <S3Provider>."
1326
+ const { store, operations, pendingKeys, get } = useOperationStore();
1327
+ const transfer = useCallback(
1328
+ async (call, fileName, fileSize) => {
1329
+ const { key, signal } = call;
1330
+ const opts = optionsRef.current;
1331
+ const api = requireApi(opts.api ?? apiRef.current, "useFetchDownload");
1332
+ const base = {
1333
+ fileName: fileName ?? null,
1334
+ fileSize,
1335
+ error: null,
1336
+ progress: transferProgress(0, fileSize ?? 0)
1337
+ };
1338
+ try {
1339
+ const before = await abortable(
1340
+ runBeforeCallback("beforeDownload", opts.beforeDownload, key),
1341
+ signal
1919
1342
  );
1920
- const generation = ++generationRef.current;
1921
- inFlightRef.current = true;
1922
- if (opts.beforeDelete) {
1923
- const allowed = await opts.beforeDelete(key);
1924
- if (generation !== generationRef.current) return;
1925
- if (!allowed) {
1926
- inFlightRef.current = false;
1927
- objectKeyRef.current = null;
1928
- patch((draft) => {
1929
- draft.phase = "error";
1930
- draft.error = hookBlockedError(
1931
- "Delete blocked by beforeDelete hook"
1932
- );
1933
- draft.objectKey = key;
1934
- });
1935
- opts.onError?.(key, new Error("blocked"), "confirming");
1936
- return;
1343
+ if (before.status === "blocked") return { status: "blocked", key };
1344
+ if (before.status === "error") {
1345
+ call.publish({ ...base, phase: "error", error: before.error });
1346
+ return { status: "error", key, error: before.error };
1937
1347
  }
1938
- }
1939
- patch((draft) => {
1940
- draft.phase = "deleting";
1941
- draft.error = null;
1942
- draft.objectKey = key;
1943
- });
1944
- opts.onDeleteStart?.(key);
1945
- try {
1946
- await api.delete({ route: opts.route, key });
1947
- if (generation !== generationRef.current) return;
1948
- objectKeyRef.current = null;
1949
- patch((draft) => {
1950
- draft.phase = "success";
1951
- draft.error = null;
1952
- draft.objectKey = key;
1348
+ call.publish({ ...base, phase: "presigning" });
1349
+ const { url } = await api.download(
1350
+ {
1351
+ route: opts.route,
1352
+ key,
1353
+ name: fileName,
1354
+ disposition: opts.disposition
1355
+ },
1356
+ { signal }
1357
+ );
1358
+ call.update({ phase: "downloading" });
1359
+ const startError = runStartCallback(
1360
+ "onDownloadStart",
1361
+ optionsRef.current.onDownloadStart,
1362
+ key
1363
+ );
1364
+ if (startError) throw startError;
1365
+ const response = await fetchObject(url, signal);
1366
+ let total = declaredSize(response, fileSize);
1367
+ const name = fileName ?? parseFileName(response.headers.get("content-disposition")) ?? fileNameFromKey(key) ?? key;
1368
+ call.update({ fileName: name, fileSize: total || null });
1369
+ const speed = createThrottledSpeedUpdater(createSpeedTracker());
1370
+ let reported = null;
1371
+ let reportedAt = -Infinity;
1372
+ const report = (progress) => {
1373
+ reported = progress;
1374
+ reportedAt = Date.now();
1375
+ call.update({ progress });
1376
+ notify(optionsRef.current.onProgress, progress, key);
1377
+ };
1378
+ const blob = await readResponseBlob(response, signal, (loaded) => {
1379
+ if (total > 0 && loaded > total) total = 0;
1380
+ const progress = speed.apply(transferProgress(loaded, total));
1381
+ const done = total > 0 && loaded === total;
1382
+ if (done || Date.now() - reportedAt >= PROGRESS_INTERVAL_MS) {
1383
+ report(progress);
1384
+ }
1953
1385
  });
1954
- try {
1955
- await opts.onSuccess?.(key);
1956
- } catch (err) {
1957
- opts.onError?.(key, err, "success");
1386
+ signal.throwIfAborted();
1387
+ const final = transferProgress(blob.size, blob.size);
1388
+ if (!isSameProgress(reported, final)) {
1389
+ notify(optionsRef.current.onProgress, final, key);
1958
1390
  }
1959
- } catch (err) {
1960
- if (generation !== generationRef.current) return;
1961
- patch((draft) => {
1962
- draft.phase = "error";
1963
- draft.error = toHookError(err, "Delete failed");
1964
- draft.objectKey = key;
1965
- });
1966
- opts.onError?.(key, err, "deleting");
1967
- } finally {
1968
- if (generation === generationRef.current) {
1969
- inFlightRef.current = false;
1391
+ saveBlob(blob, name);
1392
+ call.update({ phase: "success", fileSize: blob.size, progress: final });
1393
+ return {
1394
+ status: "success",
1395
+ key,
1396
+ data: { fileName: name, size: blob.size }
1397
+ };
1398
+ } catch (error) {
1399
+ if (signal.aborted) {
1400
+ call.update({ phase: "aborted" });
1401
+ return { status: "aborted", key };
1970
1402
  }
1403
+ const apiError = toClientError(error);
1404
+ call.update({ phase: "error", error: apiError });
1405
+ return { status: "error", key, error: apiError };
1971
1406
  }
1972
1407
  },
1973
- [apiRef, optsRef, patch]
1408
+ [apiRef, optionsRef]
1409
+ );
1410
+ const download = useCallback(
1411
+ (key, { fileName, fileSize = null } = {}) => store.run(
1412
+ key,
1413
+ (call) => transfer(call, fileName, fileSize),
1414
+ (outcome) => reportOperationOutcome(optionsRef.current, outcome)
1415
+ ),
1416
+ [optionsRef, store, transfer]
1974
1417
  );
1975
- const confirmDelete = useCallback(async () => {
1976
- const key = objectKeyRef.current;
1977
- if (!key) return;
1978
- await executeDelete(key);
1979
- }, [executeDelete]);
1418
+ const cancel = useCallback((key) => store.cancel(key), [store]);
1419
+ const reset = useCallback((key) => store.reset(key), [store]);
1420
+ return {
1421
+ mode: "fetch",
1422
+ instanceId,
1423
+ operations,
1424
+ get,
1425
+ pendingKeys,
1426
+ isPending: pendingKeys.length > 0,
1427
+ download,
1428
+ cancel,
1429
+ reset
1430
+ };
1431
+ }
1432
+ function declaredSize(response, fileSize) {
1433
+ const encoding = response.headers.get("content-encoding")?.trim();
1434
+ if (encoding && encoding.toLowerCase() !== "identity") return 0;
1435
+ return Number(response.headers.get("content-length")) || fileSize || 0;
1436
+ }
1437
+ function isSameProgress(progress, next) {
1438
+ return progress?.loaded === next.loaded && progress.total === next.total;
1439
+ }
1440
+ async function fetchObject(url, signal) {
1441
+ let response;
1442
+ try {
1443
+ response = await fetch(url, { signal });
1444
+ } catch (error) {
1445
+ signal.throwIfAborted();
1446
+ throw s3Error("NETWORK_ERROR", void 0, { cause: error });
1447
+ }
1448
+ if (!response.ok) {
1449
+ const { status } = response;
1450
+ throw s3Error("DOWNLOAD_FAILED", { status }, { status });
1451
+ }
1452
+ return response;
1453
+ }
1454
+ function useDelete(options) {
1455
+ const instanceId = useId();
1456
+ const contextApi = useContext(S3Context);
1457
+ const optionsRef = useLiveRef(options);
1458
+ const apiRef = useLiveRef(contextApi);
1459
+ const batchCountRef = useRef(0);
1460
+ const { store, operations, pendingKeys, get } = useOperationStore();
1980
1461
  const remove = useCallback(
1981
- async (key) => {
1982
- if (inFlightRef.current) return;
1983
- objectKeyRef.current = key;
1984
- patch((draft) => {
1985
- draft.objectKey = key;
1986
- draft.error = null;
1987
- });
1988
- await executeDelete(key);
1462
+ async (key, { fileName } = {}) => {
1463
+ const opts = optionsRef.current;
1464
+ const api = requireApi(opts.api ?? apiRef.current, "useDelete");
1465
+ return store.run(
1466
+ key,
1467
+ async (claim2) => {
1468
+ const [outcome] = await runDelete(
1469
+ opts,
1470
+ [{ claim: claim2, fileName: fileName ?? null }],
1471
+ null,
1472
+ deleteOne(api, opts.route, key)
1473
+ );
1474
+ return outcome;
1475
+ },
1476
+ async (outcome) => {
1477
+ await reportOutcomes(opts, [outcome]);
1478
+ await runAfterCallback(opts.onSettled, toResult([outcome]));
1479
+ }
1480
+ );
1989
1481
  },
1990
- [executeDelete, patch]
1482
+ [apiRef, optionsRef, store]
1991
1483
  );
1992
1484
  const removeMany = useCallback(
1993
- async (keys) => {
1994
- const empty = { deleted: [], failed: [] };
1995
- if (inFlightRef.current || keys.length === 0) return empty;
1996
- const opts = optsRef.current;
1997
- const api = opts.api ?? apiRef.current;
1998
- if (!api)
1999
- throw new Error(
2000
- "[dimah-s3] No S3Api found. Pass `api` to useDelete or wrap with <S3Provider>."
1485
+ async (items) => {
1486
+ const opts = optionsRef.current;
1487
+ const api = requireApi(opts.api ?? apiRef.current, "useDelete");
1488
+ const calls = /* @__PURE__ */ new Map();
1489
+ const targets = [];
1490
+ for (const item of items) {
1491
+ const { key, fileName } = typeof item === "string" ? { key: item } : item;
1492
+ if (calls.has(key)) continue;
1493
+ const joined = store.join(key);
1494
+ if (joined) {
1495
+ calls.set(key, joined);
1496
+ continue;
1497
+ }
1498
+ const claim2 = store.claim(key);
1499
+ calls.set(key, claim2.promise);
1500
+ targets.push({ claim: claim2, fileName: fileName ?? null });
1501
+ }
1502
+ if (targets.length > 0) {
1503
+ const outcomes = runDelete(
1504
+ opts,
1505
+ targets,
1506
+ String(++batchCountRef.current),
1507
+ deleteMany(
1508
+ api,
1509
+ opts.route,
1510
+ targets.map(({ claim: claim2 }) => claim2.key)
1511
+ )
2001
1512
  );
2002
- if (keys.length > DELETE_BATCH_MAX_KEYS) {
2003
- throw new Error(
2004
- `[dimah-s3] deleteMany accepts at most ${DELETE_BATCH_MAX_KEYS} keys.`
1513
+ let reported;
1514
+ const report = () => reported ??= outcomes.then(
1515
+ (settled) => reportOutcomes(opts, settled)
2005
1516
  );
2006
- }
2007
- const generation = ++generationRef.current;
2008
- inFlightRef.current = true;
2009
- patch((draft) => {
2010
- draft.phase = "deleting";
2011
- draft.error = null;
2012
- draft.objectKey = null;
2013
- });
2014
- const deleted = [];
2015
- const failed = [];
2016
- try {
2017
- const { results } = await api.deleteMany({
2018
- route: opts.route,
2019
- keys
2020
- });
2021
- if (generation !== generationRef.current) return { deleted, failed };
2022
- for (const item of results) {
2023
- if (item.success) {
2024
- deleted.push(item.key);
2025
- try {
2026
- await opts.onSuccess?.(item.key);
2027
- } catch (err) {
2028
- opts.onError?.(item.key, err, "success");
2029
- }
2030
- } else {
2031
- failed.push(item.key);
2032
- opts.onError?.(
2033
- item.key,
2034
- new Error(item.error?.message ?? "Delete failed"),
2035
- "deleting"
2036
- );
2037
- }
2038
- }
2039
- if (failed.length > 0) {
2040
- patch((draft) => {
2041
- draft.phase = "error";
2042
- draft.error = toHookError(
2043
- new Error(
2044
- results.find((item) => !item.success)?.error?.message ?? "Delete failed"
2045
- ),
2046
- "Delete failed"
2047
- );
2048
- });
2049
- return { deleted, failed };
2050
- }
2051
- patch((draft) => {
2052
- draft.phase = "success";
2053
- draft.error = null;
2054
- });
2055
- return { deleted, failed };
2056
- } catch (err) {
2057
- if (generation !== generationRef.current) return { deleted, failed };
2058
- patch((draft) => {
2059
- draft.phase = "error";
2060
- draft.error = toHookError(err, "Delete failed");
1517
+ targets.forEach(({ claim: claim2 }, index) => {
1518
+ void claim2.settle(
1519
+ outcomes.then((settled) => settled[index]),
1520
+ report
1521
+ );
2061
1522
  });
2062
- opts.onError?.(keys[0] ?? "", err, "deleting");
2063
- return {
2064
- deleted,
2065
- failed: keys.filter((key) => !deleted.includes(key))
2066
- };
2067
- } finally {
2068
- if (generation === generationRef.current) {
2069
- inFlightRef.current = false;
2070
- }
2071
1523
  }
1524
+ const result = toResult(await Promise.all(calls.values()));
1525
+ await runAfterCallback(opts.onSettled, result);
1526
+ return result;
2072
1527
  },
2073
- [apiRef, optsRef, patch]
1528
+ [apiRef, optionsRef, store]
2074
1529
  );
2075
- const cancelDelete = useCallback(() => {
2076
- generationRef.current += 1;
2077
- inFlightRef.current = false;
2078
- objectKeyRef.current = null;
2079
- replace(INITIAL_STATE3);
2080
- }, [replace]);
2081
- const reset = useCallback(() => {
2082
- generationRef.current += 1;
2083
- inFlightRef.current = false;
2084
- objectKeyRef.current = null;
2085
- replace(INITIAL_STATE3);
2086
- }, [replace]);
2087
- const isConfirming = state.phase === "confirming";
2088
- const isDeleting = state.phase === "deleting";
2089
1530
  return {
2090
- phase: state.phase,
2091
- objectKey: state.objectKey,
2092
- error: state.error,
2093
- isConfirming,
2094
- isDeleting,
2095
- isPending: isConfirming || isDeleting,
2096
- requestDelete,
2097
- confirmDelete,
1531
+ instanceId,
1532
+ operations,
1533
+ get,
1534
+ pendingKeys,
1535
+ isPending: pendingKeys.length > 0,
2098
1536
  remove,
2099
1537
  removeMany,
2100
- cancelDelete,
2101
- reset
1538
+ reset: store.reset
2102
1539
  };
2103
1540
  }
2104
- var cache = /* @__PURE__ */ new Map();
2105
- var REFRESH_SKEW_MS = 15e3;
2106
- function cacheKey(route, objectKey, disposition, fileName) {
2107
- return `${route}\0${objectKey}\0${disposition}\0${fileName ?? ""}`;
1541
+ async function runDelete(options, targets, batchId, request) {
1542
+ const keys = targets.map(({ claim: claim2 }) => claim2.key);
1543
+ const before = await runBeforeCallback(
1544
+ "beforeDelete",
1545
+ options.beforeDelete,
1546
+ keys
1547
+ );
1548
+ if (before.status === "blocked") {
1549
+ return keys.map((key) => ({ status: "blocked", key }));
1550
+ }
1551
+ const hookError = before.status === "error" ? before.error : runStartCallback("onDeleteStart", options.onDeleteStart, keys);
1552
+ const claims = /* @__PURE__ */ new Map();
1553
+ for (const { claim: claim2, fileName } of targets) {
1554
+ claims.set(claim2.key, claim2);
1555
+ claim2.publish({
1556
+ batchId,
1557
+ fileName,
1558
+ phase: hookError ? "error" : "deleting",
1559
+ error: hookError
1560
+ });
1561
+ }
1562
+ const reported = /* @__PURE__ */ new Map();
1563
+ const report = (outcome) => {
1564
+ const claim2 = claims.get(outcome.key);
1565
+ if (!claim2 || reported.has(outcome.key)) return;
1566
+ reported.set(outcome.key, outcome);
1567
+ claim2.update(
1568
+ outcome.status === "error" ? { phase: "error", error: outcome.error } : { phase: "success" }
1569
+ );
1570
+ };
1571
+ if (hookError) {
1572
+ for (const key of keys) report({ status: "error", key, error: hookError });
1573
+ } else {
1574
+ try {
1575
+ await request(report);
1576
+ } catch (error) {
1577
+ const clientError = toClientError(error);
1578
+ for (const key of keys) {
1579
+ report({ status: "error", key, error: clientError });
1580
+ }
1581
+ }
1582
+ }
1583
+ return keys.map((key) => {
1584
+ const outcome = reported.get(key);
1585
+ if (outcome) return outcome;
1586
+ const missing = {
1587
+ status: "error",
1588
+ key,
1589
+ error: s3Error("UNKNOWN_ERROR")
1590
+ };
1591
+ report(missing);
1592
+ return missing;
1593
+ });
2108
1594
  }
2109
- function readFresh(key) {
2110
- const entry = cache.get(key);
2111
- if (!entry) return void 0;
2112
- if (entry.expiresAt - REFRESH_SKEW_MS <= Date.now()) {
2113
- cache.delete(key);
2114
- return void 0;
1595
+ async function reportOutcomes(options, outcomes) {
1596
+ for (const outcome of outcomes) {
1597
+ if (outcome.status === "error") {
1598
+ await runAfterCallback(options.onError, outcome.error, outcome.key);
1599
+ }
1600
+ }
1601
+ for (const outcome of outcomes) {
1602
+ if (outcome.status === "success") {
1603
+ await runAfterCallback(options.onSuccess, outcome.data, outcome.key);
1604
+ }
1605
+ }
1606
+ }
1607
+ function deleteOne(api, route, key) {
1608
+ return async (report) => {
1609
+ try {
1610
+ const data = await api.delete({ route, key });
1611
+ report({ status: "success", key, data });
1612
+ } catch (error) {
1613
+ report({ status: "error", key, error: toClientError(error) });
1614
+ }
1615
+ };
1616
+ }
1617
+ function deleteMany(api, route, keys) {
1618
+ return async (report) => {
1619
+ for (let start = 0; start < keys.length; start += DELETE_MANY_MAX_KEYS) {
1620
+ const chunk = keys.slice(start, start + DELETE_MANY_MAX_KEYS);
1621
+ const sentKeys = groupByNormalizedKey(chunk);
1622
+ const callerKeys = (key) => sentKeys.get(key) ?? [key];
1623
+ try {
1624
+ const response = await api.deleteMany({ route, keys: chunk });
1625
+ for (const deleted of response.deleted) {
1626
+ for (const key of callerKeys(deleted)) {
1627
+ report({ status: "success", key, data: { key } });
1628
+ }
1629
+ }
1630
+ for (const failed of response.failed) {
1631
+ const error = APIError.fromShape(failed.error);
1632
+ for (const key of callerKeys(failed.key)) {
1633
+ report({ status: "error", key, error });
1634
+ }
1635
+ }
1636
+ } catch (error) {
1637
+ const clientError = toClientError(error);
1638
+ for (const key of chunk) {
1639
+ report({ status: "error", key, error: clientError });
1640
+ }
1641
+ }
1642
+ }
1643
+ };
1644
+ }
1645
+ function groupByNormalizedKey(keys) {
1646
+ const groups = /* @__PURE__ */ new Map();
1647
+ for (const key of keys) {
1648
+ const normalized = normalizeObjectKey(key) ?? key;
1649
+ const group = groups.get(normalized);
1650
+ if (group) group.push(key);
1651
+ else groups.set(normalized, [key]);
1652
+ }
1653
+ return groups;
1654
+ }
1655
+ function toResult(outcomes) {
1656
+ const result = { deleted: [], failed: [], blocked: [] };
1657
+ for (const outcome of outcomes) {
1658
+ switch (outcome.status) {
1659
+ case "success":
1660
+ result.deleted.push(outcome.key);
1661
+ break;
1662
+ case "error":
1663
+ result.failed.push({ key: outcome.key, error: outcome.error });
1664
+ break;
1665
+ case "blocked":
1666
+ result.blocked.push(outcome.key);
1667
+ break;
1668
+ }
1669
+ }
1670
+ return result;
1671
+ }
1672
+
1673
+ // src/internal/lru.ts
1674
+ function createLruCache(maxSize) {
1675
+ if (!Number.isInteger(maxSize) || maxSize < 1) {
1676
+ throw new RangeError(
1677
+ "[dimah-s3] LRU cache size must be a positive integer."
1678
+ );
1679
+ }
1680
+ const entries = /* @__PURE__ */ new Map();
1681
+ return {
1682
+ get(key) {
1683
+ if (!entries.has(key)) return void 0;
1684
+ const value = entries.get(key);
1685
+ entries.delete(key);
1686
+ entries.set(key, value);
1687
+ return value;
1688
+ },
1689
+ set(key, value) {
1690
+ entries.delete(key);
1691
+ entries.set(key, value);
1692
+ for (const oldest of entries.keys()) {
1693
+ if (entries.size <= maxSize) break;
1694
+ entries.delete(oldest);
1695
+ }
1696
+ },
1697
+ delete: (key) => entries.delete(key),
1698
+ clear: () => entries.clear(),
1699
+ get size() {
1700
+ return entries.size;
1701
+ }
1702
+ };
1703
+ }
1704
+
1705
+ // src/hooks/use-object-url.ts
1706
+ var CACHE_SIZE = 500;
1707
+ var DEFAULT_REFRESH_BEFORE_MS = 6e4;
1708
+ var MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
1709
+ var RETRY_BASE_DELAY_MS = 1e3;
1710
+ var caches = /* @__PURE__ */ new WeakMap();
1711
+ function cacheFor(api) {
1712
+ let cache = caches.get(api);
1713
+ if (!cache) {
1714
+ cache = { entries: createLruCache(CACHE_SIZE), pending: /* @__PURE__ */ new Map() };
1715
+ caches.set(api, cache);
2115
1716
  }
2116
- return entry;
1717
+ return cache;
1718
+ }
1719
+ function cacheId(route, objectKey, disposition, fileName) {
1720
+ return JSON.stringify([route, objectKey, disposition, fileName ?? null]);
1721
+ }
1722
+ function presign(api, id, payload) {
1723
+ const cache = cacheFor(api);
1724
+ const running = cache.pending.get(id);
1725
+ if (running) return running;
1726
+ const signedAt = Date.now();
1727
+ const request = api.download(payload).then((response) => {
1728
+ const entry = {
1729
+ url: response.url,
1730
+ signedAt,
1731
+ expiresAt: response.mode === "proxy" ? null : signedAt + response.expiresIn * 1e3
1732
+ };
1733
+ cache.entries.set(id, entry);
1734
+ return entry;
1735
+ }).finally(() => cache.pending.delete(id));
1736
+ cache.pending.set(id, request);
1737
+ return request;
1738
+ }
1739
+ function refreshAt(entry, refreshBeforeMs) {
1740
+ if (entry.expiresAt === null) return null;
1741
+ const lifetime = entry.expiresAt - entry.signedAt;
1742
+ const lead = Math.max(0, Math.min(refreshBeforeMs, lifetime / 2));
1743
+ return entry.expiresAt - lead;
1744
+ }
1745
+ function isTransient(error) {
1746
+ const status = error.statusCode;
1747
+ return status >= 500 || status === 408 || status === 429;
1748
+ }
1749
+ function isFresh(entry, refreshBeforeMs) {
1750
+ const at = refreshAt(entry, refreshBeforeMs);
1751
+ return at === null || Date.now() < at;
2117
1752
  }
2118
1753
  function useObjectUrl(options) {
2119
1754
  const contextApi = useContext(S3Context);
2120
- const optsRef = useLiveRef(options);
2121
- const apiRef = useLiveRef(contextApi);
2122
- const generationRef = useRef(0);
2123
- const [url, setUrl] = useState(null);
2124
- const [expiresIn, setExpiresIn] = useState(null);
2125
- const [error, setError] = useState(null);
2126
- const [isLoading, setIsLoading] = useState(false);
2127
- const [tick, setTick] = useState(0);
2128
- const objectKey = options.objectKey ?? null;
2129
- const disposition = options.disposition ?? "inline";
2130
- const fileName = options.fileName;
2131
- const route = options.route;
2132
- const load = useCallback(async () => {
2133
- const opts = optsRef.current;
2134
- const key = opts.objectKey;
2135
- if (!key) {
2136
- setUrl(null);
2137
- setExpiresIn(null);
2138
- setError(null);
2139
- setIsLoading(false);
2140
- return;
2141
- }
2142
- const api = opts.api ?? apiRef.current;
2143
- if (!api) {
2144
- throw new Error(
2145
- "[dimah-s3] No S3Api found. Pass `api` to useObjectUrl or wrap with <S3Provider>."
1755
+ const {
1756
+ route,
1757
+ fileName,
1758
+ disposition = "inline",
1759
+ refreshBeforeMs = DEFAULT_REFRESH_BEFORE_MS
1760
+ } = options;
1761
+ const objectKey = options.objectKey || null;
1762
+ const api = objectKey === null ? null : requireApi(options.api ?? contextApi, "useObjectUrl");
1763
+ const id = objectKey === null ? null : cacheId(route, objectKey, disposition, fileName);
1764
+ const [state, setState] = useState(null);
1765
+ const [version, setVersion] = useState(0);
1766
+ const targetRef = useLiveRef({ api, id });
1767
+ useEffect(() => {
1768
+ if (api === null || id === null || objectKey === null) return;
1769
+ const payload = {
1770
+ route,
1771
+ key: objectKey,
1772
+ name: fileName,
1773
+ disposition
1774
+ };
1775
+ let active = true;
1776
+ let timer;
1777
+ let shown;
1778
+ let retries = 0;
1779
+ const arm = (callback, wait) => {
1780
+ clearTimeout(timer);
1781
+ const delay = Math.min(Math.max(wait, 0), MAX_TIMER_DELAY_MS);
1782
+ timer = setTimeout(callback, delay);
1783
+ };
1784
+ const show = (entry) => {
1785
+ shown = entry;
1786
+ retries = 0;
1787
+ setState({
1788
+ api,
1789
+ id,
1790
+ url: entry.url,
1791
+ expiresAt: entry.expiresAt,
1792
+ error: null,
1793
+ isLoading: false
1794
+ });
1795
+ const at = refreshAt(entry, refreshBeforeMs);
1796
+ if (at !== null) arm(load, at - Date.now());
1797
+ };
1798
+ const clear = (error) => {
1799
+ shown = void 0;
1800
+ setState({
1801
+ api,
1802
+ id,
1803
+ url: null,
1804
+ expiresAt: null,
1805
+ error,
1806
+ isLoading: false
1807
+ });
1808
+ };
1809
+ const fail = (error) => {
1810
+ const expiresAt = shown?.expiresAt ?? null;
1811
+ const remaining = expiresAt === null ? 0 : expiresAt - Date.now();
1812
+ if (shown === void 0 || expiresAt === null || remaining <= 0) {
1813
+ clear(error);
1814
+ return;
1815
+ }
1816
+ setState({
1817
+ api,
1818
+ id,
1819
+ url: shown.url,
1820
+ expiresAt,
1821
+ error,
1822
+ isLoading: false
1823
+ });
1824
+ if (isTransient(error)) {
1825
+ arm(load, Math.min(RETRY_BASE_DELAY_MS * 2 ** retries++, remaining));
1826
+ } else {
1827
+ arm(() => {
1828
+ if (active) clear(error);
1829
+ }, remaining);
1830
+ }
1831
+ };
1832
+ const load = () => {
1833
+ if (!active) return;
1834
+ const cached = cacheFor(api).entries.get(id);
1835
+ if (cached && isFresh(cached, refreshBeforeMs)) {
1836
+ show(cached);
1837
+ return;
1838
+ }
1839
+ setState(
1840
+ (previous) => previous !== null && previous.api === api && previous.id === id && (previous.expiresAt === null || previous.expiresAt > Date.now()) ? { ...previous, isLoading: true } : {
1841
+ api,
1842
+ id,
1843
+ url: null,
1844
+ expiresAt: null,
1845
+ error: null,
1846
+ isLoading: true
1847
+ }
2146
1848
  );
2147
- }
2148
- const id = cacheKey(
2149
- opts.route,
2150
- key,
2151
- opts.disposition ?? "inline",
2152
- opts.fileName
2153
- );
2154
- const cached = readFresh(id);
2155
- if (cached) {
2156
- setUrl(cached.url);
2157
- setExpiresIn(cached.expiresIn);
2158
- setError(null);
2159
- setIsLoading(false);
2160
- return;
2161
- }
2162
- const generation = ++generationRef.current;
2163
- setIsLoading(true);
2164
- try {
2165
- const result = await api.download({
2166
- route: opts.route,
2167
- key,
2168
- fileName: opts.fileName,
2169
- disposition: opts.disposition ?? "inline"
2170
- });
2171
- if (generation !== generationRef.current) return;
2172
- const ttlMs = result.expiresIn > 0 ? result.expiresIn * 1e3 : 24 * 60 * 60 * 1e3;
2173
- cache.set(id, {
2174
- url: result.url,
2175
- expiresIn: result.expiresIn,
2176
- expiresAt: Date.now() + ttlMs
2177
- });
2178
- setUrl(result.url);
2179
- setExpiresIn(result.expiresIn);
2180
- setError(null);
2181
- } catch (err) {
2182
- if (generation !== generationRef.current) return;
2183
- setUrl(null);
2184
- setExpiresIn(null);
2185
- setError(toHookError(err, "Download failed"));
2186
- } finally {
2187
- if (generation === generationRef.current) setIsLoading(false);
2188
- }
2189
- }, [apiRef, optsRef]);
2190
- useEffect(() => {
2191
- void load();
2192
- }, [load, objectKey, route, disposition, fileName, tick]);
1849
+ presign(api, id, payload).then(
1850
+ (entry) => {
1851
+ if (active) show(entry);
1852
+ },
1853
+ (error) => {
1854
+ if (active) fail(toClientError(error));
1855
+ }
1856
+ );
1857
+ };
1858
+ void Promise.resolve().then(load);
1859
+ return () => {
1860
+ active = false;
1861
+ clearTimeout(timer);
1862
+ };
1863
+ }, [
1864
+ api,
1865
+ id,
1866
+ route,
1867
+ objectKey,
1868
+ fileName,
1869
+ disposition,
1870
+ refreshBeforeMs,
1871
+ version
1872
+ ]);
2193
1873
  const refresh = useCallback(() => {
2194
- if (objectKey) {
2195
- cache.delete(cacheKey(route, objectKey, disposition, fileName));
2196
- }
2197
- setTick((n) => n + 1);
2198
- }, [disposition, fileName, objectKey, route]);
2199
- return { url, expiresIn, error, isLoading, refresh };
2200
- }
2201
- function serializeQueryKey(key) {
2202
- return JSON.stringify(key ?? []);
2203
- }
2204
- function trailsEqual(a, b) {
2205
- return a.length === b.length && a.every((folder, index) => {
2206
- const other = b[index];
2207
- return other != null && folder.id === other.id && folder.name === other.name;
2208
- });
2209
- }
2210
- function syncTrail(trail, parent) {
2211
- if (parent == null) return [];
2212
- const index = trail.findIndex((folder) => folder.id === parent);
2213
- if (index >= 0) return trail.slice(0, index + 1);
2214
- return [{ id: parent, name: parent }];
1874
+ const target = targetRef.current;
1875
+ if (target.api === null || target.id === null) return;
1876
+ cacheFor(target.api).entries.delete(target.id);
1877
+ setVersion((n) => n + 1);
1878
+ }, [targetRef]);
1879
+ const current = state !== null && state.api === api && state.id === id ? state : null;
1880
+ return {
1881
+ objectKey,
1882
+ url: current?.url ?? null,
1883
+ expiresAt: current?.expiresAt ?? null,
1884
+ error: current?.error ?? null,
1885
+ isLoading: id !== null && (current?.isLoading ?? true),
1886
+ refresh
1887
+ };
2215
1888
  }
1889
+ var EMPTY_SNAPSHOT = {
1890
+ key: null,
1891
+ scope: null,
1892
+ items: [],
1893
+ folders: [],
1894
+ nextCursor: null,
1895
+ usage: null,
1896
+ pageCount: 0
1897
+ };
1898
+ var INITIAL_STATE = {
1899
+ snapshot: EMPTY_SNAPSHOT,
1900
+ pending: null,
1901
+ failure: null
1902
+ };
2216
1903
  function useObjectList(options) {
2217
1904
  const optionsRef = useLiveRef(options);
2218
- const controlled = options.parent !== void 0;
2219
1905
  const enabled = options.enabled !== false;
2220
- const queryKey = serializeQueryKey(options.queryKey);
2221
- const [parentState, setParentState] = useState(() => {
2222
- if (options.defaultParent !== void 0) return options.defaultParent;
2223
- return options.defaultTrail?.at(-1)?.id ?? null;
2224
- });
2225
- const parent = controlled ? options.parent ?? null : parentState;
1906
+ const [parent, setParent] = useControllableState(
1907
+ options.parent,
1908
+ () => options.defaultParent !== void 0 ? options.defaultParent : options.defaultTrail?.at(-1)?.id ?? null,
1909
+ options.onParentChange
1910
+ );
2226
1911
  const [trailState, setTrailState] = useState(
2227
- () => {
2228
- const initial = options.defaultTrail ?? [];
2229
- if (options.parent !== void 0)
2230
- return syncTrail(initial, options.parent);
2231
- if (options.defaultParent !== void 0) {
2232
- return syncTrail(initial, options.defaultParent);
2233
- }
2234
- return initial;
2235
- }
1912
+ () => options.defaultTrail ?? []
2236
1913
  );
2237
1914
  const trail = useMemo(
2238
- () => controlled ? syncTrail(trailState, parent) : trailState,
2239
- [controlled, trailState, parent]
1915
+ () => syncTrail(trailState, parent),
1916
+ [trailState, parent]
1917
+ );
1918
+ const [sort, setSortValue] = useControllableState(
1919
+ options.sort,
1920
+ () => options.defaultSort ?? null,
1921
+ options.onSortChange,
1922
+ sortsEqual
2240
1923
  );
2241
- const [items, setItems] = useState([]);
2242
- const [folders, setFolders] = useState([]);
2243
- const [nextCursor, setNextCursor] = useState(null);
2244
- const [usage, setUsage] = useState(null);
2245
- const [error, setError] = useState(null);
2246
- const [status, setStatus] = useState(enabled ? "loading" : "ready");
2247
- const parentRef = useLiveRef(parent);
1924
+ const [search, setSearchValue] = useControllableState(
1925
+ options.search,
1926
+ () => options.defaultSearch ?? "",
1927
+ options.onSearchChange
1928
+ );
1929
+ const queryKey = JSON.stringify(options.queryKey ?? []);
1930
+ const trimmedSearch = search.trim();
1931
+ const request = useMemo(() => {
1932
+ const scope = JSON.stringify([queryKey, parent]);
1933
+ return {
1934
+ key: JSON.stringify([
1935
+ scope,
1936
+ sort ? `${sort.field}:${sort.direction}` : "",
1937
+ trimmedSearch
1938
+ ]),
1939
+ scope,
1940
+ parent,
1941
+ sort,
1942
+ search: trimmedSearch
1943
+ };
1944
+ }, [parent, queryKey, sort, trimmedSearch]);
1945
+ const requestRef = useLiveRef(request);
2248
1946
  const trailRef = useLiveRef(trail);
2249
- const cursorRef = useLiveRef(nextCursor);
2250
- const statusRef = useLiveRef(status);
2251
- const itemsRef = useLiveRef(items);
2252
- const foldersRef = useLiveRef(folders);
2253
- const abortRef = useRef(null);
2254
- const generationRef = useRef(0);
2255
- const applyPage = useCallback(
2256
- (page, mode) => {
2257
- if (mode === "append") {
2258
- setItems((current) => [...current, ...page.items]);
2259
- if (page.usage) setUsage(page.usage);
2260
- } else {
2261
- setItems(page.items);
2262
- setFolders(page.folders ?? []);
2263
- setUsage(page.usage ?? null);
2264
- }
2265
- const cursor = page.nextCursor ? page.nextCursor : null;
2266
- cursorRef.current = cursor;
2267
- statusRef.current = "ready";
2268
- setNextCursor(cursor);
2269
- setError(null);
2270
- setStatus("ready");
1947
+ const [state, setState] = useState(INITIAL_STATE);
1948
+ const stateRef = useRef(INITIAL_STATE);
1949
+ const update = useCallback(
1950
+ (next) => {
1951
+ stateRef.current = next(stateRef.current);
1952
+ setState(stateRef.current);
2271
1953
  },
2272
- [cursorRef, statusRef]
1954
+ []
2273
1955
  );
1956
+ const abortRef = useRef(null);
1957
+ const generationRef = useRef(0);
2274
1958
  const run = useCallback(
2275
- async (mode) => {
2276
- if (optionsRef.current.enabled === false) return;
2277
- const cursor = mode === "append" ? cursorRef.current : null;
1959
+ async (requested) => {
1960
+ const opts = optionsRef.current;
1961
+ if (opts.enabled === false) return;
1962
+ const target = requestRef.current;
1963
+ const current = stateRef.current;
1964
+ const sameKey = current.snapshot.key === target.key;
1965
+ const mode = requested === "refresh" && !sameKey ? "replace" : requested;
2278
1966
  if (mode === "append") {
2279
- if (!cursor) return;
2280
- const current = statusRef.current;
2281
- if (current === "loading" || current === "loading-more" || current === "refreshing") {
2282
- return;
2283
- }
1967
+ if (!sameKey || !current.snapshot.nextCursor || current.pending) return;
2284
1968
  }
2285
1969
  abortRef.current?.abort();
2286
1970
  const controller = new AbortController();
2287
1971
  abortRef.current = controller;
2288
1972
  const generation = ++generationRef.current;
2289
- const requestParent = parentRef.current;
2290
- const hasRows = itemsRef.current.length > 0 || foldersRef.current.length > 0;
2291
- if (mode === "replace") {
2292
- setItems([]);
2293
- setFolders([]);
2294
- setNextCursor(null);
2295
- setError(null);
2296
- statusRef.current = "loading";
2297
- setStatus("loading");
2298
- } else if (mode === "refresh") {
2299
- setError(null);
2300
- const nextStatus = hasRows ? "refreshing" : "loading";
2301
- statusRef.current = nextStatus;
2302
- setStatus(nextStatus);
2303
- } else {
2304
- statusRef.current = "loading-more";
2305
- setStatus("loading-more");
2306
- }
1973
+ const isCurrent = () => generation === generationRef.current && !controller.signal.aborted;
1974
+ update((draft) => ({ ...draft, pending: mode, failure: null }));
1975
+ const input = {
1976
+ parent: target.parent,
1977
+ sort: target.sort,
1978
+ search: target.search,
1979
+ signal: controller.signal
1980
+ };
2307
1981
  try {
2308
- const page = await optionsRef.current.query({
2309
- parent: requestParent,
2310
- cursor,
2311
- signal: controller.signal
2312
- });
2313
- if (generation !== generationRef.current || controller.signal.aborted) {
1982
+ if (mode === "append") {
1983
+ const page = await opts.query({
1984
+ ...input,
1985
+ cursor: current.snapshot.nextCursor
1986
+ });
1987
+ if (!isCurrent()) return;
1988
+ update((draft) => ({
1989
+ pending: null,
1990
+ failure: null,
1991
+ snapshot: {
1992
+ ...draft.snapshot,
1993
+ items: [...draft.snapshot.items, ...page.items],
1994
+ nextCursor: page.nextCursor || null,
1995
+ usage: page.usage ?? draft.snapshot.usage,
1996
+ pageCount: draft.snapshot.pageCount + 1
1997
+ }
1998
+ }));
2314
1999
  return;
2315
2000
  }
2316
- applyPage(page, mode);
2001
+ const pageTarget = mode === "refresh" ? Math.max(1, current.snapshot.pageCount) : 1;
2002
+ const items2 = [];
2003
+ let folders2 = [];
2004
+ let usage = null;
2005
+ let cursor = null;
2006
+ let pageCount = 0;
2007
+ do {
2008
+ const page = await opts.query({ ...input, cursor });
2009
+ if (!isCurrent()) return;
2010
+ if (pageCount === 0) folders2 = page.folders ?? [];
2011
+ for (const item of page.items) items2.push(item);
2012
+ usage = page.usage ?? usage;
2013
+ cursor = page.nextCursor || null;
2014
+ pageCount += 1;
2015
+ } while (cursor && pageCount < pageTarget);
2016
+ update(() => ({
2017
+ pending: null,
2018
+ failure: null,
2019
+ snapshot: {
2020
+ key: target.key,
2021
+ scope: target.scope,
2022
+ items: items2,
2023
+ folders: folders2,
2024
+ nextCursor: cursor,
2025
+ usage,
2026
+ pageCount
2027
+ }
2028
+ }));
2317
2029
  } catch (err) {
2318
- if (generation !== generationRef.current || controller.signal.aborted || isAbortError(err)) {
2319
- return;
2320
- }
2321
- setError(toHookError(err, "Could not load files"));
2322
- statusRef.current = "error";
2323
- setStatus("error");
2030
+ if (!isCurrent()) return;
2031
+ const error = toClientError(err);
2032
+ update((draft) => ({
2033
+ pending: null,
2034
+ failure: { mode, error },
2035
+ // A failed first page shows the error, not the previous rows.
2036
+ snapshot: mode === "replace" ? { ...EMPTY_SNAPSHOT, key: target.key, scope: target.scope } : draft.snapshot
2037
+ }));
2324
2038
  }
2325
2039
  },
2326
- [
2327
- abortRef,
2328
- applyPage,
2329
- cursorRef,
2330
- foldersRef,
2331
- generationRef,
2332
- itemsRef,
2333
- optionsRef,
2334
- parentRef,
2335
- statusRef
2336
- ]
2040
+ [optionsRef, requestRef, update]
2337
2041
  );
2338
2042
  useEffect(() => {
2339
- if (!enabled) {
2340
- abortRef.current?.abort();
2341
- return;
2342
- }
2043
+ if (!enabled) return;
2343
2044
  let active = true;
2344
- void (async () => {
2345
- await Promise.resolve();
2346
- if (!active) return;
2347
- await run("replace");
2348
- })();
2045
+ void Promise.resolve().then(() => {
2046
+ if (active) void run("replace");
2047
+ });
2349
2048
  return () => {
2350
2049
  active = false;
2351
2050
  abortRef.current?.abort();
2051
+ generationRef.current += 1;
2052
+ if (stateRef.current.pending) {
2053
+ update((draft) => ({ ...draft, pending: null }));
2054
+ }
2352
2055
  };
2353
- }, [abortRef, enabled, parent, queryKey, run]);
2056
+ }, [enabled, request.key, run, update]);
2354
2057
  const navigate = useCallback(
2355
2058
  (nextTrail) => {
2356
2059
  const nextParent = nextTrail.at(-1)?.id ?? null;
2357
- if (nextParent === parentRef.current && trailsEqual(nextTrail, trailRef.current)) {
2060
+ if (nextParent === requestRef.current.parent && trailsEqual(nextTrail, trailRef.current)) {
2358
2061
  return;
2359
2062
  }
2360
- const previousParent = parentRef.current;
2361
2063
  trailRef.current = nextTrail;
2362
2064
  setTrailState(nextTrail);
2363
- if (optionsRef.current.parent === void 0) {
2364
- parentRef.current = nextParent;
2365
- setParentState(nextParent);
2065
+ if (nextParent !== requestRef.current.parent) {
2066
+ setSearchValue("");
2067
+ setParent(nextParent);
2366
2068
  }
2367
- if (nextParent !== previousParent) {
2368
- cursorRef.current = null;
2369
- setItems([]);
2370
- setFolders([]);
2371
- setNextCursor(null);
2372
- setError(null);
2373
- statusRef.current = "loading";
2374
- setStatus("loading");
2375
- }
2376
- optionsRef.current.onParentChange?.(nextParent);
2377
2069
  },
2378
- [cursorRef, optionsRef, parentRef, statusRef, trailRef]
2070
+ [requestRef, setParent, setSearchValue, trailRef]
2379
2071
  );
2380
2072
  const openFolder = useCallback(
2381
2073
  (folder) => {
2382
2074
  const current = trailRef.current;
2383
2075
  const index = current.findIndex((entry) => entry.id === folder.id);
2384
- const next = index >= 0 ? current.slice(0, index + 1) : [...current, folder];
2385
- navigate(next);
2076
+ navigate(index >= 0 ? current.slice(0, index + 1) : [...current, folder]);
2386
2077
  },
2387
2078
  [navigate, trailRef]
2388
2079
  );
2080
+ const goUp = useCallback(() => {
2081
+ if (trailRef.current.length > 0) navigate(trailRef.current.slice(0, -1));
2082
+ }, [navigate, trailRef]);
2389
2083
  const loadMore = useCallback(() => run("append"), [run]);
2390
2084
  const refresh = useCallback(() => run("refresh"), [run]);
2085
+ const retry = useCallback(
2086
+ () => run(stateRef.current.failure?.mode === "append" ? "append" : "refresh"),
2087
+ [run]
2088
+ );
2089
+ const editSnapshot = useCallback(
2090
+ (edit) => {
2091
+ update(
2092
+ (draft) => draft.snapshot.key == null ? draft : { ...draft, snapshot: edit(draft.snapshot) }
2093
+ );
2094
+ },
2095
+ [update]
2096
+ );
2097
+ const setItems = useCallback(
2098
+ (next) => editSnapshot((snapshot2) => ({
2099
+ ...snapshot2,
2100
+ items: typeof next === "function" ? next(snapshot2.items) : next
2101
+ })),
2102
+ [editSnapshot]
2103
+ );
2104
+ const setFolders = useCallback(
2105
+ (next) => editSnapshot((snapshot2) => ({
2106
+ ...snapshot2,
2107
+ folders: typeof next === "function" ? next(snapshot2.folders) : next
2108
+ })),
2109
+ [editSnapshot]
2110
+ );
2111
+ const removeItems = useCallback(
2112
+ (keys) => {
2113
+ if (keys.length === 0) return;
2114
+ const drop = new Set(keys);
2115
+ const { getKey: keyOf } = optionsRef.current;
2116
+ setItems((items2) => items2.filter((item) => !drop.has(keyOf(item))));
2117
+ },
2118
+ [optionsRef, setItems]
2119
+ );
2120
+ const createFolder = useCallback(
2121
+ async (name) => {
2122
+ const create = optionsRef.current.createFolder;
2123
+ if (!create) {
2124
+ throw new Error("[dimah-s3] The source has no createFolder.");
2125
+ }
2126
+ const { parent: target, scope } = requestRef.current;
2127
+ let folder;
2128
+ try {
2129
+ folder = await create({ parent: target, name });
2130
+ } catch (err) {
2131
+ throw toClientError(err);
2132
+ }
2133
+ update(
2134
+ (draft) => draft.snapshot.scope === scope ? {
2135
+ ...draft,
2136
+ snapshot: {
2137
+ ...draft.snapshot,
2138
+ folders: [
2139
+ ...draft.snapshot.folders.filter(
2140
+ (entry) => entry.id !== folder.id
2141
+ ),
2142
+ folder
2143
+ ]
2144
+ }
2145
+ } : draft
2146
+ );
2147
+ return folder;
2148
+ },
2149
+ [optionsRef, requestRef, update]
2150
+ );
2151
+ const setSort = useCallback(
2152
+ (next) => setSortValue(next),
2153
+ [setSortValue]
2154
+ );
2155
+ const setSearch = useCallback(
2156
+ (next) => setSearchValue(next),
2157
+ [setSearchValue]
2158
+ );
2159
+ const { getKey, getFile: readFile } = options;
2160
+ const getFile = useMemo(
2161
+ () => readFile ?? ((item) => ({ name: getKey(item) })),
2162
+ [getKey, readFile]
2163
+ );
2164
+ const { snapshot, pending, failure } = state;
2165
+ const fresh = snapshot.key === request.key;
2166
+ const visible = fresh || snapshot.key != null && snapshot.scope === request.scope;
2167
+ const items = visible ? snapshot.items : EMPTY_SNAPSHOT.items;
2168
+ const folders = visible ? snapshot.folders : EMPTY_SNAPSHOT.folders;
2169
+ const hasRows = items.length > 0 || folders.length > 0;
2170
+ const status = readStatus({
2171
+ enabled,
2172
+ fresh,
2173
+ visible,
2174
+ hasRows,
2175
+ pending,
2176
+ failure
2177
+ });
2178
+ const entries = useMemo(
2179
+ () => createObjectListEntries(folders, items, getKey, getFile),
2180
+ [folders, getFile, getKey, items]
2181
+ );
2182
+ const nextCursor = fresh ? snapshot.nextCursor : null;
2391
2183
  return {
2184
+ entries,
2392
2185
  items,
2393
2186
  folders,
2394
2187
  trail,
2395
2188
  parent,
2396
- nextCursor,
2397
- error,
2398
- isLoading: enabled && status === "loading",
2399
- isLoadingMore: enabled && status === "loading-more",
2400
- isRefreshing: enabled && status === "refreshing",
2401
- usage,
2189
+ sort,
2190
+ search,
2191
+ usage: visible ? snapshot.usage : null,
2192
+ error: fresh ? failure?.error ?? null : null,
2193
+ status,
2194
+ isLoading: status === "loading",
2195
+ isRefreshing: status === "refreshing",
2196
+ isLoadingMore: status === "loading-more",
2402
2197
  hasMore: nextCursor != null,
2198
+ nextCursor,
2403
2199
  loadMore,
2404
2200
  refresh,
2201
+ retry,
2405
2202
  openFolder,
2406
- navigate
2203
+ navigate,
2204
+ goUp,
2205
+ setSort,
2206
+ setSearch,
2207
+ setItems,
2208
+ setFolders,
2209
+ removeItems,
2210
+ getKey,
2211
+ getFile,
2212
+ uploadOptions: options.uploadOptions,
2213
+ createFolder: options.createFolder ? createFolder : void 0
2407
2214
  };
2408
2215
  }
2409
-
2410
- // src/list/read-object-list-level.ts
2411
- function readObjectListLevel(records, input) {
2412
- const parent = normalizeFolder(input.parent);
2413
- const folders = /* @__PURE__ */ new Map();
2414
- const items = [];
2415
- for (const record of records) {
2416
- const folder = normalizeFolder(input.getFolder(record));
2417
- if (parent == null) {
2418
- if (folder == null) {
2419
- items.push(record);
2420
- continue;
2421
- }
2422
- const name2 = folder.split("/")[0];
2423
- if (!name2) continue;
2424
- folders.set(name2, { id: name2, name: name2 });
2425
- continue;
2426
- }
2427
- if (folder == null) continue;
2428
- if (folder === parent) {
2429
- items.push(record);
2430
- continue;
2431
- }
2432
- const prefix = `${parent}/`;
2433
- if (!folder.startsWith(prefix)) continue;
2434
- const name = folder.slice(prefix.length).split("/")[0];
2435
- if (!name) continue;
2436
- const id = `${parent}/${name}`;
2437
- folders.set(id, { id, name });
2216
+ function readStatus({
2217
+ enabled,
2218
+ fresh,
2219
+ visible,
2220
+ hasRows,
2221
+ pending,
2222
+ failure
2223
+ }) {
2224
+ if (!enabled) return "idle";
2225
+ if (!fresh) return visible && hasRows ? "refreshing" : "loading";
2226
+ if (pending === "append") return "loading-more";
2227
+ if (pending === "replace") return "loading";
2228
+ if (pending === "refresh") return hasRows ? "refreshing" : "loading";
2229
+ return failure ? "error" : "ready";
2230
+ }
2231
+ function sortsEqual(a, b) {
2232
+ return a === b || a?.field === b?.field && a?.direction === b?.direction;
2233
+ }
2234
+ function trailsEqual(a, b) {
2235
+ return a.length === b.length && a.every((folder, index) => {
2236
+ const other = b[index];
2237
+ return other != null && folder.id === other.id && folder.name === other.name;
2238
+ });
2239
+ }
2240
+ function syncTrail(trail, parent) {
2241
+ if (parent == null) return [];
2242
+ if (trail.at(-1)?.id === parent) return trail;
2243
+ const index = trail.findIndex((folder) => folder.id === parent);
2244
+ if (index >= 0) return trail.slice(0, index + 1);
2245
+ return [{ id: parent, name: parent }];
2246
+ }
2247
+ function selectFiles(entry) {
2248
+ return entry.kind === "file";
2249
+ }
2250
+ function useObjectListSelection(list, options = {}) {
2251
+ const mode = options.mode ?? "multiple";
2252
+ const persist = options.persist === true;
2253
+ const canSelect = options.isSelectable ?? selectFiles;
2254
+ const scope = persist ? "" : JSON.stringify(list.parent);
2255
+ const [stored, setStored] = useState(() => ({
2256
+ scope,
2257
+ selected: /* @__PURE__ */ new Map(),
2258
+ anchor: null
2259
+ }));
2260
+ let state = stored;
2261
+ if (stored.scope !== scope) {
2262
+ state = { scope, selected: /* @__PURE__ */ new Map(), anchor: null };
2263
+ setStored(state);
2438
2264
  }
2439
- return {
2440
- folders: [...folders.values()].sort(
2441
- (a, b) => a.name.localeCompare(b.name, void 0, {
2442
- numeric: true,
2443
- sensitivity: "base"
2444
- })
2265
+ const loaded = useMemo(
2266
+ () => new Map(list.entries.map((entry) => [entry.key, entry])),
2267
+ [list.entries]
2268
+ );
2269
+ const selectable = useMemo(
2270
+ () => list.entries.filter((entry) => canSelect(entry)),
2271
+ [canSelect, list.entries]
2272
+ );
2273
+ const selected = useMemo(() => {
2274
+ const result = [];
2275
+ for (const [key, entry] of state.selected) {
2276
+ const current = loaded.get(key);
2277
+ if (current) result.push(current);
2278
+ else if (persist) result.push(entry);
2279
+ }
2280
+ return result;
2281
+ }, [loaded, persist, state.selected]);
2282
+ const live = useLiveRef({
2283
+ mode,
2284
+ persist,
2285
+ scope,
2286
+ loaded,
2287
+ selectable,
2288
+ canSelect
2289
+ });
2290
+ const optionsRef = useLiveRef(options);
2291
+ const selectedRef = useLiveRef(selected);
2292
+ const baseOf = useCallback(
2293
+ (previous) => {
2294
+ const next = /* @__PURE__ */ new Map();
2295
+ if (previous.scope !== live.current.scope) return next;
2296
+ for (const [key, entry] of previous.selected) {
2297
+ const current = live.current.loaded.get(key);
2298
+ if (current) next.set(key, current);
2299
+ else if (live.current.persist) next.set(key, entry);
2300
+ }
2301
+ return next;
2302
+ },
2303
+ [live]
2304
+ );
2305
+ const toggle = useCallback(
2306
+ (key, toggleOptions = {}) => {
2307
+ const { canSelect: allowed, loaded: rows, mode: current } = live.current;
2308
+ const entry = rows.get(key);
2309
+ if (!entry || !allowed(entry)) return;
2310
+ setStored((previous) => {
2311
+ const base = baseOf(previous);
2312
+ const value = toggleOptions.value ?? !base.has(key);
2313
+ const next = {
2314
+ scope: live.current.scope,
2315
+ selected: base,
2316
+ anchor: key
2317
+ };
2318
+ if (current === "single") {
2319
+ return { ...next, selected: new Map(value ? [[key, entry]] : []) };
2320
+ }
2321
+ const range = toggleOptions.range ? rangeBetween(live.current.selectable, previous.anchor, key) : null;
2322
+ if (range) {
2323
+ for (const item of range) {
2324
+ if (value) base.set(item.key, item);
2325
+ else base.delete(item.key);
2326
+ }
2327
+ return { ...next, anchor: previous.anchor };
2328
+ }
2329
+ if (value) base.set(key, entry);
2330
+ else base.delete(key);
2331
+ return next;
2332
+ });
2333
+ },
2334
+ [baseOf, live]
2335
+ );
2336
+ const select = useCallback(
2337
+ (keys) => {
2338
+ const { canSelect: allowed, loaded: rows, mode: current } = live.current;
2339
+ const entries = toKeys(keys).flatMap((key) => {
2340
+ const entry = rows.get(key);
2341
+ return entry && allowed(entry) ? [entry] : [];
2342
+ });
2343
+ if (entries.length === 0) return;
2344
+ setStored((previous) => {
2345
+ const base = current === "single" ? /* @__PURE__ */ new Map() : baseOf(previous);
2346
+ const picked = current === "single" ? entries.slice(-1) : entries;
2347
+ for (const entry of picked) base.set(entry.key, entry);
2348
+ return {
2349
+ scope: live.current.scope,
2350
+ selected: base,
2351
+ anchor: picked.at(-1)?.key ?? previous.anchor
2352
+ };
2353
+ });
2354
+ },
2355
+ [baseOf, live]
2356
+ );
2357
+ const deselect = useCallback(
2358
+ (keys) => {
2359
+ const drop = toKeys(keys);
2360
+ if (drop.length === 0) return;
2361
+ setStored((previous) => {
2362
+ const base = baseOf(previous);
2363
+ for (const key of drop) base.delete(key);
2364
+ return { ...previous, scope: live.current.scope, selected: base };
2365
+ });
2366
+ },
2367
+ [baseOf, live]
2368
+ );
2369
+ const selectAll = useCallback(() => {
2370
+ if (live.current.mode === "single") return;
2371
+ select(live.current.selectable.map((entry) => entry.key));
2372
+ }, [live, select]);
2373
+ const clear = useCallback(() => {
2374
+ setStored({ scope: live.current.scope, selected: /* @__PURE__ */ new Map(), anchor: null });
2375
+ }, [live]);
2376
+ const signature = selected.map((entry) => entry.key).join("\0");
2377
+ const notifiedRef = useRef(signature);
2378
+ useEffect(() => {
2379
+ if (notifiedRef.current === signature) return;
2380
+ notifiedRef.current = signature;
2381
+ optionsRef.current.onSelectionChange?.(selectedRef.current);
2382
+ }, [optionsRef, selectedRef, signature]);
2383
+ const selectedKeys = useMemo(
2384
+ () => new Set(selected.map((entry) => entry.key)),
2385
+ [selected]
2386
+ );
2387
+ const selectedItems = useMemo(
2388
+ () => selected.flatMap((entry) => entry.kind === "file" ? [entry.item] : []),
2389
+ [selected]
2390
+ );
2391
+ const selectedFolders = useMemo(
2392
+ () => selected.flatMap(
2393
+ (entry) => entry.kind === "folder" ? [entry.folder] : []
2445
2394
  ),
2446
- items
2395
+ [selected]
2396
+ );
2397
+ const isSelected = useCallback(
2398
+ (key) => selectedKeys.has(key),
2399
+ [selectedKeys]
2400
+ );
2401
+ return {
2402
+ mode,
2403
+ persist,
2404
+ selected,
2405
+ selectedKeys,
2406
+ selectedItems,
2407
+ selectedFolders,
2408
+ count: selected.length,
2409
+ isSelecting: selected.length > 0,
2410
+ allSelected: selectable.length > 0 && selectable.every((entry) => selectedKeys.has(entry.key)),
2411
+ selectableCount: selectable.length,
2412
+ isSelected,
2413
+ canSelect,
2414
+ toggle,
2415
+ select,
2416
+ deselect,
2417
+ selectAll,
2418
+ clear
2447
2419
  };
2448
2420
  }
2449
- function normalizeFolder(folder) {
2450
- if (folder == null) return null;
2451
- const parts = [];
2452
- for (const raw of folder.split("/")) {
2453
- const part = raw.trim();
2454
- if (!part || part === ".") continue;
2455
- if (part === "..") {
2456
- parts.pop();
2457
- continue;
2458
- }
2459
- parts.push(part);
2421
+ function toKeys(keys) {
2422
+ return typeof keys === "string" ? [keys] : keys;
2423
+ }
2424
+ function rangeBetween(selectable, anchor, key) {
2425
+ if (anchor == null) return null;
2426
+ const from = selectable.findIndex((entry) => entry.key === anchor);
2427
+ const to = selectable.findIndex((entry) => entry.key === key);
2428
+ if (from < 0 || to < 0) return null;
2429
+ return selectable.slice(Math.min(from, to), Math.max(from, to) + 1);
2430
+ }
2431
+ function useFormatAcceptLabels() {
2432
+ const t = useTranslations();
2433
+ const groups = useMemo(
2434
+ () => ({
2435
+ image: t("Images", { note: "file type group" }),
2436
+ video: t("Videos", { note: "file type group" }),
2437
+ audio: t("Audio", { note: "file type group" }),
2438
+ text: t("Text files", { note: "file type group" }),
2439
+ font: t("Fonts", { note: "file type group" })
2440
+ }),
2441
+ [t]
2442
+ );
2443
+ return useCallback(
2444
+ (accept) => formatAcceptLabels(accept, { groups }),
2445
+ [groups]
2446
+ );
2447
+ }
2448
+ function useFormatFileSize() {
2449
+ const locale = useContext(S3LocaleContext);
2450
+ const t = useTranslations();
2451
+ return useMemo(() => {
2452
+ const units = {
2453
+ B: t("B", { note: "file size unit" }),
2454
+ KB: t("KB", { note: "file size unit" }),
2455
+ MB: t("MB", { note: "file size unit" }),
2456
+ GB: t("GB", { note: "file size unit" }),
2457
+ TB: t("TB", { note: "file size unit" }),
2458
+ PB: t("PB", { note: "file size unit" }),
2459
+ EB: t("EB", { note: "file size unit" })
2460
+ };
2461
+ return (bytes) => formatFileSize(bytes, { locale, units });
2462
+ }, [locale, t]);
2463
+ }
2464
+ function useFormatNumber() {
2465
+ const locale = useContext(S3LocaleContext);
2466
+ return useCallback(
2467
+ (value) => locale ? numberFormat(locale).format(value) : String(value),
2468
+ [locale]
2469
+ );
2470
+ }
2471
+ var numberFormats = /* @__PURE__ */ new Map();
2472
+ function numberFormat(locale) {
2473
+ let format = numberFormats.get(locale);
2474
+ if (!format) {
2475
+ format = new Intl.NumberFormat(locale);
2476
+ numberFormats.set(locale, format);
2477
+ }
2478
+ return format;
2479
+ }
2480
+
2481
+ // src/helpers/format-dimah-error.tsx
2482
+ function useFormatDimahError() {
2483
+ const t = useTranslations();
2484
+ const formatFileSize2 = useFormatFileSize();
2485
+ const formatNumber = useFormatNumber();
2486
+ return useCallback(
2487
+ (thrown) => {
2488
+ const unknownError = t("Something went wrong", { note: "API error" });
2489
+ const error = isRawAPIError(thrown) ? toClientError(thrown) : thrown;
2490
+ if (!isAPIError(error)) {
2491
+ return error instanceof Error && error.message ? error.message : unknownError;
2492
+ }
2493
+ const { code, params = {} } = error;
2494
+ if (!isCatalogCode(code)) return error.message || unknownError;
2495
+ const text = (key) => readString(params, key);
2496
+ const count = (key) => {
2497
+ const value = readNumber(params, key);
2498
+ return value === void 0 ? void 0 : formatNumber(value);
2499
+ };
2500
+ switch (code) {
2501
+ case "VALIDATION_ERROR":
2502
+ return t("Invalid request", { note: "API error" });
2503
+ case "REQUEST_TOO_LARGE":
2504
+ return t("Request is too large", { note: "API error" });
2505
+ case "UNSUPPORTED_MEDIA_TYPE":
2506
+ return t("Request format is not supported", { note: "API error" });
2507
+ case "NOT_FOUND":
2508
+ return t("Not found", { note: "API error" });
2509
+ case "UNAUTHORIZED":
2510
+ return t("Unauthorized", { note: "API error" });
2511
+ case "FORBIDDEN":
2512
+ return t("Access denied", { note: "API error" });
2513
+ case "CONFLICT":
2514
+ return t("Another change happened at the same time. Try again.", {
2515
+ note: "API error"
2516
+ });
2517
+ case "INTERNAL_ERROR":
2518
+ case "HOOK_FAILED":
2519
+ case "UNKNOWN_ERROR":
2520
+ return unknownError;
2521
+ case "S3_NETWORK_ERROR": {
2522
+ const storageCode = text("code");
2523
+ return storageCode ? t("Could not reach storage ({code})", {
2524
+ note: "API error",
2525
+ variables: { code: storageCode }
2526
+ }) : t("Could not reach storage", { note: "API error" });
2527
+ }
2528
+ case "UNKNOWN_ROUTE":
2529
+ return t("Unknown file route", { note: "API error" });
2530
+ case "FEATURE_DISABLED":
2531
+ switch (text("feature")) {
2532
+ case "upload":
2533
+ return t("Uploads are disabled", { note: "API error" });
2534
+ case "download":
2535
+ return t("Downloads are disabled", { note: "API error" });
2536
+ case "delete":
2537
+ return t("Deleting is disabled", { note: "API error" });
2538
+ case "multipart":
2539
+ return t("Large uploads are disabled", { note: "API error" });
2540
+ case "proxy":
2541
+ return t("Streaming downloads are disabled", {
2542
+ note: "API error"
2543
+ });
2544
+ default:
2545
+ return t("This feature is disabled", { note: "API error" });
2546
+ }
2547
+ case "KEY_INVALID":
2548
+ return t("Object key is invalid", { note: "API error" });
2549
+ case "OBJECT_NOT_FOUND":
2550
+ return t("File not found", { note: "API error" });
2551
+ case "RANGE_NOT_SATISFIABLE":
2552
+ return t("Requested range is not available", { note: "API error" });
2553
+ case "PRECONDITION_FAILED":
2554
+ return t("The file has changed", { note: "API error" });
2555
+ case "FILE_EMPTY":
2556
+ return t("File is empty", { note: "API error" });
2557
+ case "FILE_TOO_LARGE": {
2558
+ const maxFileSize = readNumber(params, "maxFileSize");
2559
+ return maxFileSize === void 0 ? t("File is too large", { note: "API error" }) : t("File size exceeds {size} limit", {
2560
+ note: "API error",
2561
+ variables: { size: formatFileSize2(maxFileSize) }
2562
+ });
2563
+ }
2564
+ case "FILE_TYPE_NOT_ALLOWED": {
2565
+ const type = text("type");
2566
+ return type ? t('File type "{type}" is not allowed', {
2567
+ note: "API error",
2568
+ variables: { type }
2569
+ }) : t("File type is not allowed", { note: "API error" });
2570
+ }
2571
+ case "FILE_CONTENT_MISMATCH":
2572
+ return t("File content does not match its type", {
2573
+ note: "API error"
2574
+ });
2575
+ case "CHECKSUM_REQUIRED":
2576
+ return t("A file checksum is required", { note: "API error" });
2577
+ case "QUOTA_EXCEEDED":
2578
+ return text("limit") === "files" ? t("File limit reached", { note: "API error" }) : t("Storage quota exceeded", { note: "API error" });
2579
+ case "UPLOAD_TICKET_INVALID":
2580
+ return t("Upload session is invalid", { note: "API error" });
2581
+ case "UPLOAD_TICKET_EXPIRED":
2582
+ return t("Upload session has expired", { note: "API error" });
2583
+ case "UPLOAD_SIZE_MISMATCH":
2584
+ return t("Uploaded size does not match the file", {
2585
+ note: "API error"
2586
+ });
2587
+ case "MULTIPART_PART_MISSING": {
2588
+ const partNumber = count("partNumber");
2589
+ return partNumber ? t("Uploaded part {partNumber} was not found", {
2590
+ note: "API error",
2591
+ variables: { partNumber }
2592
+ }) : t("An uploaded part was not found", { note: "API error" });
2593
+ }
2594
+ case "MULTIPART_PART_INVALID":
2595
+ return t("Upload part is out of range", { note: "API error" });
2596
+ case "OBJECT_EXISTS":
2597
+ return t("A file with this name already exists", {
2598
+ note: "API error"
2599
+ });
2600
+ case "FOLDER_INVALID":
2601
+ return t("Folder name is invalid", { note: "API error" });
2602
+ case "FOLDER_EXISTS":
2603
+ return t("A folder with this name already exists", {
2604
+ note: "API error"
2605
+ });
2606
+ case "FOLDER_NOT_EMPTY":
2607
+ return t("Folder is not empty", { note: "API error" });
2608
+ case "TOO_MANY_FILES": {
2609
+ const maxFiles = count("maxFiles");
2610
+ return maxFiles ? t("Too many files (max {maxFiles})", {
2611
+ note: "API error",
2612
+ variables: { maxFiles }
2613
+ }) : t("Too many files", { note: "API error" });
2614
+ }
2615
+ case "NETWORK_ERROR":
2616
+ return t("Network error", { note: "API error" });
2617
+ case "UPLOAD_FAILED":
2618
+ return t("Upload failed", { note: "API error" });
2619
+ case "DOWNLOAD_FAILED":
2620
+ return t("Download failed", { note: "API error" });
2621
+ case "CHECKSUM_MISMATCH":
2622
+ return t("File changed during upload", { note: "API error" });
2623
+ case "PARTIAL_FAILURE": {
2624
+ const failed = count("failed");
2625
+ const total = count("total");
2626
+ return failed && total ? t("{failed} of {total} failed", {
2627
+ note: "API error",
2628
+ variables: { failed, total }
2629
+ }) : t("Some operations failed", { note: "API error" });
2630
+ }
2631
+ }
2632
+ },
2633
+ [t, formatFileSize2, formatNumber]
2634
+ );
2635
+ }
2636
+ function isCatalogCode(code) {
2637
+ return Object.hasOwn(S3_ERROR_CODES, code);
2638
+ }
2639
+ function readString(params, key) {
2640
+ const value = params[key];
2641
+ return typeof value === "string" && value !== "" ? value : void 0;
2642
+ }
2643
+ function readNumber(params, key) {
2644
+ const value = params[key];
2645
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2646
+ }
2647
+ function useFormatEta() {
2648
+ const t = useTranslations();
2649
+ const formatNumber = useFormatNumber();
2650
+ return useCallback(
2651
+ ({ loaded, total, speed }) => {
2652
+ const remaining = total - loaded;
2653
+ if (!speed || speed <= 0 || remaining <= 0) return null;
2654
+ const seconds = Math.ceil(remaining / speed);
2655
+ if (seconds < 60) {
2656
+ return t("{seconds}s left", {
2657
+ note: "time remaining",
2658
+ variables: { seconds: formatNumber(seconds) }
2659
+ });
2660
+ }
2661
+ const totalMinutes = Math.ceil(seconds / 60);
2662
+ if (totalMinutes < 60) {
2663
+ return t("{minutes}m left", {
2664
+ note: "time remaining",
2665
+ variables: { minutes: formatNumber(totalMinutes) }
2666
+ });
2667
+ }
2668
+ const hours = formatNumber(Math.floor(totalMinutes / 60));
2669
+ const minutes = totalMinutes % 60;
2670
+ if (minutes === 0) {
2671
+ return t("{hours}h left", {
2672
+ note: "time remaining",
2673
+ variables: { hours }
2674
+ });
2675
+ }
2676
+ return t("{hours}h {minutes}m left", {
2677
+ note: "time remaining",
2678
+ variables: { hours, minutes: formatNumber(minutes) }
2679
+ });
2680
+ },
2681
+ [t, formatNumber]
2682
+ );
2683
+ }
2684
+ function useFormatSpeed() {
2685
+ const t = useTranslations();
2686
+ const formatFileSize2 = useFormatFileSize();
2687
+ return useCallback(
2688
+ (bytesPerSecond) => t("{size}/s", {
2689
+ note: "transfer speed",
2690
+ variables: { size: formatFileSize2(bytesPerSecond) }
2691
+ }),
2692
+ [t, formatFileSize2]
2693
+ );
2694
+ }
2695
+ function useFormatDate() {
2696
+ const locale = useContext(S3LocaleContext);
2697
+ return useCallback(
2698
+ (value, options) => {
2699
+ const time = toTimestamp(value);
2700
+ if (time == null) return "";
2701
+ return dateFormat(locale ?? "en", options).format(time);
2702
+ },
2703
+ [locale]
2704
+ );
2705
+ }
2706
+ var DEFAULT_DATE_OPTIONS = {
2707
+ dateStyle: "medium"
2708
+ };
2709
+ var dateFormats = /* @__PURE__ */ new Map();
2710
+ function dateFormat(locale, options = DEFAULT_DATE_OPTIONS) {
2711
+ const id = `${locale}\0${JSON.stringify(options)}`;
2712
+ let format = dateFormats.get(id);
2713
+ if (!format) {
2714
+ format = new Intl.DateTimeFormat(locale, options);
2715
+ dateFormats.set(id, format);
2460
2716
  }
2461
- return parts.length > 0 ? parts.join("/") : null;
2717
+ return format;
2462
2718
  }
2463
2719
 
2464
- export { DEFAULT_MULTIPART_THRESHOLD, S3Provider, S3UploadError, createLocalStorageStore, createMemoryStore, createS3Client, defineApi, formatAcceptLabels, formatEta, formatSpeed, formatUploadProgress, isFetchDownload, loadRouteCatalog, mergeRouteUploadPolicy, multipartResumeKey, readObjectListLevel, resolveRouteUploadPolicy, uploadFile, uploadFiles, useApi, useDelete, useDownload, useFormatDimahError, useFormatFileSize, useFormatNumber, useFormatValidateFileError, useObjectList, useObjectUrl, useRouteUploadPolicy, useUpload };
2720
+ export { S3Provider, createS3Client, useApi, useDelete, useDownload, useFetchDownload, useFormatAcceptLabels, useFormatDate, useFormatDimahError, useFormatEta, useFormatFileSize, useFormatNumber, useFormatSpeed, useObjectList, useObjectListSelection, useObjectUrl, useRouteUploadPolicy, useUpload };
2465
2721
  //# sourceMappingURL=index.js.map
2466
2722
  //# sourceMappingURL=index.js.map