@widgetic/file-browser 0.5.47 → 0.5.49

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 (34) hide show
  1. package/dist/components/core/Dropzone.svelte +42 -2
  2. package/dist/components/core/FileBrowser.svelte +221 -13
  3. package/dist/components/core/FileUploader.svelte +124 -41
  4. package/dist/components/core/RecentFiles.svelte +54 -16
  5. package/dist/components/core/SearchDropdown.svelte +6 -8
  6. package/dist/components/core/UploadPanel.svelte +7 -0
  7. package/dist/components/core/UploadPanel.svelte.d.ts +4 -0
  8. package/dist/components/core/UploadRow.svelte +9 -4
  9. package/dist/components/core/UploadRow.svelte.d.ts +2 -0
  10. package/dist/components/core/dropzoneClick.d.ts +28 -0
  11. package/dist/components/core/dropzoneClick.js +31 -0
  12. package/dist/components/ui/DropdownMenu.svelte +1 -1
  13. package/dist/i18n/messages.d.ts +13 -0
  14. package/dist/i18n/messages.js +13 -0
  15. package/dist/stores/uploadApiStore.d.ts +10 -0
  16. package/dist/utils/deleteSelectionAction.d.ts +26 -0
  17. package/dist/utils/deleteSelectionAction.js +23 -0
  18. package/dist/utils/pendingUploadDeletes.d.ts +102 -0
  19. package/dist/utils/pendingUploadDeletes.js +224 -0
  20. package/dist/utils/removeItems.d.ts +30 -0
  21. package/dist/utils/removeItems.js +92 -0
  22. package/dist/utils/searchDropdownPhase.d.ts +14 -3
  23. package/dist/utils/searchDropdownPhase.js +12 -8
  24. package/dist/utils/uploadAuth.d.ts +24 -0
  25. package/dist/utils/uploadAuth.js +65 -0
  26. package/dist/utils/uploadLimits.d.ts +76 -0
  27. package/dist/utils/uploadLimits.js +170 -0
  28. package/dist/utils/uploadRefusals.d.ts +42 -0
  29. package/dist/utils/uploadRefusals.js +70 -0
  30. package/dist/utils/videoFrame.d.ts +23 -0
  31. package/dist/utils/videoFrame.js +26 -0
  32. package/dist/utils/widgeticDelete.js +5 -3
  33. package/dist/utils/widgeticUpload.js +10 -4
  34. package/package.json +3 -3
