@uploadista/client-core 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 (172) hide show
  1. package/dist/index.d.ts +2674 -8
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +2 -12
  4. package/dist/index.js.map +1 -0
  5. package/package.json +5 -4
  6. package/tsdown.config.ts +11 -0
  7. package/.turbo/turbo-build.log +0 -5
  8. package/dist/auth/auth-http-client.d.ts +0 -50
  9. package/dist/auth/auth-http-client.d.ts.map +0 -1
  10. package/dist/auth/auth-http-client.js +0 -110
  11. package/dist/auth/direct-auth.d.ts +0 -38
  12. package/dist/auth/direct-auth.d.ts.map +0 -1
  13. package/dist/auth/direct-auth.js +0 -95
  14. package/dist/auth/index.d.ts +0 -6
  15. package/dist/auth/index.d.ts.map +0 -1
  16. package/dist/auth/index.js +0 -5
  17. package/dist/auth/no-auth.d.ts +0 -26
  18. package/dist/auth/no-auth.d.ts.map +0 -1
  19. package/dist/auth/no-auth.js +0 -33
  20. package/dist/auth/saas-auth.d.ts +0 -80
  21. package/dist/auth/saas-auth.d.ts.map +0 -1
  22. package/dist/auth/saas-auth.js +0 -167
  23. package/dist/auth/types.d.ts +0 -101
  24. package/dist/auth/types.d.ts.map +0 -1
  25. package/dist/auth/types.js +0 -8
  26. package/dist/chunk-buffer.d.ts +0 -209
  27. package/dist/chunk-buffer.d.ts.map +0 -1
  28. package/dist/chunk-buffer.js +0 -236
  29. package/dist/client/create-uploadista-client.d.ts +0 -369
  30. package/dist/client/create-uploadista-client.d.ts.map +0 -1
  31. package/dist/client/create-uploadista-client.js +0 -518
  32. package/dist/client/index.d.ts +0 -4
  33. package/dist/client/index.d.ts.map +0 -1
  34. package/dist/client/index.js +0 -3
  35. package/dist/client/uploadista-api.d.ts +0 -284
  36. package/dist/client/uploadista-api.d.ts.map +0 -1
  37. package/dist/client/uploadista-api.js +0 -444
  38. package/dist/client/uploadista-websocket-manager.d.ts +0 -110
  39. package/dist/client/uploadista-websocket-manager.d.ts.map +0 -1
  40. package/dist/client/uploadista-websocket-manager.js +0 -207
  41. package/dist/error.d.ts +0 -106
  42. package/dist/error.d.ts.map +0 -1
  43. package/dist/error.js +0 -69
  44. package/dist/logger.d.ts +0 -70
  45. package/dist/logger.d.ts.map +0 -1
  46. package/dist/logger.js +0 -59
  47. package/dist/mock-data-store.d.ts +0 -30
  48. package/dist/mock-data-store.d.ts.map +0 -1
  49. package/dist/mock-data-store.js +0 -88
  50. package/dist/network-monitor.d.ts +0 -262
  51. package/dist/network-monitor.d.ts.map +0 -1
  52. package/dist/network-monitor.js +0 -291
  53. package/dist/services/abort-controller-service.d.ts +0 -19
  54. package/dist/services/abort-controller-service.d.ts.map +0 -1
  55. package/dist/services/abort-controller-service.js +0 -4
  56. package/dist/services/checksum-service.d.ts +0 -4
  57. package/dist/services/checksum-service.d.ts.map +0 -1
  58. package/dist/services/checksum-service.js +0 -1
  59. package/dist/services/file-reader-service.d.ts +0 -38
  60. package/dist/services/file-reader-service.d.ts.map +0 -1
  61. package/dist/services/file-reader-service.js +0 -4
  62. package/dist/services/fingerprint-service.d.ts +0 -4
  63. package/dist/services/fingerprint-service.d.ts.map +0 -1
  64. package/dist/services/fingerprint-service.js +0 -1
  65. package/dist/services/http-client.d.ts +0 -182
  66. package/dist/services/http-client.d.ts.map +0 -1
  67. package/dist/services/http-client.js +0 -1
  68. package/dist/services/id-generation-service.d.ts +0 -10
  69. package/dist/services/id-generation-service.d.ts.map +0 -1
  70. package/dist/services/id-generation-service.js +0 -1
  71. package/dist/services/index.d.ts +0 -11
  72. package/dist/services/index.d.ts.map +0 -1
  73. package/dist/services/index.js +0 -10
  74. package/dist/services/platform-service.d.ts +0 -48
  75. package/dist/services/platform-service.d.ts.map +0 -1
  76. package/dist/services/platform-service.js +0 -10
  77. package/dist/services/service-container.d.ts +0 -25
  78. package/dist/services/service-container.d.ts.map +0 -1
  79. package/dist/services/service-container.js +0 -1
  80. package/dist/services/storage-service.d.ts +0 -26
  81. package/dist/services/storage-service.d.ts.map +0 -1
  82. package/dist/services/storage-service.js +0 -1
  83. package/dist/services/websocket-service.d.ts +0 -36
  84. package/dist/services/websocket-service.d.ts.map +0 -1
  85. package/dist/services/websocket-service.js +0 -4
  86. package/dist/smart-chunker.d.ts +0 -72
  87. package/dist/smart-chunker.d.ts.map +0 -1
  88. package/dist/smart-chunker.js +0 -317
  89. package/dist/storage/client-storage.d.ts +0 -148
  90. package/dist/storage/client-storage.d.ts.map +0 -1
  91. package/dist/storage/client-storage.js +0 -62
  92. package/dist/storage/in-memory-storage-service.d.ts +0 -7
  93. package/dist/storage/in-memory-storage-service.d.ts.map +0 -1
  94. package/dist/storage/in-memory-storage-service.js +0 -24
  95. package/dist/storage/index.d.ts +0 -3
  96. package/dist/storage/index.d.ts.map +0 -1
  97. package/dist/storage/index.js +0 -2
  98. package/dist/types/buffered-chunk.d.ts +0 -6
  99. package/dist/types/buffered-chunk.d.ts.map +0 -1
  100. package/dist/types/buffered-chunk.js +0 -1
  101. package/dist/types/chunk-metrics.d.ts +0 -12
  102. package/dist/types/chunk-metrics.d.ts.map +0 -1
  103. package/dist/types/chunk-metrics.js +0 -1
  104. package/dist/types/flow-result.d.ts +0 -11
  105. package/dist/types/flow-result.d.ts.map +0 -1
  106. package/dist/types/flow-result.js +0 -1
  107. package/dist/types/flow-upload-config.d.ts +0 -54
  108. package/dist/types/flow-upload-config.d.ts.map +0 -1
  109. package/dist/types/flow-upload-config.js +0 -1
  110. package/dist/types/flow-upload-item.d.ts +0 -16
  111. package/dist/types/flow-upload-item.d.ts.map +0 -1
  112. package/dist/types/flow-upload-item.js +0 -1
  113. package/dist/types/flow-upload-options.d.ts +0 -41
  114. package/dist/types/flow-upload-options.d.ts.map +0 -1
  115. package/dist/types/flow-upload-options.js +0 -1
  116. package/dist/types/index.d.ts +0 -14
  117. package/dist/types/index.d.ts.map +0 -1
  118. package/dist/types/index.js +0 -13
  119. package/dist/types/multi-flow-upload-options.d.ts +0 -33
  120. package/dist/types/multi-flow-upload-options.d.ts.map +0 -1
  121. package/dist/types/multi-flow-upload-options.js +0 -1
  122. package/dist/types/multi-flow-upload-state.d.ts +0 -9
  123. package/dist/types/multi-flow-upload-state.d.ts.map +0 -1
  124. package/dist/types/multi-flow-upload-state.js +0 -1
  125. package/dist/types/performance-insights.d.ts +0 -11
  126. package/dist/types/performance-insights.d.ts.map +0 -1
  127. package/dist/types/performance-insights.js +0 -1
  128. package/dist/types/previous-upload.d.ts +0 -20
  129. package/dist/types/previous-upload.d.ts.map +0 -1
  130. package/dist/types/previous-upload.js +0 -9
  131. package/dist/types/upload-options.d.ts +0 -40
  132. package/dist/types/upload-options.d.ts.map +0 -1
  133. package/dist/types/upload-options.js +0 -1
  134. package/dist/types/upload-response.d.ts +0 -6
  135. package/dist/types/upload-response.d.ts.map +0 -1
  136. package/dist/types/upload-response.js +0 -1
  137. package/dist/types/upload-result.d.ts +0 -57
  138. package/dist/types/upload-result.d.ts.map +0 -1
  139. package/dist/types/upload-result.js +0 -1
  140. package/dist/types/upload-session-metrics.d.ts +0 -16
  141. package/dist/types/upload-session-metrics.d.ts.map +0 -1
  142. package/dist/types/upload-session-metrics.js +0 -1
  143. package/dist/upload/chunk-upload.d.ts +0 -40
  144. package/dist/upload/chunk-upload.d.ts.map +0 -1
  145. package/dist/upload/chunk-upload.js +0 -82
  146. package/dist/upload/flow-upload.d.ts +0 -48
  147. package/dist/upload/flow-upload.d.ts.map +0 -1
  148. package/dist/upload/flow-upload.js +0 -240
  149. package/dist/upload/index.d.ts +0 -3
  150. package/dist/upload/index.d.ts.map +0 -1
  151. package/dist/upload/index.js +0 -2
  152. package/dist/upload/parallel-upload.d.ts +0 -65
  153. package/dist/upload/parallel-upload.d.ts.map +0 -1
  154. package/dist/upload/parallel-upload.js +0 -231
  155. package/dist/upload/single-upload.d.ts +0 -118
  156. package/dist/upload/single-upload.d.ts.map +0 -1
  157. package/dist/upload/single-upload.js +0 -332
  158. package/dist/upload/upload-manager.d.ts +0 -30
  159. package/dist/upload/upload-manager.d.ts.map +0 -1
  160. package/dist/upload/upload-manager.js +0 -57
  161. package/dist/upload/upload-metrics.d.ts +0 -37
  162. package/dist/upload/upload-metrics.d.ts.map +0 -1
  163. package/dist/upload/upload-metrics.js +0 -236
  164. package/dist/upload/upload-storage.d.ts +0 -32
  165. package/dist/upload/upload-storage.d.ts.map +0 -1
  166. package/dist/upload/upload-storage.js +0 -46
  167. package/dist/upload/upload-strategy.d.ts +0 -66
  168. package/dist/upload/upload-strategy.d.ts.map +0 -1
  169. package/dist/upload/upload-strategy.js +0 -171
  170. package/dist/upload/upload-utils.d.ts +0 -26
  171. package/dist/upload/upload-utils.d.ts.map +0 -1
  172. package/dist/upload/upload-utils.js +0 -80
