Core API
The Core layer implements the upload state machine, task management, and plugin system.
UploadManager
Main class for managing multiple upload tasks.
Constructor
new UploadManager(options: UploadManagerOptions)Options
interface UploadManagerOptions {
requestAdapter: RequestAdapter; // HTTP adapter (required)
maxConcurrentTasks?: number; // Max parallel uploads (default: 3)
defaultChunkSize?: number; // Default chunk size (default: 1MB)
defaultConcurrency?: number; // Default chunk concurrency (default: 3)
autoResumeUnfinished?: boolean; // Auto-resume on init (default: true)
}Methods
init()
Initialize the manager and resume unfinished tasks.
await manager.init(): Promise<void>createTask()
Create a new upload task.
manager.createTask(file: File, options?: Partial<UploadTaskOptions>): UploadTaskParameters:
file: File to uploadoptions: Task-specific options (optional)
Returns: UploadTask instance
Example:
const task = manager.createTask(file, {
chunkSize: 2 * 1024 * 1024, // 2MB chunks
concurrency: 5, // 5 parallel chunks
retryCount: 3, // Retry 3 times
});getTask()
Get a task by ID.
manager.getTask(taskId: string): UploadTask | undefinedgetAllTasks()
Get all tasks.
manager.getAllTasks(): UploadTask[]deleteTask()
Delete a task and clean up resources.
await manager.deleteTask(taskId: string): Promise<void>use()
Register a plugin.
manager.use(plugin: Plugin): voidExample
import { UploadManager, createFetchAdapter } from "@chunkflowjs/core";
const adapter = createFetchAdapter({
baseURL: "http://localhost:3000/api",
});
const manager = new UploadManager({
requestAdapter: adapter,
maxConcurrentTasks: 3,
defaultChunkSize: 1024 * 1024,
defaultConcurrency: 3,
autoResumeUnfinished: true,
});
await manager.init();
// Create and start a task
const task = manager.createTask(file);
await task.start();UploadTask
Represents a single upload task.
Properties
task.id: string // Unique task ID
task.file: File // File being uploaded
task.status: UploadStatus // Current status
task.progress: UploadProgress // Upload progressMethods
start()
Start the upload.
await task.start(): Promise<void>pause()
Pause the upload.
task.pause(): voidresume()
Resume a paused upload.
await task.resume(): Promise<void>cancel()
Cancel the upload.
task.cancel(): voidon()
Listen to events.
task.on<K extends keyof UploadEvents>(
event: K,
handler: (payload: UploadEvents[K]) => void
): voidgetStatus()
Get current status.
task.getStatus(): UploadStatusgetProgress()
Get current progress.
task.getProgress(): UploadProgressEvents
interface UploadEvents {
start: { taskId: string; file: File };
progress: { taskId: string; progress: number; speed: number };
chunkSuccess: { taskId: string; chunkIndex: number };
chunkError: { taskId: string; chunkIndex: number; error: Error };
hashProgress: { taskId: string; progress: number };
hashComplete: { taskId: string; hash: string };
success: { taskId: string; fileUrl: string };
error: { taskId: string; error: Error };
pause: { taskId: string };
resume: { taskId: string };
cancel: { taskId: string };
}Example
const task = manager.createTask(file);
task.on("start", ({ taskId, file }) => {
console.log(`Upload started: ${file.name}`);
});
task.on("progress", ({ progress, speed }) => {
console.log(`Progress: ${progress}%, Speed: ${speed} bytes/s`);
});
task.on("success", ({ fileUrl }) => {
console.log(`Upload complete: ${fileUrl}`);
});
task.on("error", ({ error }) => {
console.error(`Upload failed: ${error.message}`);
});
await task.start();UploadProgress
Progress information for an upload task.
interface UploadProgress {
uploadedBytes: number; // Bytes uploaded
totalBytes: number; // Total bytes
percentage: number; // Progress percentage (0-100)
speed: number; // Upload speed (bytes/second)
remainingTime: number; // Estimated remaining time (seconds)
uploadedChunks: number; // Number of uploaded chunks
totalChunks: number; // Total number of chunks
}ChunkSizeAdjuster
Dynamically adjusts chunk size based on upload performance.
Constructor
new ChunkSizeAdjuster(options: ChunkSizeAdjusterOptions)Options
interface ChunkSizeAdjusterOptions {
initialSize: number; // Initial chunk size
minSize: number; // Minimum chunk size
maxSize: number; // Maximum chunk size
targetTime?: number; // Target upload time per chunk (ms, default: 3000)
}Methods
adjust()
Adjust chunk size based on upload time.
adjuster.adjust(uploadTimeMs: number): numberParameters:
uploadTimeMs: Time taken to upload the last chunk (milliseconds)
Returns: New chunk size
Algorithm:
- If upload time < 50% of target → Increase size (up to max)
- If upload time > 150% of target → Decrease size (down to min)
- Otherwise → Keep current size
getCurrentSize()
Get current chunk size.
adjuster.getCurrentSize(): numberExample
const adjuster = new ChunkSizeAdjuster({
initialSize: 1024 * 1024, // 1MB
minSize: 256 * 1024, // 256KB
maxSize: 10 * 1024 * 1024, // 10MB
targetTime: 3000, // 3 seconds
});
// After uploading a chunk
const uploadTime = 1500; // 1.5 seconds (fast)
const newSize = adjuster.adjust(uploadTime);
console.log(`New chunk size: ${newSize}`); // Will be largerPlugin System
Extend ChunkFlow functionality with plugins.
Plugin Interface
interface Plugin {
name: string;
install?(manager: UploadManager): void;
onTaskCreated?(task: UploadTask): void;
onTaskStart?(task: UploadTask): void;
onTaskProgress?(task: UploadTask, progress: UploadProgress): void;
onTaskSuccess?(task: UploadTask): void;
onTaskError?(task: UploadTask, error: Error): void;
}Built-in Plugins
LoggerPlugin
Logs upload events to console.
import { LoggerPlugin } from "@chunkflowjs/core";
manager.use(new LoggerPlugin());StatisticsPlugin
Tracks upload statistics.
import { StatisticsPlugin } from "@chunkflowjs/core";
const stats = new StatisticsPlugin();
manager.use(stats);
// Get statistics
const data = stats.getStats();
console.log(data.totalUploaded);
console.log(data.successCount);
console.log(data.errorCount);Creating Custom Plugins
class CustomPlugin implements Plugin {
name = "custom";
install(manager: UploadManager) {
console.log("Plugin installed");
}
onTaskCreated(task: UploadTask) {
console.log(`Task created: ${task.id}`);
}
onTaskProgress(task: UploadTask, progress: UploadProgress) {
// Send progress to analytics
analytics.track("upload_progress", {
taskId: task.id,
percentage: progress.percentage,
});
}
onTaskSuccess(task: UploadTask) {
// Send success event
analytics.track("upload_success", {
taskId: task.id,
fileName: task.file.name,
fileSize: task.file.size,
});
}
onTaskError(task: UploadTask, error: Error) {
// Send error event
analytics.track("upload_error", {
taskId: task.id,
error: error.message,
});
}
}
manager.use(new CustomPlugin());Utility Functions
createFetchAdapter()
Create a fetch-based request adapter.
createFetchAdapter(options: FetchAdapterOptions): RequestAdapterOptions
interface FetchAdapterOptions {
baseURL: string; // API base URL
headers?: Record<string, string>; // Custom headers
timeout?: number; // Request timeout (ms)
withCredentials?: boolean; // Include credentials
onUploadProgress?: (progress: number) => void; // Upload progress callback
}Example
const adapter = createFetchAdapter({
baseURL: "http://localhost:3000/api",
headers: {
Authorization: "Bearer token",
},
timeout: 30000,
withCredentials: true,
});generateTaskId()
Generate a unique task ID.
generateTaskId(): stringType Exports
All types are exported from the core package:
import type {
UploadManager,
UploadTask,
UploadTaskOptions,
UploadProgress,
UploadStatus,
Plugin,
ChunkSizeAdjuster,
ChunkSizeAdjusterOptions,
} from "@chunkflowjs/core";See Also
- Protocol API - Type definitions
- Shared API - Common utilities
- Client React API - React integration
- Client Vue API - Vue integration