@@ -0,0 +1,224 @@
1
+ import { deleteEntity, ensureCacheOwnerFromSessionHint, getCacheOwner, readAllEntitiesForKind, writeEntity } from '@widgetic/cache-layer';
2
+ /**
3
+ * The deletes the API has still to hear about.
4
+ *
5
+ * When the visitor deletes files they leave the screen at once; the API is told afterwards, in the background. This queue
6
+ * is what makes "afterwards" safe: every upload that was taken off the screen is written down in Dexie (the local database
7
+ * of `@widgetic/cache-layer`) before anything is sent, one record per upload, and is only forgotten once the API has
8
+ * answered. So a reload, a closed tab or a network that comes and goes neither brings the files back nor loses the delete:
9
+ * - the next time the File Browser opens it finishes the queue, and does not list a file whose delete is still waiting;
10
+ * - a network error, a 5xx or a 401 is tried again, a little later each time (1 s, 2 s, 4 s … up to a minute);
11
+ * - an answer that will never change (the API says "not allowed", say) ends the record and tells the File Browser, which
12
+ * puts the file back and says so.
13
+ *
14
+ * It keeps its own kind of record next to the others in the entity store rather than using the shared mutation outbox of the
15
+ * cache layer: that outbox hands every row, whatever its kind, to the one processor that drains it (the brand kit's), so a
16
+ * row of another kind would be read by the wrong code.
17
+ */
18
+ /** The kind of entity the records are saved under (the key is `{owner}:fileBrowserPendingDeletes:{uploadId}`). */
19
+ export const PENDING_DELETES_KIND = 'fileBrowserPendingDeletes';
20
+ /** After this many failed tries the API is taken to be unreachable for good, and the delete is given up. */
21
+ export const PENDING_DELETE_MAX_ATTEMPTS = 8;
22
+ /** How many deletes are sent at the same time. */
23
+ export const PENDING_DELETE_CONCURRENCY = 4;
24
+ const BACKOFF_FIRST_MS = 1000;
25
+ const BACKOFF_CAP_MS = 60_000;
26
+ /** The queue never wakes up more often than this to look at records that are not due yet. */
27
+ const MIN_WAKE_UP_MS = 250;
28
+ /** How long to wait before asking again, after `attempts` tries have failed: 1 s, 2 s, 4 s … never more than a minute. */
29
+ export function deleteBackoffMs(attempts) {
30
+ return Math.min(BACKOFF_FIRST_MS * 2 ** Math.max(0, attempts - 1), BACKOFF_CAP_MS);
31
+ }
32
+ /**
33
+ * What an HTTP answer means for a delete. 404 and 410 mean the upload is already gone, which is what was wanted. The other
34
+ * 4xx answers (not allowed, malformed) will not change by asking again; 401 (the session is being renewed), 408, 425, 429 and
35
+ * every 5xx will. No status at all is a network error: the same.
36
+ */
37
+ export function classifyDeleteStatus(status) {
38
+ if (status === undefined || status === 0)
39
+ return 'retry';
40
+ if (status === 404 || status === 410)
41
+ return 'ok';
42
+ if (status === 401 || status === 408 || status === 425 || status === 429)
43
+ return 'retry';
44
+ if (status >= 500)
45
+ return 'retry';
46
+ if (status >= 400)
47
+ return 'permanent';
48
+ return 'ok';
49
+ }
50
+ export function createMemoryPendingDeleteStore() {
51
+ const records = new Map();
52
+ return {
53
+ async list() {
54
+ return [...records.values()].map((record) => ({ ...record }));
55
+ },
56
+ async put(record) {
57
+ records.set(record.uploadId, { ...record });
58
+ },
59
+ async remove(uploadId) {
60
+ records.delete(uploadId);
61
+ }
62
+ };
63
+ }
64
+ function isPendingUploadDelete(value) {
65
+ if (!value || typeof value !== 'object')
66
+ return false;
67
+ const record = value;
68
+ return typeof record.uploadId === 'string' && typeof record.attempts === 'number' && typeof record.nextAttemptAt === 'number';
69
+ }
70
+ /** The records of one owner (one signed-in person), kept in Dexie through the entity store of the cache layer. */
71
+ export function createCacheLayerPendingDeleteStore(ownerId) {
72
+ return {
73
+ async list() {
74
+ const all = await readAllEntitiesForKind(ownerId, PENDING_DELETES_KIND);
75
+ return Object.values(all).filter(isPendingUploadDelete);
76
+ },
77
+ async put(record) {
78
+ await writeEntity(ownerId, PENDING_DELETES_KIND, record.uploadId, record);
79
+ },
80
+ async remove(uploadId) {
81
+ await deleteEntity(ownerId, PENDING_DELETES_KIND, uploadId);
82
+ }
83
+ };
84
+ }
85
+ export function createPendingDeleteQueue(options) {
86
+ const { store } = options;
87
+ const now = options.now ?? (() => Date.now());
88
+ const maxAttempts = options.maxAttempts ?? PENDING_DELETE_MAX_ATTEMPTS;
89
+ const concurrency = Math.max(1, options.concurrency ?? PENDING_DELETE_CONCURRENCY);
90
+ const schedule = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
91
+ const cancel = options.cancel ?? ((handle) => clearTimeout(handle));
92
+ let running = null;
93
+ let passRequested = false;
94
+ let wakeUp = null;
95
+ // What the timer runs again: the latest processor and hooks anyone gave.
96
+ let lastProcess = null;
97
+ let lastHooks = {};
98
+ function clearWakeUp() {
99
+ if (wakeUp !== null)
100
+ cancel(wakeUp);
101
+ wakeUp = null;
102
+ }
103
+ async function settleRecord(record, process, hooks) {
104
+ let attempt;
105
+ try {
106
+ attempt = await process(record);
107
+ }
108
+ catch (error) {
109
+ attempt = { result: 'retry', message: error instanceof Error ? error.message : String(error) };
110
+ }
111
+ if (attempt.result === 'ok') {
112
+ await store.remove(record.uploadId);
113
+ hooks.onDeleted?.(record);
114
+ return;
115
+ }
116
+ const message = attempt.message ?? '';
117
+ const attempts = record.attempts + 1;
118
+ if (attempt.result === 'permanent' || attempts >= maxAttempts) {
119
+ await store.remove(record.uploadId);
120
+ console.warn(`[FileBrowser] Giving up on deleting "${record.name}" (${attempt.result}, after ${attempts} tries): ${message}`);
121
+ hooks.onGaveUp?.(record, message);
122
+ return;
123
+ }
124
+ await store.put({ ...record, attempts, nextAttemptAt: now() + deleteBackoffMs(attempts), lastError: message || null });
125
+ }
126
+ async function runOnce(process, hooks) {
127
+ for (;;) {
128
+ const due = (await store.list())
129
+ .filter((record) => record.nextAttemptAt <= now())
130
+ .sort((a, b) => a.createdAt - b.createdAt)
131
+ .slice(0, concurrency);
132
+ if (due.length === 0)
133
+ break;
134
+ await Promise.all(due.map((record) => settleRecord(record, process, hooks)));
135
+ }
136
+ // Records that failed and wait for their turn: wake up when the first one is due.
137
+ const waiting = await store.list();
138
+ if (waiting.length > 0) {
139
+ const earliest = Math.min(...waiting.map((record) => record.nextAttemptAt));
140
+ clearWakeUp();
141
+ wakeUp = schedule(() => {
142
+ wakeUp = null;
143
+ if (lastProcess)
144
+ void drain(lastProcess, lastHooks);
145
+ }, Math.max(earliest - now(), MIN_WAKE_UP_MS));
146
+ }
147
+ }
148
+ function drain(process, hooks = {}) {
149
+ lastProcess = process;
150
+ lastHooks = hooks;
151
+ if (running) {
152
+ // Something was written down while the run was finishing: it makes one more pass before it ends.
153
+ passRequested = true;
154
+ return running;
155
+ }
156
+ clearWakeUp();
157
+ running = (async () => {
158
+ try {
159
+ do {
160
+ passRequested = false;
161
+ await runOnce(lastProcess ?? process, lastHooks);
162
+ } while (passRequested);
163
+ }
164
+ catch (error) {
165
+ console.warn('[FileBrowser] The queue of deletes stopped:', error);
166
+ }
167
+ finally {
168
+ running = null;
169
+ }
170
+ })();
171
+ return running;
172
+ }
173
+ return {
174
+ async enqueue(uploads) {
175
+ const existing = new Set((await store.list()).map((record) => record.uploadId));
176
+ const createdAt = now();
177
+ for (const upload of uploads) {
178
+ if (existing.has(upload.uploadId))
179
+ continue;
180
+ existing.add(upload.uploadId);
181
+ await store.put({
182
+ uploadId: upload.uploadId,
183
+ name: upload.name,
184
+ attempts: 0,
185
+ nextAttemptAt: createdAt,
186
+ createdAt,
187
+ lastError: null
188
+ });
189
+ }
190
+ },
191
+ async pendingIds() {
192
+ return new Set((await store.list()).map((record) => record.uploadId));
193
+ },
194
+ drain,
195
+ stop: clearWakeUp
196
+ };
197
+ }
198
+ // ----------------------------------------------------------------------------------------------------------------
199
+ // The queue of this page
200
+ let sharedQueue = null;
201
+ let sharedQueueOwner;
202
+ /**
203
+ * The queue of the signed-in person (the cache owner). Without an owner there is nowhere to keep the records for the next
204
+ * visit, so they are kept in memory: the files still leave the screen at once and the deletes are still retried, but a reload
205
+ * before the API answers forgets them.
206
+ */
207
+ export function getPendingUploadDeleteQueue() {
208
+ let ownerId = null;
209
+ try {
210
+ ensureCacheOwnerFromSessionHint();
211
+ ownerId = getCacheOwner();
212
+ }
213
+ catch (error) {
214
+ console.warn('[FileBrowser] No cache owner for the queue of deletes; keeping it in memory:', error);
215
+ }
216
+ if (!sharedQueue || sharedQueueOwner !== ownerId) {
217
+ sharedQueue?.stop();
218
+ sharedQueue = createPendingDeleteQueue({
219
+ store: ownerId ? createCacheLayerPendingDeleteStore(ownerId) : createMemoryPendingDeleteStore()
220
+ });
221
+ sharedQueueOwner = ownerId;
222
+ }
223
+ return sharedQueue;
224
+ }
@@ -0,0 +1,30 @@
1
+ import type { FileSystemItem } from '../types';
2
+ /**
3
+ * Taking files and folders out of the tree in one step, and putting them back when the API refuses the delete.
4
+ *
5
+ * Both functions return a new root and never change the one they were given (the parts of the tree that did not change are
6
+ * shared), so a screen that still holds the old root is not surprised.
7
+ */
8
+ /** An item that was taken out, and where it sat, so that it can be put back there. */
9
+ export interface RemovedItem {
10
+ item: FileSystemItem;
11
+ /** The id of the folder it sat in, or `null` for the root. */
12
+ parentId: string | null;
13
+ /** Its position among the children of that folder. */
14
+ index: number;
15
+ }
16
+ /**
17
+ * Takes every item whose id is in `ids` out of the tree, at any depth. A folder goes with everything in it (the files in a
18
+ * folder are not listed on their own: they come back with the folder).
19
+ */
20
+ export declare function removeItemsFromTree(root: FileSystemItem, ids: ReadonlySet<string>): {
21
+ root: FileSystemItem;
22
+ removed: RemovedItem[];
23
+ };
24
+ /** Every file in an item: the item itself when it is a file, else the files of its folders, at any depth. */
25
+ export declare function filesOfItems(items: ReadonlyArray<FileSystemItem>): FileSystemItem[];
26
+ /**
27
+ * Puts items back where `removeItemsFromTree` took them from: in their folder, at their position. A folder that is gone too
28
+ * is not made again: the item goes to the root. An item whose id is already in the tree is left as it is.
29
+ */
30
+ export declare function putItemsBackInTree(root: FileSystemItem, removed: ReadonlyArray<RemovedItem>): FileSystemItem;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Takes every item whose id is in `ids` out of the tree, at any depth. A folder goes with everything in it (the files in a
3
+ * folder are not listed on their own: they come back with the folder).
4
+ */
5
+ export function removeItemsFromTree(root, ids) {
6
+ const removed = [];
7
+ function walk(node, parentId) {
8
+ const children = node.children;
9
+ if (!children || children.length === 0)
10
+ return node;
11
+ const kept = [];
12
+ let changed = false;
13
+ children.forEach((child, index) => {
14
+ if (ids.has(child.id)) {
15
+ removed.push({ item: child, parentId, index });
16
+ changed = true;
17
+ return;
18
+ }
19
+ const nextChild = child.type === 'folder' ? walk(child, child.id) : child;
20
+ if (nextChild !== child)
21
+ changed = true;
22
+ kept.push(nextChild);
23
+ });
24
+ return changed ? { ...node, children: kept } : node;
25
+ }
26
+ const nextRoot = walk(root, null);
27
+ return { root: nextRoot, removed };
28
+ }
29
+ /** Every file in an item: the item itself when it is a file, else the files of its folders, at any depth. */
30
+ export function filesOfItems(items) {
31
+ const files = [];
32
+ function walk(node) {
33
+ if (node.type === 'file') {
34
+ files.push(node);
35
+ return;
36
+ }
37
+ for (const child of node.children ?? [])
38
+ walk(child);
39
+ }
40
+ for (const item of items)
41
+ walk(item);
42
+ return files;
43
+ }
44
+ /**
45
+ * Puts items back where `removeItemsFromTree` took them from: in their folder, at their position. A folder that is gone too
46
+ * is not made again: the item goes to the root. An item whose id is already in the tree is left as it is.
47
+ */
48
+ export function putItemsBackInTree(root, removed) {
49
+ if (removed.length === 0)
50
+ return root;
51
+ const knownIds = new Set();
52
+ (function collect(node) {
53
+ knownIds.add(node.id);
54
+ for (const child of node.children ?? [])
55
+ collect(child);
56
+ })(root);
57
+ // Ascending positions, so that several items of one folder go back one after the other without moving each other.
58
+ const ordered = [...removed].sort((a, b) => a.index - b.index);
59
+ const byParent = new Map();
60
+ for (const entry of ordered) {
61
+ if (knownIds.has(entry.item.id))
62
+ continue;
63
+ const parentId = entry.parentId !== null && knownIds.has(entry.parentId) ? entry.parentId : null;
64
+ byParent.set(parentId, [...(byParent.get(parentId) ?? []), entry]);
65
+ }
66
+ if (byParent.size === 0)
67
+ return root;
68
+ function withItemsInserted(children, entries) {
69
+ const next = [...children];
70
+ for (const entry of entries)
71
+ next.splice(Math.min(entry.index, next.length), 0, entry.item);
72
+ return next;
73
+ }
74
+ function walk(node, nodeKey) {
75
+ const entries = byParent.get(nodeKey);
76
+ let children = node.children;
77
+ let changed = false;
78
+ if (children) {
79
+ const walked = children.map((child) => (child.type === 'folder' ? walk(child, child.id) : child));
80
+ if (walked.some((child, position) => child !== children[position])) {
81
+ children = walked;
82
+ changed = true;
83
+ }
84
+ }
85
+ if (entries && entries.length > 0) {
86
+ children = withItemsInserted(children ?? [], entries);
87
+ changed = true;
88
+ }
89
+ return changed ? { ...node, children } : node;
90
+ }
91
+ return walk(root, null);
92
+ }
@@ -1,4 +1,11 @@
1
- export type SearchDropdownPhase = 'idle' | 'loading' | 'results' | 'empty';
1
+ /**
2
+ * What the search panel draws:
3
+ * - `idle`: nothing (closed, or no text).
4
+ * - `pending`: the first answer for the typed text is not there yet. Nothing is drawn: no "Loading…" row and no empty card.
5
+ * - `results`: the list of what was found.
6
+ * - `empty`: the card that says nothing was found.
7
+ */
8
+ export type SearchDropdownPhase = 'idle' | 'pending' | 'results' | 'empty';
2
9
  export type SearchDropdownPhaseInput = {
3
10
  panelOpen: boolean;
4
11
  trimmedTerm: string;
@@ -9,9 +16,13 @@ export type SearchDropdownPhaseInput = {
9
16
  resultCount: number;
10
17
  };
11
18
  /**
12
- * When the panel is open with text: never show the empty card while the query for the current text is pending.
13
- * `empty` only after the settled term matches the typed term and the result list is empty.
19
+ * When the panel is open with text, it never shows a loading state. While the search for the typed text is pending, the
20
+ * panel keeps what it shows: the previous results, or the empty card when the last answer was "nothing found" (so the card
21
+ * does not blink out and back in while the person goes on typing). Before the first answer there is nothing to keep, so
22
+ * nothing is drawn (the empty card is never drawn before an answer exists).
14
23
  */
15
24
  export declare function resolveSearchDropdownPhase(input: SearchDropdownPhaseInput): SearchDropdownPhase;
16
25
  export declare function shouldShowSearchEmptyState(phase: SearchDropdownPhase): boolean;
17
26
  export declare function shouldShowSearchResultsList(phase: SearchDropdownPhase, resultCount: number): boolean;
27
+ /** The card under the field is drawn only for a list or for the empty message; while the first answer is pending it is not drawn at all. */
28
+ export declare function shouldShowSearchPanel(phase: SearchDropdownPhase): boolean;
@@ -1,23 +1,27 @@
1
1
  /**
2
- * When the panel is open with text: never show the empty card while the query for the current text is pending.
3
- * `empty` only after the settled term matches the typed term and the result list is empty.
2
+ * When the panel is open with text, it never shows a loading state. While the search for the typed text is pending, the
3
+ * panel keeps what it shows: the previous results, or the empty card when the last answer was "nothing found" (so the card
4
+ * does not blink out and back in while the person goes on typing). Before the first answer there is nothing to keep, so
5
+ * nothing is drawn (the empty card is never drawn before an answer exists).
4
6
  */
5
7
  export function resolveSearchDropdownPhase(input) {
6
8
  const { panelOpen, trimmedTerm, settledTerm, queryInFlight, resultCount } = input;
7
9
  if (!panelOpen || !trimmedTerm)
8
10
  return 'idle';
9
- if (queryInFlight || settledTerm !== trimmedTerm) {
10
- if (resultCount > 0)
11
- return 'results';
12
- return 'loading';
13
- }
14
11
  if (resultCount > 0)
15
12
  return 'results';
13
+ const answerIsPending = queryInFlight || settledTerm !== trimmedTerm;
14
+ if (answerIsPending && settledTerm === '')
15
+ return 'pending';
16
16
  return 'empty';
17
17
  }
18
18
  export function shouldShowSearchEmptyState(phase) {
19
19
  return phase === 'empty';
20
20
  }
21
21
  export function shouldShowSearchResultsList(phase, resultCount) {
22
- return resultCount > 0 && (phase === 'results' || phase === 'loading');
22
+ return resultCount > 0 && phase === 'results';
23
+ }
24
+ /** The card under the field is drawn only for a list or for the empty message; while the first answer is pending it is not drawn at all. */
25
+ export function shouldShowSearchPanel(phase) {
26
+ return phase === 'results' || phase === 'empty';
23
27
  }
@@ -0,0 +1,24 @@
1
+ import type { FileBrowserUploadConfig } from '../stores/uploadApiStore';
2
+ /** A token without a leading "Bearer ", which every request adds itself. */
3
+ export declare function bareToken(token: string): string;
4
+ /**
5
+ * The token to call the API with now: the one the page's `getAccessToken('initial')` gives, else the token the config was
6
+ * set with. A function that throws or answers with nothing falls back to the config's token; the request that follows
7
+ * says whether that one is still good.
8
+ */
9
+ export declare function currentAccessToken(config: FileBrowserUploadConfig): Promise<string>;
10
+ /**
11
+ * A new token after the API refused `refusedToken`, or `null` when there is none to try: the page gave no function, its
12
+ * function failed, or it handed back the token that was refused (asking again with it would only fail again).
13
+ */
14
+ export declare function renewedAccessToken(config: FileBrowserUploadConfig, refusedToken: string): Promise<string | null>;
15
+ /**
16
+ * Runs a request that ends in an answer with an HTTP `status` (a fetch `Response`, an upload result): with the current
17
+ * token, and once more with a fresh one when the API answers 401. Any other answer, and a 401 that no fresh token can
18
+ * fix, is returned as it is. A request whose `signal` was aborted is not started again.
19
+ */
20
+ export declare function withTokenRetriedOnce<Answer extends {
21
+ status?: number;
22
+ }>(config: FileBrowserUploadConfig, request: (accessToken: string) => Promise<Answer>, options?: {
23
+ signal?: AbortSignal;
24
+ }): Promise<Answer>;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The access token of a call to the Widgetic API, and what to do when the API refuses it.
3
+ *
4
+ * A page that sets the upload config holds a token that was good at that moment; its session is renewed while the
5
+ * File Browser stays open, and a token kept from before the renewal is refused with a 401 ("I have to refresh and try
6
+ * again"). A page that gives `getAccessToken` has the File Browser ask for the token each time it is needed, and ask
7
+ * for a fresh one when the API still refuses it, so the visitor never sees the failure.
8
+ */
9
+ const BEARER_PREFIX = /^Bearer\s+/i;
10
+ /** A token without a leading "Bearer ", which every request adds itself. */
11
+ export function bareToken(token) {
12
+ return token.trim().replace(BEARER_PREFIX, '');
13
+ }
14
+ /**
15
+ * The token to call the API with now: the one the page's `getAccessToken('initial')` gives, else the token the config was
16
+ * set with. A function that throws or answers with nothing falls back to the config's token; the request that follows
17
+ * says whether that one is still good.
18
+ */
19
+ export async function currentAccessToken(config) {
20
+ if (typeof config.getAccessToken === 'function') {
21
+ try {
22
+ const fromPage = await config.getAccessToken('initial');
23
+ if (typeof fromPage === 'string' && bareToken(fromPage) !== '')
24
+ return bareToken(fromPage);
25
+ }
26
+ catch (error) {
27
+ console.warn('[FileBrowser] The page could not give an access token; using the one it set', error);
28
+ }
29
+ }
30
+ return bareToken(config.accessToken);
31
+ }
32
+ /**
33
+ * A new token after the API refused `refusedToken`, or `null` when there is none to try: the page gave no function, its
34
+ * function failed, or it handed back the token that was refused (asking again with it would only fail again).
35
+ */
36
+ export async function renewedAccessToken(config, refusedToken) {
37
+ if (typeof config.getAccessToken !== 'function')
38
+ return null;
39
+ try {
40
+ const renewed = await config.getAccessToken('expired', refusedToken);
41
+ if (typeof renewed !== 'string' || bareToken(renewed) === '')
42
+ return null;
43
+ return bareToken(renewed) === bareToken(refusedToken) ? null : bareToken(renewed);
44
+ }
45
+ catch (error) {
46
+ console.warn('[FileBrowser] The page could not renew the access token', error);
47
+ return null;
48
+ }
49
+ }
50
+ /**
51
+ * Runs a request that ends in an answer with an HTTP `status` (a fetch `Response`, an upload result): with the current
52
+ * token, and once more with a fresh one when the API answers 401. Any other answer, and a 401 that no fresh token can
53
+ * fix, is returned as it is. A request whose `signal` was aborted is not started again.
54
+ */
55
+ export async function withTokenRetriedOnce(config, request, options = {}) {
56
+ const accessToken = await currentAccessToken(config);
57
+ const firstAnswer = await request(accessToken);
58
+ if (firstAnswer.status !== 401 || options.signal?.aborted)
59
+ return firstAnswer;
60
+ const renewedToken = await renewedAccessToken(config, accessToken);
61
+ if (renewedToken === null)
62
+ return firstAnswer;
63
+ console.warn('[FileBrowser] The API refused the access token; trying once more with a fresh one');
64
+ return request(renewedToken);
65
+ }
@@ -0,0 +1,76 @@
1
+ import type { FileBrowserUploadConfig } from '../stores/uploadApiStore';
2
+ /**
3
+ * What the Widgetic API takes as an upload, read from `GET /v1/uploads/limits`, and the check of a file against it.
4
+ *
5
+ * The File Browser lists more kinds of file than the API takes (fonts, audio, Word documents ...), so a file could be
6
+ * dropped, queued, sent, and only then be refused with "415 Unsupported file type: font/otf". Knowing the API's list
7
+ * before the first file is sent lets the File Browser say so up front, name the reason, and leave the file out of the
8
+ * list of uploads instead of showing it as a failure that "Retry" can never fix.
9
+ */
10
+ export type UploadLimits = {
11
+ /** The most bytes of a file sent in one request; `null` when the API did not say. */
12
+ multipartMaxBytes: number | null;
13
+ /** The most bytes of a resumable (TUS) upload; `null` when the API did not say. */
14
+ tusMaxBytes: number | null;
15
+ tusEnabled: boolean;
16
+ /** The MIME types a file sent in one request may have. */
17
+ multipartMimeTypes: ReadonlySet<string>;
18
+ /** The MIME types a resumable upload (a file over `WIDGETIC_MULTIPART_MAX_BYTES`) may have. */
19
+ tusMimeTypes: ReadonlySet<string>;
20
+ };
21
+ /** Why a file is not taken: its type is not one the API accepts, or it is over the biggest size the API takes. */
22
+ export type UploadRefusal = {
23
+ reason: 'unsupportedType';
24
+ mimeType: string;
25
+ } | {
26
+ reason: 'tooLarge';
27
+ maxBytes: number;
28
+ };
29
+ /**
30
+ * Reads the answer of `GET /v1/uploads/limits` (the payload is the `data` of the API's envelope; a bare payload is read
31
+ * too). `null` when it does not list the accepted types, so a changed answer never blocks an upload on a guess.
32
+ */
33
+ export declare function parseUploadLimits(json: unknown): UploadLimits | null;
34
+ /**
35
+ * The reason the API would refuse a file, or `null` when it takes it (or when the limits are not known: the API then
36
+ * decides, as it always has). The type is judged first with the list that fits the way the file is sent, because a file
37
+ * of a kind the API never takes is refused for that whatever its size.
38
+ */
39
+ export declare function refusalForFile(file: Pick<File, 'type' | 'size'>, limits: UploadLimits | null, isResumable?: boolean): UploadRefusal | null;
40
+ /** The extension of a file name with its dot and in lower case (".otf"); an empty string when the name has none. */
41
+ export declare function extensionOfFileName(fileName: string): string;
42
+ /**
43
+ * The extensions the API takes: the ones that go with every MIME type it lists, in the order the File Browser lists its
44
+ * own kinds. `null` when the limits are not known.
45
+ */
46
+ export declare function extensionsTakenBy(limits: UploadLimits | null): ReadonlySet<string> | null;
47
+ /** The extensions of a list that the API takes. The whole list when the limits are not known. */
48
+ export declare function extensionsTakenFrom(extensions: readonly string[], limits: UploadLimits | null): string[];
49
+ /**
50
+ * True when the API takes a file of this MIME type, as far as the limits say. An empty type is "not known" (a browser
51
+ * reports none for some files while they are only dragged), so it is not refused here.
52
+ */
53
+ export declare function limitsTakeMimeType(mimeType: string, limits: UploadLimits | null): boolean;
54
+ /**
55
+ * What asking the API for its limits came to: the limits (`null` when the API could not be asked or did not list its
56
+ * accepted types, so whoever asks goes on without them and the API judges each file), and whether the API refused the
57
+ * session itself (a 401 that a fresh token did not fix), so the uploader can tell the visitor to sign in again instead of
58
+ * queueing files that cannot be sent.
59
+ */
60
+ export type UploadLimitsAnswer = {
61
+ limits: UploadLimits | null;
62
+ sessionRefused: boolean;
63
+ };
64
+ /** Forgets what was read (a test, or a page that changed its API address). */
65
+ export declare function resetUploadLimitsCache(): void;
66
+ /**
67
+ * The limits of the API behind `config`: from memory when they were read in the last minute, else asked for
68
+ * (`GET {apiBasePath}/uploads/limits`, with the token the page gives and a fresh one when the API refuses it). The same
69
+ * request is the check of the session that comes before the first file of a batch. One request is shared by every caller
70
+ * that asks while it is under way.
71
+ */
72
+ export declare function loadUploadLimits(config: FileBrowserUploadConfig, options?: {
73
+ signal?: AbortSignal;
74
+ forceReload?: boolean;
75
+ now?: () => number;
76
+ }): Promise<UploadLimitsAnswer>;