@wlindabla/file_uploader 1.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +54 -28
  2. package/dist/cjs/cache/index.d.ts +198 -0
  3. package/dist/cjs/cache/index.js +318 -0
  4. package/dist/cjs/cache/index.js.map +1 -0
  5. package/dist/cjs/core/index.d.ts +271 -0
  6. package/dist/cjs/core/index.js +762 -0
  7. package/dist/cjs/core/index.js.map +1 -0
  8. package/dist/cjs/events/chunk/index.d.ts +27 -0
  9. package/dist/cjs/events/chunk/index.js +70 -0
  10. package/dist/cjs/events/chunk/index.js.map +1 -0
  11. package/dist/cjs/events/complete/index.d.ts +64 -0
  12. package/dist/cjs/events/complete/index.js +152 -0
  13. package/dist/cjs/events/complete/index.js.map +1 -0
  14. package/dist/cjs/events/index.d.ts +95 -0
  15. package/dist/cjs/events/index.js +85 -0
  16. package/dist/cjs/events/index.js.map +1 -0
  17. package/dist/cjs/events/initialize/index.d.ts +45 -0
  18. package/dist/cjs/events/initialize/index.js +105 -0
  19. package/dist/cjs/events/initialize/index.js.map +1 -0
  20. package/dist/cjs/events/state/index.d.ts +67 -0
  21. package/dist/cjs/events/state/index.js +145 -0
  22. package/dist/cjs/events/state/index.js.map +1 -0
  23. package/dist/cjs/exceptions/index.d.ts +84 -0
  24. package/dist/{exceptions → cjs/exceptions}/index.js +38 -18
  25. package/dist/cjs/exceptions/index.js.map +1 -0
  26. package/dist/cjs/index.d.ts +14 -0
  27. package/dist/cjs/index.js +33 -0
  28. package/dist/cjs/index.js.map +1 -0
  29. package/dist/cjs/subscribers/index.d.ts +34 -0
  30. package/dist/cjs/subscribers/index.js +187 -0
  31. package/dist/cjs/subscribers/index.js.map +1 -0
  32. package/dist/cjs/types/index.d.ts +110 -0
  33. package/dist/cjs/types/index.js +53 -0
  34. package/dist/cjs/types/index.js.map +1 -0
  35. package/dist/cjs/utils/index.d.ts +72 -0
  36. package/dist/cjs/utils/index.js +208 -0
  37. package/dist/cjs/utils/index.js.map +1 -0
  38. package/dist/esm/cache/index.d.mts +198 -0
  39. package/dist/esm/cache/index.js +4 -0
  40. package/dist/{index.js.map → esm/cache/index.js.map} +1 -1
  41. package/dist/{events/initialize/index.js → esm/chunk-3JTTZCSQ.js} +25 -19
  42. package/dist/esm/chunk-3JTTZCSQ.js.map +1 -0
  43. package/dist/{events/state/index.js → esm/chunk-6225YMFE.js} +38 -20
  44. package/dist/esm/chunk-6225YMFE.js.map +1 -0
  45. package/dist/esm/chunk-7QVYU63E.js +6 -0
  46. package/dist/esm/chunk-7QVYU63E.js.map +1 -0
  47. package/dist/{events/complete/index.js → esm/chunk-BNMI7DW3.js} +25 -19
  48. package/dist/esm/chunk-BNMI7DW3.js.map +1 -0
  49. package/dist/{subscribers/index.js → esm/chunk-HYNJBWW5.js} +36 -34
  50. package/dist/esm/chunk-HYNJBWW5.js.map +1 -0
  51. package/dist/{events/index.js → esm/chunk-JDL3U4OX.js} +7 -37
  52. package/dist/esm/chunk-JDL3U4OX.js.map +1 -0
  53. package/dist/{events/chunk/index.js → esm/chunk-LD2DWZRJ.js} +14 -11
  54. package/dist/esm/chunk-LD2DWZRJ.js.map +1 -0
  55. package/dist/{utils/index.js → esm/chunk-MFYC4PBP.js} +15 -22
  56. package/dist/esm/chunk-MFYC4PBP.js.map +1 -0
  57. package/dist/esm/chunk-NXYS73I4.js +125 -0
  58. package/dist/esm/chunk-NXYS73I4.js.map +1 -0
  59. package/dist/{cache/index.js → esm/chunk-PFALORWQ.js} +10 -11
  60. package/dist/esm/chunk-PFALORWQ.js.map +1 -0
  61. package/dist/{core/index.js → esm/chunk-TONVXBLH.js} +239 -231
  62. package/dist/esm/chunk-TONVXBLH.js.map +1 -0
  63. package/dist/{types/index.js → esm/chunk-X757PBC5.js} +5 -7
  64. package/dist/esm/chunk-X757PBC5.js.map +1 -0
  65. package/dist/esm/core/index.d.mts +271 -0
  66. package/dist/esm/core/index.js +12 -0
  67. package/dist/esm/core/index.js.map +1 -0
  68. package/dist/esm/events/chunk/index.d.mts +27 -0
  69. package/dist/esm/events/chunk/index.js +4 -0
  70. package/dist/esm/events/chunk/index.js.map +1 -0
  71. package/dist/esm/events/complete/index.d.mts +64 -0
  72. package/dist/esm/events/complete/index.js +4 -0
  73. package/dist/esm/events/complete/index.js.map +1 -0
  74. package/dist/esm/events/index.d.mts +95 -0
  75. package/dist/esm/events/index.js +8 -0
  76. package/dist/esm/events/index.js.map +1 -0
  77. package/dist/esm/events/initialize/index.d.mts +45 -0
  78. package/dist/esm/events/initialize/index.js +4 -0
  79. package/dist/esm/events/initialize/index.js.map +1 -0
  80. package/dist/esm/events/state/index.d.mts +67 -0
  81. package/dist/esm/events/state/index.js +4 -0
  82. package/dist/esm/events/state/index.js.map +1 -0
  83. package/dist/esm/exceptions/index.d.mts +84 -0
  84. package/dist/esm/exceptions/index.js +4 -0
  85. package/dist/esm/exceptions/index.js.map +1 -0
  86. package/dist/esm/index.d.mts +14 -0
  87. package/dist/esm/index.js +14 -0
  88. package/dist/esm/index.js.map +1 -0
  89. package/dist/esm/subscribers/index.d.mts +34 -0
  90. package/dist/esm/subscribers/index.js +10 -0
  91. package/dist/esm/subscribers/index.js.map +1 -0
  92. package/dist/esm/types/index.d.mts +110 -0
  93. package/dist/esm/types/index.js +4 -0
  94. package/dist/esm/types/index.js.map +1 -0
  95. package/dist/esm/utils/index.d.mts +72 -0
  96. package/dist/esm/utils/index.js +5 -0
  97. package/dist/esm/utils/index.js.map +1 -0
  98. package/package.json +165 -14
  99. package/dist/cache/index.js.map +0 -1
  100. package/dist/core/index.js.map +0 -1
  101. package/dist/events/chunk/index.js.map +0 -1
  102. package/dist/events/complete/index.js.map +0 -1
  103. package/dist/events/index.js.map +0 -1
  104. package/dist/events/initialize/index.js.map +0 -1
  105. package/dist/events/state/index.js.map +0 -1
  106. package/dist/exceptions/index.js.map +0 -1
  107. package/dist/index.js +0 -49
  108. package/dist/subscribers/index.js.map +0 -1
  109. package/dist/types/index.js.map +0 -1
  110. package/dist/utils/index.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/cache/index.ts"],"sourcesContent":["/*\n * This file is part of the project by AGBOKOUDJO Franck.\n *\n * (c) AGBOKOUDJO Franck <internationaleswebservices@gmail.com>\n * Phone: +229 0167 25 18 86\n * LinkedIn: https://www.linkedin.com/in/internationales-web-apps-services-120520193/\n * Company: INTERNATIONALES WEB APPS & SERVICES\n *\n * For more information, please feel free to contact the author.\n */\n\nimport { ResumeData } from \"../types\"\n\n/**\n * Interface for caching upload resume data.\n * \n * This interface extends the base cache functionality to specifically\n * handle resume data for file uploads, allowing uploads to be paused\n * and resumed across browser sessions.\n * \n * \n * @example\n * ```typescript\n * const cache: UploadResumeCacheInterface = new LocalStorageUploadResumeCache();\n * \n * // Save progress\n * await cache.setItem('video.mp4', {\n * uploadedChunks: 45,\n * totalChunks: 100,\n * lastBytePosition: 47185920\n * });\n * \n * // Resume later\n * const data = await cache.getItem('video.mp4');\n * console.log(`Resume from chunk ${data.uploadedChunks}`);\n * ```\n */\nexport interface UploadResumeCacheInterface {\n /**\n * Retrieves cached resume data for a specific upload.\n * \n * @param key - Unique identifier for the upload (typically filename or file hash)\n * @returns Promise resolving to the cached resume data\n * @throws {Error} If the key doesn't exist or data is corrupted\n */\n getItem(key: string): Promise<ResumeData>;\n\n /**\n * Stores resume data for an upload session.\n * \n * @param key - Unique identifier for the upload\n * @param data - Resume data containing upload progress information\n * @returns Promise that resolves when data is successfully cached\n * @throws {Error} If storage quota is exceeded or data is invalid\n */\n setItem(key: string, data: ResumeData): Promise<void>;\n}\n\n/**\n * Default adapter for caching resume data during file uploads.\n * \n * Implements an in-memory storage strategy with secure serialization,\n * strict data validation, and comprehensive error handling.\n * \n * This implementation serves as a foundation for specialized adapters\n * (localStorage, IndexedDB, sessionStorage, etc.).\n * \n * @implements {UploadResumeCacheInterface}\n * \n * @example\n * ```typescript\n * const adapter = new DefaultUploadResumeCacheAdapter();\n * \n * // Save resume data\n * await adapter.setItem('upload-123', {\n * fileId: 'file-abc',\n * fileName: 'document.pdf',\n * fileSize: 5242880,\n * uploadedChunks: 12,\n * lastChunkIndex: 11,\n * lastBytePosition: 1258291,\n * chunkSize: 1048576\n * });\n * \n * // Retrieve and resume\n * const resumeData = await adapter.getItem('upload-123');\n * console.log(`Resume from chunk ${resumeData.uploadedChunks}`);\n * \n * // Remove specific item\n * await adapter.removeItem('upload-123');\n * \n * // Clear all cache\n * await adapter.clear();\n * ```\n */\nexport class DefaultUploadResumeCacheAdapter implements UploadResumeCacheInterface {\n\n private cache: Map<string, ResumeData> = new Map();\n private readonly maxCacheSize: number = 100;\n\n constructor() {\n this.validateEnvironment();\n }\n\n /**\n * Validates that the runtime environment is appropriate.\n * \n * @private\n * @throws {UploadCacheError} If the environment is incompatible\n */\n private validateEnvironment(): void {\n if (typeof window === 'undefined') {\n console.warn(\n '[UploadResumeCacheAdapter] Server-side execution detected. ' +\n 'Consider a server-compatible adapter for persistent storage.'\n );\n }\n }\n\n /**\n * Validates resume data according to strict criteria.\n * \n * @private\n * @param data - The data to validate\n * @throws {UploadCacheError} If the data is invalid\n */\n private validateResumeData(data: ResumeData): void {\n if (!data || typeof data !== 'object') {\n throw new UploadCacheError(\n 'Resume data must be a valid object',\n 'INVALID_DATA'\n );\n }\n\n // Validate required fields\n const requiredFields: (keyof ResumeData)[] = [\n 'fileId',\n 'fileName',\n 'fileSize',\n 'uploadedChunks',\n 'lastChunkIndex',\n 'lastBytePosition',\n 'chunkSize'\n ];\n\n for (const field of requiredFields) {\n if (!(field in data)) {\n throw new UploadCacheError(\n `Required field '${field}' is missing`,\n 'MISSING_FIELD'\n );\n }\n }\n\n // Validate types\n if (typeof data.fileId !== 'string' || !data.fileId.trim()) {\n throw new UploadCacheError(\n 'fileId must be a non-empty string',\n 'INVALID_FILE_ID'\n );\n }\n\n if (typeof data.fileName !== 'string' || !data.fileName.trim()) {\n throw new UploadCacheError(\n 'fileName must be a non-empty string',\n 'INVALID_FILE_NAME'\n );\n }\n\n // Validate numbers\n if (!Number.isFinite(data.fileSize) || data.fileSize <= 0) {\n throw new UploadCacheError(\n 'fileSize must be a positive number',\n 'INVALID_FILE_SIZE'\n );\n }\n\n if (!Number.isFinite(data.chunkSize) || data.chunkSize <= 0) {\n throw new UploadCacheError(\n 'chunkSize must be a positive number',\n 'INVALID_CHUNK_SIZE'\n );\n }\n\n if (!Number.isInteger(data.uploadedChunks) || data.uploadedChunks < 0) {\n throw new UploadCacheError(\n 'uploadedChunks must be a non-negative integer',\n 'INVALID_UPLOADED_CHUNKS'\n );\n }\n\n if (!Number.isInteger(data.lastChunkIndex) || data.lastChunkIndex < -1) {\n throw new UploadCacheError(\n 'lastChunkIndex must be an integer >= -1',\n 'INVALID_LAST_CHUNK_INDEX'\n );\n }\n\n if (!Number.isFinite(data.lastBytePosition) || data.lastBytePosition < 0) {\n throw new UploadCacheError(\n 'lastBytePosition must be a non-negative number',\n 'INVALID_BYTE_POSITION'\n );\n }\n\n // Validate logical consistency\n if (data.uploadedChunks > 0 && data.lastBytePosition === 0) {\n throw new UploadCacheError(\n 'lastBytePosition cannot be 0 if chunks have been uploaded',\n 'INCONSISTENT_DATA'\n );\n }\n\n const expectedMaxChunks = Math.ceil(data.fileSize / data.chunkSize);\n if (data.uploadedChunks > expectedMaxChunks) {\n throw new UploadCacheError(\n `uploadedChunks (${data.uploadedChunks}) exceeds maximum expected (${expectedMaxChunks})`,\n 'INCONSISTENT_DATA'\n );\n }\n }\n\n /**\n * Retrieves resume data for a specific upload.\n * \n * @param key - Unique identifier for the upload\n * @returns Promise resolved with the resume data\n * @throws {UploadCacheError} If the key does not exist or data is corrupted\n * \n * @example\n * ```typescript\n * try {\n * const data = await adapter.getItem('upload-123');\n * console.log(`${data.uploadedChunks}/${Math.ceil(data.fileSize / data.chunkSize)} chunks`);\n * } catch (error) {\n * console.error('Failed to retrieve data:', error.message);\n * }\n * ```\n */\n async getItem(key: string): Promise<ResumeData> {\n return new Promise((resolve, reject) => {\n try {\n if (!key || typeof key !== 'string') {\n reject(new UploadCacheError(\n 'Key must be a non-empty string',\n 'INVALID_KEY'\n ));\n return;\n }\n\n const data = this.cache.get(key);\n\n if (!data) {\n reject(new UploadCacheError(\n `Resume data for key '${key}' was not found`,\n 'NOT_FOUND'\n ));\n return;\n }\n\n // Return a deep copy to prevent external mutations\n resolve(JSON.parse(JSON.stringify(data)));\n } catch (error) {\n reject(new UploadCacheError(\n `Error retrieving data: ${error instanceof Error ? error.message : String(error)}`,\n 'RETRIEVAL_ERROR'\n ));\n }\n });\n }\n\n /**\n * Stores resume data for an upload session.\n * \n * @param key - Unique identifier for the upload\n * @param data - Resume data containing upload progress information\n * @returns Promise resolved when data is successfully cached\n * @throws {UploadCacheError} If quota is exceeded or data is invalid\n * \n * @example\n * ```typescript\n * try {\n * await adapter.setItem('upload-123', {\n * fileId: 'file-abc',\n * fileName: 'video.mp4',\n * fileSize: 10737418240,\n * uploadedChunks: 45,\n * lastChunkIndex: 44,\n * lastBytePosition: 47185920,\n * chunkSize: 1048576\n * });\n * console.log('Data successfully saved');\n * } catch (error) {\n * console.error('Storage error:', error.message);\n * }\n * ```\n */\n async setItem(key: string, data: ResumeData): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n if (!key || typeof key !== 'string') {\n reject(new UploadCacheError(\n 'Key must be a non-empty string',\n 'INVALID_KEY'\n ));\n return;\n }\n\n this.validateResumeData(data);\n\n // Check cache limit\n if (this.cache.size >= this.maxCacheSize && !this.cache.has(key)) {\n reject(new UploadCacheError(\n `Cache limit (${this.maxCacheSize} entries) has been reached. ` +\n 'Remove obsolete entries or use an adapter with persistent storage.',\n 'CACHE_LIMIT_EXCEEDED'\n ));\n return;\n }\n\n // Store a deep copy\n this.cache.set(key, JSON.parse(JSON.stringify(data)));\n resolve();\n } catch (error) {\n if (error instanceof UploadCacheError) {\n reject(error);\n } else {\n reject(new UploadCacheError(\n `Error storing data: ${error instanceof Error ? error.message : String(error)}`,\n 'STORAGE_ERROR'\n ));\n }\n }\n });\n }\n\n /**\n * Removes resume data for a specific upload.\n * \n * @param key - Unique identifier for the upload\n * @returns Promise resolved after removal\n * \n * @example\n * ```typescript\n * await adapter.removeItem('upload-123');\n * ```\n */\n async removeItem(key: string): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n if (!key || typeof key !== 'string') {\n reject(new UploadCacheError(\n 'Key must be a non-empty string',\n 'INVALID_KEY'\n ));\n return;\n }\n\n this.cache.delete(key);\n resolve();\n } catch (error) {\n reject(new UploadCacheError(\n `Error removing data: ${error instanceof Error ? error.message : String(error)}`,\n 'DELETION_ERROR'\n ));\n }\n });\n }\n\n /**\n * Clears all cached resume data.\n * \n * @returns Promise resolved after complete cleanup\n * \n * @example\n * ```typescript\n * await adapter.clear();\n * console.log('Cache cleared');\n * ```\n */\n async clear(): Promise<void> {\n return new Promise((resolve) => {\n this.cache.clear();\n resolve();\n });\n }\n\n /**\n * Returns the number of entries currently in cache.\n * \n * @returns Number of cache entries\n */\n get size(): number {\n return this.cache.size;\n }\n\n /**\n * Returns cache usage as a percentage.\n * \n * @returns Usage percentage (0-100)\n */\n get usage(): number {\n return (this.cache.size / this.maxCacheSize) * 100;\n }\n}\n\n/**\n * Custom error for upload cache operations.\n * \n * @example\n * ```typescript\n * throw new UploadCacheError('Resume data not found', 'NOT_FOUND');\n * ```\n */\nexport class UploadCacheError extends Error {\n constructor(\n message: string,\n public readonly code: string\n ) {\n super(message);\n this.name = 'UploadCacheError';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+FO,MAAM,gCAAsE;AAAA,EA/FnF,OA+FmF;AAAA;AAAA;AAAA,EAEvE,QAAiC,oBAAI,IAAI;AAAA,EAChC,eAAuB;AAAA,EAExC,cAAc;AACV,SAAK,oBAAoB;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAK,MAAM,OAAO,GAAG;AACrB,gBAAQ;AAAA,MACZ,SAAS,OAAO;AACZ,eAAO,IAAI;AAAA,UACP,wBAAwB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,UAC9E;AAAA,QACJ,CAAC;AAAA,MACL;AAAA,IACJ,CAAC;AAAA,EACL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAM,QAAuB;AACzB,WAAO,IAAI,QAAQ,CAAC,YAAY;AAC5B,WAAK,MAAM,MAAM;AACjB,cAAQ;AAAA,IACZ,CAAC;AAAA,EACL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,OAAe;AACf,WAAO,KAAK,MAAM;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,QAAgB;AAChB,WAAQ,KAAK,MAAM,OAAO,KAAK,eAAgB;AAAA,EACnD;AACJ;AAUO,MAAM,yBAAyB,MAAM;AAAA,EACxC,YACI,SACgB,MAClB;AACE,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EAChB;AAAA,EAJoB;AAAA,EAjaxB,OA8Z4C;AAAA;AAAA;AAQ5C;","names":[]}
