@widgetic/file-browser 0.5.36 → 0.5.38

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 (41) hide show
  1. package/dist/components/core/FileBrowser.svelte +88 -98
  2. package/dist/components/core/FileUploader.svelte +307 -133
  3. package/dist/components/core/Header.svelte +1 -1
  4. package/dist/components/core/RecentFiles.svelte +21 -8
  5. package/dist/components/core/SearchDropdown.svelte +312 -0
  6. package/dist/components/core/SearchDropdown.svelte.d.ts +30 -0
  7. package/dist/components/core/UploadPanel.svelte +27 -15
  8. package/dist/components/core/UploadPanel.svelte.d.ts +3 -0
  9. package/dist/components/core/UploadRow.svelte +22 -1
  10. package/dist/components/core/UploadRow.svelte.d.ts +3 -0
  11. package/dist/components/core/index.d.ts +1 -0
  12. package/dist/components/core/index.js +1 -0
  13. package/dist/components/items/FileItem.svelte +28 -3
  14. package/dist/components/items/FolderItem.svelte +21 -2
  15. package/dist/components/modals/MoveDialog.svelte +16 -11
  16. package/dist/components/modals/MoveDialog.svelte.d.ts +1 -0
  17. package/dist/components/modals/SearchModal.svelte +4 -44
  18. package/dist/components/ui/DropdownMenu.svelte +7 -3
  19. package/dist/components/ui/DropdownMenu.svelte.d.ts +1 -0
  20. package/dist/i18n/messages.d.ts +7 -1
  21. package/dist/i18n/messages.js +7 -1
  22. package/dist/utils/fileNames.d.ts +9 -0
  23. package/dist/utils/fileNames.js +19 -0
  24. package/dist/utils/libraryTree.d.ts +22 -0
  25. package/dist/utils/libraryTree.js +177 -0
  26. package/dist/utils/searchItems.d.ts +27 -0
  27. package/dist/utils/searchItems.js +77 -0
  28. package/dist/utils/uploadProgressMath.d.ts +29 -0
  29. package/dist/utils/uploadProgressMath.js +66 -0
  30. package/dist/utils/uploadResponseMapping.d.ts +11 -0
  31. package/dist/utils/uploadResponseMapping.js +51 -0
  32. package/dist/utils/uploadUiHelpers.d.ts +28 -0
  33. package/dist/utils/uploadUiHelpers.js +49 -0
  34. package/dist/utils/userUploadsStorage.d.ts +2 -2
  35. package/dist/utils/userUploadsStorage.js +25 -17
  36. package/dist/utils/widgeticTusUpload.d.ts +2 -0
  37. package/dist/utils/widgeticTusUpload.js +4 -20
  38. package/dist/utils/widgeticUpload.js +3 -66
  39. package/dist/utils/xhrMultipartUpload.d.ts +16 -0
  40. package/dist/utils/xhrMultipartUpload.js +125 -0
  41. package/package.json +3 -3
