@elqnt/chat 1.0.2 → 1.0.3

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/eloquent-packages/eloquent-packages/packages/chat/dist/hooks/use-websocket-chat-customer.js"],"names":[],"mappings":"AAAA,qFAAY;AACZ;AACE;AACF,uDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACF,6EAAC","file":"/home/runner/work/eloquent-packages/eloquent-packages/packages/chat/dist/hooks/use-websocket-chat-customer.js"}
1
+ {"version":3,"sources":["../../hooks/use-websocket-chat-customer.ts","../../hooks/use-websocket-chat-base.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useState } from \"react\";\nimport { Chat, ChatEvent, ChatMessage, ChatUser } from \"../models\";\nimport {\n useWebSocketChatBase,\n UseWebSocketChatBaseConfig,\n UseWebSocketChatBaseReturn,\n} from \"./use-websocket-chat-base\";\n\nexport interface UseWebSocketChatCustomerReturn\n extends UseWebSocketChatBaseReturn {\n title: string | undefined;\n messages: ChatMessage[];\n users: ChatUser[];\n isWaiting: boolean;\n isWaitingForAgent: boolean;\n aiEngaged: boolean;\n humanAgentEngaged: boolean;\n metadata: Record<string, string>;\n status: string | undefined;\n chatKey: string;\n}\n\nexport interface UseWebSocketChatCustomerConfig\n extends Omit<UseWebSocketChatBaseConfig, \"clientType\" | \"onMessage\"> {\n chatKey: string;\n}\n\nexport const useWebSocketChatCustomer = ({\n serverBaseUrl,\n orgId,\n chatKey,\n product,\n}: UseWebSocketChatCustomerConfig): UseWebSocketChatCustomerReturn => {\n const [currentChat, setCurrentChat] = useState<Chat | undefined>(undefined);\n\n const handleMessage = useCallback((chatEvent: ChatEvent) => {\n console.log(\"Received event:\", chatEvent.type);\n\n switch (chatEvent.type) {\n case \"message\":\n if (!chatEvent.message) return;\n\n console.log(\n \"got message:\",\n chatEvent.message.role,\n \":\",\n chatEvent.message.content\n );\n // if (\n // chatEvent.message?.toolCalls?.length &&\n // chatEvent.message.toolCalls.length > 0\n // )\n // return;\n setCurrentChat((prev) => {\n if (!prev) return prev;\n return {\n ...prev,\n messages: [...prev.messages, chatEvent.message!],\n };\n });\n break;\n\n case \"chat_updated\":\n const chat = chatEvent.data?.chat?.value as Chat;\n if (chat) {\n setCurrentChat(chat);\n }\n break;\n\n case \"load_chat\":\n const history = chatEvent.data?.chat as Chat;\n if (!history) return;\n setCurrentChat(history);\n break;\n\n default:\n // console.log(\"unhandled event:\", chatEvent.type);\n break;\n }\n }, []);\n\n const base = useWebSocketChatBase({\n serverBaseUrl,\n orgId,\n clientType: \"customer\",\n onMessage: handleMessage,\n product,\n });\n\n return {\n ...base,\n chatKey,\n title: currentChat?.title,\n messages: currentChat?.messages ?? [],\n users: currentChat?.users ?? [],\n isWaiting: currentChat?.isWaiting ?? false,\n isWaitingForAgent: currentChat?.isWaitingForAgent ?? false,\n aiEngaged: currentChat?.aiEngaged ?? false,\n humanAgentEngaged: currentChat?.humanAgentEngaged ?? false,\n metadata: currentChat?.metadata ?? {},\n status: currentChat?.status,\n };\n};\n","\"use client\";\n\nimport { ProductNameTS } from \"@elqnt/types\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { ChatEvent } from \"../models\";\n\n// Connection state enum\nexport type ConnectionState =\n | \"disconnected\"\n | \"connecting\"\n | \"connected\"\n | \"reconnecting\";\n\n// Error types\nexport interface WebSocketError {\n code:\n | \"CONNECTION_FAILED\"\n | \"PARSE_ERROR\"\n | \"SEND_FAILED\"\n | \"TIMEOUT\"\n | \"NETWORK_ERROR\";\n message: string;\n retryable: boolean;\n timestamp: number;\n}\n\n// Retry configuration\nexport interface RetryConfig {\n maxRetries?: number;\n intervals?: number[];\n backoffMultiplier?: number;\n maxBackoffTime?: number;\n}\n\n// Connection metrics\nexport interface ConnectionMetrics {\n latency: number;\n messagesSent: number;\n messagesReceived: number;\n messagesQueued: number;\n reconnectCount: number;\n lastError?: WebSocketError;\n connectedAt?: number;\n lastMessageAt?: number;\n}\n\n// Message queue configuration\nexport interface QueueConfig {\n maxSize?: number;\n dropStrategy?: \"oldest\" | \"newest\";\n}\n\n// Logger interface\nexport interface Logger {\n debug: (message: string, ...args: any[]) => void;\n info: (message: string, ...args: any[]) => void;\n warn: (message: string, ...args: any[]) => void;\n error: (message: string, ...args: any[]) => void;\n}\n\n// Default logger (can be overridden)\nconst createDefaultLogger = (debug: boolean): Logger => ({\n debug: debug ? console.log : () => {},\n info: console.info,\n warn: console.warn,\n error: console.error,\n});\n\nexport interface UseWebSocketChatBaseConfig {\n serverBaseUrl: string;\n orgId: string;\n clientType: \"customer\" | \"humanAgent\" | \"observer\";\n product: ProductNameTS;\n onMessage?: (event: ChatEvent) => void;\n retryConfig?: RetryConfig;\n queueConfig?: QueueConfig;\n debug?: boolean;\n logger?: Logger;\n heartbeatInterval?: number; // in milliseconds, 0 to disable\n heartbeatTimeout?: number; // in milliseconds\n}\n\nexport interface UseWebSocketChatBaseReturn {\n connectionState: ConnectionState;\n isConnected: boolean;\n sendMessage: (\n event: Omit<ChatEvent, \"timestamp\">,\n overrideUserId?: string\n ) => Promise<void>;\n error: WebSocketError | undefined;\n connect: (userId: string) => Promise<void>;\n startNewChat: (\n userId: string,\n data?: { [key: string]: any }\n ) => Promise<string>;\n startTime: Date | undefined;\n disconnect: (intentional?: boolean) => void;\n metrics: ConnectionMetrics;\n on: (eventType: string, handler: (data: any) => void) => () => void;\n off: (eventType: string, handler: (data: any) => void) => void;\n clearError: () => void;\n}\n\n// Default configurations\nconst DEFAULT_RETRY_CONFIG: RetryConfig = {\n maxRetries: 10,\n intervals: [1000, 2000, 5000],\n backoffMultiplier: 1.5,\n maxBackoffTime: 30000,\n};\n\nconst DEFAULT_QUEUE_CONFIG: QueueConfig = {\n maxSize: 100,\n dropStrategy: \"oldest\",\n};\n\nconst DEFAULT_HEARTBEAT_INTERVAL = 30000; // 30 seconds\nconst DEFAULT_HEARTBEAT_TIMEOUT = 5000; // 5 seconds\n\n// Type guards\nfunction isChatEvent(data: any): data is ChatEvent {\n return (\n data &&\n typeof data === \"object\" &&\n (typeof data.type === \"string\" || data.message)\n );\n}\n\nfunction hasValidChatKey(data: any): boolean {\n return data?.chatKey && typeof data.chatKey === \"string\";\n}\n\nexport const useWebSocketChatBase = ({\n serverBaseUrl,\n orgId,\n clientType,\n product,\n onMessage,\n retryConfig = DEFAULT_RETRY_CONFIG,\n queueConfig = DEFAULT_QUEUE_CONFIG,\n debug = false,\n logger = createDefaultLogger(debug),\n heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL,\n heartbeatTimeout = DEFAULT_HEARTBEAT_TIMEOUT,\n}: UseWebSocketChatBaseConfig): UseWebSocketChatBaseReturn => {\n // State\n const [connectionState, setConnectionState] =\n useState<ConnectionState>(\"disconnected\");\n const [error, setError] = useState<WebSocketError | undefined>(undefined);\n const [startTime, setStartTime] = useState<Date | undefined>(undefined);\n const [metrics, setMetrics] = useState<ConnectionMetrics>({\n latency: 0,\n messagesSent: 0,\n messagesReceived: 0,\n messagesQueued: 0,\n reconnectCount: 0,\n });\n\n // Refs\n const wsRef = useRef<WebSocket | undefined>(undefined);\n const reconnectTimeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);\n const retryCountRef = useRef(0);\n const messageQueueRef = useRef<ChatEvent[]>([]);\n const mountedRef = useRef(false);\n const currentChatKeyRef = useRef<string | undefined>(undefined);\n const currentUserIdRef = useRef<string | undefined>(undefined);\n const intentionalDisconnectRef = useRef(false);\n const eventHandlersRef = useRef<Map<string, Set<(data: any) => void>>>(\n new Map()\n );\n const onMessageRef = useRef(onMessage);\n const pendingMessagesRef = useRef<\n Map<\n string,\n {\n resolve: () => void;\n reject: (error: Error) => void;\n timeout: NodeJS.Timeout;\n }\n >\n >(new Map());\n const heartbeatIntervalRef = useRef<NodeJS.Timeout | undefined>(undefined);\n const heartbeatTimeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);\n const lastPongRef = useRef<number>(Date.now());\n const chatCreationPromiseRef = useRef<{\n resolve: (value: string) => void;\n reject: (reason?: any) => void;\n } | null>(null);\n\n // Load chat retry state\n const loadChatRetryMapRef = useRef<Map<string, {\n retryCount: number;\n timeoutId: NodeJS.Timeout | null;\n }>>(new Map());\n\n // Update onMessage ref when it changes\n useEffect(() => {\n onMessageRef.current = onMessage;\n }, [onMessage]);\n\n // Computed state\n const isConnected = connectionState === \"connected\";\n\n // Event subscription system\n const on = useCallback((eventType: string, handler: (data: any) => void) => {\n if (!eventHandlersRef.current.has(eventType)) {\n eventHandlersRef.current.set(eventType, new Set());\n }\n eventHandlersRef.current.get(eventType)!.add(handler);\n\n // Return unsubscribe function\n return () => off(eventType, handler);\n }, []);\n\n const off = useCallback((eventType: string, handler: (data: any) => void) => {\n const handlers = eventHandlersRef.current.get(eventType);\n if (handlers) {\n handlers.delete(handler);\n if (handlers.size === 0) {\n eventHandlersRef.current.delete(eventType);\n }\n }\n }, []);\n\n // Emit event to all registered handlers\n const emit = useCallback(\n (eventType: string, data: any) => {\n const handlers = eventHandlersRef.current.get(eventType);\n if (handlers) {\n handlers.forEach((handler) => {\n try {\n handler(data);\n } catch (error) {\n logger.error(`Error in event handler for ${eventType}:`, error);\n }\n });\n }\n },\n [logger]\n );\n\n // Update metrics\n const updateMetrics = useCallback((updates: Partial<ConnectionMetrics>) => {\n setMetrics((prev) => ({ ...prev, ...updates }));\n }, []);\n\n // Queue management\n const addToQueue = useCallback(\n (event: ChatEvent) => {\n const currentQueueSize = messageQueueRef.current.length;\n const maxSize = queueConfig.maxSize || DEFAULT_QUEUE_CONFIG.maxSize!;\n\n if (currentQueueSize >= maxSize) {\n if (queueConfig.dropStrategy === \"newest\") {\n logger.warn(\"Message queue full, dropping new message\");\n return false;\n } else {\n // Drop oldest\n const dropped = messageQueueRef.current.shift();\n logger.warn(\"Message queue full, dropped oldest message\", dropped);\n }\n }\n\n messageQueueRef.current.push(event);\n updateMetrics({ messagesQueued: messageQueueRef.current.length });\n return true;\n },\n [queueConfig, logger, updateMetrics]\n );\n\n // Calculate retry interval\n const calculateRetryInterval = useCallback(\n (retryCount: number): number => {\n const config = { ...DEFAULT_RETRY_CONFIG, ...retryConfig };\n const {\n intervals = [],\n backoffMultiplier = 1.5,\n maxBackoffTime = 30000,\n } = config;\n\n if (retryCount < intervals.length) {\n return intervals[retryCount];\n }\n\n // Exponential backoff after predefined intervals\n const baseInterval = intervals[intervals.length - 1] || 5000;\n const backoffTime =\n baseInterval *\n Math.pow(backoffMultiplier, retryCount - intervals.length + 1);\n return Math.min(backoffTime, maxBackoffTime);\n },\n [retryConfig]\n );\n\n // Heartbeat mechanism\n const startHeartbeat = useCallback(() => {\n if (!heartbeatInterval || heartbeatInterval <= 0) return;\n\n const sendPing = () => {\n if (wsRef.current?.readyState === WebSocket.OPEN) {\n const pingTime = Date.now();\n wsRef.current.send(\n JSON.stringify({ type: \"ping\", timestamp: pingTime })\n );\n\n // Set timeout for pong response\n heartbeatTimeoutRef.current = setTimeout(() => {\n logger.warn(\"Heartbeat timeout - no pong received\");\n // Force reconnection\n if (wsRef.current) {\n wsRef.current.close(4000, \"Heartbeat timeout\");\n }\n }, heartbeatTimeout);\n }\n };\n\n // Clear existing interval\n if (heartbeatIntervalRef.current) {\n clearInterval(heartbeatIntervalRef.current);\n }\n\n // Start new interval\n heartbeatIntervalRef.current = setInterval(sendPing, heartbeatInterval);\n logger.debug(\"Heartbeat started\");\n }, [heartbeatInterval, heartbeatTimeout, logger]);\n\n const stopHeartbeat = useCallback(() => {\n if (heartbeatIntervalRef.current) {\n clearInterval(heartbeatIntervalRef.current);\n heartbeatIntervalRef.current = undefined;\n }\n if (heartbeatTimeoutRef.current) {\n clearTimeout(heartbeatTimeoutRef.current);\n heartbeatTimeoutRef.current = undefined;\n }\n logger.debug(\"Heartbeat stopped\");\n }, [logger]);\n\n // Cleanup function\n const cleanup = useCallback(() => {\n if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {\n wsRef.current.close(1000, \"Cleanup\");\n }\n wsRef.current = undefined;\n if (reconnectTimeoutRef.current) {\n clearTimeout(reconnectTimeoutRef.current);\n reconnectTimeoutRef.current = undefined;\n }\n stopHeartbeat();\n\n // Clear pending message promises\n pendingMessagesRef.current.forEach(({ reject, timeout }) => {\n clearTimeout(timeout);\n reject(new Error(\"Connection closed\"));\n });\n pendingMessagesRef.current.clear();\n\n // Clear load chat retry timeouts\n loadChatRetryMapRef.current.forEach((retryState) => {\n if (retryState.timeoutId) {\n clearTimeout(retryState.timeoutId);\n }\n });\n loadChatRetryMapRef.current.clear();\n }, [stopHeartbeat]);\n\n // Connect function\n const connect = useCallback(\n async (userId: string): Promise<void> => {\n if (!mountedRef.current) {\n mountedRef.current = true;\n }\n\n // Guard: Don't connect if orgId is not available\n if (!orgId) {\n const error: WebSocketError = {\n code: \"CONNECTION_FAILED\",\n message: \"Cannot connect: orgId is undefined\",\n retryable: false,\n timestamp: Date.now(),\n };\n logger.error(\"Cannot connect: orgId is undefined\");\n setError(error);\n return Promise.reject(error);\n }\n\n if (wsRef.current?.readyState === WebSocket.OPEN) {\n logger.debug(\"Already connected\");\n return Promise.resolve();\n }\n\n if (\n connectionState === \"connecting\" ||\n connectionState === \"reconnecting\"\n ) {\n logger.debug(\"Connection already in progress\");\n return Promise.resolve();\n }\n\n // Check max retries\n const maxRetries =\n retryConfig.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries!;\n if (\n retryCountRef.current >= maxRetries &&\n !intentionalDisconnectRef.current\n ) {\n const error: WebSocketError = {\n code: \"CONNECTION_FAILED\",\n message: `Max retries (${maxRetries}) exceeded`,\n retryable: false,\n timestamp: Date.now(),\n };\n setError(error);\n updateMetrics({ lastError: error });\n return Promise.reject(error);\n }\n\n cleanup();\n setConnectionState(\n retryCountRef.current > 0 ? \"reconnecting\" : \"connecting\"\n );\n intentionalDisconnectRef.current = false;\n\n return new Promise<void>((resolve, reject) => {\n try {\n const wsUrl = `${serverBaseUrl}?orgId=${orgId}&userId=${userId}&clientType=${clientType}&product=${product}`;\n const connectionStartTime = Date.now();\n\n logger.debug(\"Connecting to WebSocket:\", wsUrl);\n console.log(`⏳ Initiating WebSocket connection to ${serverBaseUrl}...`);\n\n const ws = new WebSocket(wsUrl);\n\n ws.onopen = () => {\n if (!mountedRef.current) {\n ws.close(1000, \"Component unmounted\");\n reject(new Error(\"Component unmounted\"));\n return;\n }\n\n const connectionTimeMs = Date.now() - connectionStartTime;\n const connectionTimeSec = (connectionTimeMs / 1000).toFixed(2);\n\n logger.info(\"✅ WebSocket connected\", {\n userId,\n retryCount: retryCountRef.current,\n connectionTime: `${connectionTimeSec}s (${connectionTimeMs}ms)`,\n });\n\n console.log(`🔌 WebSocket connection established in ${connectionTimeSec} seconds`);\n\n setConnectionState(\"connected\");\n setError(undefined);\n const wasReconnecting = retryCountRef.current > 0;\n retryCountRef.current = 0;\n\n // Update metrics\n updateMetrics({\n connectedAt: Date.now(),\n latency: connectionTimeMs,\n reconnectCount: wasReconnecting\n ? metrics.reconnectCount + 1\n : metrics.reconnectCount,\n });\n\n // Process queued messages\n while (\n messageQueueRef.current.length > 0 &&\n ws.readyState === WebSocket.OPEN\n ) {\n const event = messageQueueRef.current.shift();\n if (event) {\n ws.send(JSON.stringify({ ...event, timestamp: Date.now() }));\n updateMetrics({\n messagesSent: metrics.messagesSent + 1,\n messagesQueued: messageQueueRef.current.length,\n });\n }\n }\n\n // Store the userId for reconnection\n currentUserIdRef.current = userId;\n\n // If we have a chat key, resubscribe to the chat\n if (currentChatKeyRef.current) {\n if (!orgId) {\n logger.error(\"Cannot resubscribe to chat: orgId is undefined\");\n } else {\n logger.info(\n \"Resubscribing to chat after reconnection:\",\n currentChatKeyRef.current\n );\n const resubscribeEvent: ChatEvent = {\n type: \"load_chat\",\n orgId,\n chatKey: currentChatKeyRef.current,\n userId,\n timestamp: Date.now(),\n data: {},\n };\n ws.send(JSON.stringify(resubscribeEvent));\n }\n }\n\n // Start heartbeat\n startHeartbeat();\n\n // Emit connected event\n emit(\"connected\", { userId, wasReconnecting });\n\n // Resolve the promise\n resolve();\n };\n\n ws.onmessage = (event) => {\n if (!mountedRef.current) return;\n\n try {\n const data = JSON.parse(event.data);\n\n if (!isChatEvent(data)) {\n logger.warn(\"Received invalid message format:\", data);\n return;\n }\n\n const chatEvent = data as ChatEvent;\n logger.debug(\"Message received:\", chatEvent.type);\n\n // Update metrics\n updateMetrics({\n messagesReceived: metrics.messagesReceived + 1,\n lastMessageAt: Date.now(),\n });\n\n // Handle pong response\n if (chatEvent.type === \"pong\") {\n if (heartbeatTimeoutRef.current) {\n clearTimeout(heartbeatTimeoutRef.current);\n heartbeatTimeoutRef.current = undefined;\n }\n const latency =\n Date.now() - (chatEvent.timestamp || Date.now());\n lastPongRef.current = Date.now();\n updateMetrics({ latency });\n return;\n }\n\n // Handle specific events internally for connection management\n switch (chatEvent.type) {\n case \"new_chat_created\":\n const newChatKey = chatEvent.data?.chatKey as string;\n if (newChatKey) {\n logger.info(\"New chat created with key:\", newChatKey);\n currentChatKeyRef.current = newChatKey;\n\n // Resolve the promise if waiting for chat creation\n if (chatCreationPromiseRef.current) {\n chatCreationPromiseRef.current.resolve(newChatKey);\n chatCreationPromiseRef.current = null;\n }\n\n // Send load_chat to subscribe to the new chat (only if orgId is valid)\n if (!orgId) {\n logger.error(\"Cannot send load_chat: orgId is undefined\");\n return;\n }\n\n const loadChatEvent: ChatEvent = {\n type: \"load_chat\",\n orgId,\n chatKey: newChatKey,\n userId: currentUserIdRef.current || userId,\n timestamp: Date.now(),\n data: {},\n };\n ws.send(JSON.stringify(loadChatEvent));\n }\n break;\n\n case \"load_chat_response\":\n const chat = chatEvent.data?.chat;\n if (chat && chat.key) {\n logger.info(\"Chat loaded with key:\", chat.key);\n currentChatKeyRef.current = chat.key;\n\n // Clear retry state for this chat on success\n const retryState = loadChatRetryMapRef.current.get(chat.key);\n if (retryState) {\n if (retryState.timeoutId) {\n clearTimeout(retryState.timeoutId);\n }\n loadChatRetryMapRef.current.delete(chat.key);\n }\n } else if (!chat) {\n logger.warn(\"Chat load failed, clearing key\");\n currentChatKeyRef.current = undefined;\n }\n break;\n\n case \"chat_ended\":\n logger.info(\"Chat ended, clearing key\");\n currentChatKeyRef.current = undefined;\n break;\n\n case \"error\":\n const errorMessage =\n chatEvent.data?.message || \"Unknown error\";\n logger.error(\"Received error from server:\", errorMessage);\n\n // Check if this is a \"key not found\" error for load_chat\n if (errorMessage.includes(\"nats: key not found\") || errorMessage.includes(\"Failed to load chat\")) {\n const chatKeyFromError = currentChatKeyRef.current;\n if (chatKeyFromError) {\n const maxRetries = 5;\n let retryState = loadChatRetryMapRef.current.get(chatKeyFromError);\n\n if (!retryState) {\n retryState = { retryCount: 0, timeoutId: null };\n loadChatRetryMapRef.current.set(chatKeyFromError, retryState);\n }\n\n if (retryState.retryCount < maxRetries) {\n // Exponential backoff: 200ms, 400ms, 800ms, 1.6s, 3.2s\n const delay = 200 * Math.pow(2, retryState.retryCount);\n retryState.retryCount++;\n\n logger.info(\n `Chat load failed, retrying (${retryState.retryCount}/${maxRetries}) in ${delay}ms...`,\n chatKeyFromError\n );\n\n retryState.timeoutId = setTimeout(() => {\n if (!wsRef.current || !mountedRef.current) return;\n\n // Check if orgId is valid before retrying\n if (!orgId) {\n logger.error(\"Cannot retry load_chat: orgId is undefined\", chatKeyFromError);\n loadChatRetryMapRef.current.delete(chatKeyFromError);\n return;\n }\n\n logger.debug(\"Retrying load_chat:\", chatKeyFromError);\n const retryLoadEvent: ChatEvent = {\n type: \"load_chat\",\n orgId,\n chatKey: chatKeyFromError,\n userId: currentUserIdRef.current || \"\",\n timestamp: Date.now(),\n data: {},\n };\n ws.send(JSON.stringify(retryLoadEvent));\n }, delay);\n } else {\n logger.error(\"Max retries reached for loading chat:\", chatKeyFromError);\n loadChatRetryMapRef.current.delete(chatKeyFromError);\n }\n }\n }\n\n const wsError: WebSocketError = {\n code: \"NETWORK_ERROR\",\n message: errorMessage,\n retryable: true,\n timestamp: Date.now(),\n };\n setError(wsError);\n updateMetrics({ lastError: wsError });\n break;\n }\n\n // Emit event to subscribers\n emit(chatEvent.type || \"message\", chatEvent);\n\n // Call the legacy onMessage handler\n if (onMessageRef.current) {\n onMessageRef.current(chatEvent);\n }\n } catch (error) {\n logger.error(\"Failed to parse WebSocket message:\", error);\n const parseError: WebSocketError = {\n code: \"PARSE_ERROR\",\n message: \"Failed to parse message\",\n retryable: false,\n timestamp: Date.now(),\n };\n setError(parseError);\n updateMetrics({ lastError: parseError });\n }\n };\n\n ws.onclose = (event) => {\n if (!mountedRef.current) return;\n\n logger.info(\"WebSocket closed\", {\n code: event.code,\n reason: event.reason,\n });\n setConnectionState(\"disconnected\");\n wsRef.current = undefined;\n stopHeartbeat();\n\n // Emit disconnected event\n emit(\"disconnected\", { code: event.code, reason: event.reason });\n\n // Handle reconnection\n if (\n event.code !== 1000 &&\n !intentionalDisconnectRef.current &&\n mountedRef.current\n ) {\n const retryInterval = calculateRetryInterval(\n retryCountRef.current\n );\n retryCountRef.current++;\n\n logger.info(\n `Reconnecting in ${retryInterval}ms (attempt ${retryCountRef.current})`\n );\n\n if (reconnectTimeoutRef.current) {\n clearTimeout(reconnectTimeoutRef.current);\n }\n reconnectTimeoutRef.current = setTimeout(() => {\n connect(userId);\n }, retryInterval);\n }\n };\n\n ws.onerror = (error) => {\n logger.error(\"WebSocket error:\", error);\n if (!mountedRef.current) return;\n\n const wsError: WebSocketError = {\n code: \"CONNECTION_FAILED\",\n message: \"WebSocket connection failed\",\n retryable: true,\n timestamp: Date.now(),\n };\n setError(wsError);\n updateMetrics({ lastError: wsError });\n\n // Reject the promise on error\n reject(wsError);\n };\n\n wsRef.current = ws;\n } catch (error) {\n logger.error(\"Failed to create WebSocket:\", error);\n const wsError: WebSocketError = {\n code: \"CONNECTION_FAILED\",\n message:\n error instanceof Error\n ? error.message\n : \"Failed to create connection\",\n retryable: true,\n timestamp: Date.now(),\n };\n setError(wsError);\n updateMetrics({ lastError: wsError });\n reject(wsError);\n }\n });\n },\n [\n serverBaseUrl,\n orgId,\n clientType,\n product,\n connectionState,\n logger,\n retryConfig,\n metrics,\n updateMetrics,\n cleanup,\n calculateRetryInterval,\n startHeartbeat,\n emit,\n ]\n );\n\n // Send message with promise\n const sendMessage = useCallback(\n (\n event: Omit<ChatEvent, \"timestamp\">,\n overrideUserId?: string\n ): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (!mountedRef.current) {\n reject(new Error(\"Component not mounted\"));\n return;\n }\n\n const fullEvent: ChatEvent = {\n ...event,\n timestamp: Date.now(),\n };\n\n const messageId = `${fullEvent.type}_${fullEvent.timestamp}_${Math.random()}`;\n logger.debug(\"Sending message:\", fullEvent.type);\n\n if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {\n // Queue the message\n if (addToQueue(fullEvent)) {\n logger.debug(\"Message queued, attempting to connect\");\n if (connectionState === \"disconnected\" && overrideUserId) {\n connect(overrideUserId)\n .then(() => resolve())\n .catch(reject);\n } else {\n // Message is queued, will be sent when connected\n resolve();\n }\n } else {\n reject(new Error(\"Message queue full\"));\n }\n return;\n }\n\n try {\n wsRef.current.send(JSON.stringify(fullEvent));\n updateMetrics({ messagesSent: metrics.messagesSent + 1 });\n logger.debug(\"Message sent successfully\");\n resolve();\n } catch (error) {\n logger.error(\"Failed to send message:\", error);\n if (addToQueue(fullEvent)) {\n // Message queued for retry\n resolve();\n } else {\n const sendError: WebSocketError = {\n code: \"SEND_FAILED\",\n message:\n error instanceof Error\n ? error.message\n : \"Failed to send message\",\n retryable: true,\n timestamp: Date.now(),\n };\n setError(sendError);\n updateMetrics({ lastError: sendError });\n reject(sendError);\n }\n }\n });\n },\n [connectionState, connect, addToQueue, logger, metrics, updateMetrics]\n );\n\n // Start new chat with promise\n const startNewChat = useCallback(\n (userId: string, data?: { [key: string]: any }): Promise<string> => {\n return new Promise((resolve, reject) => {\n if (!userId) {\n reject(new Error(\"User ID is required\"));\n return;\n }\n\n logger.info(\"Requesting new chat from server with userId:\", userId);\n setStartTime(new Date());\n\n // Set up promise handlers\n chatCreationPromiseRef.current = { resolve, reject };\n\n // Send request to server to create new chat\n sendMessage(\n {\n type: \"new_chat\",\n orgId,\n chatKey: \"\", // Server will generate\n userId,\n data: data ?? {},\n },\n userId\n ).catch((error) => {\n chatCreationPromiseRef.current = null;\n reject(error);\n });\n\n // Set timeout for chat creation\n setTimeout(() => {\n if (chatCreationPromiseRef.current) {\n chatCreationPromiseRef.current = null;\n reject(new Error(\"Chat creation timed out\"));\n }\n }, 30000); // 30 second timeout\n });\n },\n [sendMessage, orgId, logger]\n );\n\n // Disconnect function\n const disconnect = useCallback(\n (intentional: boolean = true) => {\n logger.info(\"Disconnecting WebSocket\", { intentional });\n intentionalDisconnectRef.current = intentional;\n cleanup();\n setConnectionState(\"disconnected\");\n messageQueueRef.current = [];\n retryCountRef.current = 0;\n mountedRef.current = false;\n currentChatKeyRef.current = undefined;\n currentUserIdRef.current = undefined;\n },\n [cleanup, logger]\n );\n\n // Clear error\n const clearError = useCallback(() => {\n setError(undefined);\n }, []);\n\n // Cleanup on unmount\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n disconnect(true);\n };\n }, []);\n\n return {\n connectionState,\n isConnected,\n sendMessage,\n error,\n connect,\n startNewChat,\n startTime,\n disconnect,\n metrics,\n on,\n off,\n clearError,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,IAAAA,gBAAsC;;;ACCtC,mBAAyD;AA0DzD,IAAM,sBAAsB,CAAC,WAA4B;AAAA,EACvD,OAAO,QAAQ,QAAQ,MAAM,MAAM;AAAA,EAAC;AAAA,EACpC,MAAM,QAAQ;AAAA,EACd,MAAM,QAAQ;AAAA,EACd,OAAO,QAAQ;AACjB;AAsCA,IAAM,uBAAoC;AAAA,EACxC,YAAY;AAAA,EACZ,WAAW,CAAC,KAAM,KAAM,GAAI;AAAA,EAC5B,mBAAmB;AAAA,EACnB,gB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