@@ -0,0 +1,271 @@
1
+ import { EventDispatcherInterface } from '@wlindabla/event_dispatcher';
2
+ import { UploadOptions, UploadEndpoints, UploadState, ResumeData } from '../types/index.js';
3
+ import { UploadResumeCacheInterface } from '../cache/index.js';
4
+ import '@wlindabla/http_client';
5
+
6
+ /**
7
+ * ChunkedFileUploader
8
+ *
9
+ * A production-ready, event-driven chunked file upload engine for Browser and Node.js.
10
+ *
11
+ * Designed and developed by **AGBOKOUDJO Franck** at
12
+ * **INTERNATIONALES WEB APPS & SERVICES**, this class provides a robust,
13
+ * framework-agnostic solution for uploading large files to a remote server
14
+ * by splitting them into smaller chunks and sending them in parallel with
15
+ * configurable concurrency control.
16
+ *
17
+ * ---
18
+ *
19
+ * ### How It Works
20
+ *
21
+ * The upload process follows a strict three-phase lifecycle:
22
+ *
23
+ * 1. **Initialization** — A session is opened with the server via the `init` endpoint.
24
+ * The file is identified by its name, size, type, and a SHA-256 hash of its
25
+ * first megabyte. The server returns a unique `mediaId` that identifies the session.
26
+ *
27
+ * 2. **Chunk Upload** — The file is sliced into fixed-size chunks and uploaded
28
+ * concurrently using `p-limit`. Each chunk carries its index, the total number
29
+ * of chunks, and the session `mediaId`. Failed chunks are retried automatically
30
+ * with exponential backoff up to `maxRetries` attempts.
31
+ *
32
+ * 3. **Finalization** — Once all chunks are successfully uploaded, the `finalize`
33
+ * endpoint is called to instruct the server to assemble the chunks into the
34
+ * final file.
35
+ *
36
+ * ---
37
+ *
38
+ * ### Event-Driven Architecture
39
+ *
40
+ * This class follows the **Symfony EventDispatcher pattern** via
41
+ * `@wlindabla/event_dispatcher`. Every meaningful moment in the upload
42
+ * lifecycle emits a typed event that your application can listen to:
43
+ *
44
+ * ```
45
+ * IDLE → INITIALIZING → UPLOADING → FINALIZING → COMPLETED
46
+ * ↓ ↓
47
+ * FAILED PAUSED ↔ UPLOADING
48
+ * ↓
49
+ * CANCELLED
50
+ * ```
51
+ *
52
+ * All event name constants are centralized in {@link HttpFileUploaderEvents}.
53
+ *
54
+ * ---
55
+ *
56
+ * ### Subscriber Registration (Required)
57
+ *
58
+ * Before calling `.upload()`, you **must** register the two built-in subscribers
59
+ * on your dispatcher. They handle the HTTP communication for the init and finalize phases:
60
+ *
61
+ * ```typescript
62
+ * // Browser
63
+ * const dispatcher = new BrowserEventDispatcher(document);
64
+ * dispatcher.addSubscriber(new InitializeUploadSubscriber(dispatcher));
65
+ * dispatcher.addSubscriber(new FinalizeUploadSubscriber(dispatcher));
66
+ *
67
+ * // Node.js
68
+ * const dispatcher = new NodeEventDispatcher();
69
+ * dispatcher.addSubscriber(new InitializeUploadSubscriber(dispatcher));
70
+ * dispatcher.addSubscriber(new FinalizeUploadSubscriber(dispatcher));
71
+ * ```
72
+ *
73
+ * ---
74
+ *
75
+ * ### Fluent Builder API
76
+ *
77
+ * The class exposes a fluent API to configure the upload before starting:
78
+ *
79
+ * ```typescript
80
+ * const uploader = new ChunkedFileUploader(dispatcher, cache, options);
81
+ *
82
+ * await uploader
83
+ * .withFile(file)
84
+ * .withEndpoints({
85
+ * init: 'https://api.example.com/upload/init',
86
+ * upload: 'https://api.example.com/upload/chunk',
87
+ * finalize: 'https://api.example.com/upload/finalize'
88
+ * })
89
+ * .upload();
90
+ * ```
91
+ *
92
+ * ---
93
+ *
94
+ * ### Resumable Uploads
95
+ *
96
+ * When `autoSave: true` is set in options, the upload progress is persisted
97
+ * after each successful chunk via the {@link UploadResumeCacheInterface}.
98
+ * A failed or interrupted upload can be resumed later:
99
+ *
100
+ * ```typescript
101
+ * const resumeData = await uploader.loadResumeData(file.name);
102
+ *
103
+ * if (resumeData) {
104
+ * await uploader
105
+ * .withFile(file)
106
+ * .withEndpoints(endpoints)
107
+ * .resumeUpload(resumeData);
108
+ * }
109
+ * ```
110
+ *
111
+ * ---
112
+ *
113
+ * ### Concurrency
114
+ *
115
+ * Multiple chunks can be uploaded simultaneously. The `concurrency` option
116
+ * controls how many parallel uploads are active at any given time.
117
+ * The default value is `3`, which provides a good balance between speed
118
+ * and server/network load:
119
+ *
120
+ * ```typescript
121
+ * // Upload 5 chunks in parallel
122
+ * new ChunkedFileUploader(dispatcher, cache, { concurrency: 5 });
123
+ * ```
124
+ *
125
+ * ---
126
+ *
127
+ * ### Pause, Resume and Cancel
128
+ *
129
+ * The upload can be paused, resumed, or cancelled at any time:
130
+ *
131
+ * ```typescript
132
+ * uploader.pause(); // Pauses after the current chunk finishes
133
+ * uploader.resume(); // Resumes from where it was paused
134
+ * uploader.cancel(); // Aborts immediately via AbortController
135
+ * ```
136
+ *
137
+ * ---
138
+ *
139
+ * ### Cache
140
+ *
141
+ * The library does **not** provide a built-in cache implementation to stay
142
+ * lightweight and environment-agnostic. You must implement
143
+ * {@link UploadResumeCacheInterface} with your preferred storage backend
144
+ * (localStorage, IndexedDB, Redis, filesystem, etc.).
145
+ *
146
+ * ---
147
+ *
148
+ * @author AGBOKOUDJO Franck <internationaleswebservices@gmail.com>
149
+ * @company INTERNATIONALES WEB APPS & SERVICES
150
+ * @phone +229 0167 25 18 86
151
+ * @linkedin https://www.linkedin.com/in/internationales-web-apps-services-120520193/
152
+ * @github https://github.com/Agbokoudjo/file_uploader
153
+ *
154
+ * @version 2.0.1
155
+ * @since 1.0.0
156
+ * @license MIT
157
+ *
158
+ * @see {@link HttpFileUploaderEvents} All event name constants
159
+ * @see {@link UploadResumeCacheInterface} Cache interface to implement
160
+ * @see {@link InitializeUploadSubscriber} Handles the init HTTP phase
161
+ * @see {@link FinalizeUploadSubscriber} Handles the finalize HTTP phase
162
+ * @see {@link UploadOptions} Full configuration reference
163
+ * @see {@link https://github.com/Agbokoudjo/file_uploader | GitHub Repository}
164
+ */
165
+ declare class ChunkedFileUploader {
166
+ private readonly _uploadEventDispatcher;
167
+ private readonly uploadResumeData;
168
+ private options;
169
+ private _file;
170
+ private _endpoints;
171
+ private isPaused;
172
+ private startTime;
173
+ private uploadedBytes;
174
+ private abortController;
175
+ private state;
176
+ private totalChunks;
177
+ private percentage;
178
+ private uploadedChunks;
179
+ private lastUploadedChunkIndex;
180
+ /**
181
+ * @param _uploadEventDispatcher: new BrowserEventDispatcher(), //or new NodeJSEventDispatcher() if you have an environment NodeJs
182
+ * @param uploadResumeData: UploadResumeCacheInterface
183
+ * @param options: UploadOptions
184
+ */
185
+ constructor(_uploadEventDispatcher: EventDispatcherInterface, uploadResumeData: UploadResumeCacheInterface, options: UploadOptions);
186
+ /**
187
+ * Starts the chunked file upload process.
188
+ *
189
+ * @throws {Error} If file or endpoints are not set
190
+ * @throws {InitializeUploadFailureException} If server initialization fails
191
+ * @throws {FileUploadChunkError} If a chunk fails after all retries
192
+ *
193
+ * @example
194
+ * ```typescript
195
+ * const uploader = new ChunkedFileUploader(dispatcher, cache, options);
196
+ *
197
+ * uploader
198
+ * .withFile(file)
199
+ * .withEndpoints({ init, upload, finalize });
200
+ *
201
+ * await uploader.upload();
202
+ * ```
203
+ */
204
+ upload(): Promise<void>;
205
+ withFile(file: File): this;
206
+ withEndpoints(endpoints: UploadEndpoints): this;
207
+ private get endPointOptions();
208
+ private get file();
209
+ /**
210
+ * Upload all chunks with concurrency control using p-limit
211
+ *
212
+ * @param file - File to upload
213
+ * @param chunkSize - Size of each chunk
214
+ * @param fileId - Server file ID
215
+ * @param fileHash - File hash
216
+ * @param maxRetries - Max retry attempts per chunk
217
+ * @param concurrency - Number of concurrent uploads (default: 3)
218
+ */
219
+ private uploadChunksWithConcurrency;
220
+ /**
221
+ * Process a single chunk: slice, upload with retry, and save progress.
222
+ *
223
+ * @param file - The file being uploaded
224
+ * @param currentChunkIndex - Index of the current chunk (0-based)
225
+ * @param chunkSize - Size of each chunk in bytes
226
+ * @param fileId - Server-provided file/session ID
227
+ * @param fileHash - SHA-256 hash of the file
228
+ * @param maxRetries - Maximum number of retry attempts
229
+ *
230
+ * @throws {UploadCancelledException} If upload is cancelled
231
+ * @throws {FileUploadChunkError} If chunk upload fails after all retries
232
+ */
233
+ private processChunk;
234
+ private uploadChunkWithRetry;
235
+ private uploadChunk;
236
+ private createChunkAbortSignal;
237
+ private notifyProgress;
238
+ private sleep;
239
+ /**
240
+ * Save current upload progress to cache for resume capability
241
+ *
242
+ * @param fileId - Server-provided file/session ID
243
+ * @param chunkSize - Size of each chunk in bytes
244
+ * @returns Saved resume data
245
+ */
246
+ private saveResumeData;
247
+ private setState;
248
+ getState(): UploadState;
249
+ private handleUploadFailure;
250
+ cancel(): void;
251
+ pause(): void;
252
+ resume(): void;
253
+ /**
254
+ * Load previously saved resume data
255
+ *
256
+ * @param fileName - Name of the file to resume
257
+ * @returns Resume data or null if not found
258
+ */
259
+ loadResumeData(fileName: string): Promise<ResumeData | null>;
260
+ /**
261
+ * Resume upload from saved state
262
+ *
263
+ * @param resumeData - Previously saved resume data
264
+ * @returns Upload result
265
+ */
266
+ resumeUpload(resumeData: ResumeData): Promise<void>;
267
+ private updateProgress;
268
+ private finalizeUpload;
269
+ }
270
+
271
+ export { ChunkedFileUploader };