@@ -0,0 +1,66 @@
1
+ /** Minimum sampling window before we show a time-left estimate (ms). */
2
+ export const UPLOAD_TIME_ESTIMATE_MIN_SAMPLES_MS = 1000;
3
+ /** Visual throttle for progress UI (ms). */
4
+ export const UPLOAD_UI_PROGRESS_THROTTLE_MS = 100;
5
+ /**
6
+ * Exponential moving average of throughput (bytes per second) from (time, cumulative uploaded) samples.
7
+ * Returns a non-negative finite rate or undefined when there is not enough data.
8
+ */
9
+ export function movingAverageThroughputBps(previousBps, prevSample, next, smoothing = 0.35) {
10
+ if (!prevSample || next.uploadedBytes <= prevSample.uploadedBytes)
11
+ return previousBps;
12
+ const dt = next.t - prevSample.t;
13
+ if (dt <= 0)
14
+ return previousBps;
15
+ const inst = ((next.uploadedBytes - prevSample.uploadedBytes) / dt) * 1000;
16
+ if (!Number.isFinite(inst) || inst < 0)
17
+ return previousBps;
18
+ if (previousBps === undefined || !Number.isFinite(previousBps))
19
+ return inst;
20
+ return smoothing * inst + (1 - smoothing) * previousBps;
21
+ }
22
+ /**
23
+ * Seconds left from remaining bytes and average throughput; never negative or NaN.
24
+ */
25
+ export function secondsRemainingFromThroughput(remainingBytes, throughputBps) {
26
+ if (throughputBps === undefined || throughputBps <= 0)
27
+ return undefined;
28
+ if (remainingBytes <= 0)
29
+ return 0;
30
+ const secs = remainingBytes / throughputBps;
31
+ if (!Number.isFinite(secs))
32
+ return undefined;
33
+ return Math.max(0, secs);
34
+ }
35
+ /**
36
+ * Overall fractional progress from per-file byte counts (0–1). Completed/failed items contribute full size when `includeComplete` is true.
37
+ */
38
+ export function overallBytesProgressRatio(params) {
39
+ let sumUploaded = 0;
40
+ let sumTotal = 0;
41
+ for (const it of params.items) {
42
+ const total = Math.max(0, it.bytesTotal || 0);
43
+ if (total === 0)
44
+ continue;
45
+ sumTotal += total;
46
+ if (it.status === 'complete' && params.includeComplete) {
47
+ sumUploaded += total;
48
+ }
49
+ else if (it.status === 'failed') {
50
+ sumUploaded += Math.min(total, Math.max(0, it.bytesUploaded));
51
+ }
52
+ else {
53
+ // uploading (or cancelled mid-flight — row removed before this runs)
54
+ const uploaded = Math.min(total, Math.max(0, it.bytesUploaded));
55
+ sumUploaded += uploaded;
56
+ }
57
+ }
58
+ if (sumTotal <= 0)
59
+ return 0;
60
+ return Math.min(1, Math.max(0, sumUploaded / sumTotal));
61
+ }
62
+ export function ratioToPercent(ratio) {
63
+ if (!Number.isFinite(ratio))
64
+ return 0;
65
+ return Math.round(Math.min(1, Math.max(0, ratio)) * 100);
66
+ }
@@ -0,0 +1,11 @@
1
+ import type { WidgeticUploadResult } from './widgeticUpload';
2
+ /**
3
+ * Infer a MIME type for stored files (matches previous widgeticUpload behavior).
4
+ */
5
+ export declare function inferImageMime(mime: string, fileName: string, url: string): string;
6
+ type UploadJsonRow = Record<string, unknown>;
7
+ /**
8
+ * Map a successful POST /uploads JSON body to {@link WidgeticUploadResult}, or an error when `url` is missing.
9
+ */
10
+ export declare function mapWidgeticUploadSuccessJson(data: UploadJsonRow, file: File): WidgeticUploadResult;
11
+ export {};
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Infer a MIME type for stored files (matches previous widgeticUpload behavior).
3
+ */
4
+ export function inferImageMime(mime, fileName, url) {
5
+ const stored = (mime || '').toLowerCase();
6
+ if (stored.startsWith('image/'))
7
+ return stored;
8
+ const hint = `${fileName} ${url}`.split(/[?#]/)[0];
9
+ if (/\.(png)(\?|$)/i.test(hint))
10
+ return 'image/png';
11
+ if (/\.(gif)(\?|$)/i.test(hint))
12
+ return 'image/gif';
13
+ if (/\.(webp)(\?|$)/i.test(hint))
14
+ return 'image/webp';
15
+ if (/\.(svg)(\?|$)/i.test(hint))
16
+ return 'image/svg+xml';
17
+ if (/\.(jpe?g|heic|heif)(\?|$)/i.test(hint))
18
+ return 'image/jpeg';
19
+ if (stored.startsWith('video/') || stored.startsWith('audio/') || stored.includes('pdf'))
20
+ return stored;
21
+ if (/\.(mp3|wav|mp4|webm|pdf|zip)(\?|$)/i.test(hint))
22
+ return stored;
23
+ if (url)
24
+ return stored || 'image/jpeg';
25
+ return stored;
26
+ }
27
+ /**
28
+ * Map a successful POST /uploads JSON body to {@link WidgeticUploadResult}, or an error when `url` is missing.
29
+ */
30
+ export function mapWidgeticUploadSuccessJson(data, file) {
31
+ const url = data.url || '';
32
+ if (!url) {
33
+ return { success: false, error: 'Upload response missing url' };
34
+ }
35
+ const fileName = (data.file_name || data.fileName || file.name);
36
+ const fileId = (data.id || `upload_${Date.now()}`);
37
+ const storedMimeType = inferImageMime((data.mime_type || data.mimeType || file.type) || '', fileName, url);
38
+ return {
39
+ success: true,
40
+ file: {
41
+ id: fileId,
42
+ name: fileName,
43
+ type: 'file',
44
+ size: (data.file_size ?? data.fileSize ?? file.size),
45
+ modified: new Date().toISOString(),
46
+ url,
47
+ thumbnail: storedMimeType.startsWith('image/') ? url : undefined,
48
+ mimeType: storedMimeType || undefined,
49
+ },
50
+ };
51
+ }
@@ -0,0 +1,28 @@
1
+ import type { Translate } from '../i18n/context';
2
+ import { type ThroughputSample } from './uploadProgressMath';
3
+ export type UploadPhase = 'starting' | 'uploading' | 'finishing';
4
+ export declare function formatUploadPercent(locale: string, ratio01: number): string;
5
+ /** Throughput estimate from cumulative bytes and wall clock; returns optional seconds left string via catalog. */
6
+ export declare function updateThroughputEstimateState(params: {
7
+ bytesUploaded: number;
8
+ bytesTotal: number;
9
+ now: number;
10
+ prevSample: ThroughputSample | undefined;
11
+ throughputBps: number | undefined;
12
+ firstSampleAt: number | undefined;
13
+ }): {
14
+ nextSample: ThroughputSample;
15
+ throughputBps: number | undefined;
16
+ firstSampleAt: number | undefined;
17
+ secondsLeft: number | undefined;
18
+ };
19
+ export declare function formatTimeLeftPhrase(translate: Translate, secondsLeft: number | undefined): string | undefined;
20
+ export declare function buildActiveRowStatusText(params: {
21
+ translate: Translate;
22
+ locale: string;
23
+ phase: UploadPhase;
24
+ displayPercent01: number;
25
+ bytesUploaded: number;
26
+ bytesTotal: number;
27
+ secondsLeft: number | undefined;
28
+ }): string;
@@ -0,0 +1,49 @@
1
+ import { formatFileSize } from './fileUtils';
2
+ import { movingAverageThroughputBps, secondsRemainingFromThroughput, UPLOAD_TIME_ESTIMATE_MIN_SAMPLES_MS, } from './uploadProgressMath';
3
+ export function formatUploadPercent(locale, ratio01) {
4
+ const safe = Number.isFinite(ratio01) ? Math.min(1, Math.max(0, ratio01)) : 0;
5
+ return new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 0 }).format(safe);
6
+ }
7
+ /** Throughput estimate from cumulative bytes and wall clock; returns optional seconds left string via catalog. */
8
+ export function updateThroughputEstimateState(params) {
9
+ const { bytesUploaded, bytesTotal, now, prevSample, throughputBps, firstSampleAt } = params;
10
+ const nextSample = { t: now, uploadedBytes: bytesUploaded };
11
+ const nextThroughput = movingAverageThroughputBps(throughputBps, prevSample, nextSample);
12
+ const startedAt = firstSampleAt ?? now;
13
+ const remainingBytes = Math.max(0, bytesTotal - bytesUploaded);
14
+ const secs = now - startedAt >= UPLOAD_TIME_ESTIMATE_MIN_SAMPLES_MS
15
+ ? secondsRemainingFromThroughput(remainingBytes, nextThroughput)
16
+ : undefined;
17
+ return {
18
+ nextSample,
19
+ throughputBps: nextThroughput,
20
+ firstSampleAt: startedAt,
21
+ secondsLeft: secs,
22
+ };
23
+ }
24
+ export function formatTimeLeftPhrase(translate, secondsLeft) {
25
+ if (secondsLeft === undefined)
26
+ return undefined;
27
+ if (!Number.isFinite(secondsLeft) || secondsLeft < 0)
28
+ return undefined;
29
+ if (secondsLeft < 1)
30
+ return translate('upload.time.lessThanSecond');
31
+ if (secondsLeft < 60)
32
+ return translate('upload.time.seconds', { count: Math.max(1, Math.round(secondsLeft)) });
33
+ return translate('upload.time.minutes', { count: Math.max(1, Math.round(secondsLeft / 60)) });
34
+ }
35
+ export function buildActiveRowStatusText(params) {
36
+ const { translate, locale, phase, displayPercent01, bytesUploaded, bytesTotal, secondsLeft } = params;
37
+ const pct = formatUploadPercent(locale, displayPercent01);
38
+ const sent = formatFileSize(bytesUploaded, translate, locale);
39
+ const total = formatFileSize(bytesTotal, translate, locale);
40
+ if (phase === 'finishing') {
41
+ return translate('upload.rowFinishingSized', { total });
42
+ }
43
+ const timePhrase = formatTimeLeftPhrase(translate, secondsLeft);
44
+ const timeLeft = timePhrase ? translate('upload.timeLeft', { time: timePhrase }) : undefined;
45
+ if (timeLeft) {
46
+ return translate('upload.rowActiveWithTime', { percent: pct, sent, total, time: timeLeft });
47
+ }
48
+ return translate('upload.rowActive', { percent: pct, sent, total });
49
+ }
@@ -14,11 +14,11 @@ export declare function saveUserUpload(file: FileSystemItem): void;
14
14
  */