package/dist/index.d.ts CHANGED
@@ -1,9 +1,2675 @@
1
- export * from "./chunk-buffer";
2
- export * from "./client";
3
- export * from "./error";
4
- export * from "./logger";
5
- export * from "./network-monitor";
6
- export * from "./services";
7
- export * from "./storage";
8
- export * from "./types";
1
+ import { UploadStrategyNegotiator } from "@uploadista/core/upload";
2
+ import { DataStoreCapabilities, InputFile, UploadEvent, UploadFile } from "@uploadista/core/types";
3
+ import z from "zod";
4
+ import * as _uploadista_core0 from "@uploadista/core";
5
+ import { UploadFile as UploadFile$1 } from "@uploadista/core";
6
+ import { FlowData, FlowEvent, FlowJob } from "@uploadista/core/flow";
7
+
8
+ //#region src/types/buffered-chunk.d.ts
9
+ interface BufferedChunk {
10
+ data: Uint8Array;
11
+ size: number;
12
+ timestamp: number;
13
+ }
14
+ //#endregion
15
+ //#region src/chunk-buffer.d.ts
16
+ /**
17
+ * Configuration options for ChunkBuffer.
18
+ *
19
+ * Controls how the buffer accumulates chunks before flushing them to the datastore.
20
+ * This is essential for datastores with minimum chunk size requirements (e.g., AWS S3's 5MB minimum).
21
+ */
22
+ interface ChunkBufferConfig {
23
+ /**
24
+ * Minimum chunk size required by the datastore before flushing (in bytes).
25
+ * For example, AWS S3 requires a minimum of 5MB per multipart upload part.
26
+ */
27
+ minThreshold: number;
28
+ /**
29
+ * Maximum buffer size before forcing a flush (in bytes).
30
+ * Defaults to 2x minThreshold. Prevents memory issues with very slow uploads.
31
+ */
32
+ maxBufferSize?: number;
33
+ /**
34
+ * Maximum time to wait before flushing pending data (in milliseconds).
35
+ * Defaults to 30000ms (30 seconds). Ensures timely uploads even with slow data arrival.
36
+ */
37
+ timeoutMs?: number;
38
+ }
39
+ /**
40
+ * ChunkBuffer accumulates small chunks until they meet the minimum threshold
41
+ * required by the datastore (e.g., S3's 5MB minimum part size).
42
+ *
43
+ * This prevents inefficient upload/download cycles of incomplete parts by buffering
44
+ * small chunks in memory until they reach the datastore's minimum size requirement.
45
+ * The buffer automatically flushes when the threshold is met, the maximum buffer
46
+ * size is exceeded, or a timeout occurs.
47
+ *
48
+ * @example Basic usage with S3's 5MB minimum
49
+ * ```typescript
50
+ * const buffer = new ChunkBuffer({
51
+ * minThreshold: 5 * 1024 * 1024, // 5MB
52
+ * maxBufferSize: 10 * 1024 * 1024, // 10MB
53
+ * timeoutMs: 30000, // 30 seconds
54
+ * });
55
+ *
56
+ * // Add chunks as they arrive
57
+ * const chunk1 = new Uint8Array(2 * 1024 * 1024); // 2MB
58
+ * buffer.add(chunk1); // Returns null (below threshold)
59
+ *
60
+ * const chunk2 = new Uint8Array(3 * 1024 * 1024); // 3MB
61
+ * const buffered = buffer.add(chunk2); // Returns combined 5MB chunk
62
+ * ```
63
+ *
64
+ * @example Handling incomplete uploads
65
+ * ```typescript
66
+ * const buffer = new ChunkBuffer({ minThreshold: 5 * 1024 * 1024 });
67
+ *
68
+ * // After adding several small chunks
69
+ * buffer.add(smallChunk1);
70
+ * buffer.add(smallChunk2);
71
+ *
72
+ * // Force flush remaining data at end of upload
73
+ * if (buffer.hasPendingData()) {
74
+ * const finalChunk = buffer.flush();
75
+ * await uploadFinalChunk(finalChunk);
76
+ * }
77
+ * ```
78
+ */
79
+ declare class ChunkBuffer {
80
+ private buffer;
81
+ private currentSize;
82
+ private config;
83
+ private lastAddTime;
84
+ /**
85
+ * Creates a new ChunkBuffer instance.
86
+ *
87
+ * @param config - Buffer configuration including thresholds and timeout
88
+ */
89
+ constructor(config: ChunkBufferConfig);
90
+ /**
91
+ * Adds a chunk to the buffer and returns the accumulated chunk if the flush threshold is met.
92
+ *
93
+ * The buffer will automatically flush (return the combined chunk) when:
94
+ * - The total buffered size meets or exceeds minThreshold
95
+ * - The total buffered size exceeds maxBufferSize
96
+ * - The time since the last chunk exceeds timeoutMs
97
+ *
98
+ * @param chunk - The chunk data to add to the buffer
99
+ * @returns The combined buffered chunk if flush conditions are met, null otherwise
100
+ *
101
+ * @example Progressive buffering
102
+ * ```typescript
103
+ * const buffer = new ChunkBuffer({ minThreshold: 1024 * 1024 }); // 1MB
104
+ *
105
+ * // First chunk doesn't meet threshold
106
+ * const result1 = buffer.add(new Uint8Array(512 * 1024)); // 512KB
107
+ * console.log(result1); // null
108
+ *
109
+ * // Second chunk triggers flush
110
+ * const result2 = buffer.add(new Uint8Array(512 * 1024)); // 512KB
111
+ * console.log(result2?.size); // 1048576 (1MB total)
112
+ * ```
113
+ */
114
+ add(chunk: Uint8Array): BufferedChunk | null;
115
+ /**
116
+ * Forces the buffer to flush immediately, returning all accumulated data.
117
+ *
118
+ * This is typically called at the end of an upload to ensure any remaining
119
+ * buffered data is sent, even if it hasn't reached the minimum threshold.
120
+ *
121
+ * @returns The combined buffered chunk, or null if the buffer is empty
122
+ *
123
+ * @example Flushing at upload completion
124
+ * ```typescript
125
+ * const buffer = new ChunkBuffer({ minThreshold: 5 * 1024 * 1024 });
126
+ *
127
+ * // Upload file in chunks
128
+ * for (const chunk of fileChunks) {
129
+ * const buffered = buffer.add(chunk);
130
+ * if (buffered) await uploadChunk(buffered);
131
+ * }
132
+ *
133
+ * // Upload any remaining data
134
+ * const final = buffer.flush();
135
+ * if (final) await uploadChunk(final);
136
+ * ```
137
+ */
138
+ flush(): BufferedChunk | null;
139
+ /**
140
+ * Checks if the buffer should be flushed based on size, max buffer, or timeout conditions.
141
+ *
142
+ * Returns true if any of these conditions are met:
143
+ * - Current size >= minThreshold
144
+ * - Current size >= maxBufferSize
145
+ * - Time since last add > timeoutMs
146
+ *
147
+ * @returns True if the buffer should be flushed
148
+ *
149
+ * @example Manual flush control
150
+ * ```typescript
151
+ * const buffer = new ChunkBuffer({ minThreshold: 1024 * 1024 });
152
+ *
153
+ * buffer.add(smallChunk);
154
+ *
155
+ * if (buffer.shouldFlush()) {
156
+ * const data = buffer.flush();
157
+ * await upload(data);
158
+ * }
159
+ * ```
160
+ */
161
+ shouldFlush(): boolean;
162
+ /**
163
+ * Returns the current buffer state without flushing.
164
+ *
165
+ * Useful for monitoring buffer status and making informed decisions
166
+ * about when to manually flush or adjust upload strategies.
167
+ *
168
+ * @returns Object containing buffer metrics
169
+ *
170
+ * @example Monitoring buffer state
171
+ * ```typescript
172
+ * const buffer = new ChunkBuffer({ minThreshold: 1024 * 1024 });
173
+ * buffer.add(chunk);
174
+ *
175
+ * const info = buffer.getBufferInfo();
176
+ * console.log(`Buffered: ${info.size} bytes in ${info.chunkCount} chunks`);
177
+ * console.log(`Ready to flush: ${info.isReadyToFlush}`);
178
+ * console.log(`Time since last add: ${info.timeSinceLastAdd}ms`);
179
+ * ```
180
+ */
181
+ getBufferInfo(): {
182
+ size: number;
183
+ chunkCount: number;
184
+ isReadyToFlush: boolean;
185
+ timeSinceLastAdd: number;
186
+ };
187
+ /**
188
+ * Checks if the buffer has any pending data that hasn't been flushed.
189
+ *
190
+ * Useful for determining if a final flush is needed at upload completion.
191
+ *
192
+ * @returns True if there are chunks waiting in the buffer
193
+ *
194
+ * @example Ensuring complete upload
195
+ * ```typescript
196
+ * // Upload all chunks
197
+ * for (const chunk of chunks) {
198
+ * const buffered = buffer.add(chunk);
199
+ * if (buffered) await upload(buffered);
200
+ * }
201
+ *
202
+ * // Don't forget the last partial chunk!
203
+ * if (buffer.hasPendingData()) {
204
+ * await upload(buffer.flush());
205
+ * }
206
+ * ```
207
+ */
208
+ hasPendingData(): boolean;
209
+ /**
210
+ * Clears the buffer without returning data.
211
+ *
212
+ * This discards all buffered chunks and resets the buffer state.
213
+ * Use with caution as this will lose any pending data.
214
+ */
215
+ reset(): void;
216
+ /**
217
+ * Returns the minimum threshold this buffer is configured for.
218
+ *
219
+ * @returns Minimum chunk size in bytes before flushing
220
+ */
221
+ getMinThreshold(): number;
222
+ }
223
+ //#endregion
224
+ //#region src/services/abort-controller-service.d.ts
225
+ /**
226
+ * Platform-agnostic AbortController interface
227
+ */
228
+ interface AbortControllerLike {
229
+ readonly signal: AbortSignalLike;
230
+ abort(reason?: unknown): void;
231
+ }
232
+ interface AbortSignalLike {
233
+ readonly aborted: boolean;
234
+ addEventListener(type: "abort", listener: () => void): void;
235
+ removeEventListener(type: "abort", listener: () => void): void;
236
+ }
237
+ interface AbortControllerFactory {
238
+ /**
239
+ * Create a new AbortController instance
240
+ */
241
+ create(): AbortControllerLike;
242
+ }
243
+ //#endregion
244
+ //#region src/services/http-client.d.ts
245
+ /**
246
+ * Platform-agnostic request body type.
247
+ *
248
+ * Supports various data formats for HTTP request bodies across different platforms.
249
+ */
250
+ type RequestBody = string | Uint8Array | ArrayBuffer | null | undefined;
251
+ /**
252
+ * Platform-agnostic HTTP headers interface.
253
+ *
254
+ * Provides a subset of the Web Headers API that works across platforms.
255
+ */
256
+ interface HeadersLike {
257
+ /** Retrieves a header value by name, or null if not found */
258
+ get(name: string): string | null;
259
+ /** Checks if a header exists */
260
+ has(name: string): boolean;
261
+ /** Iterates over all headers */
262
+ forEach(callback: (value: string, name: string) => void): void;
263
+ }
264
+ /**
265
+ * Options for HTTP requests.
266
+ *
267
+ * Platform-agnostic configuration for making HTTP requests with support
268
+ * for headers, body data, abort signals, timeouts, and credentials.
269
+ */
270
+ interface HttpRequestOptions {
271
+ /** HTTP method (GET, POST, PATCH, DELETE, etc.) */
272
+ method?: string;
273
+ /** Request headers as key-value pairs */
274
+ headers?: Record<string, string>;
275
+ /** Request body data */
276
+ body?: unknown;
277
+ /** Abort signal for cancelling the request */
278
+ signal?: AbortSignalLike;
279
+ /** Request timeout in milliseconds */
280
+ timeout?: number;
281
+ /** Credentials mode for cross-origin requests */
282
+ credentials?: "include" | "omit" | "same-origin";
283
+ }
284
+ /**
285
+ * Platform-agnostic HTTP response interface.
286
+ *
287
+ * Provides a subset of the Web Response API that works across platforms.
288
+ */
289
+ interface HttpResponse {
290
+ /** HTTP status code (200, 404, 500, etc.) */
291
+ status: number;
292
+ /** HTTP status text (OK, Not Found, etc.) */
293
+ statusText: string;
294
+ /** Response headers */
295
+ headers: HeadersLike;
296
+ /** True if status is in the 200-299 range */
297
+ ok: boolean;
298
+ /** Parses response body as JSON */
299
+ json(): Promise<unknown>;
300
+ /** Reads response body as text */
301
+ text(): Promise<string>;
302
+ /** Reads response body as ArrayBuffer */
303
+ arrayBuffer(): Promise<ArrayBuffer>;
304
+ }
305
+ /**
306
+ * Configuration for HTTP connection pooling.
307
+ *
308
+ * Controls how connections are managed, reused, and maintained for optimal
309
+ * upload performance. Properly configured connection pooling can significantly
310
+ * improve upload speeds by reusing existing connections.
311
+ */
312
+ interface ConnectionPoolConfig {
313
+ /** Maximum number of concurrent connections per host. Defaults to 8. */
314
+ maxConnectionsPerHost?: number;
315
+ /** Timeout for establishing new connections in milliseconds. Defaults to 20000. */
316
+ connectionTimeout?: number;
317
+ /** How long to keep idle connections alive in milliseconds. Defaults to 90000. */
318
+ keepAliveTimeout?: number;
319
+ /** Enable HTTP/2 for connection multiplexing. Defaults to true. */
320
+ enableHttp2?: boolean;
321
+ /** Automatically retry requests on connection errors. Defaults to true. */
322
+ retryOnConnectionError?: boolean;
323
+ }
324
+ /**
325
+ * Basic connection pool metrics.
326
+ *
327
+ * Provides insight into connection pool performance and efficiency.
328
+ */
329
+ interface ConnectionMetrics {
330
+ /** Number of currently active connections */
331
+ activeConnections: number;
332
+ /** Total connections created since pool initialization */
333
+ totalConnections: number;
334
+ /** Ratio of connection reuse (0-1, higher is better) */
335
+ reuseRate: number;
336
+ /** Average time to establish connections in milliseconds */
337
+ averageConnectionTime: number;
338
+ }
339
+ /**
340
+ * Connection pool health assessment.
341
+ *
342
+ * Provides diagnostic information about connection pool health
343
+ * and recommendations for optimization.
344
+ */
345
+ interface ConnectionHealth {
346
+ /** Overall health status */
347
+ status: "healthy" | "degraded" | "poor";
348
+ /** Health score from 0-100 (higher is better) */
349
+ score: number;
350
+ /** List of identified issues affecting performance */
351
+ issues: string[];
352
+ /** Recommendations for improving connection pool performance */
353
+ recommendations: string[];
354
+ }
355
+ /**
356
+ * HTTP/2 support and status information.
357
+ *
358
+ * Indicates whether HTTP/2 is available and being used,
359
+ * which can significantly improve upload performance through multiplexing.
360
+ */
361
+ interface Http2Info {
362
+ /** Whether HTTP/2 is supported by the platform */
363
+ supported: boolean;
364
+ /** Whether HTTP/2 was detected on the server */
365
+ detected: boolean;
366
+ /** HTTP version being used (e.g., "2.0", "1.1") */
367
+ version: string;
368
+ /** Whether HTTP/2 multiplexing is actively being used */
369
+ multiplexingActive: boolean;
370
+ }
371
+ /**
372
+ * Detailed connection pool metrics with health diagnostics.
373
+ *
374
+ * Extends basic metrics with comprehensive diagnostic information
375
+ * for troubleshooting performance issues.
376
+ */
377
+ interface DetailedConnectionMetrics extends ConnectionMetrics {
378
+ /** Connection pool health assessment */
379
+ health: ConnectionHealth;
380
+ /** Average requests per second */
381
+ requestsPerSecond: number;
382
+ /** Ratio of failed requests (0-1) */
383
+ errorRate: number;
384
+ /** Number of requests that timed out */
385
+ timeouts: number;
386
+ /** Number of requests that were retried */
387
+ retries: number;
388
+ /** Number of fast connections (likely reused) */
389
+ fastConnections: number;
390
+ /** Number of slow connections (likely new) */
391
+ slowConnections: number;
392
+ /** HTTP/2 support and usage information */
393
+ http2Info: Http2Info;
394
+ }
395
+ /**
396
+ * HTTP client interface that provides connection pooling capabilities
397
+ * for optimized upload performance.
398
+ */
399
+ interface HttpClient {
400
+ /**
401
+ * Make an HTTP request using connection pooling
402
+ */
403
+ request(url: string, options?: HttpRequestOptions): Promise<HttpResponse>;
404
+ /**
405
+ * Get current connection pool metrics
406
+ */
407
+ getMetrics(): ConnectionMetrics;
408
+ /**
409
+ * Get detailed connection metrics with health diagnostics
410
+ */
411
+ getDetailedMetrics(): DetailedConnectionMetrics;
412
+ /**
413
+ * Reset connection pool and metrics
414
+ */
415
+ reset(): void;
416
+ /**
417
+ * Gracefully close all connections
418
+ */
419
+ close(): Promise<void>;
420
+ /**
421
+ * Warm up connections by making preflight requests
422
+ */
423
+ warmupConnections(urls: string[]): Promise<void>;
424
+ }
425
+ //#endregion
426
+ //#region src/logger.d.ts
427
+ /**
428
+ * Logger interface for Uploadista client operations.
429
+ *
430
+ * Provides structured logging capabilities for debugging upload progress,
431
+ * flow execution, and client operations. Platform implementations should
432
+ * provide their own logging functions (e.g., console.log, custom loggers).
433
+ *
434
+ * @example Using with console
435
+ * ```typescript
436
+ * const logger = createLogger(true, console.log);
437
+ * logger.log('Upload started');
438
+ * logger.warn('Retrying failed chunk');
439
+ * logger.error('Upload failed');
440
+ * ```
441
+ */
442
+ type Logger = {
443
+ /**
444
+ * Log informational messages (e.g., upload progress, state changes)
445
+ */
446
+ log: (message: string) => void;
447
+ /**
448
+ * Log warning messages (e.g., retry attempts, degraded performance)
449
+ */
450
+ warn: (message: string) => void;
451
+ /**
452
+ * Log error messages (e.g., upload failures, network errors)
453
+ */
454
+ error: (message: string) => void;
455
+ };
456
+ /**
457
+ * Platform-specific logging function type.
458
+ *
459
+ * Accepts a message string and outputs it to the appropriate logging destination.
460
+ * This abstraction allows the client to work across different platforms
461
+ * (browser, Node.js, React Native) with their own logging mechanisms.
462
+ */
463
+ type LogFunction = (message: string) => void;
464
+ /**
465
+ * Creates a Logger instance with configurable output.
466
+ *
467
+ * This factory function creates a logger that can be enabled/disabled
468
+ * and customized with a platform-specific logging function.
469
+ *
470
+ * @param enabled - Whether logging is enabled. When false, all log calls are no-ops
471
+ * @param logFn - Optional custom logging function. Defaults to no-op. Pass console.log for browser/Node.js
472
+ * @returns A Logger instance with log, warn, and error methods
473
+ *
474
+ * @example Basic usage with console
475
+ * ```typescript
476
+ * const logger = createLogger(true, console.log);
477
+ * logger.log('Upload started');
478
+ * ```
479
+ *
480
+ * @example Disabled logger (no output)
481
+ * ```typescript
482
+ * const logger = createLogger(false);
483
+ * logger.log('This will not be logged');
484
+ * ```
485
+ *
486
+ * @example Custom logging function
487
+ * ```typescript
488
+ * const customLog = (msg: string) => {
489
+ * // Send to analytics service
490
+ * analytics.track('upload_log', { message: msg });
491
+ * };
492
+ * const logger = createLogger(true, customLog);
493
+ * ```
494
+ */
495
+ declare function createLogger(enabled: boolean, logFn?: LogFunction): Logger;
496
+ //#endregion
497
+ //#region src/services/platform-service.d.ts
498
+ /**
499
+ * Platform-agnostic service for platform-specific APIs
500
+ * Provides abstraction for timer functions and platform detection
501
+ */
502
+ type Timeout = unknown;
503
+ interface PlatformService {
504
+ /**
505
+ * Schedule a callback to run after a delay
506
+ */
507
+ setTimeout: (callback: () => void, ms: number | undefined) => Timeout;
508
+ /**
509
+ * Cancel a scheduled callback
510
+ */
511
+ clearTimeout: (id: Timeout) => void;
512
+ /**
513
+ * Check if we're in a browser environment
514
+ */
515
+ isBrowser: () => boolean;
516
+ /**
517
+ * Check if network is online
518
+ */
519
+ isOnline: () => boolean;
520
+ /**
521
+ * Check if a value is a File-like object
522
+ */
523
+ isFileLike: (value: unknown) => boolean;
524
+ /**
525
+ * Get file name from File-like object
526
+ */
527
+ getFileName: (file: unknown) => string | undefined;
528
+ /**
529
+ * Get file type from File-like object
530
+ */
531
+ getFileType: (file: unknown) => string | undefined;
532
+ /**
533
+ * Get file size from File-like object
534
+ */
535
+ getFileSize: (file: unknown) => number | undefined;
536
+ /**
537
+ * Get file last modified timestamp from File-like object
538
+ */
539
+ getFileLastModified: (file: unknown) => number | undefined;
540
+ }
541
+ /**
542
+ * Simple async wait utility
543
+ */
544
+ declare function wait(platformService: PlatformService, ms: number): Promise<void>;
545
+ //#endregion
546
+ //#region src/auth/types.d.ts
547
+ declare class BaseAuthManager {
548
+ private type;
549
+ constructor(type: "direct" | "saas" | "no-auth");
550
+ getType(): "direct" | "saas" | "no-auth";
551
+ }
552
+ /**
553
+ * Credentials that can be attached to HTTP requests.
554
+ * Supports headers and cookies for maximum flexibility.
555
+ */
556
+ type RequestCredentials = {
557
+ /** HTTP headers to attach (e.g., Authorization, X-API-Key) */
558
+ headers?: Record<string, string>;
559
+ /** Cookies to attach (primarily for browser environments) */
560
+ cookies?: Record<string, string>;
561
+ };
562
+ /**
563
+ * Direct auth mode configuration.
564
+ * Users provide a function that returns credentials to attach to every request.
565
+ * This mode supports any authentication protocol (OAuth, JWT, sessions, API keys, etc.)
566
+ *
567
+ * @example Bearer token
568
+ * ```typescript
569
+ * {
570
+ * mode: 'direct',
571
+ * getCredentials: async () => ({
572
+ * headers: {
573
+ * 'Authorization': `Bearer ${await getAccessToken()}`
574
+ * }
575
+ * })
576
+ * }
577
+ * ```
578
+ *
579
+ * @example API key
580
+ * ```typescript
581
+ * {
582
+ * mode: 'direct',
583
+ * getCredentials: () => ({
584
+ * headers: {
585
+ * 'X-API-Key': process.env.API_KEY
586
+ * }
587
+ * })
588
+ * }
589
+ * ```
590
+ */
591
+ type DirectAuthConfig = {
592
+ mode: "direct";
593
+ /**
594
+ * Function called before each HTTP request to obtain credentials.
595
+ * Can be async to support token refresh or other async operations.
596
+ * Should not throw - return empty object if credentials unavailable.
597
+ */
598
+ getCredentials?: () => RequestCredentials | Promise<RequestCredentials>;
599
+ };
600
+ /**
601
+ * SaaS auth mode configuration.
602
+ * Client requests JWT tokens from a user-controlled auth server,
603
+ * which validates credentials and issues tokens using a secure API key.
604
+ *
605
+ * Token exchange flow:
606
+ * 1. Client calls getCredentials() to get user credentials
607
+ * 2. Client sends credentials to authServerUrl
608
+ * 3. Auth server validates and returns JWT token
609
+ * 4. Client attaches token to uploadista engine requests
610
+ *
611
+ * @example
612
+ * ```typescript
613
+ * {
614
+ * mode: 'saas',
615
+ * authServerUrl: 'https://auth.myapp.com/token',
616
+ * getCredentials: async () => ({
617
+ * username: await getUsername(),
618
+ * password: await getPassword()
619
+ * })
620
+ * }
621
+ * ```
622
+ */
623
+ type SaasAuthConfig = {
624
+ mode: "saas";
625
+ /**
626
+ * URL of the user's auth server that issues JWT tokens.
627
+ * Should be a GET endpoint that accepts client id and returns { token, expiresIn }.
628
+ */
629
+ authServerUrl: string;
630
+ /**
631
+ * Function that returns user credentials to send to the auth server.
632
+ * The auth server will validate these credentials before issuing a token.
633
+ * Credentials format is client id
634
+ */
635
+ clientId: string;
636
+ };
637
+ /**
638
+ * Authentication configuration for the uploadista client.
639
+ * Supports two modes:
640
+ * - Direct: Bring your own auth (any protocol)
641
+ * - SaaS: Standard JWT token exchange with auth server
642
+ *
643
+ * Use a discriminated union to ensure type safety - TypeScript will
644
+ * enforce that the correct fields are present for each mode.
645
+ */
646
+ type AuthConfig = DirectAuthConfig | SaasAuthConfig;
647
+ //#endregion
648
+ //#region src/auth/direct-auth.d.ts
649
+ /**
650
+ * Direct auth manager - handles credential attachment for "bring your own auth" mode.
651
+ *
652
+ * This manager calls the user-provided getCredentials() function before each request
653
+ * and attaches the returned credentials (headers, cookies) to the HTTP request.
654
+ *
655
+ * Supports any authentication protocol: OAuth, JWT, API keys, session cookies, etc.
656
+ */
657
+ declare class DirectAuthManager extends BaseAuthManager {
658
+ private config;
659
+ private platformService;
660
+ private logger;
661
+ constructor(config: DirectAuthConfig, platformService: PlatformService, logger: Logger);
662
+ /**
663
+ * Attach credentials to an HTTP request by calling getCredentials() and
664
+ * merging the returned headers/cookies with the request.
665
+ *
666
+ * @param headers - Existing request headers
667
+ * @returns Updated headers with credentials attached
668
+ * @throws Error if getCredentials() throws or returns invalid data
669
+ */
670
+ attachCredentials(headers?: Record<string, string>): Promise<Record<string, string>>;
671
+ /**
672
+ * Validate that headers is a valid object with string keys and values
673
+ */
674
+ private validateHeaders;
675
+ /**
676
+ * Attach cookies to request headers.
677
+ * In browser environments, cookies are automatically handled by fetch().
678
+ * In Node.js, we need to manually add them to the Cookie header.
679
+ */
680
+ private attachCookies;
681
+ }
682
+ //#endregion
683
+ //#region src/auth/no-auth.d.ts
684
+ /**
685
+ * No-auth manager - pass-through implementation for backward compatibility.
686
+ *
687
+ * When no auth configuration is provided, this manager is used to maintain
688
+ * a consistent interface without adding any authentication to requests.
689
+ */
690
+ declare class NoAuthManager extends BaseAuthManager {
691
+ constructor();
692
+ /**
693
+ * Pass through headers without modification.
694
+ *
695
+ * @param headers - Existing request headers
696
+ * @returns Same headers unchanged
697
+ */
698
+ attachCredentials(headers?: Record<string, string>): Promise<Record<string, string>>;
699
+ /**
700
+ * No-op for clearing tokens (NoAuthManager doesn't cache anything)
701
+ */
702
+ clearToken(_jobId: string): void;
703
+ /**
704
+ * No-op for clearing all tokens
705
+ */
706
+ clearAllTokens(): void;
707
+ }
708
+ //#endregion
709
+ //#region src/auth/saas-auth.d.ts
710
+ /**
711
+ * Token response from the auth server
712
+ */
713
+ type TokenResponse = {
714
+ /** JWT token to use for authentication */
715
+ token: string;
716
+ /** Token expiration time in seconds (optional) */
717
+ expiresIn?: number;
718
+ };
719
+ /**
720
+ * SaaS auth manager - handles JWT token exchange with an auth server.
721
+ *
722
+ * Token exchange flow:
723
+ * 1. Client calls getCredentials() to get user credentials
724
+ * 2. Manager sends credentials to authServerUrl
725
+ * 3. Auth server validates credentials and returns JWT token
726
+ * 4. Manager caches token and attaches it to uploadista requests
727
+ * 5. Token is cached per job to minimize auth overhead
728
+ *
729
+ * Security: API keys are kept server-side in the auth server, never exposed to clients.
730
+ */
731
+ declare class SaasAuthManager extends BaseAuthManager {
732
+ private config;
733
+ private httpClient;
734
+ /** Token cache: maps job ID to cached token */
735
+ private tokenCache;
736
+ /** Global token for requests without a specific job ID */
737
+ private globalToken;
738
+ constructor(config: SaasAuthConfig, httpClient: HttpClient);
739
+ /**
740
+ * Fetch a JWT token from the auth server using user credentials.
741
+ *
742
+ * @returns Token response with JWT and optional expiry
743
+ * @throws Error if auth server is unreachable or returns an error
744
+ */
745
+ fetchToken(): Promise<TokenResponse>;
746
+ /**
747
+ * Get a cached token for a specific job, or fetch a new one if not cached.
748
+ *
749
+ * @param jobId - Optional job ID to cache token for specific job
750
+ * @returns Cached or newly fetched token
751
+ */
752
+ private getOrFetchToken;
753
+ /**
754
+ * Check if a cached token is expired.
755
+ * Adds a 60-second buffer to avoid using tokens that are about to expire.
756
+ */
757
+ private isTokenExpired;
758
+ /**
759
+ * Attach JWT token to an HTTP request as Authorization Bearer header.
760
+ *
761
+ * @param headers - Existing request headers
762
+ * @param jobId - Optional job ID to use cached token for specific job
763
+ * @returns Updated headers with Authorization header
764
+ * @throws Error if token fetch fails
765
+ */
766
+ attachToken(headers?: Record<string, string>, jobId?: string): Promise<Record<string, string>>;
767
+ /**
768
+ * Clear cached token for a specific job.
769
+ * Should be called when a job completes to free memory.
770
+ *
771
+ * @param jobId - Job ID to clear token for
772
+ */
773
+ clearToken(jobId: string): void;
774
+ /**
775
+ * Clear all cached tokens.
776
+ * Useful for logout or when switching users.
777
+ */
778
+ clearAllTokens(): void;
779
+ /**
780
+ * Get cache statistics for debugging and monitoring.
781
+ */
782
+ getCacheStats(): {
783
+ cachedJobCount: number;
784
+ hasGlobalToken: boolean;
785
+ };
786
+ }
787
+ //#endregion
788
+ //#region src/auth/auth-http-client.d.ts
789
+ /**
790
+ * Union type of all auth managers
791
+ */
792
+ type AuthManager = DirectAuthManager | SaasAuthManager | NoAuthManager;
793
+ //#endregion
794
+ //#region src/network-monitor.d.ts
795
+ /**
796
+ * Assessment of current network conditions based on upload performance.
797
+ *
798
+ * Used by smart chunking algorithms to adapt chunk sizes based on network quality.
799
+ */
800
+ interface NetworkCondition {
801
+ /**
802
+ * Classification of network speed and stability:
803
+ * - "slow": Average speed below slowThreshold (default 50 KB/s)
804
+ * - "fast": Average speed above fastThreshold (default 5 MB/s)
805
+ * - "unstable": High variance in upload speeds
806
+ * - "unknown": Insufficient data to determine condition
807
+ */
808
+ type: "slow" | "fast" | "unstable" | "unknown";
809
+ /**
810
+ * Confidence level in the assessment (0-1).
811
+ * Higher values indicate more samples and more reliable assessment.
812
+ */
813
+ confidence: number;
814
+ }
815
+ /**
816
+ * Aggregated network performance metrics.
817
+ *
818
+ * Provides a comprehensive view of upload performance over time,
819
+ * useful for debugging connectivity issues and optimizing upload strategies.
820
+ */
821
+ interface NetworkMetrics {
822
+ /** Average upload speed in bytes per second */
823
+ averageSpeed: number;
824
+ /** Average network latency in milliseconds */
825
+ latency: number;
826
+ /** Ratio of successful uploads (0-1) */
827
+ successRate: number;
828
+ /** Ratio of failed uploads (0-1) */
829
+ errorRate: number;
830
+ /** Total number of upload requests made */
831
+ totalRequests: number;
832
+ /** Total bytes uploaded successfully */
833
+ totalBytes: number;
834
+ /** Total time spent uploading in milliseconds */
835
+ totalTime: number;
836
+ }
837
+ /**
838
+ * Individual upload sample for network analysis.
839
+ *
840
+ * Each successful or failed upload is recorded as a sample,
841
+ * which is used to calculate network metrics and conditions.
842
+ */
843
+ interface UploadSample {
844
+ /** Size of the uploaded chunk in bytes */
845
+ size: number;
846
+ /** Time taken to upload in milliseconds */
847
+ duration: number;
848
+ /** Whether the upload succeeded */
849
+ success: boolean;
850
+ /** Unix timestamp when the upload occurred */
851
+ timestamp: number;
852
+ /** Optional network latency measurement in milliseconds */
853
+ latency?: number;
854
+ }
855
+ /**
856
+ * Configuration options for NetworkMonitor.
857
+ *
858
+ * Controls how network conditions are assessed and how upload samples
859
+ * are analyzed to determine optimal chunking strategies.
860
+ */
861
+ interface NetworkMonitorConfig {
862
+ /** Maximum number of samples to keep in memory. Defaults to 100. */
863
+ maxSamples?: number;
864
+ /** Smoothing factor for exponential moving average (0-1). Defaults to 0.1. */
865
+ smoothingFactor?: number;
866
+ /** Minimum samples required before assessing network condition. Defaults to 5. */
867
+ minSamplesForCondition?: number;
868
+ /** Upload speed threshold for "slow" classification in bytes/second. Defaults to 50 KB/s. */
869
+ slowThreshold?: number;
870
+ /** Upload speed threshold for "fast" classification in bytes/second. Defaults to 5 MB/s. */
871
+ fastThreshold?: number;
872
+ /** Coefficient of variation threshold for "unstable" classification. Defaults to 0.5. */
873
+ unstableThreshold?: number;
874
+ }
875
+ /**
876
+ * Monitors network performance during uploads to enable adaptive chunking.
877
+ *
878
+ * Tracks upload samples over time and analyzes them to determine network conditions
879
+ * (slow, fast, unstable). This information is used by smart chunking algorithms to
880
+ * dynamically adjust chunk sizes for optimal upload performance.
881
+ *
882
+ * The monitor maintains a rolling window of recent samples and calculates various
883
+ * metrics including average speed, latency, success rate, and throughput stability.
884
+ *
885
+ * @example Basic usage with smart chunking
886
+ * ```typescript
887
+ * const monitor = new NetworkMonitor({
888
+ * maxSamples: 100,
889
+ * slowThreshold: 50 * 1024, // 50 KB/s
890
+ * fastThreshold: 5 * 1024 * 1024, // 5 MB/s
891
+ * });
892
+ *
893
+ * // Record each upload
894
+ * monitor.recordUpload(
895
+ * chunkSize, // bytes
896
+ * duration, // milliseconds
897
+ * true, // success
898
+ * latency // optional latency
899
+ * );
900
+ *
901
+ * // Get current network condition
902
+ * const condition = monitor.getNetworkCondition();
903
+ * if (condition.type === 'slow') {
904
+ * // Use smaller chunks
905
+ * chunkSize = 256 * 1024;
906
+ * } else if (condition.type === 'fast') {
907
+ * // Use larger chunks
908
+ * chunkSize = 5 * 1024 * 1024;
909
+ * }
910
+ * ```
911
+ *
912
+ * @example Monitoring network metrics
913
+ * ```typescript
914
+ * const monitor = new NetworkMonitor();
915
+ *
916
+ * // After some uploads
917
+ * const metrics = monitor.getCurrentMetrics();
918
+ * console.log(`Average speed: ${metrics.averageSpeed / 1024} KB/s`);
919
+ * console.log(`Success rate: ${metrics.successRate * 100}%`);
920
+ * console.log(`Average latency: ${metrics.latency}ms`);
921
+ * ```
922
+ */
923
+ declare class NetworkMonitor {
924
+ private samples;
925
+ private config;
926
+ private _currentMetrics;
927
+ /**
928
+ * Creates a new NetworkMonitor instance.
929
+ *
930
+ * @param config - Optional configuration for thresholds and sample management
931
+ */
932
+ constructor(config?: NetworkMonitorConfig);
933
+ /**
934
+ * Adds a raw upload sample to the monitor.
935
+ *
936
+ * This is called internally by recordUpload but can also be used
937
+ * to add pre-constructed samples for testing or custom tracking.
938
+ *
939
+ * @param sample - The upload sample to add
940
+ */
941
+ addSample(sample: UploadSample): void;
942
+ /**
943
+ * Records an upload operation for network analysis.
944
+ *
945
+ * This is the primary method for tracking upload performance. Each chunk upload
946
+ * should be recorded to build an accurate picture of network conditions.
947
+ *
948
+ * @param size - Size of the uploaded chunk in bytes
949
+ * @param duration - Time taken to upload in milliseconds
950
+ * @param success - Whether the upload succeeded
951
+ * @param latency - Optional network latency measurement in milliseconds
952
+ *
953
+ * @example Recording successful upload
954
+ * ```typescript
955
+ * const startTime = Date.now();
956
+ * await uploadChunk(data);
957
+ * const duration = Date.now() - startTime;
958
+ * monitor.recordUpload(data.length, duration, true);
959
+ * ```
960
+ *
961
+ * @example Recording failed upload
962
+ * ```typescript
963
+ * try {
964
+ * const startTime = Date.now();
965
+ * await uploadChunk(data);
966
+ * monitor.recordUpload(data.length, Date.now() - startTime, true);
967
+ * } catch (error) {
968
+ * monitor.recordUpload(data.length, Date.now() - startTime, false);
969
+ * }
970
+ * ```
971
+ */
972
+ recordUpload(size: number, duration: number, success: boolean, latency?: number): void;
973
+ /**
974
+ * Returns the current network metrics.
975
+ *
976
+ * Provides aggregated statistics about all recorded uploads including
977
+ * average speed, latency, success rate, and totals.
978
+ *
979
+ * @returns A snapshot of current network performance metrics
980
+ *
981
+ * @example
982
+ * ```typescript
983
+ * const metrics = monitor.getCurrentMetrics();
984
+ * console.log(`Speed: ${(metrics.averageSpeed / 1024).toFixed(2)} KB/s`);
985
+ * console.log(`Success: ${(metrics.successRate * 100).toFixed(1)}%`);
986
+ * console.log(`Latency: ${metrics.latency.toFixed(0)}ms`);
987
+ * ```
988
+ */
989
+ getCurrentMetrics(): NetworkMetrics;
990
+ /**
991
+ * Analyzes recent upload samples to determine current network condition.
992
+ *
993
+ * Uses statistical analysis (coefficient of variation, average speed) to classify
994
+ * the network as slow, fast, unstable, or unknown. The confidence level indicates
995
+ * how reliable the assessment is based on the number of samples collected.
996
+ *
997
+ * @returns Current network condition with confidence level
998
+ *
999
+ * @example Adaptive chunking based on network condition
1000
+ * ```typescript
1001
+ * const condition = monitor.getNetworkCondition();
1002
+ *
1003
+ * if (condition.confidence > 0.7) {
1004
+ * switch (condition.type) {
1005
+ * case 'fast':
1006
+ * chunkSize = 10 * 1024 * 1024; // 10MB
1007
+ * break;
1008
+ * case 'slow':
1009
+ * chunkSize = 256 * 1024; // 256KB
1010
+ * break;
1011
+ * case 'unstable':
1012
+ * chunkSize = 1 * 1024 * 1024; // 1MB, conservative
1013
+ * break;
1014
+ * }
1015
+ * }
1016
+ * ```
1017
+ */
1018
+ getNetworkCondition(): NetworkCondition;
1019
+ /**
1020
+ * Calculates the optimal upload throughput based on recent successful uploads.
1021
+ *
1022
+ * Uses a weighted average that gives more weight to recent samples,
1023
+ * providing a responsive measure of current network capacity.
1024
+ *
1025
+ * @returns Optimal throughput in bytes per second, or 0 if no successful samples
1026
+ *
1027
+ * @example Using for chunk size calculation
1028
+ * ```typescript
1029
+ * const throughput = monitor.getOptimalThroughput();
1030
+ * // Target 1 second per chunk
1031
+ * const optimalChunkSize = Math.min(throughput, MAX_CHUNK_SIZE);
1032
+ * ```
1033
+ */
1034
+ getOptimalThroughput(): number;
1035
+ /**
1036
+ * Resets all samples and metrics to initial state.
1037
+ *
1038
+ * Useful when network conditions change significantly or when
1039
+ * starting a new upload session.
1040
+ *
1041
+ * @example Resetting between uploads
1042
+ * ```typescript
1043
+ * // Complete first upload
1044
+ * await uploadFile1();
1045
+ *
1046
+ * // Reset metrics before starting a new upload
1047
+ * monitor.reset();
1048
+ * await uploadFile2();
1049
+ * ```
1050
+ */
1051
+ reset(): void;
1052
+ private getRecentSuccessfulSamples;
1053
+ private updateMetrics;
1054
+ private createEmptyMetrics;
1055
+ }
1056
+ //#endregion
1057
+ //#region src/services/checksum-service.d.ts
1058
+ interface ChecksumService {
1059
+ computeChecksum(data: Uint8Array): Promise<string>;
1060
+ }
1061
+ //#endregion
1062
+ //#region src/services/file-reader-service.d.ts
1063
+ /**
1064
+ * Platform-agnostic file reader service
1065
+ */
1066
+ type SliceResult = {
1067
+ done: true;
1068
+ value: null;
1069
+ size: null;
1070
+ } | {
1071
+ done: boolean;
1072
+ value: Uint8Array;
1073
+ size: number;
1074
+ };
1075
+ interface FileSource {
1076
+ input: unknown;
1077
+ size: number | null;
1078
+ name: string | null;
1079
+ type: string | null;
1080
+ lastModified: number | null;
1081
+ slice: (start: number, end: number) => Promise<SliceResult>;
1082
+ close: () => void;
1083
+ }
1084
+ interface FileReaderService<UploadInput> {
1085
+ /**
1086
+ * Open a file for reading
1087
+ */
1088
+ openFile(input: UploadInput, chunkSize: number): Promise<FileSource>;
1089
+ }
1090
+ interface Base64Service {
1091
+ /**
1092
+ * Encode data to base64
1093
+ */
1094
+ toBase64(data: ArrayBuffer): string;
1095
+ /**
1096
+ * Decode base64 to data
1097
+ */
1098
+ fromBase64(data: string): ArrayBuffer;
1099
+ }
1100
+ //#endregion
1101
+ //#region src/services/fingerprint-service.d.ts
1102
+ interface FingerprintService<UploadInput> {
1103
+ computeFingerprint(file: UploadInput, endpoint: string): Promise<string | null>;
1104
+ }
1105
+ //#endregion
1106
+ //#region src/services/id-generation-service.d.ts
1107
+ /**
1108
+ * Platform-agnostic ID generation service
1109
+ */
1110
+ interface IdGenerationService {
1111
+ /**
1112
+ * Generate a unique identifier
1113
+ */
1114
+ generate(): string;
1115
+ }
1116
+ //#endregion
1117
+ //#region src/services/websocket-service.d.ts
1118
+ /**
1119
+ * Platform-agnostic WebSocket interface
1120
+ */
1121
+ interface WebSocketEventMap {
1122
+ open: unknown;
1123
+ close: unknown;
1124
+ error: unknown;
1125
+ message: unknown;
1126
+ }
1127
+ interface WebSocketLike {
1128
+ readyState: number;
1129
+ readonly CONNECTING: number;
1130
+ readonly OPEN: number;
1131
+ readonly CLOSING: number;
1132
+ readonly CLOSED: number;
1133
+ onopen: (() => void) | null;
1134
+ onclose: ((event: {
1135
+ code: number;
1136
+ reason: string;
1137
+ }) => void) | null;
1138
+ onerror: ((event: {
1139
+ message: string;
1140
+ }) => void) | null;
1141
+ onmessage: ((event: {
1142
+ data: string;
1143
+ }) => void) | null;
1144
+ send(data: string | Uint8Array): void;
1145
+ close(code?: number, reason?: string): void;
1146
+ }
1147
+ interface WebSocketFactory {
1148
+ /**
1149
+ * Create a WebSocket connection to the given URL
1150
+ */
1151
+ create(url: string): WebSocketLike;
1152
+ }
1153
+ //#endregion
1154
+ //#region src/smart-chunker.d.ts
1155
+ interface DatastoreConstraints {
1156
+ minChunkSize: number;
1157
+ maxChunkSize: number;
1158
+ optimalChunkSize: number;
1159
+ requiresOrderedChunks?: boolean;
1160
+ }
1161
+ interface SmartChunkerConfig {
1162
+ enabled?: boolean;
1163
+ fallbackChunkSize?: number;
1164
+ minChunkSize?: number;
1165
+ maxChunkSize?: number;
1166
+ initialChunkSize?: number;
1167
+ targetUtilization?: number;
1168
+ adaptationRate?: number;
1169
+ conservativeMode?: boolean;
1170
+ connectionPoolingAware?: boolean;
1171
+ datastoreConstraints?: DatastoreConstraints;
1172
+ }
1173
+ //#endregion
1174
+ //#region src/services/storage-service.d.ts
1175
+ /**
1176
+ * Platform-agnostic storage service for persisting upload state
1177
+ */
1178
+ interface StorageService {
1179
+ /**
1180
+ * Get an item from storage
1181
+ */
1182
+ getItem(key: string): Promise<string | null>;
1183
+ /**
1184
+ * Set an item in storage
1185
+ */
1186
+ setItem(key: string, value: string): Promise<void>;
1187
+ /**
1188
+ * Remove an item from storage
1189
+ */
1190
+ removeItem(key: string): Promise<void>;
1191
+ /**
1192
+ * Get all items in storage
1193
+ */
1194
+ findAll(): Promise<Record<string, string>>;
1195
+ /**
1196
+ * Find items by prefix
1197
+ */
1198
+ find(prefix: string): Promise<Record<string, string>>;
1199
+ }
1200
+ //#endregion
1201
+ //#region src/types/previous-upload.d.ts
1202
+ type PreviousUpload = {
1203
+ size: number | null;
1204
+ metadata: {
1205
+ [key: string]: string | number | boolean;
1206
+ };
1207
+ creationTime: string;
1208
+ uploadId?: string;
1209
+ parallelUploadUrls?: string[];
1210
+ clientStorageKey: string;
1211
+ };
1212
+ declare const previousUploadSchema: z.ZodObject<{
1213
+ size: z.ZodNullable<z.ZodNumber>;
1214
+ metadata: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
1215
+ creationTime: z.ZodString;
1216
+ uploadId: z.ZodOptional<z.ZodString>;
1217
+ parallelUploadUrls: z.ZodOptional<z.ZodArray<z.ZodString>>;
1218
+ clientStorageKey: z.ZodString;
1219
+ }, z.core.$strip>;
1220
+ //#endregion
1221
+ //#region src/storage/client-storage.d.ts
1222
+ /**
1223
+ * Client-side storage interface for managing upload resumption data.
1224
+ *
1225
+ * Provides methods to store, retrieve, and manage previous upload information,
1226
+ * enabling the client to resume interrupted uploads from where they left off.
1227
+ * This is essential for implementing reliable upload resumption across sessions.
1228
+ *
1229
+ * Storage keys are namespaced with "uploadista::" prefix and organized by
1230
+ * file fingerprint to allow quick lookup of resumable uploads.
1231
+ *
1232
+ * @example Finding resumable uploads
1233
+ * ```typescript
1234
+ * const storage = createClientStorage(localStorage);
1235
+ *
1236
+ * // Find all previous uploads
1237
+ * const allUploads = await storage.findAllUploads();
1238
+ *
1239
+ * // Find uploads for a specific file
1240
+ * const fingerprint = await computeFingerprint(file);
1241
+ * const matches = await storage.findUploadsByFingerprint(fingerprint);
1242
+ *
1243
+ * if (matches.length > 0) {
1244
+ * // Resume from the most recent upload
1245
+ * const uploadId = matches[0].uploadId;
1246
+ * await resumeUpload(uploadId);
1247
+ * }
1248
+ * ```
1249
+ */
1250
+ type ClientStorage = {
1251
+ /**
1252
+ * Retrieves all stored upload records from client storage.
1253
+ *
1254
+ * Useful for debugging or displaying a list of resumable uploads to the user.
1255
+ *
1256
+ * @returns Array of all previous upload records
1257
+ */
1258
+ findAllUploads: () => Promise<PreviousUpload[]>;
1259
+ /**
1260
+ * Finds previous upload records matching a specific file fingerprint.
1261
+ *
1262
+ * This is the primary method for discovering resumable uploads.
1263
+ * Returns uploads sorted by most recent first.
1264
+ *
1265
+ * @param fingerprint - The file fingerprint to search for
1266
+ * @returns Array of matching upload records, or empty array if none found
1267
+ *
1268
+ * @example
1269
+ * ```typescript
1270
+ * const fingerprint = await computeFingerprint(file);
1271
+ * const previous = await storage.findUploadsByFingerprint(fingerprint);
1272
+ *
1273
+ * if (previous.length > 0) {
1274
+ * console.log(`Found ${previous.length} resumable uploads`);
1275
+ * console.log(`Last upload was ${previous[0].offset} bytes`);
1276
+ * }
1277
+ * ```
1278
+ */
1279
+ findUploadsByFingerprint: (fingerprint: string) => Promise<PreviousUpload[]>;
1280
+ /**
1281
+ * Removes an upload record from client storage.
1282
+ *
1283
+ * Called after an upload completes successfully or is explicitly cancelled
1284
+ * to clean up storage and prevent stale resumption attempts.
1285
+ *
1286
+ * @param clientStorageKey - The storage key returned by addUpload
1287
+ *
1288
+ * @example Cleanup after successful upload
1289
+ * ```typescript
1290
+ * await uploadFile(file);
1291
+ * await storage.removeUpload(storageKey);
1292
+ * ```
1293
+ */
1294
+ removeUpload: (clientStorageKey: string) => Promise<void>;
1295
+ /**
1296
+ * Stores an upload record in client storage for future resumption.
1297
+ *
1298
+ * Creates a namespaced storage key that includes the file fingerprint,
1299
+ * making it easy to find resumable uploads later.
1300
+ *
1301
+ * @param fingerprint - File fingerprint for organizing uploads
1302
+ * @param upload - Upload metadata to store (uploadId, offset, etc.)
1303
+ * @param options - Options object containing ID generation service
1304
+ * @returns The storage key that can be used to remove this upload later, or undefined if storage failed
1305
+ *
1306
+ * @example Storing upload progress
1307
+ * ```typescript
1308
+ * const fingerprint = await computeFingerprint(file);
1309
+ * const key = await storage.addUpload(
1310
+ * fingerprint,
1311
+ * { uploadId: 'abc123', offset: 1024000 },
1312
+ * { generateId: idService }
1313
+ * );
1314
+ *
1315
+ * // Later, remove when complete
1316
+ * if (key) await storage.removeUpload(key);
1317
+ * ```
1318
+ */
1319
+ addUpload: (fingerprint: string, upload: PreviousUpload, {
1320
+ generateId
1321
+ }: {
1322
+ generateId: IdGenerationService;
1323
+ }) => Promise<string | undefined>;
1324
+ };
1325
+ /**
1326
+ * Creates a ClientStorage instance using the provided storage service.
1327
+ *
1328
+ * This factory function wraps a platform-specific StorageService (e.g., localStorage,
1329
+ * AsyncStorage) with the ClientStorage interface, providing a consistent API
1330
+ * for upload resumption across different platforms.
1331
+ *
1332
+ * @param storageService - Platform-specific storage implementation
1333
+ * @returns ClientStorage instance for managing upload records
1334
+ *
1335
+ * @example Browser with localStorage
1336
+ * ```typescript
1337
+ * const storage = createClientStorage({
1338
+ * find: async (prefix) => {
1339
+ * const items: Record<string, string> = {};
1340
+ * for (let i = 0; i < localStorage.length; i++) {
1341
+ * const key = localStorage.key(i);
1342
+ * if (key?.startsWith(prefix)) {
1343
+ * items[key] = localStorage.getItem(key) || '';
1344
+ * }
1345
+ * }
1346
+ * return items;
1347
+ * },
1348
+ * setItem: async (key, value) => localStorage.setItem(key, value),
1349
+ * removeItem: async (key) => localStorage.removeItem(key),
1350
+ * });
1351
+ * ```
1352
+ *
1353
+ * @example React Native with AsyncStorage
1354
+ * ```typescript
1355
+ * const storage = createClientStorage({
1356
+ * find: async (prefix) => {
1357
+ * const keys = await AsyncStorage.getAllKeys();
1358
+ * const matching = keys.filter(k => k.startsWith(prefix));
1359
+ * const pairs = await AsyncStorage.multiGet(matching);
1360
+ * return Object.fromEntries(pairs);
1361
+ * },
1362
+ * setItem: async (key, value) => AsyncStorage.setItem(key, value),
1363
+ * removeItem: async (key) => AsyncStorage.removeItem(key),
1364
+ * });
1365
+ * ```
1366
+ */
1367
+ declare function createClientStorage(storageService: StorageService): ClientStorage;
1368
+ //#endregion
1369
+ //#region src/types/flow-upload-config.d.ts
1370
+ /**
1371
+ * Configuration for uploading a file through a flow pipeline.
1372
+ *
1373
+ * Flows enable processing uploaded files through a sequence of transformation
1374
+ * nodes (e.g., image resize, format conversion, validation) before final storage.
1375
+ *
1376
+ * @example Basic flow upload
1377
+ * ```typescript
1378
+ * const config: FlowUploadConfig = {
1379
+ * flowId: 'image-optimization',
1380
+ * storageId: 'processed-images',
1381
+ * };
1382
+ *
1383
+ * await client.uploadWithFlow(file, config, {
1384
+ * onProgress: (progress) => console.log(`${progress}%`),
1385
+ * onSuccess: (result) => console.log('Processed:', result),
1386
+ * });
1387
+ * ```
1388
+ *
1389
+ * @example With specific output node
1390
+ * ```typescript
1391
+ * const config: FlowUploadConfig = {
1392
+ * flowId: 'multi-format-conversion',
1393
+ * storageId: 'images',
1394
+ * outputNodeId: 'webp-output', // Get WebP version instead of first output
1395
+ * metadata: {
1396
+ * userId: '123',
1397
+ * album: 'vacation-2024',
1398
+ * },
1399
+ * };
1400
+ * ```
1401
+ */
1402
+ type FlowUploadConfig = {
1403
+ /** Unique identifier of the flow to execute */
1404
+ flowId: string;
1405
+ /** Storage backend where flow outputs will be saved */
1406
+ storageId: string;
1407
+ /**
1408
+ * Specify which output node to use for single-value callbacks like onSuccess.
1409
+ *
1410
+ * For flows with multiple output nodes, this determines which output
1411
+ * is passed to the onSuccess callback. If not specified, uses the first
1412
+ * output node. The onFlowComplete callback receives all outputs regardless.
1413
+ */
1414
+ outputNodeId?: string;
1415
+ /**
1416
+ * Additional metadata to attach to the upload and flow execution.
1417
+ *
1418
+ * This metadata is stored with the upload and can be used for tracking,
1419
+ * filtering, or providing context to flow nodes.
1420
+ */
1421
+ metadata?: Record<string, string>;
1422
+ };
1423
+ //#endregion
1424
+ //#region src/client/uploadista-api.d.ts
1425
+ /**
1426
+ * Response from upload-related API calls.
1427
+ *
1428
+ * Contains the upload metadata and HTTP status code.
1429
+ */
1430
+ type UploadistaUploadResponse = {
1431
+ /** Upload file metadata, undefined if request failed */
1432
+ upload?: UploadFile;
1433
+ /** HTTP status code */
1434
+ status: number;
1435
+ };
1436
+ /**
1437
+ * Response from delete upload API call.
1438
+ */
1439
+ type UploadistaDeleteUploadResponse = {
1440
+ /** Successfully deleted (no content) */
1441
+ status: 204;
1442
+ } | {
1443
+ /** Other status codes (e.g., 404, 500) */
1444
+ status: number;
1445
+ };
1446
+ /**
1447
+ * Response from flow retrieval API call.
1448
+ */
1449
+ type FlowResponse = {
1450
+ /** HTTP status code */
1451
+ status: number;
1452
+ /** Flow configuration and metadata */
1453
+ flow: FlowData;
1454
+ };
1455
+ /**
1456
+ * Unified Uploadista API interface combining upload and flow operations.
1457
+ *
1458
+ * This low-level API provides direct access to server endpoints for:
1459
+ * - Upload CRUD operations (create, get, delete, patch chunks)
1460
+ * - Flow operations (get, run, continue)
1461
+ * - Job status tracking
1462
+ * - WebSocket connections for real-time updates
1463
+ * - Server capabilities discovery
1464
+ * - Connection pooling metrics
1465
+ *
1466
+ * Most applications should use the higher-level {@link UploadistaClient} instead,
1467
+ * which provides a more convenient interface with automatic retry, resumption,
1468
+ * and smart chunking.
1469
+ *
1470
+ * @example Direct API usage (advanced)
1471
+ * ```typescript
1472
+ * const api = createUploadistaApi(baseUrl, basePath, {
1473
+ * httpClient,
1474
+ * logger,
1475
+ * authManager,
1476
+ * webSocketFactory,
1477
+ * });
1478
+ *
1479
+ * // Create an upload
1480
+ * const { upload } = await api.createUpload({
1481
+ * storageId: 'my-storage',
1482
+ * size: 1024000,
1483
+ * metadata: { filename: 'test.txt' },
1484
+ * });
1485
+ *
1486
+ * // Upload a chunk
1487
+ * const chunk = new Uint8Array(1024);
1488
+ * await api.uploadChunk(upload.id, chunk, {});
1489
+ *
1490
+ * // Check status
1491
+ * const { upload: updated } = await api.getUpload(upload.id);
1492
+ * console.log(`Progress: ${updated.offset}/${updated.size}`);
1493
+ * ```
1494
+ *
1495
+ * @see {@link createUploadistaApi} for creating an instance
1496
+ */
1497
+ type UploadistaApi = {
1498
+ /**
1499
+ * Retrieves upload metadata and current status.
1500
+ *
1501
+ * @param uploadId - Unique upload identifier
1502
+ * @returns Upload metadata including current offset and status
1503
+ * @throws {UploadistaError} If upload not found or request fails
1504
+ */
1505
+ getUpload: (uploadId: string) => Promise<UploadistaUploadResponse>;
1506
+ /**
1507
+ * Deletes an upload and its associated data.
1508
+ *
1509
+ * @param uploadId - Unique upload identifier
1510
+ * @returns Response with status 204 on success
1511
+ * @throws {UploadistaError} If upload not found or deletion fails
1512
+ */
1513
+ deleteUpload: (uploadId: string) => Promise<UploadistaDeleteUploadResponse>;
1514
+ /**
1515
+ * Creates a new upload on the server.
1516
+ *
1517
+ * @param body - Upload configuration including storageId, size, and metadata
1518
+ * @returns Created upload metadata with unique ID
1519
+ * @throws {UploadistaError} If creation fails or validation errors occur
1520
+ */
1521
+ createUpload: (body: InputFile) => Promise<UploadistaUploadResponse>;
1522
+ /**
1523
+ * Uploads a chunk of data to an existing upload.
1524
+ *
1525
+ * @param uploadId - Upload identifier to append data to
1526
+ * @param data - Chunk data bytes, or null to finalize without data
1527
+ * @param options - Upload options including abort controller and progress callback
1528
+ * @returns Updated upload metadata with new offset
1529
+ * @throws {UploadistaError} If chunk upload fails or upload is locked
1530
+ */
1531
+ uploadChunk: (uploadId: string, data: Uint8Array | null, options: {
1532
+ abortController?: AbortControllerLike;
1533
+ onProgress?: (bytes: number, total: number) => void;
1534
+ }) => Promise<UploadistaUploadResponse>;
1535
+ /**
1536
+ * Retrieves flow configuration and metadata.
1537
+ *
1538
+ * @param flowId - Unique flow identifier
1539
+ * @returns Flow configuration including nodes and edges
1540
+ * @throws {UploadistaError} If flow not found
1541
+ */
1542
+ getFlow: (flowId: string) => Promise<FlowResponse>;
1543
+ /**
1544
+ * Executes a flow with the provided inputs.
1545
+ *
1546
+ * @param flowId - Flow to execute
1547
+ * @param storageId - Storage backend to use for flow outputs
1548
+ * @param inputs - Input data for flow nodes (keyed by node ID)
1549
+ * @returns Job metadata including job ID and initial state
1550
+ * @throws {UploadistaError} If flow execution fails or inputs are invalid
1551
+ */
1552
+ runFlow: (flowId: string, storageId: string, inputs: Record<string, unknown>) => Promise<{
1553
+ status: number;
1554
+ job: FlowJob;
1555
+ }>;
1556
+ /**
1557
+ * Continues a paused flow execution with new data.
1558
+ *
1559
+ * Used for interactive flows that wait for user input or external data.
1560
+ *
1561
+ * @param jobId - Job identifier for the paused flow
1562
+ * @param nodeId - Node ID where execution should continue
1563
+ * @param newData - Data to provide to the node
1564
+ * @param options - Options including content type for binary data
1565
+ * @returns Updated job metadata
1566
+ * @throws {UploadistaError} If job not found or continuation fails
1567
+ */
1568
+ continueFlow: (jobId: string, nodeId: string, newData: unknown, options?: {
1569
+ contentType?: "application/json" | "application/octet-stream";
1570
+ }) => Promise<FlowJob>;
1571
+ /**
1572
+ * Retrieves current job status and outputs.
1573
+ *
1574
+ * Works for both upload and flow jobs.
1575
+ *
1576
+ * @param jobId - Job identifier
1577
+ * @returns Job metadata including state, progress, and outputs
1578
+ * @throws {UploadistaError} If job not found
1579
+ */
1580
+ getJobStatus: (jobId: string) => Promise<FlowJob>;
1581
+ /**
1582
+ * Opens a WebSocket connection for upload progress events.
1583
+ *
1584
+ * @param uploadId - Upload to monitor
1585
+ * @returns WebSocket instance for receiving real-time updates
1586
+ */
1587
+ openUploadWebSocket: (uploadId: string) => Promise<WebSocketLike>;
1588
+ /**
1589
+ * Opens a WebSocket connection for flow job events.
1590
+ *
1591
+ * @param jobId - Flow job to monitor
1592
+ * @returns WebSocket instance for receiving real-time updates
1593
+ */
1594
+ openFlowWebSocket: (jobId: string) => Promise<WebSocketLike>;
1595
+ /**
1596
+ * Closes a WebSocket connection.
1597
+ *
1598
+ * @param ws - WebSocket instance to close
1599
+ */
1600
+ closeWebSocket: (ws: WebSocketLike) => void;
1601
+ /**
1602
+ * Returns current connection pool metrics.
1603
+ *
1604
+ * @returns Basic metrics including active connections and reuse rate
1605
+ */
1606
+ getConnectionMetrics: () => ConnectionMetrics;
1607
+ /**
1608
+ * Returns detailed connection pool metrics with health diagnostics.
1609
+ *
1610
+ * @returns Comprehensive metrics including health status and recommendations
1611
+ */
1612
+ getDetailedConnectionMetrics: () => DetailedConnectionMetrics;
1613
+ /**
1614
+ * Pre-warms connections to the specified URLs.
1615
+ *
1616
+ * Useful for reducing latency on first upload by establishing
1617
+ * connections ahead of time.
1618
+ *
1619
+ * @param urls - URLs to pre-connect to
1620
+ */
1621
+ warmupConnections: (urls: string[]) => Promise<void>;
1622
+ /**
1623
+ * Fetches server capabilities for the specified storage backend.
1624
+ *
1625
+ * Returns information about chunk size constraints, supported features,
1626
+ * and storage-specific requirements. Falls back to default capabilities
1627
+ * if the request fails.
1628
+ *
1629
+ * @param storageId - Storage backend identifier
1630
+ * @returns Storage capabilities including chunk size limits
1631
+ */
1632
+ getCapabilities: (storageId: string) => Promise<DataStoreCapabilities>;
1633
+ };
1634
+ /**
1635
+ * Creates an Uploadista API instance for direct server communication.
1636
+ *
1637
+ * This factory creates a low-level API client that handles:
1638
+ * - HTTP requests to upload and flow endpoints
1639
+ * - Authentication via AuthManager (optional)
1640
+ * - WebSocket connections for real-time updates
1641
+ * - Error mapping from server to client error types
1642
+ * - Connection pooling and metrics
1643
+ *
1644
+ * Most applications should use {@link createUploadistaClient} instead,
1645
+ * which wraps this API with higher-level features like automatic retry,
1646
+ * resumption, and smart chunking.
1647
+ *
1648
+ * @param baseURL - Base URL of the Uploadista server (e.g., "https://upload.example.com")
1649
+ * @param uploadistBasePath - Base path for endpoints, typically "uploadista"
1650
+ * @param options - Configuration object
1651
+ * @param options.httpClient - HTTP client for making requests
1652
+ * @param options.logger - Optional logger for debugging
1653
+ * @param options.authManager - Optional authentication manager
1654
+ * @param options.webSocketFactory - Factory for creating WebSocket connections
1655
+ * @returns UploadistaApi instance
1656
+ *
1657
+ * @example Basic API instance
1658
+ * ```typescript
1659
+ * import { createUploadistaApi } from '@uploadista/client-core';
1660
+ *
1661
+ * const api = createUploadistaApi(
1662
+ * 'https://upload.example.com',
1663
+ * 'uploadista',
1664
+ * {
1665
+ * httpClient: myHttpClient,
1666
+ * logger: console,
1667
+ * webSocketFactory: {
1668
+ * create: (url) => new WebSocket(url),
1669
+ * },
1670
+ * }
1671
+ * );
1672
+ *
1673
+ * // Use the API directly
1674
+ * const { upload } = await api.createUpload({
1675
+ * storageId: 'my-storage',
1676
+ * size: 1024,
1677
+ * });
1678
+ * ```
1679
+ *
1680
+ * @example With authentication
1681
+ * ```typescript
1682
+ * const authManager = new DirectAuthManager(authConfig, platformService, logger);
1683
+ *
1684
+ * const api = createUploadistaApi(baseUrl, 'uploadista', {
1685
+ * httpClient,
1686
+ * logger,
1687
+ * authManager, // Automatically adds auth headers to requests
1688
+ * webSocketFactory,
1689
+ * });
1690
+ * ```
1691
+ *
1692
+ * @see {@link UploadistaApi} for the API interface
1693
+ * @see {@link createUploadistaClient} for the high-level client
1694
+ */
1695
+ declare function createUploadistaApi(baseURL: string, uploadistBasePath: string, {
1696
+ httpClient: baseHttpClient,
1697
+ logger,
1698
+ authManager,
1699
+ webSocketFactory
1700
+ }: {
1701
+ httpClient: HttpClient;
1702
+ logger?: Logger;
1703
+ authManager?: AuthManager;
1704
+ webSocketFactory: WebSocketFactory;
1705
+ }): UploadistaApi;
1706
+ //#endregion
1707
+ //#region src/error.d.ts
1708
+ /**
1709
+ * Specific error types that can occur during upload and flow operations.
1710
+ *
1711
+ * These error names provide fine-grained categorization of failures,
1712
+ * allowing applications to implement targeted error handling and recovery strategies.
1713
+ *
1714
+ * @example Error handling by type
1715
+ * ```typescript
1716
+ * try {
1717
+ * await client.upload(file);
1718
+ * } catch (error) {
1719
+ * if (error instanceof UploadistaError) {
1720
+ * if (error.isNetworkError()) {
1721
+ * // Retry network-related failures
1722
+ * console.log('Network issue, retrying...');
1723
+ * } else if (error.name === 'UPLOAD_NOT_FOUND') {
1724
+ * // Handle missing upload
1725
+ * console.log('Upload not found, starting fresh');
1726
+ * }
1727
+ * }
1728
+ * }
1729
+ * ```
1730
+ */
1731
+ type UploadistaErrorName = "UPLOAD_SIZE_NOT_SPECIFIED" | "NETWORK_ERROR" | "NETWORK_UNEXPECTED_RESPONSE" | "UPLOAD_CHUNK_FAILED" | "WRONG_UPLOAD_SIZE" | "UPLOAD_LOCKED" | "UPLOAD_NOT_FOUND" | "CREATE_UPLOAD_FAILED" | "DELETE_UPLOAD_FAILED" | "PARALLEL_SEGMENT_CREATION_FAILED" | "PARALLEL_SEGMENT_UPLOAD_FAILED" | "FLOW_NOT_FOUND" | "FLOW_INIT_FAILED" | "FLOW_RUN_FAILED" | "FLOW_CONTINUE_FAILED" | "FLOW_UNEXPECTED_STATE" | "FLOW_INCOMPATIBLE" | "FLOW_NO_UPLOAD_ID" | "FLOW_TIMEOUT" | "FLOW_FINALIZE_FAILED" | "JOB_NOT_FOUND" | "WEBSOCKET_AUTH_FAILED";
1732
+ /**
1733
+ * Custom error class for all Uploadista client operations.
1734
+ *
1735
+ * Extends the standard Error class with additional context including
1736
+ * typed error names, HTTP status codes, and underlying error causes.
1737
+ * This allows for precise error handling and debugging.
1738
+ *
1739
+ * @example Basic error handling
1740
+ * ```typescript
1741
+ * try {
1742
+ * await client.upload(file);
1743
+ * } catch (error) {
1744
+ * if (error instanceof UploadistaError) {
1745
+ * console.log(`Error: ${error.name} - ${error.message}`);
1746
+ * console.log(`HTTP Status: ${error.status}`);
1747
+ * }
1748
+ * }
1749
+ * ```
1750
+ *
1751
+ * @example Network error detection
1752
+ * ```typescript
1753
+ * try {
1754
+ * await client.upload(file);
1755
+ * } catch (error) {
1756
+ * if (error instanceof UploadistaError && error.isNetworkError()) {
1757
+ * // Implement retry logic for network failures
1758
+ * await retryWithBackoff(() => client.upload(file));
1759
+ * }
1760
+ * }
1761
+ * ```
1762
+ */
1763
+ declare class UploadistaError extends Error {
1764
+ /**
1765
+ * Typed error name indicating the specific type of failure
1766
+ */
1767
+ name: UploadistaErrorName;
1768
+ /**
1769
+ * Human-readable error message describing what went wrong
1770
+ */
1771
+ message: string;
1772
+ /**
1773
+ * The underlying error that caused this failure, if any
1774
+ */
1775
+ cause: Error | undefined;
1776
+ /**
1777
+ * HTTP status code from the server response, if applicable
1778
+ */
1779
+ status: number | undefined;
1780
+ /**
1781
+ * Creates a new UploadistaError instance.
1782
+ *
1783
+ * @param options - Error configuration
1784
+ * @param options.name - Typed error name for categorization
1785
+ * @param options.message - Descriptive error message
1786
+ * @param options.cause - Optional underlying error that caused this failure
1787
+ * @param options.status - Optional HTTP status code from server response
1788
+ */
1789
+ constructor({
1790
+ name,
1791
+ message,
1792
+ cause,
1793
+ status
1794
+ }: {
1795
+ name: UploadistaErrorName;
1796
+ message: string;
1797
+ cause?: Error;
1798
+ status?: number;
1799
+ });
1800
+ /**
1801
+ * Checks if this error is related to network connectivity issues.
1802
+ *
1803
+ * Network errors are typically transient and may succeed on retry,
1804
+ * making them good candidates for automatic retry logic.
1805
+ *
1806
+ * @returns True if this is a network-related error
1807
+ *
1808
+ * @example
1809
+ * ```typescript
1810
+ * if (error.isNetworkError()) {
1811
+ * // Safe to retry
1812
+ * await retry(() => uploadChunk());
1813
+ * }
1814
+ * ```
1815
+ */
1816
+ isNetworkError(): boolean;
1817
+ }
1818
+ //#endregion
1819
+ //#region src/services/service-container.d.ts
1820
+ /**
1821
+ * Service container for dependency injection
1822
+ */
1823
+ interface ServiceContainer<UploadInput> {
1824
+ storage: StorageService;
1825
+ idGeneration: IdGenerationService;
1826
+ httpClient: HttpClient;
1827
+ fileReader: FileReaderService<UploadInput>;
1828
+ base64?: Base64Service;
1829
+ websocket: WebSocketFactory;
1830
+ abortController: AbortControllerFactory;
1831
+ platform: PlatformService;
1832
+ checksumService: ChecksumService;
1833
+ fingerprintService: FingerprintService<UploadInput>;
1834
+ }
1835
+ //#endregion
1836
+ //#region src/types/upload-response.d.ts
1837
+ type UploadResponse = {
1838
+ upload?: UploadFile$1;
1839
+ status: number;
1840
+ };
1841
+ //#endregion
1842
+ //#region src/upload/chunk-upload.d.ts
1843
+ type OnProgress = (uploadId: string, bytesSent: number, bytesTotal: number | null) => void;
1844
+ type OnShouldRetry = (error: UploadistaError, retryAttempt: number) => boolean;
1845
+ //#endregion
1846
+ //#region src/types/chunk-metrics.d.ts
1847
+ interface ChunkMetrics {
1848
+ chunkIndex: number;
1849
+ size: number;
1850
+ duration: number;
1851
+ speed: number;
1852
+ success: boolean;
1853
+ retryCount: number;
1854
+ timestamp: number;
1855
+ networkCondition?: string;
1856
+ chunkingStrategy?: string;
1857
+ }
1858
+ //#endregion
1859
+ //#region src/types/performance-insights.d.ts
1860
+ interface PerformanceInsights {
1861
+ overallEfficiency: number;
1862
+ chunkingEffectiveness: number;
1863
+ networkStability: number;
1864
+ recommendations: string[];
1865
+ optimalChunkSizeRange: {
1866
+ min: number;
1867
+ max: number;
1868
+ };
1869
+ }
1870
+ //#endregion
1871
+ //#region src/types/upload-session-metrics.d.ts
1872
+ interface UploadSessionMetrics {
1873
+ uploadId: string;
1874
+ totalSize: number;
1875
+ totalDuration: number;
1876
+ chunksCompleted: number;
1877
+ chunksTotal: number;
1878
+ averageSpeed: number;
1879
+ peakSpeed: number;
1880
+ minSpeed: number;
1881
+ totalRetries: number;
1882
+ successRate: number;
1883
+ adaptiveChunkingEnabled: boolean;
1884
+ startTime: number;
1885
+ endTime?: number;
1886
+ }
1887
+ //#endregion
1888
+ //#region src/upload/upload-metrics.d.ts
1889
+ interface UploadMetricsConfig {
1890
+ maxChunkHistory?: number;
1891
+ enableDetailedMetrics?: boolean;
1892
+ performanceThresholds?: {
1893
+ slowSpeed: number;
1894
+ fastSpeed: number;
1895
+ highRetryRate: number;
1896
+ };
1897
+ }
1898
+ //#endregion
1899
+ //#region src/upload/single-upload.d.ts
1900
+ type Callbacks = {
1901
+ onProgress?: OnProgress;
1902
+ onChunkComplete?: (chunkSize: number, bytesAccepted: number, bytesTotal: number | null) => void;
1903
+ onSuccess?: (payload: UploadFile) => void;
1904
+ onError?: (error: Error | UploadistaError) => void;
1905
+ onStart?: (file: {
1906
+ uploadId: string;
1907
+ size: number | null;
1908
+ }) => void;
1909
+ onJobStart?: (jobId: string) => void;
1910
+ onShouldRetry?: OnShouldRetry;
1911
+ };
1912
+ //#endregion
1913
+ //#region src/upload/upload-manager.d.ts
1914
+ /**
1915
+ * Abort any running request and stop the current upload. After abort is called, no event
1916
+ * handler will be invoked anymore. You can use the `start` method to resume the upload
1917
+ * again.
1918
+ * If `shouldTerminate` is true, the `terminate` function will be called to remove the
1919
+ * current upload from the server.
1920
+ */
1921
+ declare function abort({
1922
+ uploadId,
1923
+ uploadIdStorageKey,
1924
+ retryTimeout,
1925
+ shouldTerminate,
1926
+ abortController,
1927
+ uploadistaApi,
1928
+ platformService,
1929
+ retryDelays,
1930
+ clientStorage
1931
+ }: {
1932
+ uploadId: string;
1933
+ uploadIdStorageKey: string | undefined;
1934
+ retryTimeout: Timeout | null;
1935
+ shouldTerminate: boolean;
1936
+ abortController: AbortControllerLike;
1937
+ uploadistaApi: UploadistaApi;
1938
+ platformService: PlatformService;
1939
+ retryDelays?: number[];
1940
+ clientStorage: ClientStorage;
1941
+ }): Promise<void>;
1942
+ //#endregion
1943
+ //#region src/upload/upload-strategy.d.ts
1944
+ type UploadStrategyConfig = {
1945
+ preferredStrategy?: "single" | "parallel" | "auto";
1946
+ minFileSizeForParallel?: number;
1947
+ enableCapabilityNegotiation?: boolean;
1948
+ onStrategySelected?: (strategy: {
1949
+ chosen: "single" | "parallel";
1950
+ chunkSize: number;
1951
+ parallelUploads: number;
1952
+ reasoning: string[];
1953
+ warnings: string[];
1954
+ }) => void;
1955
+ };
1956
+ //#endregion
1957
+ //#region src/client/uploadista-websocket-manager.d.ts
1958
+ type UploadistaEvent = UploadEvent | FlowEvent;
1959
+ type UploadistaWebSocketEventHandler = (event: UploadistaEvent) => void;
1960
+ type UploadistaWebSocketMessage = {
1961
+ type: "connection";
1962
+ message: string;
1963
+ id: string;
1964
+ timestamp: string;
1965
+ } | {
1966
+ type: "subscribed";
1967
+ payload: {
1968
+ uploadId?: string;
1969
+ jobId?: string;
1970
+ };
1971
+ timestamp: string;
1972
+ } | {
1973
+ type: "error";
1974
+ message: string;
1975
+ code?: string;
1976
+ } | {
1977
+ type: "pong";
1978
+ timestamp: string;
1979
+ } | {
1980
+ type: "upload_event";
1981
+ payload: UploadEvent;
1982
+ } | {
1983
+ type: "flow_event";
1984
+ payload: FlowEvent;
1985
+ };
1986
+ /**
1987
+ * Unified WebSocket management for both upload and flow events
1988
+ */
1989
+ declare class UploadistaWebSocketManager {
1990
+ private uploadistaApi;
1991
+ private logger;
1992
+ private onEvent?;
1993
+ private uploadWebsockets;
1994
+ private flowWebsockets;
1995
+ constructor(uploadistaApi: UploadistaApi, logger: Logger, onEvent?: UploadistaWebSocketEventHandler | undefined);
1996
+ /**
1997
+ * Open a WebSocket connection for upload events
1998
+ */
1999
+ openUploadWebSocket(uploadId: string): Promise<WebSocketLike>;
2000
+ /**
2001
+ * Open a WebSocket connection for flow/job events
2002
+ */
2003
+ openFlowWebSocket(jobId: string): Promise<WebSocketLike>;
2004
+ /**
2005
+ * Open a unified WebSocket connection - automatically determines if it's for upload or flow
2006
+ * based on the ID format (upload IDs typically start with 'upload-', job IDs start with 'job-')
2007
+ */
2008
+ openWebSocket(id: string): Promise<WebSocketLike>;
2009
+ /**
2010
+ * Close upload WebSocket connection
2011
+ */
2012
+ closeUploadWebSocket(uploadId: string): void;
2013
+ /**
2014
+ * Close flow WebSocket connection
2015
+ */
2016
+ closeFlowWebSocket(jobId: string): void;
2017
+ /**
2018
+ * Close WebSocket connection by ID (auto-detects type)
2019
+ */
2020
+ closeWebSocket(id: string): void;
2021
+ /**
2022
+ * Close all WebSocket connections (both upload and flow)
2023
+ */
2024
+ closeAll(): void;
2025
+ /**
2026
+ * Send ping to flow WebSocket
2027
+ */
2028
+ sendPing(jobId: string): boolean;
2029
+ /**
2030
+ * Get upload WebSocket by ID
2031
+ */
2032
+ getUploadWebSocket(uploadId: string): WebSocketLike | undefined;
2033
+ /**
2034
+ * Get flow WebSocket by ID
2035
+ */
2036
+ getFlowWebSocket(jobId: string): WebSocketLike | undefined;
2037
+ /**
2038
+ * Check if upload WebSocket is connected
2039
+ */
2040
+ isUploadConnected(uploadId: string): boolean;
2041
+ /**
2042
+ * Check if flow WebSocket is connected
2043
+ */
2044
+ isFlowConnected(jobId: string): boolean;
2045
+ /**
2046
+ * Check if WebSocket is connected (auto-detects type)
2047
+ */
2048
+ isConnected(id: string): boolean;
2049
+ /**
2050
+ * Get total number of active WebSocket connections
2051
+ */
2052
+ getConnectionCount(): number;
2053
+ /**
2054
+ * Get connection counts by type
2055
+ */
2056
+ getConnectionCountByType(): {
2057
+ upload: number;
2058
+ flow: number;
2059
+ total: number;
2060
+ };
2061
+ }
2062
+ //#endregion
2063
+ //#region src/client/create-uploadista-client.d.ts
2064
+ /**
2065
+ * Options for individual upload operations.
2066
+ *
2067
+ * Extends the base upload callbacks with configuration for deferred length,
2068
+ * size overrides, metadata, and checksum computation.
2069
+ */
2070
+ type UploadistaUploadOptions = {
2071
+ /**
2072
+ * Whether to defer specifying the upload size until later.
2073
+ * Useful for streaming uploads where size isn't known upfront.
2074
+ * Defaults to false.
2075
+ */
2076
+ uploadLengthDeferred?: boolean;
2077
+ /**
2078
+ * Manual override for upload size in bytes.
2079
+ * If not provided, size is determined from the file/blob.
2080
+ */
2081
+ uploadSize?: number;
2082
+ /**
2083
+ * Custom metadata to attach to the upload.
2084
+ * Stored as key-value pairs on the server.
2085
+ */
2086
+ metadata?: Record<string, string>;
2087
+ /**
2088
+ * Whether to compute checksums for uploaded chunks.
2089
+ * Enables integrity verification but adds computational overhead.
2090
+ * Defaults to false.
2091
+ */
2092
+ computeChecksum?: boolean;
2093
+ /**
2094
+ * Checksum algorithm to use (e.g., "sha256", "md5").
2095
+ * Only relevant if computeChecksum is true.
2096
+ */
2097
+ checksumAlgorithm?: string;
2098
+ } & Callbacks;
2099
+ /**
2100
+ * Configuration options for creating an Uploadista client.
2101
+ *
2102
+ * This comprehensive configuration object allows customization of all aspects
2103
+ * of upload behavior including chunking, retries, authentication, storage,
2104
+ * network monitoring, and platform-specific services.
2105
+ *
2106
+ * @template UploadInput - The platform-specific file/blob type (e.g., File, Blob, Buffer)
2107
+ */
2108
+ type UploadistaClientOptions<UploadInput> = {
2109
+ /** Base URL of the Uploadista server (e.g., "https://upload.example.com") */
2110
+ baseUrl: string;
2111
+ /** Base path for Uploadista endpoints. Defaults to "uploadista" */
2112
+ uploadistaBasePath?: string;
2113
+ /** Storage backend identifier configured on the server */
2114
+ storageId: string;
2115
+ /** Retry delay intervals in milliseconds. Defaults to [1000, 3000, 5000] */
2116
+ retryDelays?: number[];
2117
+ /** Default chunk size in bytes for uploads */
2118
+ chunkSize: number;
2119
+ /** Number of parallel upload streams. Defaults to 1 (sequential) */
2120
+ parallelUploads?: number;
2121
+ /** Chunk size for parallel uploads. Required if parallelUploads > 1 */
2122
+ parallelChunkSize?: number;
2123
+ /** Service for computing checksums of uploaded chunks */
2124
+ checksumService: ChecksumService;
2125
+ /** Strategy configuration for determining upload approach (single/parallel/chunked) */
2126
+ uploadStrategy?: UploadStrategyConfig;
2127
+ /** Smart chunking configuration for adaptive chunk sizes based on network conditions */
2128
+ smartChunking?: SmartChunkerConfig;
2129
+ /** Network monitoring configuration for tracking upload performance */
2130
+ networkMonitoring?: NetworkMonitorConfig;
2131
+ /** Upload metrics configuration for performance insights */
2132
+ uploadMetrics?: UploadMetricsConfig;
2133
+ /** HTTP client with connection pooling support */
2134
+ httpClient: HttpClient;
2135
+ /** Service for generating unique IDs */
2136
+ generateId: IdGenerationService;
2137
+ /** Client-side storage for upload resumption data */
2138
+ clientStorage: ClientStorage;
2139
+ /** Platform-specific file reading service */
2140
+ fileReader: FileReaderService<UploadInput>;
2141
+ /** Logger for debugging and monitoring */
2142
+ logger: Logger;
2143
+ /** Service for computing file fingerprints for resumption */
2144
+ fingerprintService: FingerprintService<UploadInput>;
2145
+ /** Whether to store fingerprints for upload resumption. Defaults to true */
2146
+ storeFingerprintForResuming: boolean;
2147
+ /** Factory for creating WebSocket connections */
2148
+ webSocketFactory: WebSocketFactory;
2149
+ /** Factory for creating abort controllers */
2150
+ abortControllerFactory: AbortControllerFactory;
2151
+ /** Platform-specific service for timers and async operations */
2152
+ platformService: PlatformService;
2153
+ /** Global error handler for all upload operations */
2154
+ onError?: (error: Error) => void;
2155
+ /** WebSocket event handler for real-time upload/flow events */
2156
+ onEvent?: UploadistaWebSocketEventHandler;
2157
+ /**
2158
+ * Optional authentication configuration.
2159
+ * Supports two modes:
2160
+ * - Direct: Bring your own auth (headers, cookies, custom tokens)
2161
+ * - SaaS: Standard JWT token exchange with auth server
2162
+ *
2163
+ * If omitted, client operates in no-auth mode (backward compatible).
2164
+ *
2165
+ * @example Direct mode with Bearer token
2166
+ * ```typescript
2167
+ * auth: {
2168
+ * mode: 'direct',
2169
+ * getCredentials: () => ({
2170
+ * headers: { 'Authorization': 'Bearer token123' }
2171
+ * })
2172
+ * }
2173
+ * ```
2174
+ *
2175
+ * @example SaaS mode with auth server
2176
+ * ```typescript
2177
+ * auth: {
2178
+ * mode: 'saas',
2179
+ * authServerUrl: 'https://auth.myapp.com/token',
2180
+ * getCredentials: () => ({ username: 'user', password: 'pass' })
2181
+ * }
2182
+ * ```
2183
+ */
2184
+ auth?: AuthConfig;
2185
+ };
2186
+ /**
2187
+ * Default connection pooling configuration with health monitoring.
2188
+ *
2189
+ * Optimized for typical upload scenarios with support for HTTP/2 multiplexing,
2190
+ * connection reuse, and automatic retry on connection errors.
2191
+ */
2192
+ declare const defaultConnectionPoolingConfig: ConnectionPoolConfig;
2193
+ /**
2194
+ * Creates a unified Uploadista client for file uploads and flow processing.
2195
+ *
2196
+ * This is the primary factory function for creating an Uploadista client instance.
2197
+ * It configures all upload capabilities including:
2198
+ * - Resumable chunked uploads with automatic retry
2199
+ * - Parallel upload streams for large files
2200
+ * - Smart chunking based on network conditions
2201
+ * - Flow-based file processing pipelines
2202
+ * - WebSocket support for real-time progress
2203
+ * - Authentication (direct, SaaS, or no-auth modes)
2204
+ *
2205
+ * The client automatically:
2206
+ * - Fetches server capabilities and adapts upload strategy
2207
+ * - Monitors network performance for optimal chunking
2208
+ * - Stores upload state for resumption across sessions
2209
+ * - Manages WebSocket connections for progress tracking
2210
+ *
2211
+ * @template UploadInput - Platform-specific file type (File, Blob, Buffer, etc.)
2212
+ * @param options - Comprehensive client configuration
2213
+ * @returns Uploadista client instance with upload and flow methods
2214
+ *
2215
+ * @example Basic browser setup
2216
+ * ```typescript
2217
+ * import { createUploadistaClient } from '@uploadista/client-core';
2218
+ * import { browserServices } from '@uploadista/client-browser';
2219
+ *
2220
+ * const client = createUploadistaClient({
2221
+ * baseUrl: 'https://upload.example.com',
2222
+ * storageId: 'my-storage',
2223
+ * chunkSize: 5 * 1024 * 1024, // 5MB chunks
2224
+ * ...browserServices,
2225
+ * });
2226
+ *
2227
+ * // Upload a file
2228
+ * const { abort } = await client.upload(file, {
2229
+ * onProgress: (progress) => console.log(`${progress}% complete`),
2230
+ * onSuccess: (result) => console.log('Upload complete:', result),
2231
+ * });
2232
+ * ```
2233
+ *
2234
+ * @example Upload with flow processing
2235
+ * ```typescript
2236
+ * const client = createUploadistaClient(config);
2237
+ *
2238
+ * // Upload and process through a flow
2239
+ * const { abort, jobId } = await client.uploadWithFlow(file, {
2240
+ * flowId: 'image-optimization-flow',
2241
+ * storageId: 'images',
2242
+ * outputNodeId: 'optimized-output',
2243
+ * }, {
2244
+ * onProgress: (progress) => console.log(`${progress}%`),
2245
+ * onSuccess: (result) => console.log('Processed:', result),
2246
+ * });
2247
+ *
2248
+ * // Monitor job status
2249
+ * const status = await client.getJobStatus(jobId);
2250
+ * ```
2251
+ *
2252
+ * @example Parallel uploads for large files
2253
+ * ```typescript
2254
+ * const client = createUploadistaClient({
2255
+ * baseUrl: 'https://upload.example.com',
2256
+ * storageId: 'large-files',
2257
+ * chunkSize: 10 * 1024 * 1024, // 10MB
2258
+ * parallelUploads: 4, // 4 concurrent streams
2259
+ * parallelChunkSize: 5 * 1024 * 1024, // 5MB per stream
2260
+ * ...browserServices,
2261
+ * });
2262
+ *
2263
+ * await client.upload(largeFile);
2264
+ * ```
2265
+ *
2266
+ * @example With authentication
2267
+ * ```typescript
2268
+ * const client = createUploadistaClient({
2269
+ * baseUrl: 'https://upload.example.com',
2270
+ * storageId: 'protected',
2271
+ * chunkSize: 5 * 1024 * 1024,
2272
+ * auth: {
2273
+ * mode: 'direct',
2274
+ * getCredentials: async () => ({
2275
+ * headers: {
2276
+ * 'Authorization': `Bearer ${await getToken()}`,
2277
+ * },
2278
+ * }),
2279
+ * },
2280
+ * ...browserServices,
2281
+ * });
2282
+ * ```
2283
+ *
2284
+ * @example Smart chunking with network monitoring
2285
+ * ```typescript
2286
+ * const client = createUploadistaClient({
2287
+ * baseUrl: 'https://upload.example.com',
2288
+ * storageId: 'adaptive',
2289
+ * chunkSize: 1 * 1024 * 1024, // Fallback: 1MB
2290
+ * smartChunking: {
2291
+ * enabled: true,
2292
+ * minChunkSize: 256 * 1024, // 256KB min
2293
+ * maxChunkSize: 10 * 1024 * 1024, // 10MB max
2294
+ * },
2295
+ * networkMonitoring: {
2296
+ * slowThreshold: 50 * 1024, // 50 KB/s
2297
+ * fastThreshold: 5 * 1024 * 1024, // 5 MB/s
2298
+ * },
2299
+ * ...browserServices,
2300
+ * });
2301
+ *
2302
+ * // Monitor network conditions
2303
+ * const condition = client.getNetworkCondition();
2304
+ * console.log(`Network: ${condition.type} (confidence: ${condition.confidence})`);
2305
+ * ```
2306
+ *
2307
+ * @see {@link UploadistaClientOptions} for full configuration options
2308
+ * @see {@link UploadistaUploadOptions} for per-upload options
2309
+ */
2310
+ declare function createUploadistaClient<UploadInput>({
2311
+ baseUrl: _baseUrl,
2312
+ uploadistaBasePath,
2313
+ storageId,
2314
+ retryDelays,
2315
+ chunkSize,
2316
+ parallelUploads,
2317
+ parallelChunkSize,
2318
+ uploadStrategy,
2319
+ smartChunking,
2320
+ networkMonitoring,
2321
+ uploadMetrics,
2322
+ checksumService,
2323
+ onEvent,
2324
+ generateId,
2325
+ httpClient,
2326
+ logger,
2327
+ fileReader,
2328
+ fingerprintService,
2329
+ clientStorage,
2330
+ storeFingerprintForResuming,
2331
+ webSocketFactory,
2332
+ abortControllerFactory,
2333
+ platformService,
2334
+ auth
2335
+ }: UploadistaClientOptions<UploadInput>): {
2336
+ upload: (file: UploadInput, {
2337
+ uploadLengthDeferred,
2338
+ uploadSize,
2339
+ onProgress,
2340
+ onChunkComplete,
2341
+ onSuccess,
2342
+ onShouldRetry,
2343
+ onError
2344
+ }?: UploadistaUploadOptions) => Promise<{
2345
+ abort: () => void;
2346
+ }>;
2347
+ uploadWithFlow: (file: UploadInput, flowConfig: FlowUploadConfig, {
2348
+ onProgress,
2349
+ onChunkComplete,
2350
+ onSuccess,
2351
+ onShouldRetry,
2352
+ onJobStart,
2353
+ onError
2354
+ }?: Omit<UploadistaUploadOptions, "uploadLengthDeferred" | "uploadSize" | "metadata">) => Promise<{
2355
+ abort: () => void;
2356
+ jobId: string;
2357
+ }>;
2358
+ abort: (params: Parameters<typeof abort>[0]) => Promise<void>;
2359
+ getFlow: (flowId: string) => Promise<{
2360
+ status: number;
2361
+ flow: _uploadista_core0.FlowData;
2362
+ }>;
2363
+ runFlow: ({
2364
+ flowId,
2365
+ inputs,
2366
+ storageId: flowStorageId
2367
+ }: {
2368
+ flowId: string;
2369
+ inputs: Record<string, unknown>;
2370
+ storageId?: string;
2371
+ }) => Promise<{
2372
+ status: number;
2373
+ job: _uploadista_core0.FlowJob;
2374
+ }>;
2375
+ continueFlow: ({
2376
+ jobId,
2377
+ nodeId,
2378
+ newData,
2379
+ contentType
2380
+ }: {
2381
+ jobId: string;
2382
+ nodeId: string;
2383
+ newData: unknown;
2384
+ contentType?: "application/json" | "application/octet-stream";
2385
+ }) => Promise<_uploadista_core0.FlowJob>;
2386
+ getJobStatus: (jobId: string) => Promise<_uploadista_core0.FlowJob>;
2387
+ openUploadWebSocket: (uploadId: string) => Promise<WebSocketLike>;
2388
+ openFlowWebSocket: (jobId: string) => Promise<WebSocketLike>;
2389
+ openWebSocket: (id: string) => Promise<WebSocketLike>;
2390
+ closeWebSocket: (id: string) => void;
2391
+ closeAllWebSockets: () => void;
2392
+ sendPing: (jobId: string) => boolean;
2393
+ isWebSocketConnected: (id: string) => boolean;
2394
+ getWebSocketConnectionCount: () => number;
2395
+ getWebSocketConnectionCountByType: () => {
2396
+ upload: number;
2397
+ flow: number;
2398
+ total: number;
2399
+ };
2400
+ getNetworkMetrics: () => NetworkMetrics;
2401
+ getNetworkCondition: () => NetworkCondition;
2402
+ getChunkingInsights: () => PerformanceInsights;
2403
+ exportMetrics: () => {
2404
+ session: Partial<UploadSessionMetrics>;
2405
+ chunks: ChunkMetrics[];
2406
+ insights: PerformanceInsights;
2407
+ };
2408
+ getConnectionMetrics: () => ConnectionMetrics;
2409
+ getDetailedConnectionMetrics: () => DetailedConnectionMetrics;
2410
+ warmupConnections: (urls: string[]) => Promise<void>;
2411
+ getConnectionPoolingInsights: () => Promise<{
2412
+ isOptimized: boolean;
2413
+ reuseRate: number;
2414
+ recommendedMinChunkSize: number;
2415
+ connectionOverhead: number;
2416
+ }>;
2417
+ resetMetrics: () => Promise<void>;
2418
+ validateConfiguration: (options: UploadistaClientOptions<UploadInput>) => {
2419
+ valid: boolean;
2420
+ errors: string[];
2421
+ warnings: string[];
2422
+ };
2423
+ validateConfigurationAsync: (options: UploadistaClientOptions<UploadInput>) => Promise<{
2424
+ valid: boolean;
2425
+ errors: string[];
2426
+ warnings: string[];
2427
+ capabilities: DataStoreCapabilities;
2428
+ }>;
2429
+ getCapabilities: () => Promise<DataStoreCapabilities>;
2430
+ };
2431
+ /**
2432
+ * Uploadista client instance type.
2433
+ *
2434
+ * The client provides methods for:
2435
+ * - **Upload operations**: upload(), uploadWithFlow()
2436
+ * - **Flow operations**: getFlow(), runFlow(), continueFlow()
2437
+ * - **Job management**: getJobStatus()
2438
+ * - **WebSocket management**: openUploadWebSocket(), openFlowWebSocket(), closeWebSocket()
2439
+ * - **Metrics and diagnostics**: getNetworkMetrics(), getChunkingInsights(), exportMetrics()
2440
+ * - **Connection pooling**: getConnectionMetrics(), warmupConnections()
2441
+ * - **Configuration validation**: validateConfiguration(), validateConfigurationAsync()
2442
+ *
2443
+ * @example Basic usage
2444
+ * ```typescript
2445
+ * const client = createUploadistaClient(config);
2446
+ *
2447
+ * // Upload a file
2448
+ * await client.upload(file, {
2449
+ * onProgress: (progress) => console.log(`${progress}%`),
2450
+ * onSuccess: (result) => console.log('Done:', result.id),
2451
+ * });
2452
+ *
2453
+ * // Get network metrics
2454
+ * const metrics = client.getNetworkMetrics();
2455
+ * console.log(`Speed: ${metrics.averageSpeed / 1024} KB/s`);
2456
+ * ```
2457
+ *
2458
+ * @see {@link createUploadistaClient} for creating an instance
2459
+ */
2460
+ type UploadistaClient = ReturnType<typeof createUploadistaClient>;
2461
+ //#endregion
2462
+ //#region src/storage/in-memory-storage-service.d.ts
2463
+ /**
2464
+ * In-memory fallback storage service for Expo
2465
+ * Used when AsyncStorage is not available or for testing
2466
+ */
2467
+ declare function createInMemoryStorageService(): StorageService;
2468
+ //#endregion
2469
+ //#region src/types/flow-result.d.ts
2470
+ type FlowResult<TOutput = UploadFile> = {
2471
+ type: "success";
2472
+ value: TOutput;
2473
+ } | {
2474
+ type: "error";
2475
+ error: Error;
2476
+ } | {
2477
+ type: "cancelled";
2478
+ };
2479
+ //#endregion
2480
+ //#region src/types/flow-upload-item.d.ts
2481
+ /**
2482
+ * Flow upload item for multi-flow-upload tracking
2483
+ */
2484
+ interface FlowUploadItem<UploadInput> {
2485
+ id: string;
2486
+ file: UploadInput;
2487
+ status: "pending" | "uploading" | "success" | "error" | "aborted";
2488
+ progress: number;
2489
+ bytesUploaded: number;
2490
+ totalBytes: number;
2491
+ error: Error | null;
2492
+ result: UploadFile$1 | null;
2493
+ jobId: string | null;
2494
+ }
2495
+ //#endregion
2496
+ //#region src/types/flow-upload-options.d.ts
2497
+ interface FlowUploadOptions<TOutput = UploadFile> {
2498
+ /**
2499
+ * Flow configuration
2500
+ */
2501
+ flowConfig: FlowUploadConfig;
2502
+ /**
2503
+ * Called when upload progress updates
2504
+ */
2505
+ onProgress?: (progress: number, bytesUploaded: number, totalBytes: number | null) => void;
2506
+ /**
2507
+ * Called when a chunk completes
2508
+ */
2509
+ onChunkComplete?: (chunkSize: number, bytesAccepted: number, bytesTotal: number | null) => void;
2510
+ /**
2511
+ * Called when the flow completes successfully (receives full flow outputs)
2512
+ * This is the recommended callback for multi-output flows
2513
+ * Format: { [outputNodeId]: result, ... }
2514
+ */
2515
+ onFlowComplete?: (outputs: Record<string, unknown>) => void;
2516
+ /**
2517
+ * Called when upload succeeds (legacy, single-output flows)
2518
+ * For single-output flows, receives the value from the specified outputNodeId
2519
+ * or the first output node if outputNodeId is not specified
2520
+ */
2521
+ onSuccess?: (result: TOutput) => void;
2522
+ /**
2523
+ * Called when upload fails
2524
+ */
2525
+ onError?: (error: Error) => void;
2526
+ /**
2527
+ * Called when upload is aborted
2528
+ */
2529
+ onAbort?: () => void;
2530
+ /**
2531
+ * Custom retry logic
2532
+ */
2533
+ onShouldRetry?: (error: Error, retryAttempt: number) => boolean;
2534
+ }
2535
+ //#endregion
2536
+ //#region src/types/multi-flow-upload-options.d.ts
2537
+ interface MultiFlowUploadOptions<UploadInput> {
2538
+ /**
2539
+ * Flow configuration
2540
+ */
2541
+ flowConfig: FlowUploadConfig;
2542
+ /**
2543
+ * Maximum number of concurrent uploads (default: 3)
2544
+ */
2545
+ maxConcurrent?: number;
2546
+ /**
2547
+ * Called when an individual upload progresses
2548
+ */
2549
+ onItemProgress?: (item: FlowUploadItem<UploadInput>) => void;
2550
+ /**
2551
+ * Called when an individual upload succeeds
2552
+ */
2553
+ onItemSuccess?: (item: FlowUploadItem<UploadInput>) => void;
2554
+ /**
2555
+ * Called when an individual upload fails
2556
+ */
2557
+ onItemError?: (item: FlowUploadItem<UploadInput>, error: Error) => void;
2558
+ /**
2559
+ * Called when all uploads complete
2560
+ */
2561
+ onComplete?: (items: FlowUploadItem<UploadInput>[]) => void;
2562
+ /**
2563
+ * Custom retry logic
2564
+ */
2565
+ onShouldRetry?: (error: Error, retryAttempt: number) => boolean;
2566
+ }
2567
+ //#endregion
2568
+ //#region src/types/multi-flow-upload-state.d.ts
2569
+ interface MultiFlowUploadState<UploadInput> {
2570
+ items: FlowUploadItem<UploadInput>[];
2571
+ totalProgress: number;
2572
+ activeUploads: number;
2573
+ completedUploads: number;
2574
+ failedUploads: number;
2575
+ }
2576
+ //#endregion
2577
+ //#region src/types/upload-options.d.ts
2578
+ interface UploadOptions {
2579
+ /**
2580
+ * Upload metadata to attach to the file
2581
+ */
2582
+ metadata?: Record<string, string>;
2583
+ /**
2584
+ * Whether to defer the upload size calculation
2585
+ */
2586
+ uploadLengthDeferred?: boolean;
2587
+ /**
2588
+ * Manual upload size override
2589
+ */
2590
+ uploadSize?: number;
2591
+ /**
2592
+ * Called when upload progress updates
2593
+ */
2594
+ onProgress?: (progress: number, bytesUploaded: number, totalBytes: number | null) => void;
2595
+ /**
2596
+ * Called when a chunk completes
2597
+ */
2598
+ onChunkComplete?: (chunkSize: number, bytesAccepted: number, bytesTotal: number | null) => void;
2599
+ /**
2600
+ * Called when upload succeeds
2601
+ */
2602
+ onSuccess?: (result: UploadFile$1) => void;
2603
+ /**
2604
+ * Called when upload fails
2605
+ */
2606
+ onError?: (error: Error) => void;
2607
+ /**
2608
+ * Called when upload is aborted
2609
+ */
2610
+ onAbort?: () => void;
2611
+ /**
2612
+ * Custom retry logic
2613
+ */
2614
+ onShouldRetry?: (error: Error, retryAttempt: number) => boolean;
2615
+ }
2616
+ //#endregion
2617
+ //#region src/types/upload-result.d.ts
2618
+ /**
2619
+ * Discriminated union representing the result of an upload operation.
2620
+ *
2621
+ * Provides a type-safe way to handle the three possible outcomes of an upload:
2622
+ * success, error, or cancellation. This pattern enables exhaustive checking
2623
+ * of all cases at compile time.
2624
+ *
2625
+ * @template TOutput - The type of the successful result value. Defaults to UploadFile
2626
+ *
2627
+ * @example Handling upload results
2628
+ * ```typescript
2629
+ * function handleUploadResult(result: UploadResult) {
2630
+ * switch (result.type) {
2631
+ * case 'success':
2632
+ * console.log('Upload complete:', result.value.id);
2633
+ * break;
2634
+ * case 'error':
2635
+ * console.error('Upload failed:', result.error.message);
2636
+ * break;
2637
+ * case 'cancelled':
2638
+ * console.log('Upload was cancelled by user');
2639
+ * break;
2640
+ * }
2641
+ * }
2642
+ * ```
2643
+ *
2644
+ * @example With custom output type
2645
+ * ```typescript
2646
+ * interface ProcessedImage {
2647
+ * url: string;
2648
+ * width: number;
2649
+ * height: number;
2650
+ * }
2651
+ *
2652
+ * const result: UploadResult<ProcessedImage> = await uploadAndProcess(file);
2653
+ *
2654
+ * if (result.type === 'success') {
2655
+ * console.log(`Image processed: ${result.value.width}x${result.value.height}`);
2656
+ * }
2657
+ * ```
2658
+ */
2659
+ type UploadResult<TOutput = UploadFile$1> = {
2660
+ /** Indicates the upload completed successfully */
2661
+ type: "success";
2662
+ /** The successful result value (e.g., upload metadata or processed output) */
2663
+ value: TOutput;
2664
+ } | {
2665
+ /** Indicates the upload failed with an error */
2666
+ type: "error";
2667
+ /** The error that caused the upload to fail */
2668
+ error: Error;
2669
+ } | {
2670
+ /** Indicates the upload was cancelled by the user or application */
2671
+ type: "cancelled";
2672
+ };
2673
+ //#endregion
2674
+ export { AbortControllerFactory, AbortControllerLike, AbortSignalLike, Base64Service, ChecksumService, ChunkBuffer, ChunkBufferConfig, ChunkMetrics, ClientStorage, ConnectionHealth, ConnectionMetrics, ConnectionPoolConfig, DetailedConnectionMetrics, FileReaderService, FileSource, FingerprintService, FlowResponse, FlowResult, FlowUploadConfig, FlowUploadItem, FlowUploadOptions, HeadersLike, Http2Info, HttpClient, HttpRequestOptions, HttpResponse, IdGenerationService, LogFunction, Logger, MultiFlowUploadOptions, MultiFlowUploadState, NetworkCondition, NetworkMetrics, NetworkMonitor, NetworkMonitorConfig, PerformanceInsights, PlatformService, PreviousUpload, RequestBody, ServiceContainer, SliceResult, StorageService, Timeout, UploadOptions, UploadResponse, UploadResult, UploadSample, UploadSessionMetrics, UploadistaApi, UploadistaClient, UploadistaClientOptions, UploadistaDeleteUploadResponse, UploadistaError, UploadistaErrorName, UploadistaEvent, UploadistaUploadOptions, UploadistaUploadResponse, UploadistaWebSocketEventHandler, UploadistaWebSocketManager, UploadistaWebSocketMessage, WebSocketEventMap, WebSocketFactory, WebSocketLike, createClientStorage, createInMemoryStorageService, createLogger, createUploadistaApi, createUploadistaClient, defaultConnectionPoolingConfig, previousUploadSchema, wait };
9
2675
  //# sourceMappingURL=index.d.ts.map