@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,9 +1,834 @@
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
 
22
+ // hooks/use-websocket-chat-admin.ts
23
+ var use_websocket_chat_admin_exports = {};
24
+ __export(use_websocket_chat_admin_exports, {
25
+ useWebSocketChatAdmin: () => useWebSocketChatAdmin
26
+ });
27
+ module.exports = __toCommonJS(use_websocket_chat_admin_exports);
28
+ var import_react2 = require("react");
3
29
 
4
- var _chunkE2FJX52Rjs = require('../chunk-E2FJX52R.js');
5
- require('../chunk-DTFTLFSY.js');
30
+ // models/chat-models.ts
31
+ var ChatRoleHumanAgent = "humanAgent";
6
32
 
33
+ // hooks/use-websocket-chat-base.ts
34
+ var import_react = require("react");
35
+ var createDefaultLogger = (debug) => ({
36
+ debug: debug ? console.log : () => {
37
+ },
38
+ info: console.info,
39
+ warn: console.warn,
40
+ error: console.error
41
+ });
42
+ var DEFAULT_RETRY_CONFIG = {
43
+ maxRetries: 10,
44
+ intervals: [1e3, 2e3, 5e3],
45
+ backoffMultiplier: 1.5,
46
+ maxBackoffTime: 3e4
47
+ };
48
+ var DEFAULT_QUEUE_CONFIG = {
49
+ maxSize: 100,
50
+ dropStrategy: "oldest"
51
+ };
52
+ var DEFAULT_HEARTBEAT_INTERVAL = 3e4;
53
+ var DEFAULT_HEARTBEAT_TIMEOUT = 5e3;
54
+ function isChatEvent(data) {
55
+ return data && typeof data === "object" && (typeof data.type === "string" || data.message);
56
+ }
57
+ var useWebSocketChatBase = ({
58
+ serverBaseUrl,
59
+ orgId,
60
+ clientType,
61
+ product,
62
+ onMessage,
63
+ retryConfig = DEFAULT_RETRY_CONFIG,
64
+ queueConfig = DEFAULT_QUEUE_CONFIG,
65
+ debug = false,
66
+ logger = createDefaultLogger(debug),
67
+ heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL,
68
+ heartbeatTimeout = DEFAULT_HEARTBEAT_TIMEOUT
69
+ }) => {
70
+ const [connectionState, setConnectionState] = (0, import_react.useState)("disconnected");
71
+ const [error, setError] = (0, import_react.useState)(void 0);
72
+ const [startTime, setStartTime] = (0, import_react.useState)(void 0);
73
+ const [metrics, setMetrics] = (0, import_react.useState)({
74
+ latency: 0,
75
+ messagesSent: 0,
76
+ messagesReceived: 0,
77
+ messagesQueued: 0,
78
+ reconnectCount: 0
79
+ });
80
+ const wsRef = (0, import_react.useRef)(void 0);
81
+ const reconnectTimeoutRef = (0, import_react.useRef)(void 0);
82
+ const retryCountRef = (0, import_react.useRef)(0);
83
+ const messageQueueRef = (0, import_react.useRef)([]);
84
+ const mountedRef = (0, import_react.useRef)(false);
85
+ const currentChatKeyRef = (0, import_react.useRef)(void 0);
86
+ const currentUserIdRef = (0, import_react.useRef)(void 0);
87
+ const intentionalDisconnectRef = (0, import_react.useRef)(false);
88
+ const eventHandlersRef = (0, import_react.useRef)(
89
+ /* @__PURE__ */ new Map()
90
+ );
91
+ const onMessageRef = (0, import_react.useRef)(onMessage);
92
+ const pendingMessagesRef = (0, import_react.useRef)(/* @__PURE__ */ new Map());
93
+ const heartbeatIntervalRef = (0, import_react.useRef)(void 0);
94
+ const heartbeatTimeoutRef = (0, import_react.useRef)(void 0);
95
+ const lastPongRef = (0, import_react.useRef)(Date.now());
96
+ const chatCreationPromiseRef = (0, import_react.useRef)(null);
97
+ const loadChatRetryMapRef = (0, import_react.useRef)(/* @__PURE__ */ new Map());
98
+ (0, import_react.useEffect)(() => {
99
+ onMessageRef.current = onMessage;
100
+ }, [onMessage]);
101
+ const isConnected = connectionState === "connected";
102
+ const on = (0, import_react.useCallback)((eventType, handler) => {
103
+ if (!eventHandlersRef.current.has(eventType)) {
104
+ eventHandlersRef.current.set(eventType, /* @__PURE__ */ new Set());
105
+ }
106
+ eventHandlersRef.current.get(eventType).add(handler);
107
+ return () => off(eventType, handler);
108
+ }, []);
109
+ const off = (0, import_react.useCallback)((eventType, handler) => {
110
+ const handlers = eventHandlersRef.current.get(eventType);
111
+ if (handlers) {
112
+ handlers.delete(handler);
113
+ if (handlers.size === 0) {
114
+ eventHandlersRef.current.delete(eventType);
115
+ }
116
+ }
117
+ }, []);
118
+ const emit = (0, import_react.useCallback)(
119
+ (eventType, data) => {
120
+ const handlers = eventHandlersRef.current.get(eventType);
121
+ if (handlers) {
122
+ handlers.forEach((handler) => {
123
+ try {
124
+ handler(data);
125
+ } catch (error2) {
126
+ logger.error(`Error in event handler for ${eventType}:`, error2);
127
+ }
128
+ });
129
+ }
130
+ },
131
+ [logger]
132
+ );
133
+ const updateMetrics = (0, import_react.useCallback)((updates) => {
134
+ setMetrics((prev) => ({ ...prev, ...updates }));
135
+ }, []);
136
+ const addToQueue = (0, import_react.useCallback)(
137
+ (event) => {
138
+ const currentQueueSize = messageQueueRef.current.length;
139
+ const maxSize = queueConfig.maxSize || DEFAULT_QUEUE_CONFIG.maxSize;
140
+ if (currentQueueSize >= maxSize) {
141
+ if (queueConfig.dropStrategy === "newest") {
142
+ logger.warn("Message queue full, dropping new message");
143
+ return false;
144
+ } else {
145
+ const dropped = messageQueueRef.current.shift();
146
+ logger.warn("Message queue full, dropped oldest message", dropped);
147
+ }
148
+ }
149
+ messageQueueRef.current.push(event);
150
+ updateMetrics({ messagesQueued: messageQueueRef.current.length });
151
+ return true;
152
+ },
153
+ [queueConfig, logger, updateMetrics]
154
+ );
155
+ const calculateRetryInterval = (0, import_react.useCallback)(
156
+ (retryCount) => {
157
+ const config = { ...DEFAULT_RETRY_CONFIG, ...retryConfig };
158
+ const {
159
+ intervals = [],
160
+ backoffMultiplier = 1.5,
161
+ maxBackoffTime = 3e4
162
+ } = config;
163
+ if (retryCount < intervals.length) {
164
+ return intervals[retryCount];
165
+ }
166
+ const baseInterval = intervals[intervals.length - 1] || 5e3;
167
+ const backoffTime = baseInterval * Math.pow(backoffMultiplier, retryCount - intervals.length + 1);
168
+ return Math.min(backoffTime, maxBackoffTime);
169
+ },
170
+ [retryConfig]
171
+ );
172
+ const startHeartbeat = (0, import_react.useCallback)(() => {
173
+ if (!heartbeatInterval || heartbeatInterval <= 0) return;
174
+ const sendPing = () => {
175
+ if (wsRef.current?.readyState === WebSocket.OPEN) {
176
+ const pingTime = Date.now();
177
+ wsRef.current.send(
178
+ JSON.stringify({ type: "ping", timestamp: pingTime })
179
+ );
180
+ heartbeatTimeoutRef.current = setTimeout(() => {
181
+ logger.warn("Heartbeat timeout - no pong received");
182
+ if (wsRef.current) {
183
+ wsRef.current.close(4e3, "Heartbeat timeout");
184
+ }
185
+ }, heartbeatTimeout);
186
+ }
187
+ };
188
+ if (heartbeatIntervalRef.current) {
189
+ clearInterval(heartbeatIntervalRef.current);
190
+ }
191
+ heartbeatIntervalRef.current = setInterval(sendPing, heartbeatInterval);
192
+ logger.debug("Heartbeat started");
193
+ }, [heartbeatInterval, heartbeatTimeout, logger]);
194
+ const stopHeartbeat = (0, import_react.useCallback)(() => {
195
+ if (heartbeatIntervalRef.current) {
196
+ clearInterval(heartbeatIntervalRef.current);
197
+ heartbeatIntervalRef.current = void 0;
198
+ }
199
+ if (heartbeatTimeoutRef.current) {
200
+ clearTimeout(heartbeatTimeoutRef.current);
201
+ heartbeatTimeoutRef.current = void 0;
202
+ }
203
+ logger.debug("Heartbeat stopped");
204
+ }, [logger]);
205
+ const cleanup = (0, import_react.useCallback)(() => {
206
+ if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
207
+ wsRef.current.close(1e3, "Cleanup");
208
+ }
209
+ wsRef.current = void 0;
210
+ if (reconnectTimeoutRef.current) {
211
+ clearTimeout(reconnectTimeoutRef.current);
212
+ reconnectTimeoutRef.current = void 0;
213
+ }
214
+ stopHeartbeat();
215
+ pendingMessagesRef.current.forEach(({ reject, timeout }) => {
216
+ clearTimeout(timeout);
217
+ reject(new Error("Connection closed"));
218
+ });
219
+ pendingMessagesRef.current.clear();
220
+ loadChatRetryMapRef.current.forEach((retryState) => {
221
+ if (retryState.timeoutId) {
222
+ clearTimeout(retryState.timeoutId);
223
+ }
224
+ });
225
+ loadChatRetryMapRef.current.clear();
226
+ }, [stopHeartbeat]);
227
+ const connect = (0, import_react.useCallback)(
228
+ async (userId) => {
229
+ if (!mountedRef.current) {
230
+ mountedRef.current = true;
231
+ }
232
+ if (!orgId) {
233
+ const error2 = {
234
+ code: "CONNECTION_FAILED",
235
+ message: "Cannot connect: orgId is undefined",
236
+ retryable: false,
237
+ timestamp: Date.now()
238
+ };
239
+ logger.error("Cannot connect: orgId is undefined");
240
+ setError(error2);
241
+ return Promise.reject(error2);
242
+ }
243
+ if (wsRef.current?.readyState === WebSocket.OPEN) {
244
+ logger.debug("Already connected");
245
+ return Promise.resolve();
246
+ }
247
+ if (connectionState === "connecting" || connectionState === "reconnecting") {
248
+ logger.debug("Connection already in progress");
249
+ return Promise.resolve();
250
+ }
251
+ const maxRetries = retryConfig.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries;
252
+ if (retryCountRef.current >= maxRetries && !intentionalDisconnectRef.current) {
253
+ const error2 = {
254
+ code: "CONNECTION_FAILED",
255
+ message: `Max retries (${maxRetries}) exceeded`,
256
+ retryable: false,
257
+ timestamp: Date.now()
258
+ };
259
+ setError(error2);
260
+ updateMetrics({ lastError: error2 });
261
+ return Promise.reject(error2);
262
+ }
263
+ cleanup();
264
+ setConnectionState(
265
+ retryCountRef.current > 0 ? "reconnecting" : "connecting"
266
+ );
267
+ intentionalDisconnectRef.current = false;
268
+ return new Promise((resolve, reject) => {
269
+ try {
270
+ const wsUrl = `${serverBaseUrl}?orgId=${orgId}&userId=${userId}&clientType=${clientType}&product=${product}`;
271
+ const connectionStartTime = Date.now();
272
+ logger.debug("Connecting to WebSocket:", wsUrl);
273
+ console.log(`\u23F3 Initiating WebSocket connection to ${serverBaseUrl}...`);
274
+ const ws = new WebSocket(wsUrl);
275
+ ws.onopen = () => {
276
+ if (!mountedRef.current) {
277
+ ws.close(1e3, "Component unmounted");
278
+ reject(new Error("Component unmounted"));
279
+ return;
280
+ }
281
+ const connectionTimeMs = Date.now() - connectionStartTime;
282
+ const connectionTimeSec = (connectionTimeMs / 1e3).toFixed(2);
283
+ logger.info("\u2705 WebSocket connected", {
284
+ userId,
285
+ retryCount: retryCountRef.current,
286
+ connectionTime: `${connectionTimeSec}s (${connectionTimeMs}ms)`
287
+ });
288
+ console.log(`\u{1F50C} WebSocket connection established in ${connectionTimeSec} seconds`);
289
+ setConnectionState("connected");
290
+ setError(void 0);
291
+ const wasReconnecting = retryCountRef.current > 0;
292
+ retryCountRef.current = 0;
293
+ updateMetrics({
294
+ connectedAt: Date.now(),
295
+ latency: connectionTimeMs,
296
+ reconnectCount: wasReconnecting ? metrics.reconnectCount + 1 : metrics.reconnectCount
297
+ });
298
+ while (messageQueueRef.current.length > 0 && ws.readyState === WebSocket.OPEN) {
299
+ const event = messageQueueRef.current.shift();
300
+ if (event) {
301
+ ws.send(JSON.stringify({ ...event, timestamp: Date.now() }));
302
+ updateMetrics({
303
+ messagesSent: metrics.messagesSent + 1,
304
+ messagesQueued: messageQueueRef.current.length
305
+ });
306
+ }
307
+ }
308
+ currentUserIdRef.current = userId;
309
+ if (currentChatKeyRef.current) {
310
+ if (!orgId) {
311
+ logger.error("Cannot resubscribe to chat: orgId is undefined");
312
+ } else {
313
+ logger.info(
314
+ "Resubscribing to chat after reconnection:",
315
+ currentChatKeyRef.current
316
+ );
317
+ const resubscribeEvent = {
318
+ type: "load_chat",
319
+ orgId,
320
+ chatKey: currentChatKeyRef.current,
321
+ userId,
322
+ timestamp: Date.now(),
323
+ data: {}
324
+ };
325
+ ws.send(JSON.stringify(resubscribeEvent));
326
+ }
327
+ }
328
+ startHeartbeat();
329
+ emit("connected", { userId, wasReconnecting });
330
+ resolve();
331
+ };
332
+ ws.onmessage = (event) => {
333
+ if (!mountedRef.current) return;
334
+ try {
335
+ const data = JSON.parse(event.data);
336
+ if (!isChatEvent(data)) {
337
+ logger.warn("Received invalid message format:", data);
338
+ return;
339
+ }
340
+ const chatEvent = data;
341
+ logger.debug("Message received:", chatEvent.type);
342
+ updateMetrics({
343
+ messagesReceived: metrics.messagesReceived + 1,
344
+ lastMessageAt: Date.now()
345
+ });
346
+ if (chatEvent.type === "pong") {
347
+ if (heartbeatTimeoutRef.current) {
348
+ clearTimeout(heartbeatTimeoutRef.current);
349
+ heartbeatTimeoutRef.current = void 0;
350
+ }
351
+ const latency = Date.now() - (chatEvent.timestamp || Date.now());
352
+ lastPongRef.current = Date.now();
353
+ updateMetrics({ latency });
354
+ return;
355
+ }
356
+ switch (chatEvent.type) {
357
+ case "new_chat_created":
358
+ const newChatKey = chatEvent.data?.chatKey;
359
+ if (newChatKey) {
360
+ logger.info("New chat created with key:", newChatKey);
361
+ currentChatKeyRef.current = newChatKey;
362
+ if (chatCreationPromiseRef.current) {
363
+ chatCreationPromiseRef.current.resolve(newChatKey);
364
+ chatCreationPromiseRef.current = null;
365
+ }
366
+ if (!orgId) {
367
+ logger.error("Cannot send load_chat: orgId is undefined");
368
+ return;
369
+ }
370
+ const loadChatEvent = {
371
+ type: "load_chat",
372
+ orgId,
373
+ chatKey: newChatKey,
374
+ userId: currentUserIdRef.current || userId,
375
+ timestamp: Date.now(),
376
+ data: {}
377
+ };
378
+ ws.send(JSON.stringify(loadChatEvent));
379
+ }
380
+ break;
381
+ case "load_chat_response":
382
+ const chat = chatEvent.data?.chat;
383
+ if (chat && chat.key) {
384
+ logger.info("Chat loaded with key:", chat.key);
385
+ currentChatKeyRef.current = chat.key;
386
+ const retryState = loadChatRetryMapRef.current.get(chat.key);
387
+ if (retryState) {
388
+ if (retryState.timeoutId) {
389
+ clearTimeout(retryState.timeoutId);
390
+ }
391
+ loadChatRetryMapRef.current.delete(chat.key);
392
+ }
393
+ } else if (!chat) {
394
+ logger.warn("Chat load failed, clearing key");
395
+ currentChatKeyRef.current = void 0;
396
+ }
397
+ break;
398
+ case "chat_ended":
399
+ logger.info("Chat ended, clearing key");
400
+ currentChatKeyRef.current = void 0;
401
+ break;
402
+ case "error":
403
+ const errorMessage = chatEvent.data?.message || "Unknown error";
404
+ logger.error("Received error from server:", errorMessage);
405
+ if (errorMessage.includes("nats: key not found") || errorMessage.includes("Failed to load chat")) {
406
+ const chatKeyFromError = currentChatKeyRef.current;
407
+ if (chatKeyFromError) {
408
+ const maxRetries2 = 5;
409
+ let retryState = loadChatRetryMapRef.current.get(chatKeyFromError);
410
+ if (!retryState) {
411
+ retryState = { retryCount: 0, timeoutId: null };
412
+ loadChatRetryMapRef.current.set(chatKeyFromError, retryState);
413
+ }
414
+ if (retryState.retryCount < maxRetries2) {
415
+ const delay = 200 * Math.pow(2, retryState.retryCount);
416
+ retryState.retryCount++;
417
+ logger.info(
418
+ `Chat load failed, retrying (${retryState.retryCount}/${maxRetries2}) in ${delay}ms...`,
419
+ chatKeyFromError
420
+ );
421
+ retryState.timeoutId = setTimeout(() => {
422
+ if (!wsRef.current || !mountedRef.current) return;
423
+ if (!orgId) {
424
+ logger.error("Cannot retry load_chat: orgId is undefined", chatKeyFromError);
425
+ loadChatRetryMapRef.current.delete(chatKeyFromError);
426
+ return;
427
+ }
428
+ logger.debug("Retrying load_chat:", chatKeyFromError);
429
+ const retryLoadEvent = {
430
+ type: "load_chat",
431
+ orgId,
432
+ chatKey: chatKeyFromError,
433
+ userId: currentUserIdRef.current || "",
434
+ timestamp: Date.now(),
435
+ data: {}
436
+ };
437
+ ws.send(JSON.stringify(retryLoadEvent));
438
+ }, delay);
439
+ } else {
440
+ logger.error("Max retries reached for loading chat:", chatKeyFromError);
441
+ loadChatRetryMapRef.current.delete(chatKeyFromError);
442
+ }
443
+ }
444
+ }
445
+ const wsError = {
446
+ code: "NETWORK_ERROR",
447
+ message: errorMessage,
448
+ retryable: true,
449
+ timestamp: Date.now()
450
+ };
451
+ setError(wsError);
452
+ updateMetrics({ lastError: wsError });
453
+ break;
454
+ }
455
+ emit(chatEvent.type || "message", chatEvent);
456
+ if (onMessageRef.current) {
457
+ onMessageRef.current(chatEvent);
458
+ }
459
+ } catch (error2) {
460
+ logger.error("Failed to parse WebSocket message:", error2);
461
+ const parseError = {
462
+ code: "PARSE_ERROR",
463
+ message: "Failed to parse message",
464
+ retryable: false,
465
+ timestamp: Date.now()
466
+ };
467
+ setError(parseError);
468
+ updateMetrics({ lastError: parseError });
469
+ }
470
+ };
471
+ ws.onclose = (event) => {
472
+ if (!mountedRef.current) return;
473
+ logger.info("WebSocket closed", {
474
+ code: event.code,
475
+ reason: event.reason
476
+ });
477
+ setConnectionState("disconnected");
478
+ wsRef.current = void 0;
479
+ stopHeartbeat();
480
+ emit("disconnected", { code: event.code, reason: event.reason });
481
+ if (event.code !== 1e3 && !intentionalDisconnectRef.current && mountedRef.current) {
482
+ const retryInterval = calculateRetryInterval(
483
+ retryCountRef.current
484
+ );
485
+ retryCountRef.current++;
486
+ logger.info(
487
+ `Reconnecting in ${retryInterval}ms (attempt ${retryCountRef.current})`
488
+ );
489
+ if (reconnectTimeoutRef.current) {
490
+ clearTimeout(reconnectTimeoutRef.current);
491
+ }
492
+ reconnectTimeoutRef.current = setTimeout(() => {
493
+ connect(userId);
494
+ }, retryInterval);
495
+ }
496
+ };
497
+ ws.onerror = (error2) => {
498
+ logger.error("WebSocket error:", error2);
499
+ if (!mountedRef.current) return;
500
+ const wsError = {
501
+ code: "CONNECTION_FAILED",
502
+ message: "WebSocket connection failed",
503
+ retryable: true,
504
+ timestamp: Date.now()
505
+ };
506
+ setError(wsError);
507
+ updateMetrics({ lastError: wsError });
508
+ reject(wsError);
509
+ };
510
+ wsRef.current = ws;
511
+ } catch (error2) {
512
+ logger.error("Failed to create WebSocket:", error2);
513
+ const wsError = {
514
+ code: "CONNECTION_FAILED",
515
+ message: error2 instanceof Error ? error2.message : "Failed to create connection",
516
+ retryable: true,
517
+ timestamp: Date.now()
518
+ };
519
+ setError(wsError);
520
+ updateMetrics({ lastError: wsError });
521
+ reject(wsError);
522
+ }
523
+ });
524
+ },
525
+ [
526
+ serverBaseUrl,
527
+ orgId,
528
+ clientType,
529
+ product,
530
+ connectionState,
531
+ logger,
532
+ retryConfig,
533
+ metrics,
534
+ updateMetrics,
535
+ cleanup,
536
+ calculateRetryInterval,
537
+ startHeartbeat,
538
+ emit
539
+ ]
540
+ );
541
+ const sendMessage = (0, import_react.useCallback)(
542
+ (event, overrideUserId) => {
543
+ return new Promise((resolve, reject) => {
544
+ if (!mountedRef.current) {
545
+ reject(new Error("Component not mounted"));
546
+ return;
547
+ }
548
+ const fullEvent = {
549
+ ...event,
550
+ timestamp: Date.now()
551
+ };
552
+ const messageId = `${fullEvent.type}_${fullEvent.timestamp}_${Math.random()}`;
553
+ logger.debug("Sending message:", fullEvent.type);
554
+ if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
555
+ if (addToQueue(fullEvent)) {
556
+ logger.debug("Message queued, attempting to connect");
557
+ if (connectionState === "disconnected" && overrideUserId) {
558
+ connect(overrideUserId).then(() => resolve()).catch(reject);
559
+ } else {
560
+ resolve();
561
+ }
562
+ } else {
563
+ reject(new Error("Message queue full"));
564
+ }
565
+ return;
566
+ }
567
+ try {
568
+ wsRef.current.send(JSON.stringify(fullEvent));
569
+ updateMetrics({ messagesSent: metrics.messagesSent + 1 });
570
+ logger.debug("Message sent successfully");
571
+ resolve();
572
+ } catch (error2) {
573
+ logger.error("Failed to send message:", error2);
574
+ if (addToQueue(fullEvent)) {
575
+ resolve();
576
+ } else {
577
+ const sendError = {
578
+ code: "SEND_FAILED",
579
+ message: error2 instanceof Error ? error2.message : "Failed to send message",
580
+ retryable: true,
581
+ timestamp: Date.now()
582
+ };
583
+ setError(sendError);
584
+ updateMetrics({ lastError: sendError });
585
+ reject(sendError);
586
+ }
587
+ }
588
+ });
589
+ },
590
+ [connectionState, connect, addToQueue, logger, metrics, updateMetrics]
591
+ );
592
+ const startNewChat = (0, import_react.useCallback)(
593
+ (userId, data) => {
594
+ return new Promise((resolve, reject) => {
595
+ if (!userId) {
596
+ reject(new Error("User ID is required"));
597
+ return;
598
+ }
599
+ logger.info("Requesting new chat from server with userId:", userId);
600
+ setStartTime(/* @__PURE__ */ new Date());
601
+ chatCreationPromiseRef.current = { resolve, reject };
602
+ sendMessage(
603
+ {
604
+ type: "new_chat",
605
+ orgId,
606
+ chatKey: "",
607
+ // Server will generate
608
+ userId,
609
+ data: data ?? {}
610
+ },
611
+ userId
612
+ ).catch((error2) => {
613
+ chatCreationPromiseRef.current = null;
614
+ reject(error2);
615
+ });
616
+ setTimeout(() => {
617
+ if (chatCreationPromiseRef.current) {
618
+ chatCreationPromiseRef.current = null;
619
+ reject(new Error("Chat creation timed out"));
620
+ }
621
+ }, 3e4);
622
+ });
623
+ },
624
+ [sendMessage, orgId, logger]
625
+ );
626
+ const disconnect = (0, import_react.useCallback)(
627
+ (intentional = true) => {
628
+ logger.info("Disconnecting WebSocket", { intentional });
629
+ intentionalDisconnectRef.current = intentional;
630
+ cleanup();
631
+ setConnectionState("disconnected");
632
+ messageQueueRef.current = [];
633
+ retryCountRef.current = 0;
634
+ mountedRef.current = false;
635
+ currentChatKeyRef.current = void 0;
636
+ currentUserIdRef.current = void 0;
637
+ },
638
+ [cleanup, logger]
639
+ );
640
+ const clearError = (0, import_react.useCallback)(() => {
641
+ setError(void 0);
642
+ }, []);
643
+ (0, import_react.useEffect)(() => {
644
+ mountedRef.current = true;
645
+ return () => {
646
+ mountedRef.current = false;
647
+ disconnect(true);
648
+ };
649
+ }, []);
650
+ return {
651
+ connectionState,
652
+ isConnected,
653
+ sendMessage,
654
+ error,
655
+ connect,
656
+ startNewChat,
657
+ startTime,
658
+ disconnect,
659
+ metrics,
660
+ on,
661
+ off,
662
+ clearError
663
+ };
664
+ };
7
665
 