15
15
  export declare function saveUserUploadsBatch(files: FileSystemItem[]): void;
16
16
  /**
17
- * Load the saved library tree children from L1 (legacy fallback).
17
+ * Load the saved library tree children (the children of the synthetic root) from L1, with legacy migration.
18
18
  */
19
19
  export declare function loadLibraryTreeChildren(): Promise<FileSystemItem[] | null>;
20
20
  /**
21
- * Persist the library tree children to L1 (fire-and-forget).
21
+ * Persist the library tree children (the whole root: Uploads, sibling folders, loose files) to L1 (fire-and-forget).
22
22
  */
23
23
  export declare function saveLibraryTreeChildren(children: FileSystemItem[]): void;
24
24
  /**
@@ -1,3 +1,4 @@
1
+ import { mergeApiFilesIntoSavedTree, migrateLegacyUploadsOnlyChildren } from './libraryTree';
1
2
  import { CACHE_POLICIES, getCacheOwner, readEntity, writeEntity } from '@widgetic/cache-layer';
2
3
  // Legacy localStorage keys, read once for migration then superseded by L1.
3
4
  const LEGACY_STORAGE_KEY = 'widgetic-file-browser-uploads';
@@ -6,6 +7,8 @@ const LEGACY_LIBRARY_TREE_KEY = 'widgetic-file-browser-library-tree';
6
7
  const UPLOADS_KIND = 'fileBrowserUploads';
7
8
  /** Entity kind for the saved "My uploads" tree in the L1 store. */
