@elqnt/chat 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/hooks/use-websocket-chat-admin.d.mts +3 -2
  2. package/dist/hooks/use-websocket-chat-admin.d.ts +3 -2
  3. package/dist/hooks/use-websocket-chat-admin.js +829 -4
  4. package/dist/hooks/use-websocket-chat-admin.js.map +1 -1
  5. package/dist/hooks/use-websocket-chat-admin.mjs +805 -4
  6. package/dist/hooks/use-websocket-chat-admin.mjs.map +1 -1
  7. package/dist/hooks/use-websocket-chat-base.d.mts +68 -2
  8. package/dist/hooks/use-websocket-chat-base.d.ts +68 -2
  9. package/dist/hooks/use-websocket-chat-base.js +661 -6
  10. package/dist/hooks/use-websocket-chat-base.js.map +1 -1
  11. package/dist/hooks/use-websocket-chat-base.mjs +634 -3
  12. package/dist/hooks/use-websocket-chat-base.mjs.map +1 -1
  13. package/dist/hooks/use-websocket-chat-customer.d.mts +3 -2
  14. package/dist/hooks/use-websocket-chat-customer.d.ts +3 -2
  15. package/dist/hooks/use-websocket-chat-customer.js +726 -5
  16. package/dist/hooks/use-websocket-chat-customer.js.map +1 -1
  17. package/dist/hooks/use-websocket-chat-customer.mjs +701 -4
  18. package/dist/hooks/use-websocket-chat-customer.mjs.map +1 -1
  19. package/dist/index.d.mts +3 -2
  20. package/dist/index.d.ts +3 -2
  21. package/dist/index.js +1685 -590
  22. package/dist/index.js.map +1 -1
  23. package/dist/index.mjs +1064 -197
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/{use-websocket-chat-base-CZDONnTz.d.ts → models/index.d.mts} +2 -66
  26. package/dist/{use-websocket-chat-base-CZDONnTz.d.mts → models/index.d.ts} +2 -66
  27. package/dist/models/index.js +555 -0
  28. package/dist/models/index.js.map +1 -0
  29. package/dist/{chunk-AC5J5LX5.mjs → models/index.mjs} +146 -318
  30. package/dist/models/index.mjs.map +1 -0
  31. package/package.json +6 -1
  32. package/dist/chunk-3PXNBY7J.js +0 -73
  33. package/dist/chunk-3PXNBY7J.js.map +0 -1
  34. package/dist/chunk-AC5J5LX5.mjs.map +0 -1
  35. package/dist/chunk-DTFTLFSY.js +0 -637
  36. package/dist/chunk-DTFTLFSY.js.map +0 -1
  37. package/dist/chunk-E2FJX52R.js +0 -529
  38. package/dist/chunk-E2FJX52R.js.map +0 -1
  39. package/dist/chunk-F6OOS4ZM.mjs +0 -637
  40. package/dist/chunk-F6OOS4ZM.mjs.map +0 -1
  41. package/dist/chunk-XVYABY2Z.mjs +0 -73
  42. package/dist/chunk-XVYABY2Z.mjs.map +0 -1
@@ -1,8 +1,663 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});"use client";
1
+ "use client";
2
+ "use strict";
3
+ "use client";
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
2
21
 
