@uploadista/client-browser 0.0.3 → 0.0.4

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 (59) hide show
  1. package/dist/index.d.ts +561 -6
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +2 -7
  4. package/dist/index.js.map +1 -0
  5. package/package.json +6 -5
  6. package/tsdown.config.ts +12 -0
  7. package/.turbo/turbo-build.log +0 -5
  8. package/.turbo/turbo-check.log +0 -130
  9. package/dist/client/create-uploadista-client.d.ts +0 -182
  10. package/dist/client/create-uploadista-client.d.ts.map +0 -1
  11. package/dist/client/create-uploadista-client.js +0 -76
  12. package/dist/client/index.d.ts +0 -2
  13. package/dist/client/index.d.ts.map +0 -1
  14. package/dist/client/index.js +0 -1
  15. package/dist/framework-utils.d.ts +0 -201
  16. package/dist/framework-utils.d.ts.map +0 -1
  17. package/dist/framework-utils.js +0 -282
  18. package/dist/http-client.d.ts +0 -44
  19. package/dist/http-client.d.ts.map +0 -1
  20. package/dist/http-client.js +0 -489
  21. package/dist/services/abort-controller-factory.d.ts +0 -30
  22. package/dist/services/abort-controller-factory.d.ts.map +0 -1
  23. package/dist/services/abort-controller-factory.js +0 -98
  24. package/dist/services/checksum-service.d.ts +0 -30
  25. package/dist/services/checksum-service.d.ts.map +0 -1
  26. package/dist/services/checksum-service.js +0 -44
  27. package/dist/services/create-browser-services.d.ts +0 -36
  28. package/dist/services/create-browser-services.d.ts.map +0 -1
  29. package/dist/services/create-browser-services.js +0 -56
  30. package/dist/services/file-reader.d.ts +0 -91
  31. package/dist/services/file-reader.d.ts.map +0 -1
  32. package/dist/services/file-reader.js +0 -251
  33. package/dist/services/fingerprint-service.d.ts +0 -41
  34. package/dist/services/fingerprint-service.d.ts.map +0 -1
  35. package/dist/services/fingerprint-service.js +0 -64
  36. package/dist/services/id-generation/id-generation.d.ts +0 -40
  37. package/dist/services/id-generation/id-generation.d.ts.map +0 -1
  38. package/dist/services/id-generation/id-generation.js +0 -58
  39. package/dist/services/platform-service.d.ts +0 -38
  40. package/dist/services/platform-service.d.ts.map +0 -1
  41. package/dist/services/platform-service.js +0 -221
  42. package/dist/services/storage/local-storage-service.d.ts +0 -55
  43. package/dist/services/storage/local-storage-service.d.ts.map +0 -1
  44. package/dist/services/storage/local-storage-service.js +0 -178
  45. package/dist/services/storage/session-storage-service.d.ts +0 -55
  46. package/dist/services/storage/session-storage-service.d.ts.map +0 -1
  47. package/dist/services/storage/session-storage-service.js +0 -179
  48. package/dist/services/websocket-factory.d.ts +0 -46
  49. package/dist/services/websocket-factory.d.ts.map +0 -1
  50. package/dist/services/websocket-factory.js +0 -196
  51. package/dist/types/index.d.ts +0 -2
  52. package/dist/types/index.d.ts.map +0 -1
  53. package/dist/types/index.js +0 -1
  54. package/dist/types/upload-input.d.ts +0 -26
  55. package/dist/types/upload-input.d.ts.map +0 -1
  56. package/dist/types/upload-input.js +0 -1
  57. package/dist/utils/hash-util.d.ts +0 -60
  58. package/dist/utils/hash-util.d.ts.map +0 -1
  59. package/dist/utils/hash-util.js +0 -75
