@uploadista/react 0.0.20 → 0.1.0-beta.5
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.
- package/dist/components/index.d.mts +3 -3
- package/dist/components/index.mjs +1 -1
- package/dist/index.d.mts +4 -548
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -2
- package/dist/upload-zone-CH8B2-hl.mjs +2 -0
- package/dist/upload-zone-CH8B2-hl.mjs.map +1 -0
- package/dist/{uploadista-provider-Cb13AK7Z.d.mts → uploadista-provider-DwKXudoT.d.mts} +558 -15
- package/dist/uploadista-provider-DwKXudoT.d.mts.map +1 -0
- package/dist/use-upload-BgaJmdwF.mjs.map +1 -1
- package/dist/use-uploadista-client-CkzVVmFT.d.mts.map +1 -1
- package/dist/use-uploadista-events-KhJ4knam.mjs.map +1 -1
- package/package.json +12 -9
- package/src/__tests__/event-utils.test.ts +179 -0
- package/src/__tests__/setup.ts +40 -0
- package/src/__tests__/uploadista-provider.test.tsx +316 -0
- package/src/__tests__/use-drag-drop.test.tsx +476 -0
- package/src/__tests__/use-upload.test.tsx +317 -0
- package/src/__tests__/use-uploadista-client.test.tsx +208 -0
- package/src/components/flow-primitives.tsx +3 -8
- package/src/components/index.tsx +37 -6
- package/src/components/upload-primitives.tsx +22 -19
- package/src/components/upload-zone.tsx +1 -2
- package/src/hooks/event-utils.ts +1 -1
- package/src/hooks/use-upload-events.ts +2 -5
- package/src/index.ts +89 -96
- package/vitest.config.ts +16 -0
- package/dist/flow-upload-list-BJSCZ4Ty.mjs +0 -2
- package/dist/flow-upload-list-BJSCZ4Ty.mjs.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/uploadista-provider-Cb13AK7Z.d.mts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-uploadista-events-KhJ4knam.mjs","names":["initialMetrics: UploadMetrics","estimatedTimeRemaining: number | null","newMetrics: UploadMetrics","fileMetric: FileUploadMetrics"],"sources":["../src/hooks/event-utils.ts","../src/hooks/use-flow-events.ts","../src/hooks/use-upload-events.ts","../src/hooks/use-upload-metrics.ts","../src/hooks/use-uploadista-events.ts"],"sourcesContent":["import type { UploadistaEvent } from \"@uploadista/client-browser\";\nimport { EventType, type FlowEvent } from \"@uploadista/core/flow\";\nimport { UploadEventType, type UploadEvent } from \"@uploadista/core/types\";\n\n/**\n * Type guard to check if an event is a flow event\n */\nexport function isFlowEvent(event: UploadistaEvent): event is FlowEvent {\n if (!(\"eventType\" in event)) return false;\n const e = event as { eventType: unknown };\n return (\n e.eventType === EventType.JobStart ||\n e.eventType === EventType.JobEnd ||\n e.eventType === EventType.FlowStart ||\n e.eventType === EventType.FlowEnd ||\n e.eventType === EventType.FlowError ||\n e.eventType === EventType.FlowPause ||\n e.eventType === EventType.FlowCancel ||\n e.eventType === EventType.NodeStart ||\n e.eventType === EventType.NodeEnd ||\n e.eventType === EventType.NodePause ||\n e.eventType === EventType.NodeResume ||\n e.eventType === EventType.NodeError ||\n e.eventType === EventType.NodeStream ||\n e.eventType === EventType.NodeResponse\n );\n}\n\n/**\n * Type guard to check if an event is an upload event\n */\nexport function isUploadEvent(event: UploadistaEvent): event is UploadEvent {\n if (!(\"type\" in event)) return false;\n const e = event as { type: unknown };\n return (\n e.type === UploadEventType.UPLOAD_STARTED ||\n e.type === UploadEventType.UPLOAD_PROGRESS ||\n e.type === UploadEventType.UPLOAD_COMPLETE ||\n e.type === UploadEventType.UPLOAD_FAILED ||\n e.type === UploadEventType.UPLOAD_VALIDATION_SUCCESS ||\n e.type === UploadEventType.UPLOAD_VALIDATION_FAILED ||\n e.type === UploadEventType.UPLOAD_VALIDATION_WARNING\n );\n}\n","import type {\n FlowEventFlowCancel,\n FlowEventFlowEnd,\n FlowEventFlowError,\n FlowEventFlowPause,\n FlowEventFlowStart,\n FlowEventJobEnd,\n FlowEventJobStart,\n FlowEventNodeEnd,\n FlowEventNodeError,\n FlowEventNodePause,\n FlowEventNodeResume,\n FlowEventNodeStart,\n} from \"@uploadista/core/flow\";\nimport { EventType } from \"@uploadista/core/flow\";\nimport { useEffect } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\nimport { isFlowEvent } from \"./event-utils\";\n\n/**\n * Options for handling flow execution events.\n *\n * All callbacks are optional - only provide handlers for events you care about.\n */\nexport interface UseFlowEventsOptions {\n /** Called when a job starts execution */\n onJobStart?: (event: FlowEventJobStart) => void;\n /** Called when a job completes (success or failure) */\n onJobEnd?: (event: FlowEventJobEnd) => void;\n /** Called when a flow begins execution */\n onFlowStart?: (event: FlowEventFlowStart) => void;\n /** Called when a flow completes successfully */\n onFlowEnd?: (event: FlowEventFlowEnd) => void;\n /** Called when a flow encounters an error */\n onFlowError?: (event: FlowEventFlowError) => void;\n /** Called when a flow is paused by user request */\n onFlowPause?: (event: FlowEventFlowPause) => void;\n /** Called when a flow is cancelled by user request */\n onFlowCancel?: (event: FlowEventFlowCancel) => void;\n /** Called when a node starts processing */\n onNodeStart?: (event: FlowEventNodeStart) => void;\n /** Called when a node completes successfully */\n onNodeEnd?: (event: FlowEventNodeEnd) => void;\n /** Called when a node pauses (waiting for additional data) */\n onNodePause?: (event: FlowEventNodePause) => void;\n /** Called when a paused node resumes execution */\n onNodeResume?: (event: FlowEventNodeResume) => void;\n /** Called when a node encounters an error */\n onNodeError?: (event: FlowEventNodeError) => void;\n}\n\n/**\n * Structured hook for handling flow execution events with type-safe callbacks.\n *\n * This hook provides a clean API for listening to specific flow events without\n * needing to manually filter events or use type guards.\n *\n * Must be used within UploadistaProvider.\n *\n * @param options - Object with optional callbacks for each flow event type\n *\n * @example\n * ```tsx\n * import { useFlowEvents } from '@uploadista/react';\n *\n * function FlowMonitor() {\n * useFlowEvents({\n * onFlowStart: (event) => {\n * console.log('Flow started:', event.flowId);\n * },\n * onNodeStart: (event) => {\n * console.log('Node started:', event.nodeName);\n * },\n * onNodeEnd: (event) => {\n * console.log('Node completed:', event.nodeName, event.result);\n * },\n * onFlowEnd: (event) => {\n * console.log('Flow completed with outputs:', event.outputs);\n * },\n * onFlowError: (event) => {\n * console.error('Flow failed:', event.error);\n * },\n * });\n *\n * return <div>Monitoring flow execution...</div>;\n * }\n * ```\n */\nexport function useFlowEvents(options: UseFlowEventsOptions): void {\n const { subscribeToEvents } = useUploadistaContext();\n\n useEffect(() => {\n const unsubscribe = subscribeToEvents((event) => {\n // Only handle flow events\n if (!isFlowEvent(event)) return;\n\n // Route to appropriate callback based on event type\n switch (event.eventType) {\n case EventType.JobStart:\n options.onJobStart?.(event);\n break;\n case EventType.JobEnd:\n options.onJobEnd?.(event);\n break;\n case EventType.FlowStart:\n options.onFlowStart?.(event);\n break;\n case EventType.FlowEnd:\n options.onFlowEnd?.(event);\n break;\n case EventType.FlowError:\n options.onFlowError?.(event);\n break;\n case EventType.FlowPause:\n options.onFlowPause?.(event);\n break;\n case EventType.FlowCancel:\n options.onFlowCancel?.(event);\n break;\n case EventType.NodeStart:\n options.onNodeStart?.(event);\n break;\n case EventType.NodeEnd:\n options.onNodeEnd?.(event);\n break;\n case EventType.NodePause:\n options.onNodePause?.(event);\n break;\n case EventType.NodeResume:\n options.onNodeResume?.(event);\n break;\n case EventType.NodeError:\n options.onNodeError?.(event);\n break;\n }\n });\n\n return unsubscribe;\n }, [subscribeToEvents, options]);\n}\n","import { UploadEventType, type UploadEvent } from \"@uploadista/core/types\";\nimport { useEffect } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\nimport { isUploadEvent } from \"./event-utils\";\n\n/**\n * Upload progress event data\n */\nexport interface UploadProgressEventData {\n id: string;\n progress: number;\n total: number;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload started/complete event data (contains full UploadFile)\n */\nexport interface UploadFileEventData {\n // This will contain the full UploadFile schema\n [key: string]: unknown;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload failed event data\n */\nexport interface UploadFailedEventData {\n id: string;\n error: string;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload validation success event data\n */\nexport interface UploadValidationSuccessEventData {\n id: string;\n validationType: \"checksum\" | \"mimetype\";\n algorithm?: string;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload validation failed event data\n */\nexport interface UploadValidationFailedEventData {\n id: string;\n reason: string;\n expected: string;\n actual: string;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload validation warning event data\n */\nexport interface UploadValidationWarningEventData {\n id: string;\n message: string;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Options for handling upload events.\n *\n * All callbacks are optional - only provide handlers for events you care about.\n */\nexport interface UseUploadEventsOptions {\n /** Called when an upload starts */\n onUploadStarted?: (data: UploadFileEventData) => void;\n /** Called with upload progress updates */\n onUploadProgress?: (data: UploadProgressEventData) => void;\n /** Called when an upload completes successfully */\n onUploadComplete?: (data: UploadFileEventData) => void;\n /** Called when an upload fails */\n onUploadFailed?: (data: UploadFailedEventData) => void;\n /** Called when upload validation succeeds */\n onUploadValidationSuccess?: (data: UploadValidationSuccessEventData) => void;\n /** Called when upload validation fails */\n onUploadValidationFailed?: (data: UploadValidationFailedEventData) => void;\n /** Called when upload validation produces a warning */\n onUploadValidationWarning?: (data: UploadValidationWarningEventData) => void;\n}\n\n/**\n * Structured hook for handling upload events with type-safe callbacks.\n *\n * This hook provides a clean API for listening to specific upload events without\n * needing to manually filter events or use type guards.\n *\n * Must be used within UploadistaProvider.\n *\n * @param options - Object with optional callbacks for each upload event type\n *\n * @example\n * ```tsx\n * import { useUploadEvents } from '@uploadista/react';\n *\n * function UploadMonitor() {\n * useUploadEvents({\n * onUploadStarted: (data) => {\n * console.log('Upload started:', data.id);\n * },\n * onUploadProgress: (data) => {\n * const percent = (data.progress / data.total) * 100;\n * console.log(`Upload progress: ${percent}%`);\n * },\n * onUploadComplete: (data) => {\n * console.log('Upload completed:', data);\n * },\n * onUploadFailed: (data) => {\n * console.error('Upload failed:', data.error);\n * },\n * });\n *\n * return <div>Monitoring uploads...</div>;\n * }\n * ```\n */\nexport function useUploadEvents(options: UseUploadEventsOptions): void {\n const { subscribeToEvents } = useUploadistaContext();\n\n useEffect(() => {\n const unsubscribe = subscribeToEvents((event) => {\n // Only handle upload events\n if (!isUploadEvent(event)) return;\n\n // Route to appropriate callback based on event type\n // Note: flow context is at the top level of the event, not inside data\n const flowContext = \"flow\" in event ? event.flow : undefined;\n\n switch (event.type) {\n case UploadEventType.UPLOAD_STARTED:\n options.onUploadStarted?.({\n ...(event.data as unknown as Omit<UploadFileEventData, \"flow\">),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_PROGRESS:\n options.onUploadProgress?.({\n ...(event.data as unknown as Omit<\n UploadProgressEventData,\n \"flow\"\n >),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_COMPLETE:\n options.onUploadComplete?.({\n ...(event.data as unknown as Omit<UploadFileEventData, \"flow\">),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_FAILED:\n options.onUploadFailed?.({\n ...(event.data as unknown as Omit<UploadFailedEventData, \"flow\">),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_VALIDATION_SUCCESS:\n options.onUploadValidationSuccess?.({\n ...(event.data as unknown as Omit<\n UploadValidationSuccessEventData,\n \"flow\"\n >),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_VALIDATION_FAILED:\n options.onUploadValidationFailed?.({\n ...(event.data as unknown as Omit<\n UploadValidationFailedEventData,\n \"flow\"\n >),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_VALIDATION_WARNING:\n options.onUploadValidationWarning?.({\n ...(event.data as unknown as Omit<\n UploadValidationWarningEventData,\n \"flow\"\n >),\n flow: flowContext,\n });\n break;\n }\n });\n\n return unsubscribe;\n }, [subscribeToEvents, options]);\n}\n","import type {\n ChunkMetrics,\n PerformanceInsights,\n UploadSessionMetrics,\n} from \"@uploadista/client-core\";\nimport React, { useCallback, useRef, useState } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\n\nexport type Timeout = ReturnType<typeof setInterval>;\n\nexport interface UploadMetrics {\n /**\n * Total bytes uploaded across all files\n */\n totalBytesUploaded: number;\n\n /**\n * Total bytes to upload across all files\n */\n totalBytes: number;\n\n /**\n * Overall upload speed in bytes per second\n */\n averageSpeed: number;\n\n /**\n * Current upload speed in bytes per second\n */\n currentSpeed: number;\n\n /**\n * Estimated time remaining in milliseconds\n */\n estimatedTimeRemaining: number | null;\n\n /**\n * Total number of files being tracked\n */\n totalFiles: number;\n\n /**\n * Number of files completed\n */\n completedFiles: number;\n\n /**\n * Number of files currently uploading\n */\n activeUploads: number;\n\n /**\n * Overall progress as percentage (0-100)\n */\n progress: number;\n\n /**\n * Peak upload speed achieved\n */\n peakSpeed: number;\n\n /**\n * Start time of the first upload\n */\n startTime: number | null;\n\n /**\n * End time of the last completed upload\n */\n endTime: number | null;\n\n /**\n * Total duration of all uploads\n */\n totalDuration: number | null;\n\n /**\n * Detailed performance insights from the upload client\n */\n insights: PerformanceInsights;\n\n /**\n * Session metrics for completed uploads\n */\n sessionMetrics: Partial<UploadSessionMetrics>[];\n\n /**\n * Detailed chunk metrics from recent uploads\n */\n chunkMetrics: ChunkMetrics[];\n}\n\nexport interface FileUploadMetrics {\n id: string;\n filename: string;\n size: number;\n bytesUploaded: number;\n progress: number;\n speed: number;\n startTime: number;\n endTime: number | null;\n duration: number | null;\n isComplete: boolean;\n}\n\nexport interface UseUploadMetricsOptions {\n /**\n * Interval for calculating current speed (in milliseconds)\n */\n speedCalculationInterval?: number;\n\n /**\n * Number of speed samples to keep for average calculation\n */\n speedSampleSize?: number;\n\n /**\n * Called when metrics are updated\n */\n onMetricsUpdate?: (metrics: UploadMetrics) => void;\n\n /**\n * Called when a file upload starts\n */\n onFileStart?: (fileMetrics: FileUploadMetrics) => void;\n\n /**\n * Called when a file upload progresses\n */\n onFileProgress?: (fileMetrics: FileUploadMetrics) => void;\n\n /**\n * Called when a file upload completes\n */\n onFileComplete?: (fileMetrics: FileUploadMetrics) => void;\n}\n\nexport interface UseUploadMetricsReturn {\n /**\n * Current overall metrics\n */\n metrics: UploadMetrics;\n\n /**\n * Individual file metrics\n */\n fileMetrics: FileUploadMetrics[];\n\n /**\n * Start tracking a new file upload\n */\n startFileUpload: (id: string, filename: string, size: number) => void;\n\n /**\n * Update progress for a file upload\n */\n updateFileProgress: (id: string, bytesUploaded: number) => void;\n\n /**\n * Mark a file upload as complete\n */\n completeFileUpload: (id: string) => void;\n\n /**\n * Remove a file from tracking\n */\n removeFile: (id: string) => void;\n\n /**\n * Reset all metrics\n */\n reset: () => void;\n\n /**\n * Get metrics for a specific file\n */\n getFileMetrics: (id: string) => FileUploadMetrics | undefined;\n\n /**\n * Export metrics as JSON\n */\n exportMetrics: () => {\n overall: UploadMetrics;\n files: FileUploadMetrics[];\n exportTime: number;\n };\n}\n\nconst initialMetrics: UploadMetrics = {\n totalBytesUploaded: 0,\n totalBytes: 0,\n averageSpeed: 0,\n currentSpeed: 0,\n estimatedTimeRemaining: null,\n totalFiles: 0,\n completedFiles: 0,\n activeUploads: 0,\n progress: 0,\n peakSpeed: 0,\n startTime: null,\n endTime: null,\n totalDuration: null,\n insights: {\n overallEfficiency: 0,\n chunkingEffectiveness: 0,\n networkStability: 0,\n recommendations: [],\n optimalChunkSizeRange: { min: 256 * 1024, max: 2 * 1024 * 1024 },\n },\n sessionMetrics: [],\n chunkMetrics: [],\n};\n\n/**\n * React hook for tracking detailed upload metrics and performance statistics.\n * Provides comprehensive monitoring of upload progress, speed, and timing data.\n *\n * @param options - Configuration and event handlers\n * @returns Upload metrics state and control methods\n *\n * @example\n * ```tsx\n * const uploadMetrics = useUploadMetrics({\n * speedCalculationInterval: 1000, // Update speed every second\n * speedSampleSize: 10, // Keep last 10 speed samples for average\n * onMetricsUpdate: (metrics) => {\n * console.log(`Overall progress: ${metrics.progress}%`);\n * console.log(`Speed: ${(metrics.currentSpeed / 1024).toFixed(1)} KB/s`);\n * console.log(`ETA: ${metrics.estimatedTimeRemaining}ms`);\n * },\n * onFileComplete: (fileMetrics) => {\n * console.log(`${fileMetrics.filename} completed in ${fileMetrics.duration}ms`);\n * },\n * });\n *\n * // Start tracking a file\n * const handleFileStart = (file: File) => {\n * uploadMetrics.startFileUpload(file.name, file.name, file.size);\n * };\n *\n * // Update progress during upload\n * const handleProgress = (fileId: string, bytesUploaded: number) => {\n * uploadMetrics.updateFileProgress(fileId, bytesUploaded);\n * };\n *\n * // Display metrics\n * return (\n * <div>\n * <div>Overall Progress: {uploadMetrics.metrics.progress}%</div>\n * <div>Speed: {(uploadMetrics.metrics.currentSpeed / 1024).toFixed(1)} KB/s</div>\n * <div>Files: {uploadMetrics.metrics.completedFiles}/{uploadMetrics.metrics.totalFiles}</div>\n *\n * {uploadMetrics.metrics.estimatedTimeRemaining && (\n * <div>ETA: {Math.round(uploadMetrics.metrics.estimatedTimeRemaining / 1000)}s</div>\n * )}\n *\n * {uploadMetrics.fileMetrics.map((file) => (\n * <div key={file.id}>\n * {file.filename}: {file.progress}% ({(file.speed / 1024).toFixed(1)} KB/s)\n * </div>\n * ))}\n * </div>\n * );\n * ```\n */\nexport function useUploadMetrics(\n options: UseUploadMetricsOptions = {},\n): UseUploadMetricsReturn {\n const {\n speedCalculationInterval = 1000,\n speedSampleSize = 10,\n onMetricsUpdate,\n onFileStart,\n onFileProgress,\n onFileComplete,\n } = options;\n\n const uploadClient = useUploadistaContext();\n\n const [metrics, setMetrics] = useState<UploadMetrics>(initialMetrics);\n const [fileMetrics, setFileMetrics] = useState<FileUploadMetrics[]>([]);\n\n const speedSamplesRef = useRef<Array<{ time: number; bytes: number }>>([]);\n const lastUpdateRef = useRef<number>(0);\n const intervalRef = useRef<Timeout | null>(null);\n\n const calculateSpeed = useCallback(\n (currentTime: number, totalBytesUploaded: number) => {\n const sample = { time: currentTime, bytes: totalBytesUploaded };\n speedSamplesRef.current.push(sample);\n\n // Keep only recent samples\n if (speedSamplesRef.current.length > speedSampleSize) {\n speedSamplesRef.current = speedSamplesRef.current.slice(\n -speedSampleSize,\n );\n }\n\n // Calculate current speed (bytes per second)\n let currentSpeed = 0;\n if (speedSamplesRef.current.length >= 2) {\n const recent =\n speedSamplesRef.current[speedSamplesRef.current.length - 1];\n const previous =\n speedSamplesRef.current[speedSamplesRef.current.length - 2];\n if (recent && previous) {\n const timeDiff = (recent.time - previous.time) / 1000; // Convert to seconds\n const bytesDiff = recent.bytes - previous.bytes;\n currentSpeed = timeDiff > 0 ? bytesDiff / timeDiff : 0;\n }\n }\n\n // Calculate average speed\n let averageSpeed = 0;\n if (speedSamplesRef.current.length >= 2) {\n const first = speedSamplesRef.current[0];\n const last =\n speedSamplesRef.current[speedSamplesRef.current.length - 1];\n if (first && last) {\n const totalTime = (last.time - first.time) / 1000; // Convert to seconds\n const totalBytes = last.bytes - first.bytes;\n averageSpeed = totalTime > 0 ? totalBytes / totalTime : 0;\n }\n }\n\n return { currentSpeed, averageSpeed };\n },\n [speedSampleSize],\n );\n\n const updateMetrics = useCallback(() => {\n const now = Date.now();\n\n // Calculate totals from file metrics\n const totalBytes = fileMetrics.reduce((sum, file) => sum + file.size, 0);\n const totalBytesUploaded = fileMetrics.reduce(\n (sum, file) => sum + file.bytesUploaded,\n 0,\n );\n const completedFiles = fileMetrics.filter((file) => file.isComplete).length;\n const activeUploads = fileMetrics.filter(\n (file) => !file.isComplete && file.bytesUploaded > 0,\n ).length;\n\n // Calculate speeds\n const { currentSpeed, averageSpeed } = calculateSpeed(\n now,\n totalBytesUploaded,\n );\n\n // Calculate progress\n const progress =\n totalBytes > 0 ? Math.round((totalBytesUploaded / totalBytes) * 100) : 0;\n\n // Calculate estimated time remaining\n let estimatedTimeRemaining: number | null = null;\n if (currentSpeed > 0) {\n const remainingBytes = totalBytes - totalBytesUploaded;\n estimatedTimeRemaining = (remainingBytes / currentSpeed) * 1000; // Convert to milliseconds\n }\n\n // Find start and end times\n const activeTimes = fileMetrics.filter((file) => file.startTime > 0);\n const startTime =\n activeTimes.length > 0\n ? Math.min(...activeTimes.map((file) => file.startTime))\n : null;\n\n const completedTimes = fileMetrics.filter((file) => file.endTime !== null);\n const endTime =\n completedTimes.length > 0 && completedFiles === fileMetrics.length\n ? Math.max(\n ...completedTimes\n .map((file) => file.endTime)\n .filter((time) => time !== null),\n )\n : null;\n\n const totalDuration = startTime && endTime ? endTime - startTime : null;\n\n const newMetrics: UploadMetrics = {\n totalBytesUploaded,\n totalBytes,\n averageSpeed,\n currentSpeed,\n estimatedTimeRemaining,\n totalFiles: fileMetrics.length,\n completedFiles,\n activeUploads,\n progress,\n peakSpeed: Math.max(metrics.peakSpeed, currentSpeed),\n startTime,\n endTime,\n totalDuration,\n insights: uploadClient.client.getChunkingInsights(),\n sessionMetrics: [uploadClient.client.exportMetrics().session],\n chunkMetrics: uploadClient.client.exportMetrics().chunks,\n };\n\n setMetrics(newMetrics);\n onMetricsUpdate?.(newMetrics);\n }, [\n fileMetrics,\n metrics.peakSpeed,\n calculateSpeed,\n onMetricsUpdate,\n uploadClient.client,\n ]);\n\n // Set up periodic speed calculations\n const setupSpeedCalculation = useCallback(() => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n }\n\n intervalRef.current = setInterval(() => {\n if (\n fileMetrics.some((file) => !file.isComplete && file.bytesUploaded > 0)\n ) {\n updateMetrics();\n }\n }, speedCalculationInterval);\n\n return () => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n intervalRef.current = null;\n }\n };\n }, [speedCalculationInterval, updateMetrics, fileMetrics]);\n\n const startFileUpload = useCallback(\n (id: string, filename: string, size: number) => {\n const now = Date.now();\n\n const fileMetric: FileUploadMetrics = {\n id,\n filename,\n size,\n bytesUploaded: 0,\n progress: 0,\n speed: 0,\n startTime: now,\n endTime: null,\n duration: null,\n isComplete: false,\n };\n\n setFileMetrics((prev) => {\n const existing = prev.find((file) => file.id === id);\n if (existing) {\n return prev.map((file) => (file.id === id ? fileMetric : file));\n }\n return [...prev, fileMetric];\n });\n\n onFileStart?.(fileMetric);\n\n // Start speed calculation if this is the first active upload\n if (fileMetrics.filter((file) => !file.isComplete).length === 0) {\n setupSpeedCalculation();\n }\n },\n [fileMetrics, onFileStart, setupSpeedCalculation],\n );\n\n const updateFileProgress = useCallback(\n (id: string, bytesUploaded: number) => {\n const now = Date.now();\n\n setFileMetrics((prev) =>\n prev.map((file) => {\n if (file.id !== id) return file;\n\n const timeDiff = (now - file.startTime) / 1000; // seconds\n const speed = timeDiff > 0 ? bytesUploaded / timeDiff : 0;\n const progress =\n file.size > 0 ? Math.round((bytesUploaded / file.size) * 100) : 0;\n\n const updatedFile = {\n ...file,\n bytesUploaded,\n progress,\n speed,\n };\n\n onFileProgress?.(updatedFile);\n return updatedFile;\n }),\n );\n\n // Trigger metrics update\n setTimeout(updateMetrics, 0);\n },\n [onFileProgress, updateMetrics],\n );\n\n const completeFileUpload = useCallback(\n (id: string) => {\n const now = Date.now();\n\n setFileMetrics((prev) =>\n prev.map((file) => {\n if (file.id !== id) return file;\n\n const duration = now - file.startTime;\n const speed = duration > 0 ? (file.size / duration) * 1000 : 0; // bytes per second\n\n const completedFile = {\n ...file,\n bytesUploaded: file.size,\n progress: 100,\n speed,\n endTime: now,\n duration,\n isComplete: true,\n };\n\n onFileComplete?.(completedFile);\n return completedFile;\n }),\n );\n\n // Trigger metrics update\n setTimeout(updateMetrics, 0);\n },\n [onFileComplete, updateMetrics],\n );\n\n const removeFile = useCallback(\n (id: string) => {\n setFileMetrics((prev) => prev.filter((file) => file.id !== id));\n setTimeout(updateMetrics, 0);\n },\n [updateMetrics],\n );\n\n const reset = useCallback(() => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n intervalRef.current = null;\n }\n\n setMetrics(initialMetrics);\n setFileMetrics([]);\n speedSamplesRef.current = [];\n lastUpdateRef.current = 0;\n }, []);\n\n const getFileMetrics = useCallback(\n (id: string) => {\n return fileMetrics.find((file) => file.id === id);\n },\n [fileMetrics],\n );\n\n const exportMetrics = useCallback(() => {\n return {\n overall: metrics,\n files: fileMetrics,\n exportTime: Date.now(),\n };\n }, [metrics, fileMetrics]);\n\n // Cleanup on unmount\n React.useEffect(() => {\n return () => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n }\n };\n }, []);\n\n return {\n metrics,\n fileMetrics,\n startFileUpload,\n updateFileProgress,\n completeFileUpload,\n removeFile,\n reset,\n getFileMetrics,\n exportMetrics,\n };\n}\n","import type { UploadistaEvent } from \"@uploadista/client-core\";\nimport { useEffect } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\n\n/**\n * Simple hook that subscribes to all Uploadista events (both flow and upload events).\n *\n * This is a low-level hook that provides access to all events. For more structured\n * event handling, consider using `useFlowEvents` or `useUploadEvents` instead.\n *\n * Must be used within UploadistaProvider.\n *\n * @param callback - Function called for every event emitted by the Uploadista client\n *\n * @example\n * ```tsx\n * import { useUploadistaEvents, isFlowEvent, isUploadEvent } from '@uploadista/react';\n *\n * function MyComponent() {\n * useUploadistaEvents((event) => {\n * if (isFlowEvent(event)) {\n * console.log('Flow event:', event.eventType);\n * } else if (isUploadEvent(event)) {\n * console.log('Upload event:', event.type);\n * }\n * });\n *\n * return <div>Listening to all events...</div>;\n * }\n * ```\n */\nexport function useUploadistaEvents(\n callback: (event: UploadistaEvent) => void,\n): void {\n const { subscribeToEvents } = useUploadistaContext();\n\n useEffect(() => {\n const unsubscribe = subscribeToEvents(callback);\n return unsubscribe;\n }, [subscribeToEvents, callback]);\n}\n"],"mappings":"yOAOA,SAAgB,EAAY,EAA4C,CACtE,GAAI,EAAE,cAAe,GAAQ,MAAO,GACpC,IAAM,EAAI,EACV,OACE,EAAE,YAAc,EAAU,UAC1B,EAAE,YAAc,EAAU,QAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,SAC1B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,EACH,cAAe,EAAK,KACpB,SAAU,IACV,QACA,QAAS,EACT,WACA,WAAY,GACb,CAGD,OADA,IAAiB,EAAc,CACxB,GACP,CACH,CAGD,WAAW,EAAe,EAAE,EAE9B,CAAC,EAAgB,EAAc,CAChC,CAEK,EAAa,EAChB,GAAe,CACd,EAAgB,GAAS,EAAK,OAAQ,GAAS,EAAK,KAAO,EAAG,CAAC,CAC/D,WAAW,EAAe,EAAE,EAE9B,CAAC,EAAc,CAChB,CAEK,EAAQ,MAAkB,CAC9B,AAEE,EAAY,WADZ,cAAc,EAAY,QAAQ,CACZ,MAGxB,EAAW,EAAe,CAC1B,EAAe,EAAE,CAAC,CAClB,EAAgB,QAAU,EAAE,CAC5B,EAAc,QAAU,GACvB,EAAE,CAAC,CAEA,EAAiB,EACpB,GACQ,EAAY,KAAM,GAAS,EAAK,KAAO,EAAG,CAEnD,CAAC,EAAY,CACd,CAEK,EAAgB,OACb,CACL,QAAS,EACT,MAAO,EACP,WAAY,KAAK,KAAK,CACvB,EACA,CAAC,EAAS,EAAY,CAAC,CAW1B,OARA,EAAM,kBACS,CACP,EAAY,SACd,cAAc,EAAY,QAAQ,EAGrC,EAAE,CAAC,CAEC,CACL,UACA,cACA,kBACA,qBACA,qBACA,aACA,QACA,iBACA,gBACD,CCxiBH,SAAgB,EACd,EACM,CACN,GAAM,CAAE,qBAAsB,GAAsB,CAEpD,MACsB,EAAkB,EAAS,CAE9C,CAAC,EAAmB,EAAS,CAAC"}
|
|
1
|
+
{"version":3,"file":"use-uploadista-events-KhJ4knam.mjs","names":[],"sources":["../src/hooks/event-utils.ts","../src/hooks/use-flow-events.ts","../src/hooks/use-upload-events.ts","../src/hooks/use-upload-metrics.ts","../src/hooks/use-uploadista-events.ts"],"sourcesContent":["import type { UploadistaEvent } from \"@uploadista/client-browser\";\nimport { EventType, type FlowEvent } from \"@uploadista/core/flow\";\nimport { type UploadEvent, UploadEventType } from \"@uploadista/core/types\";\n\n/**\n * Type guard to check if an event is a flow event\n */\nexport function isFlowEvent(event: UploadistaEvent): event is FlowEvent {\n if (!(\"eventType\" in event)) return false;\n const e = event as { eventType: unknown };\n return (\n e.eventType === EventType.JobStart ||\n e.eventType === EventType.JobEnd ||\n e.eventType === EventType.FlowStart ||\n e.eventType === EventType.FlowEnd ||\n e.eventType === EventType.FlowError ||\n e.eventType === EventType.FlowPause ||\n e.eventType === EventType.FlowCancel ||\n e.eventType === EventType.NodeStart ||\n e.eventType === EventType.NodeEnd ||\n e.eventType === EventType.NodePause ||\n e.eventType === EventType.NodeResume ||\n e.eventType === EventType.NodeError ||\n e.eventType === EventType.NodeStream ||\n e.eventType === EventType.NodeResponse\n );\n}\n\n/**\n * Type guard to check if an event is an upload event\n */\nexport function isUploadEvent(event: UploadistaEvent): event is UploadEvent {\n if (!(\"type\" in event)) return false;\n const e = event as { type: unknown };\n return (\n e.type === UploadEventType.UPLOAD_STARTED ||\n e.type === UploadEventType.UPLOAD_PROGRESS ||\n e.type === UploadEventType.UPLOAD_COMPLETE ||\n e.type === UploadEventType.UPLOAD_FAILED ||\n e.type === UploadEventType.UPLOAD_VALIDATION_SUCCESS ||\n e.type === UploadEventType.UPLOAD_VALIDATION_FAILED ||\n e.type === UploadEventType.UPLOAD_VALIDATION_WARNING\n );\n}\n","import type {\n FlowEventFlowCancel,\n FlowEventFlowEnd,\n FlowEventFlowError,\n FlowEventFlowPause,\n FlowEventFlowStart,\n FlowEventJobEnd,\n FlowEventJobStart,\n FlowEventNodeEnd,\n FlowEventNodeError,\n FlowEventNodePause,\n FlowEventNodeResume,\n FlowEventNodeStart,\n} from \"@uploadista/core/flow\";\nimport { EventType } from \"@uploadista/core/flow\";\nimport { useEffect } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\nimport { isFlowEvent } from \"./event-utils\";\n\n/**\n * Options for handling flow execution events.\n *\n * All callbacks are optional - only provide handlers for events you care about.\n */\nexport interface UseFlowEventsOptions {\n /** Called when a job starts execution */\n onJobStart?: (event: FlowEventJobStart) => void;\n /** Called when a job completes (success or failure) */\n onJobEnd?: (event: FlowEventJobEnd) => void;\n /** Called when a flow begins execution */\n onFlowStart?: (event: FlowEventFlowStart) => void;\n /** Called when a flow completes successfully */\n onFlowEnd?: (event: FlowEventFlowEnd) => void;\n /** Called when a flow encounters an error */\n onFlowError?: (event: FlowEventFlowError) => void;\n /** Called when a flow is paused by user request */\n onFlowPause?: (event: FlowEventFlowPause) => void;\n /** Called when a flow is cancelled by user request */\n onFlowCancel?: (event: FlowEventFlowCancel) => void;\n /** Called when a node starts processing */\n onNodeStart?: (event: FlowEventNodeStart) => void;\n /** Called when a node completes successfully */\n onNodeEnd?: (event: FlowEventNodeEnd) => void;\n /** Called when a node pauses (waiting for additional data) */\n onNodePause?: (event: FlowEventNodePause) => void;\n /** Called when a paused node resumes execution */\n onNodeResume?: (event: FlowEventNodeResume) => void;\n /** Called when a node encounters an error */\n onNodeError?: (event: FlowEventNodeError) => void;\n}\n\n/**\n * Structured hook for handling flow execution events with type-safe callbacks.\n *\n * This hook provides a clean API for listening to specific flow events without\n * needing to manually filter events or use type guards.\n *\n * Must be used within UploadistaProvider.\n *\n * @param options - Object with optional callbacks for each flow event type\n *\n * @example\n * ```tsx\n * import { useFlowEvents } from '@uploadista/react';\n *\n * function FlowMonitor() {\n * useFlowEvents({\n * onFlowStart: (event) => {\n * console.log('Flow started:', event.flowId);\n * },\n * onNodeStart: (event) => {\n * console.log('Node started:', event.nodeName);\n * },\n * onNodeEnd: (event) => {\n * console.log('Node completed:', event.nodeName, event.result);\n * },\n * onFlowEnd: (event) => {\n * console.log('Flow completed with outputs:', event.outputs);\n * },\n * onFlowError: (event) => {\n * console.error('Flow failed:', event.error);\n * },\n * });\n *\n * return <div>Monitoring flow execution...</div>;\n * }\n * ```\n */\nexport function useFlowEvents(options: UseFlowEventsOptions): void {\n const { subscribeToEvents } = useUploadistaContext();\n\n useEffect(() => {\n const unsubscribe = subscribeToEvents((event) => {\n // Only handle flow events\n if (!isFlowEvent(event)) return;\n\n // Route to appropriate callback based on event type\n switch (event.eventType) {\n case EventType.JobStart:\n options.onJobStart?.(event);\n break;\n case EventType.JobEnd:\n options.onJobEnd?.(event);\n break;\n case EventType.FlowStart:\n options.onFlowStart?.(event);\n break;\n case EventType.FlowEnd:\n options.onFlowEnd?.(event);\n break;\n case EventType.FlowError:\n options.onFlowError?.(event);\n break;\n case EventType.FlowPause:\n options.onFlowPause?.(event);\n break;\n case EventType.FlowCancel:\n options.onFlowCancel?.(event);\n break;\n case EventType.NodeStart:\n options.onNodeStart?.(event);\n break;\n case EventType.NodeEnd:\n options.onNodeEnd?.(event);\n break;\n case EventType.NodePause:\n options.onNodePause?.(event);\n break;\n case EventType.NodeResume:\n options.onNodeResume?.(event);\n break;\n case EventType.NodeError:\n options.onNodeError?.(event);\n break;\n }\n });\n\n return unsubscribe;\n }, [subscribeToEvents, options]);\n}\n","import { UploadEventType } from \"@uploadista/core/types\";\nimport { useEffect } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\nimport { isUploadEvent } from \"./event-utils\";\n\n/**\n * Upload progress event data\n */\nexport interface UploadProgressEventData {\n id: string;\n progress: number;\n total: number;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload started/complete event data (contains full UploadFile)\n */\nexport interface UploadFileEventData {\n // This will contain the full UploadFile schema\n [key: string]: unknown;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload failed event data\n */\nexport interface UploadFailedEventData {\n id: string;\n error: string;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload validation success event data\n */\nexport interface UploadValidationSuccessEventData {\n id: string;\n validationType: \"checksum\" | \"mimetype\";\n algorithm?: string;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload validation failed event data\n */\nexport interface UploadValidationFailedEventData {\n id: string;\n reason: string;\n expected: string;\n actual: string;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload validation warning event data\n */\nexport interface UploadValidationWarningEventData {\n id: string;\n message: string;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Options for handling upload events.\n *\n * All callbacks are optional - only provide handlers for events you care about.\n */\nexport interface UseUploadEventsOptions {\n /** Called when an upload starts */\n onUploadStarted?: (data: UploadFileEventData) => void;\n /** Called with upload progress updates */\n onUploadProgress?: (data: UploadProgressEventData) => void;\n /** Called when an upload completes successfully */\n onUploadComplete?: (data: UploadFileEventData) => void;\n /** Called when an upload fails */\n onUploadFailed?: (data: UploadFailedEventData) => void;\n /** Called when upload validation succeeds */\n onUploadValidationSuccess?: (data: UploadValidationSuccessEventData) => void;\n /** Called when upload validation fails */\n onUploadValidationFailed?: (data: UploadValidationFailedEventData) => void;\n /** Called when upload validation produces a warning */\n onUploadValidationWarning?: (data: UploadValidationWarningEventData) => void;\n}\n\n/**\n * Structured hook for handling upload events with type-safe callbacks.\n *\n * This hook provides a clean API for listening to specific upload events without\n * needing to manually filter events or use type guards.\n *\n * Must be used within UploadistaProvider.\n *\n * @param options - Object with optional callbacks for each upload event type\n *\n * @example\n * ```tsx\n * import { useUploadEvents } from '@uploadista/react';\n *\n * function UploadMonitor() {\n * useUploadEvents({\n * onUploadStarted: (data) => {\n * console.log('Upload started:', data.id);\n * },\n * onUploadProgress: (data) => {\n * const percent = (data.progress / data.total) * 100;\n * console.log(`Upload progress: ${percent}%`);\n * },\n * onUploadComplete: (data) => {\n * console.log('Upload completed:', data);\n * },\n * onUploadFailed: (data) => {\n * console.error('Upload failed:', data.error);\n * },\n * });\n *\n * return <div>Monitoring uploads...</div>;\n * }\n * ```\n */\nexport function useUploadEvents(options: UseUploadEventsOptions): void {\n const { subscribeToEvents } = useUploadistaContext();\n\n useEffect(() => {\n const unsubscribe = subscribeToEvents((event) => {\n // Only handle upload events\n if (!isUploadEvent(event)) return;\n\n // Route to appropriate callback based on event type\n // Note: flow context is at the top level of the event, not inside data\n const flowContext = \"flow\" in event ? event.flow : undefined;\n\n switch (event.type) {\n case UploadEventType.UPLOAD_STARTED:\n options.onUploadStarted?.({\n ...(event.data as unknown as Omit<UploadFileEventData, \"flow\">),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_PROGRESS:\n options.onUploadProgress?.({\n ...(event.data as unknown as Omit<UploadProgressEventData, \"flow\">),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_COMPLETE:\n options.onUploadComplete?.({\n ...(event.data as unknown as Omit<UploadFileEventData, \"flow\">),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_FAILED:\n options.onUploadFailed?.({\n ...(event.data as unknown as Omit<UploadFailedEventData, \"flow\">),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_VALIDATION_SUCCESS:\n options.onUploadValidationSuccess?.({\n ...(event.data as unknown as Omit<\n UploadValidationSuccessEventData,\n \"flow\"\n >),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_VALIDATION_FAILED:\n options.onUploadValidationFailed?.({\n ...(event.data as unknown as Omit<\n UploadValidationFailedEventData,\n \"flow\"\n >),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_VALIDATION_WARNING:\n options.onUploadValidationWarning?.({\n ...(event.data as unknown as Omit<\n UploadValidationWarningEventData,\n \"flow\"\n >),\n flow: flowContext,\n });\n break;\n }\n });\n\n return unsubscribe;\n }, [subscribeToEvents, options]);\n}\n","import type {\n ChunkMetrics,\n PerformanceInsights,\n UploadSessionMetrics,\n} from \"@uploadista/client-core\";\nimport React, { useCallback, useRef, useState } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\n\nexport type Timeout = ReturnType<typeof setInterval>;\n\nexport interface UploadMetrics {\n /**\n * Total bytes uploaded across all files\n */\n totalBytesUploaded: number;\n\n /**\n * Total bytes to upload across all files\n */\n totalBytes: number;\n\n /**\n * Overall upload speed in bytes per second\n */\n averageSpeed: number;\n\n /**\n * Current upload speed in bytes per second\n */\n currentSpeed: number;\n\n /**\n * Estimated time remaining in milliseconds\n */\n estimatedTimeRemaining: number | null;\n\n /**\n * Total number of files being tracked\n */\n totalFiles: number;\n\n /**\n * Number of files completed\n */\n completedFiles: number;\n\n /**\n * Number of files currently uploading\n */\n activeUploads: number;\n\n /**\n * Overall progress as percentage (0-100)\n */\n progress: number;\n\n /**\n * Peak upload speed achieved\n */\n peakSpeed: number;\n\n /**\n * Start time of the first upload\n */\n startTime: number | null;\n\n /**\n * End time of the last completed upload\n */\n endTime: number | null;\n\n /**\n * Total duration of all uploads\n */\n totalDuration: number | null;\n\n /**\n * Detailed performance insights from the upload client\n */\n insights: PerformanceInsights;\n\n /**\n * Session metrics for completed uploads\n */\n sessionMetrics: Partial<UploadSessionMetrics>[];\n\n /**\n * Detailed chunk metrics from recent uploads\n */\n chunkMetrics: ChunkMetrics[];\n}\n\nexport interface FileUploadMetrics {\n id: string;\n filename: string;\n size: number;\n bytesUploaded: number;\n progress: number;\n speed: number;\n startTime: number;\n endTime: number | null;\n duration: number | null;\n isComplete: boolean;\n}\n\nexport interface UseUploadMetricsOptions {\n /**\n * Interval for calculating current speed (in milliseconds)\n */\n speedCalculationInterval?: number;\n\n /**\n * Number of speed samples to keep for average calculation\n */\n speedSampleSize?: number;\n\n /**\n * Called when metrics are updated\n */\n onMetricsUpdate?: (metrics: UploadMetrics) => void;\n\n /**\n * Called when a file upload starts\n */\n onFileStart?: (fileMetrics: FileUploadMetrics) => void;\n\n /**\n * Called when a file upload progresses\n */\n onFileProgress?: (fileMetrics: FileUploadMetrics) => void;\n\n /**\n * Called when a file upload completes\n */\n onFileComplete?: (fileMetrics: FileUploadMetrics) => void;\n}\n\nexport interface UseUploadMetricsReturn {\n /**\n * Current overall metrics\n */\n metrics: UploadMetrics;\n\n /**\n * Individual file metrics\n */\n fileMetrics: FileUploadMetrics[];\n\n /**\n * Start tracking a new file upload\n */\n startFileUpload: (id: string, filename: string, size: number) => void;\n\n /**\n * Update progress for a file upload\n */\n updateFileProgress: (id: string, bytesUploaded: number) => void;\n\n /**\n * Mark a file upload as complete\n */\n completeFileUpload: (id: string) => void;\n\n /**\n * Remove a file from tracking\n */\n removeFile: (id: string) => void;\n\n /**\n * Reset all metrics\n */\n reset: () => void;\n\n /**\n * Get metrics for a specific file\n */\n getFileMetrics: (id: string) => FileUploadMetrics | undefined;\n\n /**\n * Export metrics as JSON\n */\n exportMetrics: () => {\n overall: UploadMetrics;\n files: FileUploadMetrics[];\n exportTime: number;\n };\n}\n\nconst initialMetrics: UploadMetrics = {\n totalBytesUploaded: 0,\n totalBytes: 0,\n averageSpeed: 0,\n currentSpeed: 0,\n estimatedTimeRemaining: null,\n totalFiles: 0,\n completedFiles: 0,\n activeUploads: 0,\n progress: 0,\n peakSpeed: 0,\n startTime: null,\n endTime: null,\n totalDuration: null,\n insights: {\n overallEfficiency: 0,\n chunkingEffectiveness: 0,\n networkStability: 0,\n recommendations: [],\n optimalChunkSizeRange: { min: 256 * 1024, max: 2 * 1024 * 1024 },\n },\n sessionMetrics: [],\n chunkMetrics: [],\n};\n\n/**\n * React hook for tracking detailed upload metrics and performance statistics.\n * Provides comprehensive monitoring of upload progress, speed, and timing data.\n *\n * @param options - Configuration and event handlers\n * @returns Upload metrics state and control methods\n *\n * @example\n * ```tsx\n * const uploadMetrics = useUploadMetrics({\n * speedCalculationInterval: 1000, // Update speed every second\n * speedSampleSize: 10, // Keep last 10 speed samples for average\n * onMetricsUpdate: (metrics) => {\n * console.log(`Overall progress: ${metrics.progress}%`);\n * console.log(`Speed: ${(metrics.currentSpeed / 1024).toFixed(1)} KB/s`);\n * console.log(`ETA: ${metrics.estimatedTimeRemaining}ms`);\n * },\n * onFileComplete: (fileMetrics) => {\n * console.log(`${fileMetrics.filename} completed in ${fileMetrics.duration}ms`);\n * },\n * });\n *\n * // Start tracking a file\n * const handleFileStart = (file: File) => {\n * uploadMetrics.startFileUpload(file.name, file.name, file.size);\n * };\n *\n * // Update progress during upload\n * const handleProgress = (fileId: string, bytesUploaded: number) => {\n * uploadMetrics.updateFileProgress(fileId, bytesUploaded);\n * };\n *\n * // Display metrics\n * return (\n * <div>\n * <div>Overall Progress: {uploadMetrics.metrics.progress}%</div>\n * <div>Speed: {(uploadMetrics.metrics.currentSpeed / 1024).toFixed(1)} KB/s</div>\n * <div>Files: {uploadMetrics.metrics.completedFiles}/{uploadMetrics.metrics.totalFiles}</div>\n *\n * {uploadMetrics.metrics.estimatedTimeRemaining && (\n * <div>ETA: {Math.round(uploadMetrics.metrics.estimatedTimeRemaining / 1000)}s</div>\n * )}\n *\n * {uploadMetrics.fileMetrics.map((file) => (\n * <div key={file.id}>\n * {file.filename}: {file.progress}% ({(file.speed / 1024).toFixed(1)} KB/s)\n * </div>\n * ))}\n * </div>\n * );\n * ```\n */\nexport function useUploadMetrics(\n options: UseUploadMetricsOptions = {},\n): UseUploadMetricsReturn {\n const {\n speedCalculationInterval = 1000,\n speedSampleSize = 10,\n onMetricsUpdate,\n onFileStart,\n onFileProgress,\n onFileComplete,\n } = options;\n\n const uploadClient = useUploadistaContext();\n\n const [metrics, setMetrics] = useState<UploadMetrics>(initialMetrics);\n const [fileMetrics, setFileMetrics] = useState<FileUploadMetrics[]>([]);\n\n const speedSamplesRef = useRef<Array<{ time: number; bytes: number }>>([]);\n const lastUpdateRef = useRef<number>(0);\n const intervalRef = useRef<Timeout | null>(null);\n\n const calculateSpeed = useCallback(\n (currentTime: number, totalBytesUploaded: number) => {\n const sample = { time: currentTime, bytes: totalBytesUploaded };\n speedSamplesRef.current.push(sample);\n\n // Keep only recent samples\n if (speedSamplesRef.current.length > speedSampleSize) {\n speedSamplesRef.current = speedSamplesRef.current.slice(\n -speedSampleSize,\n );\n }\n\n // Calculate current speed (bytes per second)\n let currentSpeed = 0;\n if (speedSamplesRef.current.length >= 2) {\n const recent =\n speedSamplesRef.current[speedSamplesRef.current.length - 1];\n const previous =\n speedSamplesRef.current[speedSamplesRef.current.length - 2];\n if (recent && previous) {\n const timeDiff = (recent.time - previous.time) / 1000; // Convert to seconds\n const bytesDiff = recent.bytes - previous.bytes;\n currentSpeed = timeDiff > 0 ? bytesDiff / timeDiff : 0;\n }\n }\n\n // Calculate average speed\n let averageSpeed = 0;\n if (speedSamplesRef.current.length >= 2) {\n const first = speedSamplesRef.current[0];\n const last =\n speedSamplesRef.current[speedSamplesRef.current.length - 1];\n if (first && last) {\n const totalTime = (last.time - first.time) / 1000; // Convert to seconds\n const totalBytes = last.bytes - first.bytes;\n averageSpeed = totalTime > 0 ? totalBytes / totalTime : 0;\n }\n }\n\n return { currentSpeed, averageSpeed };\n },\n [speedSampleSize],\n );\n\n const updateMetrics = useCallback(() => {\n const now = Date.now();\n\n // Calculate totals from file metrics\n const totalBytes = fileMetrics.reduce((sum, file) => sum + file.size, 0);\n const totalBytesUploaded = fileMetrics.reduce(\n (sum, file) => sum + file.bytesUploaded,\n 0,\n );\n const completedFiles = fileMetrics.filter((file) => file.isComplete).length;\n const activeUploads = fileMetrics.filter(\n (file) => !file.isComplete && file.bytesUploaded > 0,\n ).length;\n\n // Calculate speeds\n const { currentSpeed, averageSpeed } = calculateSpeed(\n now,\n totalBytesUploaded,\n );\n\n // Calculate progress\n const progress =\n totalBytes > 0 ? Math.round((totalBytesUploaded / totalBytes) * 100) : 0;\n\n // Calculate estimated time remaining\n let estimatedTimeRemaining: number | null = null;\n if (currentSpeed > 0) {\n const remainingBytes = totalBytes - totalBytesUploaded;\n estimatedTimeRemaining = (remainingBytes / currentSpeed) * 1000; // Convert to milliseconds\n }\n\n // Find start and end times\n const activeTimes = fileMetrics.filter((file) => file.startTime > 0);\n const startTime =\n activeTimes.length > 0\n ? Math.min(...activeTimes.map((file) => file.startTime))\n : null;\n\n const completedTimes = fileMetrics.filter((file) => file.endTime !== null);\n const endTime =\n completedTimes.length > 0 && completedFiles === fileMetrics.length\n ? Math.max(\n ...completedTimes\n .map((file) => file.endTime)\n .filter((time) => time !== null),\n )\n : null;\n\n const totalDuration = startTime && endTime ? endTime - startTime : null;\n\n const newMetrics: UploadMetrics = {\n totalBytesUploaded,\n totalBytes,\n averageSpeed,\n currentSpeed,\n estimatedTimeRemaining,\n totalFiles: fileMetrics.length,\n completedFiles,\n activeUploads,\n progress,\n peakSpeed: Math.max(metrics.peakSpeed, currentSpeed),\n startTime,\n endTime,\n totalDuration,\n insights: uploadClient.client.getChunkingInsights(),\n sessionMetrics: [uploadClient.client.exportMetrics().session],\n chunkMetrics: uploadClient.client.exportMetrics().chunks,\n };\n\n setMetrics(newMetrics);\n onMetricsUpdate?.(newMetrics);\n }, [\n fileMetrics,\n metrics.peakSpeed,\n calculateSpeed,\n onMetricsUpdate,\n uploadClient.client,\n ]);\n\n // Set up periodic speed calculations\n const setupSpeedCalculation = useCallback(() => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n }\n\n intervalRef.current = setInterval(() => {\n if (\n fileMetrics.some((file) => !file.isComplete && file.bytesUploaded > 0)\n ) {\n updateMetrics();\n }\n }, speedCalculationInterval);\n\n return () => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n intervalRef.current = null;\n }\n };\n }, [speedCalculationInterval, updateMetrics, fileMetrics]);\n\n const startFileUpload = useCallback(\n (id: string, filename: string, size: number) => {\n const now = Date.now();\n\n const fileMetric: FileUploadMetrics = {\n id,\n filename,\n size,\n bytesUploaded: 0,\n progress: 0,\n speed: 0,\n startTime: now,\n endTime: null,\n duration: null,\n isComplete: false,\n };\n\n setFileMetrics((prev) => {\n const existing = prev.find((file) => file.id === id);\n if (existing) {\n return prev.map((file) => (file.id === id ? fileMetric : file));\n }\n return [...prev, fileMetric];\n });\n\n onFileStart?.(fileMetric);\n\n // Start speed calculation if this is the first active upload\n if (fileMetrics.filter((file) => !file.isComplete).length === 0) {\n setupSpeedCalculation();\n }\n },\n [fileMetrics, onFileStart, setupSpeedCalculation],\n );\n\n const updateFileProgress = useCallback(\n (id: string, bytesUploaded: number) => {\n const now = Date.now();\n\n setFileMetrics((prev) =>\n prev.map((file) => {\n if (file.id !== id) return file;\n\n const timeDiff = (now - file.startTime) / 1000; // seconds\n const speed = timeDiff > 0 ? bytesUploaded / timeDiff : 0;\n const progress =\n file.size > 0 ? Math.round((bytesUploaded / file.size) * 100) : 0;\n\n const updatedFile = {\n ...file,\n bytesUploaded,\n progress,\n speed,\n };\n\n onFileProgress?.(updatedFile);\n return updatedFile;\n }),\n );\n\n // Trigger metrics update\n setTimeout(updateMetrics, 0);\n },\n [onFileProgress, updateMetrics],\n );\n\n const completeFileUpload = useCallback(\n (id: string) => {\n const now = Date.now();\n\n setFileMetrics((prev) =>\n prev.map((file) => {\n if (file.id !== id) return file;\n\n const duration = now - file.startTime;\n const speed = duration > 0 ? (file.size / duration) * 1000 : 0; // bytes per second\n\n const completedFile = {\n ...file,\n bytesUploaded: file.size,\n progress: 100,\n speed,\n endTime: now,\n duration,\n isComplete: true,\n };\n\n onFileComplete?.(completedFile);\n return completedFile;\n }),\n );\n\n // Trigger metrics update\n setTimeout(updateMetrics, 0);\n },\n [onFileComplete, updateMetrics],\n );\n\n const removeFile = useCallback(\n (id: string) => {\n setFileMetrics((prev) => prev.filter((file) => file.id !== id));\n setTimeout(updateMetrics, 0);\n },\n [updateMetrics],\n );\n\n const reset = useCallback(() => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n intervalRef.current = null;\n }\n\n setMetrics(initialMetrics);\n setFileMetrics([]);\n speedSamplesRef.current = [];\n lastUpdateRef.current = 0;\n }, []);\n\n const getFileMetrics = useCallback(\n (id: string) => {\n return fileMetrics.find((file) => file.id === id);\n },\n [fileMetrics],\n );\n\n const exportMetrics = useCallback(() => {\n return {\n overall: metrics,\n files: fileMetrics,\n exportTime: Date.now(),\n };\n }, [metrics, fileMetrics]);\n\n // Cleanup on unmount\n React.useEffect(() => {\n return () => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n }\n };\n }, []);\n\n return {\n metrics,\n fileMetrics,\n startFileUpload,\n updateFileProgress,\n completeFileUpload,\n removeFile,\n reset,\n getFileMetrics,\n exportMetrics,\n };\n}\n","import type { UploadistaEvent } from \"@uploadista/client-core\";\nimport { useEffect } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\n\n/**\n * Simple hook that subscribes to all Uploadista events (both flow and upload events).\n *\n * This is a low-level hook that provides access to all events. For more structured\n * event handling, consider using `useFlowEvents` or `useUploadEvents` instead.\n *\n * Must be used within UploadistaProvider.\n *\n * @param callback - Function called for every event emitted by the Uploadista client\n *\n * @example\n * ```tsx\n * import { useUploadistaEvents, isFlowEvent, isUploadEvent } from '@uploadista/react';\n *\n * function MyComponent() {\n * useUploadistaEvents((event) => {\n * if (isFlowEvent(event)) {\n * console.log('Flow event:', event.eventType);\n * } else if (isUploadEvent(event)) {\n * console.log('Upload event:', event.type);\n * }\n * });\n *\n * return <div>Listening to all events...</div>;\n * }\n * ```\n */\nexport function useUploadistaEvents(\n callback: (event: UploadistaEvent) => void,\n): void {\n const { subscribeToEvents } = useUploadistaContext();\n\n useEffect(() => {\n const unsubscribe = subscribeToEvents(callback);\n return unsubscribe;\n }, [subscribeToEvents, callback]);\n}\n"],"mappings":"yOAOA,SAAgB,EAAY,EAA4C,CACtE,GAAI,EAAE,cAAe,GAAQ,MAAO,GACpC,IAAM,EAAI,EACV,OACE,EAAE,YAAc,EAAU,UAC1B,EAAE,YAAc,EAAU,QAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,SAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,YAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,SAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,YAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,YAC1B,EAAE,YAAc,EAAU,aAO9B,SAAgB,EAAc,EAA8C,CAC1E,G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Ac,CAChB,CAEK,EAAQ,MAAkB,CAC9B,AAEE,EAAY,WADZ,cAAc,EAAY,QAAQ,CACZ,MAGxB,EAAW,EAAe,CAC1B,EAAe,EAAE,CAAC,CAClB,EAAgB,QAAU,EAAE,CAC5B,EAAc,QAAU,GACvB,EAAE,CAAC,CAEA,EAAiB,EACpB,GACQ,EAAY,KAAM,GAAS,EAAK,KAAO,EAAG,CAEnD,CAAC,EAAY,CACd,CAEK,EAAgB,OACb,CACL,QAAS,EACT,MAAO,EACP,WAAY,KAAK,KAAK,CACvB,EACA,CAAC,EAAS,EAAY,CAAC,CAW1B,OARA,EAAM,kBACS,CACP,EAAY,SACd,cAAc,EAAY,QAAQ,EAGrC,EAAE,CAAC,CAEC,CACL,UACA,cACA,kBACA,qBACA,qBACA,aACA,QACA,iBACA,gBACD,CCxiBH,SAAgB,EACd,EACM,CACN,GAAM,CAAE,qBAAsB,GAAsB,CAEpD,MACsB,EAAkB,EAAS,CAE9C,CAAC,EAAmB,EAAS,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uploadista/react",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.1.0-beta.5",
|
|
5
5
|
"description": "React client for Uploadista",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Uploadista",
|
|
@@ -22,23 +22,26 @@
|
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"react": "19.2.3",
|
|
24
24
|
"react-dom": "19.2.3",
|
|
25
|
-
"@uploadista/
|
|
26
|
-
"@uploadista/client-core": "0.0.
|
|
27
|
-
"@uploadista/
|
|
25
|
+
"@uploadista/client-browser": "0.1.0-beta.5",
|
|
26
|
+
"@uploadista/client-core": "0.1.0-beta.5",
|
|
27
|
+
"@uploadista/core": "0.1.0-beta.5"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
|
-
"@
|
|
30
|
+
"@testing-library/jest-dom": "^6.6.3",
|
|
31
|
+
"@testing-library/react": "^16.3.0",
|
|
32
|
+
"@types/react": "19.2.8",
|
|
31
33
|
"@types/react-dom": "19.2.3",
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
"
|
|
34
|
+
"jsdom": "^27.0.0",
|
|
35
|
+
"tsdown": "0.19.0",
|
|
36
|
+
"vitest": "4.0.17",
|
|
37
|
+
"@uploadista/typescript-config": "0.1.0-beta.5"
|
|
35
38
|
},
|
|
36
39
|
"scripts": {
|
|
37
40
|
"build": "tsc --noEmit && tsdown",
|
|
38
41
|
"format": "biome format --write ./src",
|
|
39
42
|
"lint": "biome lint --write ./src",
|
|
40
43
|
"check": "biome check --write ./src",
|
|
41
|
-
"test": "vitest",
|
|
44
|
+
"test": "vitest run",
|
|
42
45
|
"test:run": "vitest run",
|
|
43
46
|
"test:watch": "vitest --watch"
|
|
44
47
|
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { isFlowEvent, isUploadEvent } from "../hooks/event-utils";
|
|
3
|
+
|
|
4
|
+
describe("event-utils", () => {
|
|
5
|
+
describe("isFlowEvent", () => {
|
|
6
|
+
it("should return true for job-start event", () => {
|
|
7
|
+
const event = { eventType: "job-start" };
|
|
8
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it("should return true for job-end event", () => {
|
|
12
|
+
const event = { eventType: "job-end" };
|
|
13
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it("should return true for flow-start event", () => {
|
|
17
|
+
const event = { eventType: "flow-start" };
|
|
18
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it("should return true for flow-end event", () => {
|
|
22
|
+
const event = { eventType: "flow-end" };
|
|
23
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("should return true for flow-error event", () => {
|
|
27
|
+
const event = { eventType: "flow-error" };
|
|
28
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("should return true for flow-pause event", () => {
|
|
32
|
+
const event = { eventType: "flow-pause" };
|
|
33
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it("should return true for flow-cancel event", () => {
|
|
37
|
+
const event = { eventType: "flow-cancel" };
|
|
38
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("should return true for node-start event", () => {
|
|
42
|
+
const event = { eventType: "node-start" };
|
|
43
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("should return true for node-end event", () => {
|
|
47
|
+
const event = { eventType: "node-end" };
|
|
48
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("should return true for node-pause event", () => {
|
|
52
|
+
const event = { eventType: "node-pause" };
|
|
53
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it("should return true for node-resume event", () => {
|
|
57
|
+
const event = { eventType: "node-resume" };
|
|
58
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("should return true for node-error event", () => {
|
|
62
|
+
const event = { eventType: "node-error" };
|
|
63
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("should return true for node-stream event", () => {
|
|
67
|
+
const event = { eventType: "node-stream" };
|
|
68
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("should return true for node-response event", () => {
|
|
72
|
+
const event = { eventType: "node-response" };
|
|
73
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("should return false for upload events", () => {
|
|
77
|
+
const event = { type: "upload-started" };
|
|
78
|
+
expect(isFlowEvent(event as any)).toBe(false);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it("should return false for events without eventType", () => {
|
|
82
|
+
const event = { someOtherProperty: "value" };
|
|
83
|
+
expect(isFlowEvent(event as any)).toBe(false);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("should return false for events with unknown eventType", () => {
|
|
87
|
+
const event = { eventType: "unknown-event" };
|
|
88
|
+
expect(isFlowEvent(event as any)).toBe(false);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("should return false for empty object", () => {
|
|
92
|
+
expect(isFlowEvent({} as any)).toBe(false);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
describe("isUploadEvent", () => {
|
|
97
|
+
it("should return true for upload-started event", () => {
|
|
98
|
+
const event = { type: "upload-started" };
|
|
99
|
+
expect(isUploadEvent(event as any)).toBe(true);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it("should return true for upload-progress event", () => {
|
|
103
|
+
const event = { type: "upload-progress" };
|
|
104
|
+
expect(isUploadEvent(event as any)).toBe(true);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("should return true for upload-complete event", () => {
|
|
108
|
+
const event = { type: "upload-complete" };
|
|
109
|
+
expect(isUploadEvent(event as any)).toBe(true);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("should return true for upload-failed event", () => {
|
|
113
|
+
const event = { type: "upload-failed" };
|
|
114
|
+
expect(isUploadEvent(event as any)).toBe(true);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("should return true for upload-validation-success event", () => {
|
|
118
|
+
const event = { type: "upload-validation-success" };
|
|
119
|
+
expect(isUploadEvent(event as any)).toBe(true);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("should return true for upload-validation-failed event", () => {
|
|
123
|
+
const event = { type: "upload-validation-failed" };
|
|
124
|
+
expect(isUploadEvent(event as any)).toBe(true);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("should return true for upload-validation-warning event", () => {
|
|
128
|
+
const event = { type: "upload-validation-warning" };
|
|
129
|
+
expect(isUploadEvent(event as any)).toBe(true);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it("should return false for flow events", () => {
|
|
133
|
+
const event = { eventType: "flow-start" };
|
|
134
|
+
expect(isUploadEvent(event as any)).toBe(false);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("should return false for events without type property", () => {
|
|
138
|
+
const event = { eventType: "upload-started" };
|
|
139
|
+
expect(isUploadEvent(event as any)).toBe(false);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it("should return false for events with unknown type", () => {
|
|
143
|
+
const event = { type: "unknown-event" };
|
|
144
|
+
expect(isUploadEvent(event as any)).toBe(false);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it("should return false for empty object", () => {
|
|
148
|
+
expect(isUploadEvent({} as any)).toBe(false);
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
describe("mutually exclusive events", () => {
|
|
153
|
+
it("should only match isFlowEvent for flow events", () => {
|
|
154
|
+
const flowEvents = [
|
|
155
|
+
{ eventType: "job-start" },
|
|
156
|
+
{ eventType: "flow-start" },
|
|
157
|
+
{ eventType: "node-start" },
|
|
158
|
+
];
|
|
159
|
+
|
|
160
|
+
for (const event of flowEvents) {
|
|
161
|
+
expect(isFlowEvent(event as any)).toBe(true);
|
|
162
|
+
expect(isUploadEvent(event as any)).toBe(false);
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("should only match isUploadEvent for upload events", () => {
|
|
167
|
+
const uploadEvents = [
|
|
168
|
+
{ type: "upload-started" },
|
|
169
|
+
{ type: "upload-progress" },
|
|
170
|
+
{ type: "upload-complete" },
|
|
171
|
+
];
|
|
172
|
+
|
|
173
|
+
for (const event of uploadEvents) {
|
|
174
|
+
expect(isUploadEvent(event as any)).toBe(true);
|
|
175
|
+
expect(isFlowEvent(event as any)).toBe(false);
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
});
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import "@testing-library/jest-dom/vitest";
|
|
2
|
+
import { vi } from "vitest";
|
|
3
|
+
|
|
4
|
+
// Mock the uploadista client-browser module
|
|
5
|
+
vi.mock("@uploadista/client-browser", () => ({
|
|
6
|
+
createUploadistaClient: vi.fn(() => ({
|
|
7
|
+
upload: vi.fn(),
|
|
8
|
+
executeFlow: vi.fn(),
|
|
9
|
+
discoverFlowInputs: vi.fn(),
|
|
10
|
+
getChunkingInsights: vi.fn(() => ({
|
|
11
|
+
currentChunkSize: 1024 * 1024,
|
|
12
|
+
recommendedChunkSize: 1024 * 1024,
|
|
13
|
+
networkCondition: "good",
|
|
14
|
+
})),
|
|
15
|
+
exportMetrics: vi.fn(() => ({})),
|
|
16
|
+
getNetworkMetrics: vi.fn(() => ({
|
|
17
|
+
averageSpeed: 1024 * 1024,
|
|
18
|
+
currentSpeed: 1024 * 1024,
|
|
19
|
+
estimatedTimeRemaining: 0,
|
|
20
|
+
})),
|
|
21
|
+
getNetworkCondition: vi.fn(() => "good"),
|
|
22
|
+
resetMetrics: vi.fn(),
|
|
23
|
+
})),
|
|
24
|
+
}));
|
|
25
|
+
|
|
26
|
+
// Mock UploadManager from client-core
|
|
27
|
+
vi.mock("@uploadista/client-core", async (importOriginal) => {
|
|
28
|
+
const actual = await importOriginal<typeof import("@uploadista/client-core")>();
|
|
29
|
+
return {
|
|
30
|
+
...actual,
|
|
31
|
+
UploadManager: vi.fn().mockImplementation(() => ({
|
|
32
|
+
upload: vi.fn(),
|
|
33
|
+
abort: vi.fn(),
|
|
34
|
+
reset: vi.fn(),
|
|
35
|
+
retry: vi.fn(),
|
|
36
|
+
cleanup: vi.fn(),
|
|
37
|
+
canRetry: vi.fn(() => false),
|
|
38
|
+
})),
|
|
39
|
+
};
|
|
40
|
+
});
|