8
9
  const TREE_KIND = 'fileBrowserLibraryTree';
10
+ /** Persisted root children (Uploads folder, sibling folders, loose root files). Legacy key `current` held only Uploads' children. */
11
+ const TREE_KEY_ROOT_CHILDREN = 'root-children';
9
12
  function entityKey() {
10
13
  return 'current';
11
14
  }
@@ -101,14 +104,19 @@ async function loadAllPersistedUploads() {
101
104
  }
102
105
  }
103
106
  /**
104
- * Load the saved library tree children from L1 (legacy fallback).
107
+ * Load the saved library tree children (the children of the synthetic root) from L1, with legacy migration.
105
108
  */
106
109
  export async function loadLibraryTreeChildren() {
107
110
  const ownerId = ownerIdOrNull();
108
111
  if (ownerId) {
109
- const persisted = await readEntity(ownerId, TREE_KIND, entityKey(), CACHE_POLICIES['files.libraryTree'].staleTtlMs);
110
- if (persisted && Array.isArray(persisted)) {
111
- return persisted;
112
+ const rootPersisted = await readEntity(ownerId, TREE_KIND, TREE_KEY_ROOT_CHILDREN, CACHE_POLICIES['files.libraryTree'].staleTtlMs);
113
+ if (rootPersisted && Array.isArray(rootPersisted)) {
114
+ return rootPersisted;
115
+ }
116
+ // Legacy: only `folder_my_uploads` inner children were stored under `current`.
117
+ const legacyInner = await readEntity(ownerId, TREE_KIND, entityKey(), CACHE_POLICIES['files.libraryTree'].staleTtlMs);
118
+ if (legacyInner && Array.isArray(legacyInner)) {
119
+ return legacyInner;
112
120
  }
113
121
  }
114
122
  if (typeof localStorage === 'undefined')
@@ -125,14 +133,14 @@ export async function loadLibraryTreeChildren() {
125
133
  }
126
134
  }
127
135
  /**
128
- * Persist the library tree children to L1 (fire-and-forget).
136
+ * Persist the library tree children (the whole root: Uploads, sibling folders, loose files) to L1 (fire-and-forget).
129
137
  */
130
138
  export function saveLibraryTreeChildren(children) {
131
139
  const ownerId = ownerIdOrNull();
132
140
  if (!ownerId)
133
141
  return;
134
- void writeEntity(ownerId, TREE_KIND, entityKey(), children).catch((error) => {
135
- console.error('[userUploadsStorage] Failed to persist library tree:', error);
142
+ void writeEntity(ownerId, TREE_KIND, TREE_KEY_ROOT_CHILDREN, children).catch((error) => {
143
+ console.error('[userUploadsStorage] Failed to persist root library tree:', error);
136
144
  });
137
145
  }
138
146
  /**
@@ -160,22 +168,22 @@ export function mergeMyUploadsChildren(savedChildren, uploadFiles) {
160
168
  * the visitor's language ("Uploads" in English).
161
169
  */
162
170
  export async function createUserUploadsFileSystemRoot(files, myUploadsName = 'Uploads') {
163
- const savedChildren = await loadLibraryTreeChildren();
164
- const children = mergeMyUploadsChildren(savedChildren, files);
171
+ const savedRaw = await loadLibraryTreeChildren();
172
+ let savedChildren = null;
173
+ if (savedRaw && savedRaw.length > 0) {
174
+ const hasBuiltInUploads = savedRaw.some((c) => c.id === 'folder_my_uploads' && c.type === 'folder');
175
+ savedChildren = hasBuiltInUploads
176
+ ? savedRaw
177
+ : migrateLegacyUploadsOnlyChildren(savedRaw, myUploadsName);
178
+ }
179
+ const children = mergeApiFilesIntoSavedTree(savedChildren, files, myUploadsName);
165
180
  return {
166
181
  basePath: '',
167
182
  root: {
168
183
  id: 'root',
169
184
  name: 'Root',
170
185
  type: 'folder',
171
- children: [
172
- {
173
- id: 'folder_my_uploads',
174
- name: myUploadsName,
175
- type: 'folder',
176
- children,
177
- },
178
- ],
186
+ children,
179
187
  },
180
188
  };
181
189
  }
@@ -9,6 +9,8 @@ export type TusUploadProgress = {
9
9
  };
10
10
  export type TusUploadOptions = {
11
11
  onProgress?: (progress: TusUploadProgress) => void;
12
+ /** After all bytes are uploaded, while waiting for the server (e.g. POST …/complete). */
13
+ onAwaitingResponse?: () => void;
12
14
  abortSignal?: AbortSignal;
13
15
  };
14
16
  /**
@@ -1,4 +1,5 @@
1
1
  import * as tus from 'tus-js-client';
2
+ import { mapWidgeticUploadSuccessJson } from './uploadResponseMapping';
2
3
  /** Matches api-gateway MULTIPART_MAX_UPLOAD_BYTES — use TUS above this. */
3
4
  export const WIDGETIC_MULTIPART_MAX_BYTES = 10 * 1024 * 1024;
4
5
  const DEFAULT_TUS_CHUNK_SIZE = 5 * 1024 * 1024;
@@ -66,26 +67,7 @@ function extractTusId(uploadUrl) {
66
67
  return lastSegment || null;
67
68
  }
68
69
  function mapCompleteResponse(data, file) {
69
- const url = data.url || '';
70
- if (!url) {
71
- return { success: false, error: 'Upload response missing url' };
72
- }
73
- const fileName = (data.file_name || data.fileName || file.name);
74
- const fileId = (data.id || `upload_${Date.now()}`);
75
- // Server may have converted HEIC to JPEG — trust its mime type for the thumbnail.
76
- const storedMimeType = (data.mime_type || data.mimeType || file.type) || '';
77
- return {
78
- success: true,
79
- file: {
80
- id: fileId,
81
- name: fileName,
82
- type: 'file',
83
- size: (data.file_size ?? data.fileSize ?? file.size),
84
- modified: new Date().toISOString(),
85
- url,
86
- thumbnail: storedMimeType.startsWith('image/') ? url : undefined,
87
- },
88
- };
70
+ return mapWidgeticUploadSuccessJson(data, file);
89
71
  }
90
72
  /**
91
73
  * Resumable upload via TUS (POST/PATCH /v1/uploads/tus + POST .../complete).
@@ -162,6 +144,8 @@ export function uploadToWidgeticApiTus(file, config, options = {}) {
162
144
  onSuccess: async () => {
163
145
  if (settled)
164
146
  return;
147
+ // Chunks are on the server; finalize/processing may take a while.
148
+ options.onAwaitingResponse?.();
165
149
  const tusId = extractTusId(tusUpload?.url);
166
150
  if (!tusId) {
167
151
  finish({ success: false, error: 'TUS upload finished without upload id.' });
@@ -1,5 +1,7 @@
1
1
  import { MediaLibraryError, codeForHttpStatus } from '../mediaLibrary/errors';
2
2
  import { shouldUseTusUpload, uploadToWidgeticApiTus, } from './widgeticTusUpload';
3
+ import { inferImageMime } from './uploadResponseMapping';
4
+ import { xhrMultipartUpload } from './xhrMultipartUpload';
3
5
  /**
4
6
  * Upload a file to Widgetic API Gateway.
5
7
  * Files ≤10MB use POST /v1/uploads; larger files use TUS (/v1/uploads/tus).
@@ -21,72 +23,7 @@ export async function uploadToWidgeticApi(file, config, options = {}) {
21
23
  formData.append('conversation_id', config.conversationId);
22
24
  }
23
25
  const token = config.accessToken.replace(/^Bearer\s+/i, '');
24
- const response = await fetch(`${basePath}/uploads`, {
25
- method: 'POST',
26
- headers: {
27
- Authorization: `Bearer ${token}`,
28
- },
29
- body: formData,
30
- // Lets the visitor's Cancel stop the request instead of only hiding it.
31
- signal: options.abortSignal,
32
- });
33
- if (!response.ok) {
34
- let detail = `Upload failed (${response.status})`;
35
- try {
36
- const errJson = await response.json();
37
- detail = errJson?.message || errJson?.error?.message || detail;
38
- }
39
- catch {
40
- /* ignore */
41
- }
42
- return { success: false, error: detail, status: response.status };
43
- }
44
- const json = await response.json();
45
- const data = json?.data ?? json;
46
- const url = data.url;
47
- if (!url) {
48
- return { success: false, error: 'Upload response missing url' };
49
- }
50
- const fileName = (data.file_name || data.fileName || file.name);
51
- const fileId = (data.id || `upload_${Date.now()}`);
52
- const storedMimeType = inferImageMime((data.mime_type || data.mimeType || file.type) || '', fileName, url);
53
- return {
54
- success: true,
55
- file: {
56
- id: fileId,
57
- name: fileName,
58
- type: 'file',
59
- size: (data.file_size ?? data.fileSize ?? file.size),
60
- modified: new Date().toISOString(),
61
- url,
62
- thumbnail: storedMimeType.startsWith('image/') ? url : undefined,
63
- mimeType: storedMimeType || undefined,
64
- },
65
- };
66
- }
67
- function inferImageMime(mime, fileName, url) {
68
- const stored = (mime || '').toLowerCase();
69
- if (stored.startsWith('image/'))
70
- return stored;
71
- const hint = `${fileName} ${url}`.split(/[?#]/)[0];
72
- if (/\.(png)(\?|$)/i.test(hint))
73
- return 'image/png';
74
- if (/\.(gif)(\?|$)/i.test(hint))
75
- return 'image/gif';
76
- if (/\.(webp)(\?|$)/i.test(hint))
77
- return 'image/webp';
78
- if (/\.(svg)(\?|$)/i.test(hint))
79
- return 'image/svg+xml';
80
- if (/\.(jpe?g|heic|heif)(\?|$)/i.test(hint))
81
- return 'image/jpeg';
82
- if (stored.startsWith('video/') || stored.startsWith('audio/') || stored.includes('pdf'))
83
- return stored;
84
- if (/\.(mp3|wav|mp4|webm|pdf|zip)(\?|$)/i.test(hint))
85
- return stored;
86
- // iOS-style names without a real image extension still preview via the stored URL.
87
- if (url)
88
- return stored || 'image/jpeg';
89
- return stored;
26
+ return xhrMultipartUpload(`${basePath}/uploads`, token, formData, file, options);
90
27
  }
91
28
  /**
92
29
  * Hydrate FileBrowser "My uploads" from GET /v1/uploads.
@@ -0,0 +1,16 @@
1
+ import type { WidgeticUploadResult } from './widgeticUpload';
2
+ import type { TusUploadProgress } from './widgeticTusUpload';
3
+ export type XhrFactory = () => Pick<XMLHttpRequest, 'open' | 'setRequestHeader' | 'send' | 'abort' | 'addEventListener' | 'upload' | 'readyState' | 'status' | 'responseText'> & {
4
+ upload: XMLHttpRequest['upload'];
5
+ };
6
+ export type XhrMultipartOptions = {
7
+ abortSignal?: AbortSignal;
8
+ onProgress?: (progress: TusUploadProgress) => void;
9
+ /** After all bytes are on the wire, while waiting for HTTP response (e.g. slow server processing). */
10
+ onAwaitingResponse?: () => void;
11
+ };
12
+ /**
13
+ * Multipart POST with upload progress via XMLHttpRequest (fetch cannot observe upload progress).
14
+ * Behavior matches the previous fetch-based upload: URL, headers, FormData fields, JSON parse, error mapping.
15
+ */
16
+ export declare function xhrMultipartUpload(url: string, token: string, formData: FormData, file: File, options?: XhrMultipartOptions, createXhr?: XhrFactory): Promise<WidgeticUploadResult>;
@@ -0,0 +1,125 @@
1
+ import { mapWidgeticUploadSuccessJson } from './uploadResponseMapping';
2
+ /**
3
+ * Multipart POST with upload progress via XMLHttpRequest (fetch cannot observe upload progress).
4
+ * Behavior matches the previous fetch-based upload: URL, headers, FormData fields, JSON parse, error mapping.
5
+ */
6
+ export async function xhrMultipartUpload(url, token, formData, file, options = {}, createXhr = () => new XMLHttpRequest()) {
7
+ const authToken = token.replace(/^Bearer\s+/i, '');
8
+ const xhr = createXhr();
9
+ const xhrAny = xhr;
10
+ if (options.abortSignal)
11
+ xhrAny.__abortSignal = options.abortSignal;
12
+ let aborted = false;
13
+ const onAbort = () => {
14
+ aborted = true;
15
+ try {
16
+ xhr.abort();
17
+ }
18
+ catch {
19
+ /* ignore */
20
+ }
21
+ };
22
+ if (options.abortSignal) {
23
+ if (options.abortSignal.aborted) {
24
+ throw typeof DOMException !== 'undefined' ? new DOMException('The operation was aborted', 'AbortError') : new Error('AbortError');
25
+ }
26
+ options.abortSignal.addEventListener('abort', onAbort, { once: true });
27
+ }
28
+ const cleanup = () => {
29
+ options.abortSignal?.removeEventListener('abort', onAbort);
30
+ };
31
+ return new Promise((resolve, reject) => {
32
+ let settled = false;
33
+ const finish = (result) => {
34
+ if (settled)
35
+ return;
36
+ settled = true;
37
+ cleanup();
38
+ resolve(result);
39
+ };
40
+ const rejectAbort = () => {
41
+ if (settled)
42
+ return;
43
+ settled = true;
44
+ cleanup();
45
+ reject(typeof DOMException !== 'undefined' ? new DOMException('The operation was aborted', 'AbortError') : new Error('AbortError'));
46
+ };
47
+ /** Match `fetch` when the transport cannot reach the server so `toMediaLibraryError` maps to `libraryError.unreachable`. */
48
+ const rejectNetworkFailure = () => {
49
+ if (settled)
50
+ return;
51
+ settled = true;
52
+ cleanup();
53
+ reject(new TypeError('Failed to fetch'));
54
+ };
55
+ const tryParseJsonError = (text, status) => {
56
+ const fallback = `Upload failed (${status})`;
57
+ try {
58
+ const errJson = JSON.parse(text);
59
+ const fromTop = typeof errJson?.message === 'string' ? errJson.message : '';
60
+ const fromNested = typeof errJson?.error?.message === 'string' ? errJson.error.message : '';
61
+ return fromTop || fromNested || fallback;
62
+ }
63
+ catch {
64
+ return fallback;
65
+ }
66
+ };
67
+ xhr.addEventListener('load', () => {
68
+ if (aborted) {
69
+ rejectAbort();
70
+ return;
71
+ }
72
+ const status = xhr.status;
73
+ const text = xhr.responseText || '';
74
+ if (!status || status < 200 || status >= 300) {
75
+ finish({ success: false, error: tryParseJsonError(text, status || 0), status });
76
+ return;
77
+ }
78
+ try {
79
+ const json = JSON.parse(text);
80
+ const data = (json?.data ?? json);
81
+ finish(mapWidgeticUploadSuccessJson(data, file));
82
+ }
83
+ catch {
84
+ finish({ success: false, error: 'Upload failed (invalid JSON)' });
85
+ }
86
+ });
87
+ xhr.addEventListener('error', () => {
88
+ if (aborted) {
89
+ rejectAbort();
90
+ return;
91
+ }
92
+ rejectNetworkFailure();
93
+ });
94
+ xhr.addEventListener('abort', () => {
95
+ rejectAbort();
96
+ });
97
+ xhr.upload.addEventListener('progress', (evt) => {
98
+ if (aborted)
99
+ return;
100
+ const total = evt.lengthComputable ? evt.total : file.size;
101
+ const loaded = evt.loaded;
102
+ const safeTotal = total > 0 ? total : file.size || 1;
103
+ const percentage = safeTotal > 0 ? Math.round(Math.min(100, Math.max(0, (loaded / safeTotal) * 100))) : 0;
104
+ options.onProgress?.({ bytesUploaded: loaded, bytesTotal: safeTotal, percentage });
105
+ });
106
+ xhr.upload.addEventListener('load', () => {
107
+ if (aborted)
108
+ return;
109
+ // Bytes are on the wire; waiting for HTTP response body (can be slow for large images).
110
+ options.onAwaitingResponse?.();
111
+ });
112
+ try {
113
+ xhr.open('POST', url);
114
+ xhr.setRequestHeader('Authorization', `Bearer ${authToken}`);
115
+ xhr.send(formData);
116
+ }
117
+ catch {
118
+ if (aborted) {
119
+ rejectAbort();
120
+ return;
121
+ }
122
+ rejectNetworkFailure();
123
+ }
124
+ });
125
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/file-browser",
3
- "version": "0.5.36",
3
+ "version": "0.5.38",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "repository": {
@@ -97,7 +97,7 @@
97
97
  "@tailwindcss/postcss": "^4.3.0",
98
98
  "@types/node": "^22.13.4",
99
99
  "@widgetic/cache-layer": "^0.1.1",
100
- "@widgetic/design-system": "^0.5.23",
100
+ "@widgetic/design-system": "^0.5.24",
101
101
  "@widgetic/dev-tools": "^0.3.0",
102
102
  "concurrently": "^9.1.2",
103
103
  "eslint": "^9.0.0",
@@ -118,7 +118,7 @@
118
118
  "peerDependencies": {
119
119
  "@sveltejs/kit": "^2.20.7",
120
120
  "@widgetic/cache-layer": "^0.1.1",
121
- "@widgetic/design-system": ">=0.5.23",
121
+ "@widgetic/design-system": ">=0.5.24",
122
122
  "pdfjs-dist": "^4.10.38",
123
123
  "svelte": "^5.0.0"
124
124
  },