@@ -1,76 +0,0 @@
1
- import { createClientStorage, createLogger, createUploadistaClient as createUploadistaClientCore, } from "@uploadista/client-core";
2
- import { createBrowserServices } from "../services/create-browser-services";
3
- /**
4
- * Creates a browser-optimized Uploadista client for file uploads and flow processing.
5
- *
6
- * This factory function automatically configures all browser-specific services including:
7
- * - Fetch-based HTTP client with connection pooling
8
- * - Native WebSocket support for real-time progress
9
- * - localStorage for upload state persistence
10
- * - Web Crypto API for checksums and fingerprints
11
- * - File API for reading and chunking files
12
- * - Browser platform detection and capabilities
13
- *
14
- * The created client can handle File and Blob objects from file inputs, drag-and-drop,
15
- * or programmatically created content. It supports resumable uploads, progress tracking,
16
- * and flow-based file processing.
17
- *
18
- * @param options - Configuration options for the browser client
19
- * @returns A fully configured Uploadista client ready for browser use
20
- *
21
- * @example
22
- * ```typescript
23
- * import { createUploadistaClient } from '@uploadista/client-browser';
24
- *
25
- * // Basic usage
26
- * const client = createUploadistaClient({
27
- * endpoint: 'https://api.uploadista.com/upload'
28
- * });
29
- *
30
- * // With custom configuration
31
- * const client = createUploadistaClient({
32
- * endpoint: 'https://api.uploadista.com/upload',
33
- * connectionPooling: {
34
- * maxConnectionsPerHost: 6,
35
- * enableHttp2: true,
36
- * keepAliveTimeout: 60000
37
- * },
38
- * chunkSize: 5 * 1024 * 1024, // 5MB chunks
39
- * retryDelays: [1000, 3000, 5000],
40
- * allowedMetaFields: ['userId', 'projectId']
41
- * });
42
- *
43
- * // Upload a file
44
- * const fileInput = document.querySelector('input[type="file"]');
45
- * const file = fileInput.files[0];
46
- *
47
- * const upload = await client.upload(file, {
48
- * onProgress: (event) => {
49
- * console.log(`Progress: ${event.progress}%`);
50
- * }
51
- * });
52
- *
53
- * console.log('Upload complete:', upload.id);
54
- * ```
55
- *
56
- * @see {@link UploadistaClientOptions} for available configuration options
57
- * @see {@link BrowserUploadInput} for supported file input types
58
- */
59
- export function createUploadistaClient(options) {
60
- const services = createBrowserServices({
61
- connectionPooling: options.connectionPooling,
62
- });
63
- return createUploadistaClientCore({
64
- ...options,
65
- webSocketFactory: services.websocket,
66
- abortControllerFactory: services.abortController,
67
- platformService: services.platform,
68
- httpClient: services.httpClient,
69
- fileReader: services.fileReader,
70
- generateId: services.idGeneration,
71
- fingerprintService: services.fingerprintService,
72
- checksumService: services.checksumService,
73
- logger: createLogger(false, () => { }),
74
- clientStorage: createClientStorage(services.storage),
75
- });
76
- }
@@ -1,2 +0,0 @@
1
- export * from "./create-uploadista-client";
2
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/client/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC"}
@@ -1 +0,0 @@
1
- export * from "./create-uploadista-client";
@@ -1,201 +0,0 @@
1
- /**
2
- * Framework Integration Utilities
3
- *
4
- * This module provides TypeScript utilities and helper types for building
5
- * framework-specific wrappers around the Uploadista client.
6
- *
7
- * @module framework-utils
8
- */
9
- import type { FlowResult, UploadResult } from "@uploadista/client-core";
10
- import type { FlowEvent } from "@uploadista/core/flow";
11
- import type { UploadEvent, UploadFile } from "@uploadista/core/types";
12
- /**
13
- * Base upload state that framework wrappers should implement
14
- */
15
- export interface BaseUploadState {
16
- status: "idle" | "uploading" | "success" | "error" | "aborted";
17
- progress: number;
18
- bytesUploaded: number;
19
- totalBytes: number;
20
- error?: Error;
21
- result?: UploadResult<UploadFile>;
22
- }
23
- /**
24
- * Base flow upload state
25
- */
26
- export interface BaseFlowUploadState extends BaseUploadState {
27
- jobId?: string;
28
- flowStatus?: "pending" | "processing" | "completed" | "failed";
29
- flowResult?: FlowResult<unknown>;
30
- }
31
- /**
32
- * Progress callback signature
33
- */
34
- export type ProgressCallback = (uploadId: string, bytesUploaded: number, totalBytes: number) => void;
35
- /**
36
- * Complete callback signature
37
- */
38
- export type CompleteCallback = (uploadId: string, result: UploadResult) => void;
39
- /**
40
- * Error callback signature
41
- */
42
- export type ErrorCallback = (uploadId: string, error: Error) => void;
43
- /**
44
- * Abort callback signature
45
- */
46
- export type AbortCallback = (uploadId: string) => void;
47
- /**
48
- * Event handler signature for framework wrappers
49
- */
50
- export type EventHandler<T = unknown> = (event: T) => void;
51
- /**
52
- * WebSocket event handler signature
53
- */
54
- export type WebSocketEventHandler = (event: UploadEvent | FlowEvent) => void;
55
- /**
56
- * Framework state updater function signature
57
- * @template T - The state type
58
- */
59
- export type StateUpdater<T> = (updater: (prevState: T) => T) => void;
60
- /**
61
- * Cleanup function returned by setup functions
62
- */
63
- export type CleanupFunction = () => void;
64
- /**
65
- * Upload item for multi-upload tracking
66
- */
67
- export interface UploadItem {
68
- id: string;
69
- file: File;
70
- status: BaseUploadState["status"];
71
- progress: number;
72
- bytesUploaded: number;
73
- totalBytes: number;
74
- error?: Error;
75
- result?: UploadResult;
76
- }
77
- /**
78
- * Multi-upload aggregate statistics
79
- */
80
- export interface MultiUploadStats {
81
- totalFiles: number;
82
- completedFiles: number;
83
- failedFiles: number;
84
- totalBytes: number;
85
- uploadedBytes: number;
86
- totalProgress: number;
87
- allComplete: boolean;
88
- hasErrors: boolean;
89
- }
90
- /**
91
- * Drag and drop state
92
- */
93
- export interface DragDropState {
94
- isDragging: boolean;
95
- isOver: boolean;
96
- files: File[];
97
- }
98
- /**
99
- * File validation result
100
- */
101
- export interface FileValidationResult {
102
- valid: boolean;
103
- error?: string;
104
- }
105
- /**
106
- * File validation function signature
107
- */
108
- export type FileValidator = (file: File) => FileValidationResult;
109
- /**
110
- * Utility: Calculate aggregate upload statistics
111
- */
112
- export declare function calculateMultiUploadStats(uploads: UploadItem[]): MultiUploadStats;
113
- /**
114
- * Utility: Format file size for display
115
- */
116
- export declare function formatFileSize(bytes: number): string;
117
- /**
118
- * Utility: Format progress percentage
119
- */
120
- export declare function formatProgress(progress: number): string;
121
- /**
122
- * Utility: Get file extension
123
- */
124
- export declare function getFileExtension(filename: string): string;
125
- /**
126
- * Utility: Check if file is an image
127
- */
128
- export declare function isImageFile(file: File): boolean;
129
- /**
130
- * Utility: Check if file is a video
131
- */
132
- export declare function isVideoFile(file: File): boolean;
133
- /**
134
- * Utility: Create file size validator
135
- */
136
- export declare function createFileSizeValidator(maxSizeBytes: number): FileValidator;
137
- /**
138
- * Utility: Create file type validator
139
- */
140
- export declare function createFileTypeValidator(allowedTypes: string[]): FileValidator;
141
- /**
142
- * Utility: Compose multiple validators
143
- */
144
- export declare function composeValidators(...validators: FileValidator[]): FileValidator;
145
- /**
146
- * Utility: Generate unique upload ID
147
- */
148
- export declare function generateUploadId(): string;
149
- /**
150
- * Utility: Create delay promise for retry logic
151
- */
152
- export declare function delay(ms: number): Promise<void>;
153
- /**
154
- * Utility: Calculate exponential backoff delay
155
- */
156
- export declare function calculateBackoff(attempt: number, baseDelay?: number, maxDelay?: number): number;
157
- /**
158
- * Utility: Create retry wrapper for upload function
159
- */
160
- export declare function createRetryWrapper<T>(fn: () => Promise<T>, maxAttempts?: number, shouldRetry?: (error: unknown) => boolean): () => Promise<T>;
161
- /**
162
- * Type guard: Check if error is network-related (should retry)
163
- */
164
- export declare function isNetworkError(error: unknown): boolean;
165
- /**
166
- * Type guard: Check if error is abort-related (should not retry)
167
- */
168
- export declare function isAbortError(error: unknown): boolean;
169
- /**
170
- * Format upload speed in human-readable format
171
- */
172
- export declare function formatSpeed(bytesPerSecond: number): string;
173
- /**
174
- * Format duration in human-readable format
175
- */
176
- export declare function formatDuration(milliseconds: number): string;
177
- /**
178
- * Validate file type against accepted types
179
- */
180
- export declare function validateFileType(file: File, accept: string[]): boolean;
181
- /**
182
- * Check if a file is an audio file
183
- */
184
- export declare function isAudioFile(file: File): boolean;
185
- /**
186
- * Check if a file is a document
187
- */
188
- export declare function isDocumentFile(file: File): boolean;
189
- /**
190
- * Create a preview URL for a file (if supported)
191
- */
192
- export declare function createFilePreview(file: File): string | null;
193
- /**
194
- * Clean up a preview URL created with createFilePreview
195
- */
196
- export declare function revokeFilePreview(previewUrl: string): void;
197
- /**
198
- * Calculate progress percentage
199
- */
200
- export declare function calculateProgress(current: number, total: number): number;
201
- //# sourceMappingURL=framework-utils.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"framework-utils.d.ts","sourceRoot":"","sources":["../src/framework-utils.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACxE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEtE;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,CAAC;IAC/D,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IAC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AAO,CAiBtE;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAE/C;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAelD;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,GAAG,IAAI,CAK3D;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,CAE1D;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAGxE"}
@@ -1,282 +0,0 @@
1
- /**
2
- * Framework Integration Utilities
3
- *
4
- * This module provides TypeScript utilities and helper types for building
5
- * framework-specific wrappers around the Uploadista client.
6
- *
7
- * @module framework-utils
8
- */
9
- /**
10
- * Utility: Calculate aggregate upload statistics
11
- */
12
- export function calculateMultiUploadStats(uploads) {
13
- const totalFiles = uploads.length;
14
- const completedFiles = uploads.filter((u) => u.status === "success").length;
15
- const failedFiles = uploads.filter((u) => u.status === "error").length;
16
- const totalBytes = uploads.reduce((sum, u) => sum + u.totalBytes, 0);
17
- const uploadedBytes = uploads.reduce((sum, u) => sum + u.bytesUploaded, 0);
18
- const totalProgress = totalBytes > 0 ? (uploadedBytes / totalBytes) * 100 : 0;
19
- const allComplete = uploads.every((u) => u.status === "success");
20
- const hasErrors = uploads.some((u) => u.status === "error");
21
- return {
22
- totalFiles,
23
- completedFiles,
24
- failedFiles,
25
- totalBytes,
26
- uploadedBytes,
27
- totalProgress,
28
- allComplete,
29
- hasErrors,
30
- };
31
- }
32
- /**
33
- * Utility: Format file size for display
34
- */
35
- export function formatFileSize(bytes) {
36
- if (bytes === 0)
37
- return "0 Bytes";
38
- const k = 1024;
39
- const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
40
- const i = Math.floor(Math.log(bytes) / Math.log(k));
41
- return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
42
- }
43
- /**
44
- * Utility: Format progress percentage
45
- */
46
- export function formatProgress(progress) {
47
- return `${Math.round(progress)}%`;
48
- }
49
- /**
50
- * Utility: Get file extension
51
- */
52
- export function getFileExtension(filename) {
53
- const lastDot = filename.lastIndexOf(".");
54
- return lastDot === -1 ? "" : filename.slice(lastDot + 1).toLowerCase();
55
- }
56
- /**
57
- * Utility: Check if file is an image
58
- */
59
- export function isImageFile(file) {
60
- return file.type.startsWith("image/");
61
- }
62
- /**
63
- * Utility: Check if file is a video
64
- */
65
- export function isVideoFile(file) {
66
- return file.type.startsWith("video/");
67
- }
68
- /**
69
- * Utility: Create file size validator
70
- */
71
- export function createFileSizeValidator(maxSizeBytes) {
72
- return (file) => {
73
- if (file.size > maxSizeBytes) {
74
- return {
75
- valid: false,
76
- error: `File size exceeds maximum of ${formatFileSize(maxSizeBytes)}`,
77
- };
78
- }
79
- return { valid: true };
80
- };
81
- }
82
- /**
83
- * Utility: Create file type validator
84
- */
85
- export function createFileTypeValidator(allowedTypes) {
86
- return (file) => {
87
- const fileType = file.type.toLowerCase();
88
- const fileExt = getFileExtension(file.name);
89
- const isAllowed = allowedTypes.some((type) => {
90
- if (type.startsWith(".")) {
91
- return type.slice(1) === fileExt;
92
- }
93
- if (type.includes("*")) {
94
- const pattern = type.replace("*", "");
95
- return fileType.startsWith(pattern);
96
- }
97
- return fileType === type;
98
- });
99
- if (!isAllowed) {
100
- return {
101
- valid: false,
102
- error: `File type not allowed. Allowed types: ${allowedTypes.join(", ")}`,
103
- };
104
- }
105
- return { valid: true };
106
- };
107
- }
108
- /**
109
- * Utility: Compose multiple validators
110
- */
111
- export function composeValidators(...validators) {
112
- return (file) => {
113
- for (const validator of validators) {
114
- const result = validator(file);
115
- if (!result.valid) {
116
- return result;
117
- }
118
- }
119
- return { valid: true };
120
- };
121
- }
122
- /**
123
- * Utility: Generate unique upload ID
124
- */
125
- export function generateUploadId() {
126
- return `upload-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
127
- }
128
- /**
129
- * Utility: Create delay promise for retry logic
130
- */
131
- export function delay(ms) {
132
- return new Promise((resolve) => setTimeout(resolve, ms));
133
- }
134
- /**
135
- * Utility: Calculate exponential backoff delay
136
- */
137
- export function calculateBackoff(attempt, baseDelay = 1000, maxDelay = 30000) {
138
- const delay = Math.min(baseDelay * 2 ** attempt, maxDelay);
139
- // Add jitter to prevent thundering herd
140
- return delay + Math.random() * 1000;
141
- }
142
- /**
143
- * Utility: Create retry wrapper for upload function
144
- */
145
- export function createRetryWrapper(fn, maxAttempts = 3, shouldRetry = () => true) {
146
- return async () => {
147
- let lastError;
148
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
149
- try {
150
- return await fn();
151
- }
152
- catch (error) {
153
- lastError = error;
154
- if (attempt < maxAttempts - 1 && shouldRetry(error)) {
155
- const delayMs = calculateBackoff(attempt);
156
- await delay(delayMs);
157
- continue;
158
- }
159
- break;
160
- }
161
- }
162
- throw lastError;
163
- };
164
- }
165
- /**
166
- * Type guard: Check if error is network-related (should retry)
167
- */
168
- export function isNetworkError(error) {
169
- if (error instanceof Error) {
170
- return (error.message.includes("network") ||
171
- error.message.includes("timeout") ||
172
- error.message.includes("connection") ||
173
- error.message.includes("ECONNREFUSED") ||
174
- error.message.includes("ETIMEDOUT"));
175
- }
176
- return false;
177
- }
178
- /**
179
- * Type guard: Check if error is abort-related (should not retry)
180
- */
181
- export function isAbortError(error) {
182
- if (error instanceof Error) {
183
- return error.name === "AbortError" || error.message.includes("abort");
184
- }
185
- return false;
186
- }
187
- /**
188
- * Format upload speed in human-readable format
189
- */
190
- export function formatSpeed(bytesPerSecond) {
191
- if (bytesPerSecond === 0)
192
- return "0 B/s";
193
- const k = 1024;
194
- const sizes = ["B/s", "KB/s", "MB/s", "GB/s"];
195
- const i = Math.floor(Math.log(bytesPerSecond) / Math.log(k));
196
- return `${parseFloat((bytesPerSecond / k ** i).toFixed(1))} ${sizes[i]}`;
197
- }
198
- /**
199
- * Format duration in human-readable format
200
- */
201
- export function formatDuration(milliseconds) {
202
- if (milliseconds < 1000) {
203
- return `${Math.round(milliseconds)}ms`;
204
- }
205
- if (milliseconds < 60000) {
206
- return `${Math.round(milliseconds / 1000)}s`;
207
- }
208
- if (milliseconds < 3600000) {
209
- const minutes = Math.floor(milliseconds / 60000);
210
- const seconds = Math.round((milliseconds % 60000) / 1000);
211
- return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
212
- }
213
- const hours = Math.floor(milliseconds / 3600000);
214
- const minutes = Math.round((milliseconds % 3600000) / 60000);
215
- return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
216
- }
217
- /**
218
- * Validate file type against accepted types
219
- */
220
- export function validateFileType(file, accept) {
221
- if (!accept || accept.length === 0)
222
- return true;
223
- return accept.some((acceptType) => {
224
- if (acceptType.startsWith(".")) {
225
- // File extension check
226
- return file.name.toLowerCase().endsWith(acceptType.toLowerCase());
227
- }
228
- // MIME type check (supports wildcards like image/*)
229
- if (acceptType.endsWith("/*")) {
230
- const baseType = acceptType.slice(0, -2);
231
- return file.type.startsWith(baseType);
232
- }
233
- return file.type === acceptType;
234
- });
235
- }
236
- /**
237
- * Check if a file is an audio file
238
- */
239
- export function isAudioFile(file) {
240
- return file.type.startsWith("audio/");
241
- }
242
- /**
243
- * Check if a file is a document
244
- */
245
- export function isDocumentFile(file) {
246
- const documentTypes = [
247
- "application/pdf",
248
- "application/msword",
249
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
250
- "application/vnd.ms-excel",
251
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
252
- "application/vnd.ms-powerpoint",
253
- "application/vnd.openxmlformats-officedocument.presentationml.presentation",
254
- "text/plain",
255
- "text/csv",
256
- "application/rtf",
257
- ];
258
- return documentTypes.includes(file.type);
259
- }
260
- /**
261
- * Create a preview URL for a file (if supported)
262
- */
263
- export function createFilePreview(file) {
264
- if (isImageFile(file) || isVideoFile(file) || isAudioFile(file)) {
265
- return URL.createObjectURL(file);
266
- }
267
- return null;
268
- }
269
- /**
270
- * Clean up a preview URL created with createFilePreview
271
- */
272
- export function revokeFilePreview(previewUrl) {
273
- URL.revokeObjectURL(previewUrl);
274
- }
275
- /**
276
- * Calculate progress percentage
277
- */
278
- export function calculateProgress(current, total) {
279
- if (total === 0)
280
- return 0;
281
- return Math.min(100, Math.max(0, Math.round((current / total) * 100)));
282
- }
@@ -1,44 +0,0 @@
1
- import type { ConnectionPoolConfig, HttpClient } from "@uploadista/client-core";
2
- /**
3
- * Creates a browser-optimized HTTP client using the Fetch API.
4
- *
5
- * This factory function returns an HttpClient implementation that uses the browser's
6
- * native fetch() API with connection keep-alive headers for optimal performance.
7
- * The client automatically manages connection pooling, tracks metrics, and provides
8
- * connection health monitoring.
9
- *
10
- * @param config - Optional connection pooling configuration
11
- * @returns A configured HTTP client ready for making requests
12
- *
13
- * @example
14
- * ```typescript
15
- * import { createHttpClient } from '@uploadista/client-browser';
16
- *
17
- * // Basic usage with defaults
18
- * const client = createHttpClient();
19
- *
20
- * // With custom configuration
21
- * const client = createHttpClient({
22
- * maxConnectionsPerHost: 10,
23
- * connectionTimeout: 60000,
24
- * keepAliveTimeout: 120000,
25
- * enableHttp2: true,
26
- * retryOnConnectionError: true
27
- * });
28
- *
29
- * // Make a request
30
- * const response = await client.request('https://api.example.com/data', {
31
- * method: 'POST',
32
- * headers: { 'Content-Type': 'application/json' },
33
- * body: JSON.stringify({ key: 'value' })
34
- * });
35
- *
36
- * // Check connection health
37
- * const metrics = client.getDetailedMetrics();
38
- * console.log('Connection health:', metrics.health.status);
39
- * ```
40
- *
41
- * @see {@link BrowserHttpClient} for implementation details
42
- */
43
- export declare function createHttpClient(config?: ConnectionPoolConfig): HttpClient;
44
- //# sourceMappingURL=http-client.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"http-client.d.ts","sourceRoot":"","sources":["../src/http-client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,oBAAoB,EAGpB,UAAU,EAGX,MAAM,yBAAyB,CAAC;AAEjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,CAAC,EAAE,oBAAoB,GAAG,UAAU,CAE1E"}