8
- exports.useWebSocketChatAdmin = _chunkE2FJX52Rjs.useWebSocketChatAdmin;
666
+ // hooks/use-websocket-chat-admin.ts
667
+ var useWebSocketChatAdmin = ({
668
+ serverBaseUrl,
669
+ orgId,
670
+ product
671
+ }) => {
672
+ const [chats, setChats] = (0, import_react2.useState)(/* @__PURE__ */ new Map());
673
+ const [selectedChat, setSelectedChat] = (0, import_react2.useState)(void 0);
674
+ const handleMessage = (0, import_react2.useCallback)(
675
+ (chatEvent) => {
676
+ switch (chatEvent.type) {
677
+ case "message":
678
+ if (!selectedChat || !chatEvent.message) return;
679
+ setChats((prev) => {
680
+ const newMap = new Map(prev);
681
+ newMap.set(selectedChat.key, {
682
+ ...selectedChat,
683
+ messages: [...selectedChat.messages, chatEvent.message]
684
+ });
685
+ return newMap;
686
+ });
687
+ setSelectedChat((prev) => {
688
+ if (!prev) return prev;
689
+ return {
690
+ ...prev,
691
+ messages: [...prev.messages, chatEvent.message]
692
+ };
693
+ });
694
+ break;
695
+ case "list_chats":
696
+ const chatList = chatEvent.data?.chats;
697
+ if (!chatList) return;
698
+ setChats(new Map(chatList.map((chat) => [chat.key, chat])));
699
+ break;
700
+ case "chat_updated":
701
+ const updatedChat = chatEvent.data?.chat?.value;
702
+ if (updatedChat) {
703
+ setChats((prev) => new Map(prev).set(updatedChat.key, updatedChat));
704
+ }
705
+ break;
706
+ case "chat_removed":
707
+ const chatKey = chatEvent.data?.chatKey?.value;
708
+ if (chatKey) {
709
+ setChats((prev) => {
710
+ const newMap = new Map(prev);
711
+ newMap.delete(chatKey);
712
+ return newMap;
713
+ });
714
+ }
715
+ break;
716
+ case "load_chat":
717
+ const history = chatEvent.data?.chat?.value;
718
+ if (history) {
719
+ setChats((prev) => {
720
+ const existingChat = prev.get(history.key);
721
+ if (!existingChat) return prev;
722
+ return new Map(prev).set(history.key, {
723
+ ...existingChat,
724
+ messages: history.messages
725
+ });
726
+ });
727
+ }
728
+ break;
729
+ }
730
+ },
731
+ [selectedChat]
732
+ );
733
+ const base = useWebSocketChatBase({
734
+ serverBaseUrl,
735
+ orgId,
736
+ clientType: "humanAgent",
737
+ onMessage: handleMessage,
738
+ product
739
+ });
740
+ const selectChat = (0, import_react2.useCallback)(
741
+ (chatKey) => {
742
+ const chat = chats.get(chatKey);
743
+ if (!chat) {
744
+ console.error("Unable to select chat", chatKey);
745
+ return;
746
+ }
747
+ setSelectedChat(chat);
748
+ },
749
+ [chats, orgId, base.sendMessage]
750
+ );
751
+ const addUserToChat = (0, import_react2.useCallback)(
752
+ (orgId2, chatKey, user) => {
753
+ base.sendMessage({
754
+ type: "human_agent_joined",
755
+ orgId: orgId2,
756
+ chatKey,
757
+ userId: user.email,
758
+ data: { user }
759
+ });
760
+ setChats((prev) => {
761
+ const newMap = new Map(prev);
762
+ const chat = newMap.get(chatKey);
763
+ if (!chat) return prev;
764
+ newMap.set(chatKey, {
765
+ ...chat,
766
+ humanAgentEngaged: user.role === ChatRoleHumanAgent,
767
+ users: [...chat?.users ?? [], user]
768
+ });
769
+ return newMap;
770
+ });
771
+ setSelectedChat((prev) => {
772
+ if (!prev) return prev;
773
+ return {
774
+ ...prev,
775
+ humanAgentEngaged: user.role === ChatRoleHumanAgent,
776
+ users: [...prev.users ?? [], user]
777
+ };
778
+ });
779
+ },
780
+ [base.sendMessage]
781
+ );
782
+ const removeUserFromChat = (0, import_react2.useCallback)(
783
+ (orgId2, chatKey, userId) => {
784
+ const chat = chats.get(chatKey);
785
+ if (!chat) return;
786
+ const user = chat.users?.find((u) => u.id === userId);
787
+ if (!user) return;
788
+ base.sendMessage({
789
+ type: "human_agent_left",
790
+ orgId: orgId2,
791
+ chatKey,
792
+ userId,
793
+ data: { user }
794
+ });
795
+ setChats((prev) => {
796
+ const newMap = new Map(prev);
797
+ const chat2 = newMap.get(chatKey);
798
+ if (!chat2) return prev;
799
+ newMap.set(chatKey, {
800
+ ...chat2,
801
+ humanAgentEngaged: false,
802
+ users: chat2.users?.filter((u) => u.id !== userId)
803
+ });
804
+ return newMap;
805
+ });
806
+ },
807
+ [chats, base.sendMessage]
808
+ );
809
+ const blockUser = (0, import_react2.useCallback)(
810
+ (orgId2, chatKey, userId) => {
811
+ base.sendMessage({
812
+ type: "block_user",
813
+ orgId: orgId2,
814
+ chatKey,
815
+ userId
816
+ });
817
+ },
818
+ [base.sendMessage]
819
+ );
820
+ return {
821
+ ...base,
822
+ chats,
823
+ selectedChat,
824
+ selectChat,
825
+ addUserToChat,
826
+ removeUserFromChat,
827
+ blockUser
828
+ };
829
+ };
830
+ // Annotate the CommonJS export names for ESM import in node:
831
+ 0 && (module.exports = {
832
+ useWebSocketChatAdmin
833
+ });
9
834
  //# sourceMappingURL=use-websocket-chat-admin.js.map