3
-
4
- var _chunkDTFTLFSYjs = require('../chunk-DTFTLFSY.js');
5
-
6
-
7
- exports.useWebSocketChatBase = _chunkDTFTLFSYjs.useWebSocketChatBase;
22
+ // hooks/use-websocket-chat-base.ts
23
+ var use_websocket_chat_base_exports = {};
24
+ __export(use_websocket_chat_base_exports, {
25
+ useWebSocketChatBase: () => useWebSocketChatBase
26
+ });
27
+ module.exports = __toCommonJS(use_websocket_chat_base_exports);
28
+ var import_react = require("react");
29
+ var createDefaultLogger = (debug) => ({
30
+ debug: debug ? console.log : () => {
31
+ },
32
+ info: console.info,
33
+ warn: console.warn,
34
+ error: console.error
35
+ });
36
+ var DEFAULT_RETRY_CONFIG = {
37
+ maxRetries: 10,
38
+ intervals: [1e3, 2e3, 5e3],
39
+ backoffMultiplier: 1.5,
40
+ maxBackoffTime: 3e4
41
+ };
42
+ var DEFAULT_QUEUE_CONFIG = {
43
+ maxSize: 100,
44
+ dropStrategy: "oldest"
45
+ };
46
+ var DEFAULT_HEARTBEAT_INTERVAL = 3e4;
47
+ var DEFAULT_HEARTBEAT_TIMEOUT = 5e3;
48
+ function isChatEvent(data) {
49
+ return data && typeof data === "object" && (typeof data.type === "string" || data.message);
50
+ }
51
+ var useWebSocketChatBase = ({
52
+ serverBaseUrl,
53
+ orgId,
54
+ clientType,
55
+ product,
56
+ onMessage,
57
+ retryConfig = DEFAULT_RETRY_CONFIG,
58
+ queueConfig = DEFAULT_QUEUE_CONFIG,
59
+ debug = false,
60
+ logger = createDefaultLogger(debug),
61
+ heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL,
62
+ heartbeatTimeout = DEFAULT_HEARTBEAT_TIMEOUT
63
+ }) => {
64
+ const [connectionState, setConnectionState] = (0, import_react.useState)("disconnected");
65
+ const [error, setError] = (0, import_react.useState)(void 0);
66
+ const [startTime, setStartTime] = (0, import_react.useState)(void 0);
67
+ const [metrics, setMetrics] = (0, import_react.useState)({
68
+ latency: 0,
69
+ messagesSent: 0,
70
+ messagesReceived: 0,
71
+ messagesQueued: 0,
72
+ reconnectCount: 0
73
+ });
74
+ const wsRef = (0, import_react.useRef)(void 0);
75
+ const reconnectTimeoutRef = (0, import_react.useRef)(void 0);
76
+ const retryCountRef = (0, import_react.useRef)(0);
77
+ const messageQueueRef = (0, import_react.useRef)([]);
78
+ const mountedRef = (0, import_react.useRef)(false);
79
+ const currentChatKeyRef = (0, import_react.useRef)(void 0);
80
+ const currentUserIdRef = (0, import_react.useRef)(void 0);
81
+ const intentionalDisconnectRef = (0, import_react.useRef)(false);
82
+ const eventHandlersRef = (0, import_react.useRef)(
83
+ /* @__PURE__ */ new Map()
84
+ );
85
+ const onMessageRef = (0, import_react.useRef)(onMessage);
86
+ const pendingMessagesRef = (0, import_react.useRef)(/* @__PURE__ */ new Map());
87
+ const heartbeatIntervalRef = (0, import_react.useRef)(void 0);
88
+ const heartbeatTimeoutRef = (0, import_react.useRef)(void 0);
89
+ const lastPongRef = (0, import_react.useRef)(Date.now());
90
+ const chatCreationPromiseRef = (0, import_react.useRef)(null);
91
+ const loadChatRetryMapRef = (0, import_react.useRef)(/* @__PURE__ */ new Map());
92
+ (0, import_react.useEffect)(() => {
93
+ onMessageRef.current = onMessage;
94
+ }, [onMessage]);
95
+ const isConnected = connectionState === "connected";
96
+ const on = (0, import_react.useCallback)((eventType, handler) => {
97
+ if (!eventHandlersRef.current.has(eventType)) {
98
+ eventHandlersRef.current.set(eventType, /* @__PURE__ */ new Set());
99
+ }
100
+ eventHandlersRef.current.get(eventType).add(handler);
101
+ return () => off(eventType, handler);
102
+ }, []);
103
+ const off = (0, import_react.useCallback)((eventType, handler) => {
104
+ const handlers = eventHandlersRef.current.get(eventType);
105
+ if (handlers) {
106
+ handlers.delete(handler);
107
+ if (handlers.size === 0) {
108
+ eventHandlersRef.current.delete(eventType);
109
+ }
110
+ }
111
+ }, []);
112
+ const emit = (0, import_react.useCallback)(
113
+ (eventType, data) => {
114
+ const handlers = eventHandlersRef.current.get(eventType);
115
+ if (handlers) {
116
+ handlers.forEach((handler) => {
117
+ try {
118
+ handler(data);
119
+ } catch (error2) {
120
+ logger.error(`Error in event handler for ${eventType}:`, error2);
121
+ }
122
+ });
123
+ }
124
+ },
125
+ [logger]
126
+ );
127
+ const updateMetrics = (0, import_react.useCallback)((updates) => {
128
+ setMetrics((prev) => ({ ...prev, ...updates }));
129
+ }, []);
130
+ const addToQueue = (0, import_react.useCallback)(
131
+ (event) => {
132
+ const currentQueueSize = messageQueueRef.current.length;
133
+ const maxSize = queueConfig.maxSize || DEFAULT_QUEUE_CONFIG.maxSize;
134
+ if (currentQueueSize >= maxSize) {
135
+ if (queueConfig.dropStrategy === "newest") {
136
+ logger.warn("Message queue full, dropping new message");
137
+ return false;
138
+ } else {
139
+ const dropped = messageQueueRef.current.shift();
140
+ logger.warn("Message queue full, dropped oldest message", dropped);
141
+ }
142
+ }
143
+ messageQueueRef.current.push(event);
144
+ updateMetrics({ messagesQueued: messageQueueRef.current.length });
145
+ return true;
146
+ },
147
+ [queueConfig, logger, updateMetrics]
148
+ );
149
+ const calculateRetryInterval = (0, import_react.useCallback)(
150
+ (retryCount) => {
151
+ const config = { ...DEFAULT_RETRY_CONFIG, ...retryConfig };
152
+ const {
153
+ intervals = [],
154
+ backoffMultiplier = 1.5,
155
+ maxBackoffTime = 3e4
156
+ } = config;
157
+ if (retryCount < intervals.length) {
158
+ return intervals[retryCount];
159
+ }
160
+ const baseInterval = intervals[intervals.length - 1] || 5e3;
161
+ const backoffTime = baseInterval * Math.pow(backoffMultiplier, retryCount - intervals.length + 1);
162
+ return Math.min(backoffTime, maxBackoffTime);
163
+ },
164
+ [retryConfig]
165
+ );
166
+ const startHeartbeat = (0, import_react.useCallback)(() => {
167
+ if (!heartbeatInterval || heartbeatInterval <= 0) return;
168
+ const sendPing = () => {
169
+ if (wsRef.current?.readyState === WebSocket.OPEN) {
170
+ const pingTime = Date.now();
171
+ wsRef.current.send(
172
+ JSON.stringify({ type: "ping", timestamp: pingTime })
173
+ );
174
+ heartbeatTimeoutRef.current = setTimeout(() => {
175
+ logger.warn("Heartbeat timeout - no pong received");
176
+ if (wsRef.current) {
177
+ wsRef.current.close(4e3, "Heartbeat timeout");
178
+ }
179
+ }, heartbeatTimeout);
180
+ }
181
+ };
182
+ if (heartbeatIntervalRef.current) {
183
+ clearInterval(heartbeatIntervalRef.current);
184
+ }
185
+ heartbeatIntervalRef.current = setInterval(sendPing, heartbeatInterval);
186
+ logger.debug("Heartbeat started");
187
+ }, [heartbeatInterval, heartbeatTimeout, logger]);
188
+ const stopHeartbeat = (0, import_react.useCallback)(() => {
189
+ if (heartbeatIntervalRef.current) {
190
+ clearInterval(heartbeatIntervalRef.current);
191
+ heartbeatIntervalRef.current = void 0;
192
+ }
193
+ if (heartbeatTimeoutRef.current) {
194
+ clearTimeout(heartbeatTimeoutRef.current);
195
+ heartbeatTimeoutRef.current = void 0;
196
+ }
197
+ logger.debug("Heartbeat stopped");
198
+ }, [logger]);
199
+ const cleanup = (0, import_react.useCallback)(() => {
200
+ if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
201
+ wsRef.current.close(1e3, "Cleanup");
202
+ }
203
+ wsRef.current = void 0;
204
+ if (reconnectTimeoutRef.current) {
205
+ clearTimeout(reconnectTimeoutRef.current);
206
+ reconnectTimeoutRef.current = void 0;
207
+ }
208
+ stopHeartbeat();
209
+ pendingMessagesRef.current.forEach(({ reject, timeout }) => {
210
+ clearTimeout(timeout);
211
+ reject(new Error("Connection closed"));
212
+ });
213
+ pendingMessagesRef.current.clear();
214
+ loadChatRetryMapRef.current.forEach((retryState) => {
215
+ if (retryState.timeoutId) {
216
+ clearTimeout(retryState.timeoutId);
217
+ }
218
+ });
219
+ loadChatRetryMapRef.current.clear();
220
+ }, [stopHeartbeat]);
221
+ const connect = (0, import_react.useCallback)(
222
+ async (userId) => {
223
+ if (!mountedRef.current) {
224
+ mountedRef.current = true;
225
+ }
226
+ if (!orgId) {
227
+ const error2 = {
228
+ code: "CONNECTION_FAILED",
229
+ message: "Cannot connect: orgId is undefined",
230
+ retryable: false,
231
+ timestamp: Date.now()
232
+ };
233
+ logger.error("Cannot connect: orgId is undefined");
234
+ setError(error2);
235
+ return Promise.reject(error2);
236
+ }
237
+ if (wsRef.current?.readyState === WebSocket.OPEN) {
238
+ logger.debug("Already connected");
239
+ return Promise.resolve();
240
+ }
241
+ if (connectionState === "connecting" || connectionState === "reconnecting") {
242
+ logger.debug("Connection already in progress");
243
+ return Promise.resolve();
244
+ }
245
+ const maxRetries = retryConfig.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries;
246
+ if (retryCountRef.current >= maxRetries && !intentionalDisconnectRef.current) {
247
+ const error2 = {
248
+ code: "CONNECTION_FAILED",
249
+ message: `Max retries (${maxRetries}) exceeded`,
250
+ retryable: false,
251
+ timestamp: Date.now()
252
+ };
253
+ setError(error2);
254
+ updateMetrics({ lastError: error2 });
255
+ return Promise.reject(error2);
256
+ }
257
+ cleanup();
258
+ setConnectionState(
259
+ retryCountRef.current > 0 ? "reconnecting" : "connecting"
260
+ );
261
+ intentionalDisconnectRef.current = false;
262
+ return new Promise((resolve, reject) => {
263
+ try {
264
+ const wsUrl = `${serverBaseUrl}?orgId=${orgId}&userId=${userId}&clientType=${clientType}&product=${product}`;
265
+ const connectionStartTime = Date.now();
266
+ logger.debug("Connecting to WebSocket:", wsUrl);
267
+ console.log(`\u23F3 Initiating WebSocket connection to ${serverBaseUrl}...`);
268
+ const ws = new WebSocket(wsUrl);
269
+ ws.onopen = () => {
270
+ if (!mountedRef.current) {
271
+ ws.close(1e3, "Component unmounted");
272
+ reject(new Error("Component unmounted"));
273
+ return;
274
+ }
275
+ const connectionTimeMs = Date.now() - connectionStartTime;
276
+ const connectionTimeSec = (connectionTimeMs / 1e3).toFixed(2);
277
+ logger.info("\u2705 WebSocket connected", {
278
+ userId,
279
+ retryCount: retryCountRef.current,
280
+ connectionTime: `${connectionTimeSec}s (${connectionTimeMs}ms)`
281
+ });
282
+ console.log(`\u{1F50C} WebSocket connection established in ${connectionTimeSec} seconds`);
283
+ setConnectionState("connected");
284
+ setError(void 0);
285
+ const wasReconnecting = retryCountRef.current > 0;
286
+ retryCountRef.current = 0;
287
+ updateMetrics({
288
+ connectedAt: Date.now(),
289
+ latency: connectionTimeMs,
290
+ reconnectCount: wasReconnecting ? metrics.reconnectCount + 1 : metrics.reconnectCount
291
+ });
292
+ while (messageQueueRef.current.length > 0 && ws.readyState === WebSocket.OPEN) {
293
+ const event = messageQueueRef.current.shift();
294
+ if (event) {
295
+ ws.send(JSON.stringify({ ...event, timestamp: Date.now() }));
296
+ updateMetrics({
297
+ messagesSent: metrics.messagesSent + 1,
298
+ messagesQueued: messageQueueRef.current.length
299
+ });
300
+ }
301
+ }
302
+ currentUserIdRef.current = userId;
303
+ if (currentChatKeyRef.current) {
304
+ if (!orgId) {
305
+ logger.error("Cannot resubscribe to chat: orgId is undefined");
306
+ } else {
307
+ logger.info(
308
+ "Resubscribing to chat after reconnection:",
309
+ currentChatKeyRef.current
310
+ );
311
+ const resubscribeEvent = {
312
+ type: "load_chat",
313
+ orgId,
314
+ chatKey: currentChatKeyRef.current,
315
+ userId,
316
+ timestamp: Date.now(),
317
+ data: {}
318
+ };
319
+ ws.send(JSON.stringify(resubscribeEvent));
320
+ }
321
+ }
322
+ startHeartbeat();
323
+ emit("connected", { userId, wasReconnecting });
324
+ resolve();
325
+ };
326
+ ws.onmessage = (event) => {
327
+ if (!mountedRef.current) return;
328
+ try {
329
+ const data = JSON.parse(event.data);
330
+ if (!isChatEvent(data)) {
331
+ logger.warn("Received invalid message format:", data);
332
+ return;
333
+ }
334
+ const chatEvent = data;
335
+ logger.debug("Message received:", chatEvent.type);
336
+ updateMetrics({
337
+ messagesReceived: metrics.messagesReceived + 1,
338
+ lastMessageAt: Date.now()
339
+ });
340
+ if (chatEvent.type === "pong") {
341
+ if (heartbeatTimeoutRef.current) {
342
+ clearTimeout(heartbeatTimeoutRef.current);
343
+ heartbeatTimeoutRef.current = void 0;
344
+ }
345
+ const latency = Date.now() - (chatEvent.timestamp || Date.now());
346
+ lastPongRef.current = Date.now();
347
+ updateMetrics({ latency });
348
+ return;
349
+ }
350
+ switch (chatEvent.type) {
351
+ case "new_chat_created":
352
+ const newChatKey = chatEvent.data?.chatKey;
353
+ if (newChatKey) {
354
+ logger.info("New chat created with key:", newChatKey);
355
+ currentChatKeyRef.current = newChatKey;
356
+ if (chatCreationPromiseRef.current) {
357
+ chatCreationPromiseRef.current.resolve(newChatKey);
358
+ chatCreationPromiseRef.current = null;
359
+ }
360
+ if (!orgId) {
361
+ logger.error("Cannot send load_chat: orgId is undefined");
362
+ return;
363
+ }
364
+ const loadChatEvent = {
365
+ type: "load_chat",
366
+ orgId,
367
+ chatKey: newChatKey,
368
+ userId: currentUserIdRef.current || userId,
369
+ timestamp: Date.now(),
370
+ data: {}
371
+ };
372
+ ws.send(JSON.stringify(loadChatEvent));
373
+ }
374
+ break;
375
+ case "load_chat_response":
376
+ const chat = chatEvent.data?.chat;
377
+ if (chat && chat.key) {
378
+ logger.info("Chat loaded with key:", chat.key);
379
+ currentChatKeyRef.current = chat.key;
380
+ const retryState = loadChatRetryMapRef.current.get(chat.key);
381
+ if (retryState) {
382
+ if (retryState.timeoutId) {
383
+ clearTimeout(retryState.timeoutId);
384
+ }
385
+ loadChatRetryMapRef.current.delete(chat.key);
386
+ }
387
+ } else if (!chat) {
388
+ logger.warn("Chat load failed, clearing key");
389
+ currentChatKeyRef.current = void 0;
390
+ }
391
+ break;
392
+ case "chat_ended":
393
+ logger.info("Chat ended, clearing key");
394
+ currentChatKeyRef.current = void 0;
395
+ break;
396
+ case "error":
397
+ const errorMessage = chatEvent.data?.message || "Unknown error";
398
+ logger.error("Received error from server:", errorMessage);
399
+ if (errorMessage.includes("nats: key not found") || errorMessage.includes("Failed to load chat")) {
400
+ const chatKeyFromError = currentChatKeyRef.current;
401
+ if (chatKeyFromError) {
402
+ const maxRetries2 = 5;
403
+ let retryState = loadChatRetryMapRef.current.get(chatKeyFromError);
404
+ if (!retryState) {
405
+ retryState = { retryCount: 0, timeoutId: null };
406
+ loadChatRetryMapRef.current.set(chatKeyFromError, retryState);
407
+ }
408
+ if (retryState.retryCount < maxRetries2) {
409
+ const delay = 200 * Math.pow(2, retryState.retryCount);
410
+ retryState.retryCount++;
411
+ logger.info(
412
+ `Chat load failed, retrying (${retryState.retryCount}/${maxRetries2}) in ${delay}ms...`,
413
+ chatKeyFromError
414
+ );
415
+ retryState.timeoutId = setTimeout(() => {
416
+ if (!wsRef.current || !mountedRef.current) return;
417
+ if (!orgId) {
418
+ logger.error("Cannot retry load_chat: orgId is undefined", chatKeyFromError);
419
+ loadChatRetryMapRef.current.delete(chatKeyFromError);
420
+ return;
421
+ }
422
+ logger.debug("Retrying load_chat:", chatKeyFromError);
423
+ const retryLoadEvent = {
424
+ type: "load_chat",
425
+ orgId,
426
+ chatKey: chatKeyFromError,
427
+ userId: currentUserIdRef.current || "",
428
+ timestamp: Date.now(),
429
+ data: {}
430
+ };
431
+ ws.send(JSON.stringify(retryLoadEvent));
432
+ }, delay);
433
+ } else {
434
+ logger.error("Max retries reached for loading chat:", chatKeyFromError);
435
+ loadChatRetryMapRef.current.delete(chatKeyFromError);
436
+ }
437
+ }
438
+ }
439
+ const wsError = {
440
+ code: "NETWORK_ERROR",
441
+ message: errorMessage,
442
+ retryable: true,
443
+ timestamp: Date.now()
444
+ };
445
+ setError(wsError);
446
+ updateMetrics({ lastError: wsError });
447
+ break;
448
+ }
449
+ emit(chatEvent.type || "message", chatEvent);
450
+ if (onMessageRef.current) {
451
+ onMessageRef.current(chatEvent);
452
+ }
453
+ } catch (error2) {
454
+ logger.error("Failed to parse WebSocket message:", error2);
455
+ const parseError = {
456
+ code: "PARSE_ERROR",
457
+ message: "Failed to parse message",
458
+ retryable: false,
459
+ timestamp: Date.now()
460
+ };
461
+ setError(parseError);
462
+ updateMetrics({ lastError: parseError });
463
+ }
464
+ };
465
+ ws.onclose = (event) => {
466
+ if (!mountedRef.current) return;
467
+ logger.info("WebSocket closed", {
468
+ code: event.code,
469
+ reason: event.reason
470
+ });
471
+ setConnectionState("disconnected");
472
+ wsRef.current = void 0;
473
+ stopHeartbeat();
474
+ emit("disconnected", { code: event.code, reason: event.reason });
475
+ if (event.code !== 1e3 && !intentionalDisconnectRef.current && mountedRef.current) {
476
+ const retryInterval = calculateRetryInterval(
477
+ retryCountRef.current
478
+ );
479
+ retryCountRef.current++;
480
+ logger.info(
481
+ `Reconnecting in ${retryInterval}ms (attempt ${retryCountRef.current})`
482
+ );
483
+ if (reconnectTimeoutRef.current) {
484
+ clearTimeout(reconnectTimeoutRef.current);
485
+ }
486
+ reconnectTimeoutRef.current = setTimeout(() => {
487
+ connect(userId);
488
+ }, retryInterval);
489
+ }
490
+ };
491
+ ws.onerror = (error2) => {
492
+ logger.error("WebSocket error:", error2);
493
+ if (!mountedRef.current) return;
494
+ const wsError = {
495
+ code: "CONNECTION_FAILED",
496
+ message: "WebSocket connection failed",
497
+ retryable: true,
498
+ timestamp: Date.now()
499
+ };
500
+ setError(wsError);
501
+ updateMetrics({ lastError: wsError });
502
+ reject(wsError);
503
+ };
504
+ wsRef.current = ws;
505
+ } catch (error2) {
506
+ logger.error("Failed to create WebSocket:", error2);
507
+ const wsError = {
508
+ code: "CONNECTION_FAILED",
509
+ message: error2 instanceof Error ? error2.message : "Failed to create connection",
510
+ retryable: true,
511
+ timestamp: Date.now()
512
+ };
513
+ setError(wsError);
514
+ updateMetrics({ lastError: wsError });
515
+ reject(wsError);
516
+ }
517
+ });
518
+ },
519
+ [
520
+ serverBaseUrl,
521
+ orgId,
522
+ clientType,
523
+ product,
524
+ connectionState,
525
+ logger,
526
+ retryConfig,
527
+ metrics,
528
+ updateMetrics,
529
+ cleanup,
530
+ calculateRetryInterval,
531
+ startHeartbeat,
532
+ emit
533
+ ]
534
+ );
535
+ const sendMessage = (0, import_react.useCallback)(
536
+ (event, overrideUserId) => {
537
+ return new Promise((resolve, reject) => {
538
+ if (!mountedRef.current) {
539
+ reject(new Error("Component not mounted"));
540
+ return;
541
+ }
542
+ const fullEvent = {
543
+ ...event,
544
+ timestamp: Date.now()
545
+ };
546
+ const messageId = `${fullEvent.type}_${fullEvent.timestamp}_${Math.random()}`;
547
+ logger.debug("Sending message:", fullEvent.type);
548
+ if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
549
+ if (addToQueue(fullEvent)) {
550
+ logger.debug("Message queued, attempting to connect");
551
+ if (connectionState === "disconnected" && overrideUserId) {
552
+ connect(overrideUserId).then(() => resolve()).catch(reject);
553
+ } else {
554
+ resolve();
555
+ }
556
+ } else {
557
+ reject(new Error("Message queue full"));
558
+ }
559
+ return;
560
+ }
561
+ try {
562
+ wsRef.current.send(JSON.stringify(fullEvent));
563
+ updateMetrics({ messagesSent: metrics.messagesSent + 1 });
564
+ logger.debug("Message sent successfully");
565
+ resolve();
566
+ } catch (error2) {
567
+ logger.error("Failed to send message:", error2);
568
+ if (addToQueue(fullEvent)) {
569
+ resolve();
570
+ } else {
571
+ const sendError = {
572
+ code: "SEND_FAILED",
573
+ message: error2 instanceof Error ? error2.message : "Failed to send message",
574
+ retryable: true,
575
+ timestamp: Date.now()
576
+ };
577
+ setError(sendError);
578
+ updateMetrics({ lastError: sendError });
579
+ reject(sendError);
580
+ }
581
+ }
582
+ });
583
+ },
584
+ [connectionState, connect, addToQueue, logger, metrics, updateMetrics]
585
+ );
586
+ const startNewChat = (0, import_react.useCallback)(
587
+ (userId, data) => {
588
+ return new Promise((resolve, reject) => {
589
+ if (!userId) {
590
+ reject(new Error("User ID is required"));
591
+ return;
592
+ }
593
+ logger.info("Requesting new chat from server with userId:", userId);
594
+ setStartTime(/* @__PURE__ */ new Date());
595
+ chatCreationPromiseRef.current = { resolve, reject };
596
+ sendMessage(
597
+ {
598
+ type: "new_chat",
599
+ orgId,
600
+ chatKey: "",
601
+ // Server will generate
602
+ userId,
603
+ data: data ?? {}
604
+ },
605
+ userId
606
+ ).catch((error2) => {
607
+ chatCreationPromiseRef.current = null;
608
+ reject(error2);
609
+ });
610
+ setTimeout(() => {
611
+ if (chatCreationPromiseRef.current) {
612
+ chatCreationPromiseRef.current = null;
613
+ reject(new Error("Chat creation timed out"));
614
+ }
615
+ }, 3e4);
616
+ });
617
+ },
618
+ [sendMessage, orgId, logger]
619
+ );
620
+ const disconnect = (0, import_react.useCallback)(
621
+ (intentional = true) => {
622
+ logger.info("Disconnecting WebSocket", { intentional });
623
+ intentionalDisconnectRef.current = intentional;
624
+ cleanup();
625
+ setConnectionState("disconnected");
626
+ messageQueueRef.current = [];
627
+ retryCountRef.current = 0;
628
+ mountedRef.current = false;
629
+ currentChatKeyRef.current = void 0;
630
+ currentUserIdRef.current = void 0;
631
+ },
632
+ [cleanup, logger]
633
+ );
634
+ const clearError = (0, import_react.useCallback)(() => {
635
+ setError(void 0);
636
+ }, []);
637
+ (0, import_react.useEffect)(() => {
638
+ mountedRef.current = true;
639
+ return () => {
640
+ mountedRef.current = false;
641
+ disconnect(true);
642
+ };
643
+ }, []);
644
+ return {
645
+ connectionState,
646
+ isConnected,
647
+ sendMessage,
648
+ error,
649
+ connect,
650
+ startNewChat,
651
+ startTime,
652
+ disconnect,
653
+ metrics,
654
+ on,
655
+ off,
656
+ clearError
657
+ };
658
+ };
659
+ // Annotate the CommonJS export names for ESM import in node:
660
+ 0 && (module.exports = {
661
+ useWebSocketChatBase
662
+ });
8
663
  //# sourceMappingURL=use-websocket-chat-base.js.map