@origonai/web-chat-sdk 0.1.4 → 0.1.6

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.
@@ -2,7 +2,7 @@ import { fetchEventSource as ne } from "@microsoft/fetch-event-source";
2
2
  function J() {
3
3
  const e = Date.now(), t = new Uint8Array(16);
4
4
  crypto.getRandomValues(t), t[0] = e >> 40 & 255, t[1] = e >> 32 & 255, t[2] = e >> 24 & 255, t[3] = e >> 16 & 255, t[4] = e >> 8 & 255, t[5] = e & 255, t[6] = t[6] & 15 | 112, t[8] = t[8] & 63 | 128;
5
- const o = [...t].map((a) => a.toString(16).padStart(2, "0")).join("");
5
+ const o = [...t].map((r) => r.toString(16).padStart(2, "0")).join("");
6
6
  return `${o.slice(0, 8)}-${o.slice(8, 12)}-${o.slice(12, 16)}-${o.slice(
7
7
  16,
8
8
  20
@@ -20,20 +20,27 @@ async function oe(e) {
20
20
  function se(e) {
21
21
  let t;
22
22
  try {
23
- const o = new URL(e), a = o.pathname.split("/"), d = a.pop(), u = a.join("/");
24
- t = `wss://${o.hostname}${u}/system/${d}/wss`;
23
+ const o = new URL(e);
24
+ t = `https://${o.hostname}${o.pathname}/sse`;
25
25
  } catch (o) {
26
- console.error("Invalid base URL: ", e);
27
26
  }
28
27
  return t;
29
28
  }
30
- function ce(e) {
29
+ function ae(e) {
30
+ let t;
31
+ try {
32
+ const o = new URL(e);
33
+ t = `wss://${o.hostname}${o.pathname}/wss`;
34
+ } catch (o) {
35
+ }
36
+ return t;
37
+ }
38
+ function re(e) {
31
39
  let t;
32
40
  try {
33
41
  const o = new URL(e);
34
42
  t = `wss://${o.hostname}${o.pathname}/audio`;
35
43
  } catch (o) {
36
- console.error("getCallServerEndpoint: Invalid base URL: ", e);
37
44
  }
38
45
  return t;
39
46
  }
@@ -46,7 +53,7 @@ const T = {
46
53
  // this is human agent (dock side)
47
54
  SYSTEM: "system"
48
55
  // this is system message, for ex "Agent joined" / "Agent left"
49
- }, W = 1e4, ae = 5e3, b = {
56
+ }, W = 1e4, ce = 5e3, E = {
50
57
  MESSAGE: "message",
51
58
  TYPING: "typing",
52
59
  TYPING_STOP: "typingOff",
@@ -62,37 +69,36 @@ function ie() {
62
69
  socketConnectionTimeout: null
63
70
  };
64
71
  }
65
- let c = ie();
66
- function N() {
67
- c.pingInterval && (clearInterval(c.pingInterval), c.pingInterval = null);
72
+ let a = ie();
73
+ function A() {
74
+ a.pingInterval && (clearInterval(a.pingInterval), a.pingInterval = null);
68
75
  }
69
- function re() {
70
- N(), c.pingInterval = setInterval(() => {
71
- c.socket && c.socket.readyState === WebSocket.OPEN ? (R({ type: "ping" }), console.log("Sending keep-alive ping")) : (console.log("Socket not open, stopping ping interval"), N());
76
+ function le() {
77
+ A(), a.pingInterval = setInterval(() => {
78
+ a.socket && a.socket.readyState === WebSocket.OPEN ? U({ type: "ping" }) : A();
72
79
  }, W);
73
80
  }
74
81
  function _() {
75
- N(), c.socketDisconnectedTimeout && (clearTimeout(c.socketDisconnectedTimeout), c.socketDisconnectedTimeout = null), c.socketConnectionTimeout && (clearTimeout(c.socketConnectionTimeout), c.socketConnectionTimeout = null);
82
+ A(), a.socketDisconnectedTimeout && (clearTimeout(a.socketDisconnectedTimeout), a.socketDisconnectedTimeout = null), a.socketConnectionTimeout && (clearTimeout(a.socketConnectionTimeout), a.socketConnectionTimeout = null);
76
83
  }
77
84
  function K() {
78
- console.log("handleSocketConnected"), c.socketDisconnected = !1, $("socket");
85
+ a.socketDisconnected = !1, P("socket");
79
86
  }
80
87
  function B() {
81
- console.log("handleSocketDisconnected"), c.socketDisconnected = !0, $("sse");
88
+ a.socketDisconnected = !0, P("sse");
82
89
  }
83
- function le(e) {
90
+ function de(e) {
84
91
  return new Promise((t, o) => {
85
- if (c.socket && (c.socket.readyState === WebSocket.CONNECTING || c.socket.readyState === WebSocket.OPEN)) {
86
- console.log("Socket in connecting/open state, returning."), t(c.socket.readyState === WebSocket.OPEN);
92
+ if (a.socket && (a.socket.readyState === WebSocket.CONNECTING || a.socket.readyState === WebSocket.OPEN)) {
93
+ t(a.socket.readyState === WebSocket.OPEN);
87
94
  return;
88
95
  }
89
- console.log("Initializing socket connection..");
90
- const a = U();
91
- if (!a || !a.endpoint) {
96
+ const r = N();
97
+ if (!r || !r.endpoint) {
92
98
  o(new Error("SDK not initialized. Please initialize SDK first."));
93
99
  return;
94
100
  }
95
- const d = se(a.endpoint);
101
+ const d = ae(r.endpoint);
96
102
  if (!d) {
97
103
  o(
98
104
  new Error(
@@ -101,53 +107,53 @@ function le(e) {
101
107
  );
102
108
  return;
103
109
  }
104
- const u = P(), i = new URLSearchParams({
110
+ const u = $(), c = new URLSearchParams({
105
111
  externalId: u
106
112
  });
107
- e.sessionId && i.set("sessionId", e.sessionId), e.requestId && i.set("requestId", e.requestId), a.token && i.set("token", a.token);
108
- const f = `${d}?${i.toString()}`;
109
- c.socket = new WebSocket(f), c.socket.onopen = () => {
110
- console.log("-------- socket connected --------"), c.previouslyConnected = !0, K(), R({ type: "ping" }), clearTimeout(c.socketConnectionTimeout), re(), t(!0);
111
- }, c.socket.onmessage = (r) => {
112
- const p = JSON.parse(r.data);
113
- de(p);
114
- }, c.socket.onerror = (r) => {
115
- console.error("Socket error:", r), $("sse"), o(r);
116
- }, c.socket.onclose = (r) => {
117
- console.log("-------- socket disconnected --------: ", r.code, r.reason), r.target === c.socket && (r.code === 1006 && (c.previouslyConnected ? B() : h({
113
+ e.sessionId && c.set("sessionId", e.sessionId), e.requestId && c.set("requestId", e.requestId), r.token && c.set("token", r.token);
114
+ const f = `${d}?${c.toString()}`;
115
+ a.socket = new WebSocket(f), a.socket.onopen = () => {
116
+ a.previouslyConnected = !0, K(), U({ type: "ping" }), clearTimeout(a.socketConnectionTimeout), le(), t(!0);
117
+ }, a.socket.onmessage = (l) => {
118
+ const p = JSON.parse(l.data);
119
+ ue(p);
120
+ }, a.socket.onerror = (l) => {
121
+ P("sse"), o(l);
122
+ }, a.socket.onclose = (l) => {
123
+ l.target === a.socket && (l.code === 1006 && (a.previouslyConnected ? B() : h({
118
124
  errorText: "Unable to establish connection",
119
125
  done: !0,
120
126
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
121
- }), clearTimeout(c.socketConnectionTimeout)), c.socket = null, _());
122
- }, c.previouslyConnected || (c.socketConnectionTimeout = setTimeout(() => {
123
- console.error("Socket connection timed out"), h({
127
+ }), clearTimeout(a.socketConnectionTimeout)), a.socket = null, _());
128
+ }, a.previouslyConnected || (a.socketConnectionTimeout = setTimeout(() => {
129
+ h({
124
130
  errorText: "Unable to establish connection",
125
131
  done: !0,
126
132
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
127
133
  }), o(new Error("Socket connection timed out"));
128
- }, ae));
134
+ }, ce));
129
135
  });
130
136
  }
131
- function R(e) {
132
- console.log("sending socket event: ", e.type), !(c.socketDisconnected || !c.socket) && c.socket.send(JSON.stringify({ ...e, eventId: e.eventId || J() }));
137
+ function U(e) {
138
+ a.socketDisconnected || !a.socket || a.socket.send(JSON.stringify({ ...e, eventId: e.eventId || J() }));
133
139
  }
134
- function de(e) {
135
- switch (console.log("received socket event: ", e.type), e.type) {
140
+ function ue(e) {
141
+ switch (e.type) {
136
142
  case "pong": {
137
- c.socketDisconnected && K(), c.socketDisconnectedTimeout && clearTimeout(c.socketDisconnectedTimeout), c.socketDisconnectedTimeout = setTimeout(() => {
138
- console.log("---- socket ping timeout ----"), B();
143
+ a.socketDisconnected && K(), a.socketDisconnectedTimeout && clearTimeout(a.socketDisconnectedTimeout), a.socketDisconnectedTimeout = setTimeout(() => {
144
+ B();
139
145
  }, W + 1e3);
140
146
  break;
141
147
  }
142
- case b.TYPING: {
148
+ case E.TYPING: {
143
149
  F(!0);
144
150
  break;
145
151
  }
146
- case b.TYPING_STOP: {
152
+ case E.TYPING_STOP: {
147
153
  F(!1);
148
154
  break;
149
155
  }
150
- case b.MESSAGE: {
156
+ case E.MESSAGE: {
151
157
  const { eventId: t, data: o } = e;
152
158
  t || h({
153
159
  ...o,
@@ -156,17 +162,17 @@ function de(e) {
156
162
  });
157
163
  break;
158
164
  }
159
- case b.END: {
165
+ case E.END: {
160
166
  H();
161
167
  break;
162
168
  }
163
169
  }
164
170
  }
165
171
  function H() {
166
- console.log("Disconnecting socket"), c.socket && c.socket.close(1e3), c.previouslyConnected = !1, _(), c.socket = null, $("sse");
172
+ a.socket && a.socket.close(1e3), a.previouslyConnected = !1, _(), a.socket = null, P("sse");
167
173
  }
168
- function ue() {
169
- return c.socket !== null && c.socket.readyState === WebSocket.OPEN && !c.socketDisconnected;
174
+ function ge() {
175
+ return a.socket !== null && a.socket.readyState === WebSocket.OPEN && !a.socketDisconnected;
170
176
  }
171
177
  function Y(e = {}) {
172
178
  return {
@@ -187,43 +193,32 @@ let s = Y();
187
193
  function Pe(e) {
188
194
  s.callbacks = { ...s.callbacks, ...e };
189
195
  }
190
- function $e(e) {
191
- console.log("Initializing chat...", e), s.credentials = e, e.token && (s.authenticated = !0);
196
+ function Oe(e) {
197
+ s.credentials = e, e.token && (s.authenticated = !0);
192
198
  }
193
- function U() {
199
+ function N() {
194
200
  return s.credentials;
195
201
  }
196
- function ge(e) {
202
+ function fe(e) {
197
203
  var t, o;
198
204
  e && e !== s.sessionId && (s.sessionId = e, (o = (t = s.callbacks).onSessionUpdate) == null || o.call(t, e));
199
205
  }
200
- async function Oe(e = {}) {
201
- var t;
206
+ async function Re(e = {}) {
202
207
  try {
203
- console.log("startChat: ", e, s);
204
- let o = null;
205
- s.authenticated ? o = s.configData : (o = await me(s.credentials), s.authenticated = !0, s.configData = o);
206
- let a = [];
207
- if (e.sessionId) {
208
- const u = await ke(e.sessionId);
209
- a = ((t = u == null ? void 0 : u.sessionHistory) != null ? t : []).map((i) => ({
210
- id: i.id,
211
- text: i.text,
212
- role: i.youtubeVideo ? T.BOT : i.role,
213
- timestamp: i.timestamp,
214
- video: i.youtubeVideo,
215
- channel: i.channel,
216
- done: !0
217
- }));
218
- }
219
- const d = new URLSearchParams();
220
- return s.credentials.token || d.set("externalId", P()), s.sseUrl = `${s.credentials.endpoint}?${d.toString()}`, s.sessionId = e.sessionId, s.messages = a, console.log("Chat initiated successfully"), {
208
+ let t = null;
209
+ s.authenticated ? t = s.configData : (t = await ke(s.credentials), s.authenticated = !0, s.configData = t);
210
+ let o = [];
211
+ e.sessionId && (o = await Se(e.sessionId));
212
+ const r = new URLSearchParams();
213
+ return s.credentials.token || r.set("externalId", $()), s.sseUrl = `${se(
214
+ s.credentials.endpoint
215
+ )}?${r.toString()}`, s.sessionId = e.sessionId, s.messages = o, {
221
216
  sessionId: s.sessionId,
222
- messages: a,
223
- configData: o
217
+ messages: o,
218
+ configData: t
224
219
  };
225
- } catch (o) {
226
- throw console.error(`Failed to start chat: ${o.message}`), V(), o;
220
+ } catch (t) {
221
+ throw V(), t;
227
222
  }
228
223
  }
229
224
  function Ae() {
@@ -232,9 +227,9 @@ function Ae() {
232
227
  function V() {
233
228
  s.abortController && s.abortController.abort(), H();
234
229
  const { callbacks: e, credentials: t } = s;
235
- s = Y(e), s.credentials = t, console.log("Chat session cleaned up");
230
+ s = Y(e), s.credentials = t;
236
231
  }
237
- function P() {
232
+ function $() {
238
233
  var e;
239
234
  return (e = s.credentials) != null && e.externalId ? s.credentials.externalId : te();
240
235
  }
@@ -246,29 +241,29 @@ function F(e) {
246
241
  var t, o;
247
242
  (o = (t = s.callbacks).onTyping) == null || o.call(t, e);
248
243
  }
249
- function $(e) {
244
+ function P(e) {
250
245
  var t, o;
251
- console.log("Setting transport to:", e), s.transport = e, (o = (t = s.callbacks).onTransportUpdate) == null || o.call(t, e);
246
+ s.transport = e, (o = (t = s.callbacks).onTransportUpdate) == null || o.call(t, e);
252
247
  }
253
- function Ne({ text: e, html: t, context: o }) {
254
- return new Promise((a, d) => {
248
+ function Ue({ text: e, html: t, context: o }) {
249
+ return new Promise((r, d) => {
255
250
  (async () => {
256
- var u, i, f;
251
+ var u, c, f;
257
252
  try {
258
- const r = {
253
+ const l = {
259
254
  role: T.USER,
260
255
  text: e,
261
256
  html: t,
262
257
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
263
258
  };
264
- if (h(r), await oe(200), s.transport === "socket" && ue()) {
265
- R({
259
+ if (h(l), await oe(200), s.transport === "socket" && ge()) {
260
+ U({
266
261
  type: "message",
267
262
  data: {
268
263
  text: e,
269
264
  html: t
270
265
  }
271
- }), a(s.sessionId);
266
+ }), r(s.sessionId);
272
267
  return;
273
268
  }
274
269
  const p = {
@@ -293,24 +288,33 @@ function Ne({ text: e, html: t, context: o }) {
293
288
  signal: s.abortController.signal,
294
289
  onopen: async (g) => {
295
290
  if (!g.ok)
296
- throw console.error("Failed to send message bad response: ", g), new Error("Failed to send message");
291
+ throw new Error("Failed to send message");
297
292
  },
298
293
  onmessage: (g) => {
299
- var E, M, x, q, G, L, z;
300
- const l = JSON.parse(g.data);
294
+ var b, M, x, q, L, G, z;
295
+ const i = JSON.parse(g.data);
301
296
  if (g.event === "connected")
302
- s.sessionId = l.sessionId, s.requestId = l.requestId;
297
+ s.sessionId = i.sessionId, s.requestId = i.requestId;
303
298
  else if (g.event === "upgrade_to_websocket")
304
- console.log("Upgrade to websocket: ", l), le({
299
+ de({
305
300
  sessionId: s.sessionId,
306
- requestId: l.requestId
301
+ requestId: i.requestId
307
302
  });
308
- else if (l.message !== void 0) {
309
- if (l.streamId !== void 0) {
303
+ else if (i.error) {
304
+ const I = i.error && typeof i.error == "string" ? i.error : "Failed to connect to the system", k = s.messages.length - 1, C = {
305
+ ...s.messages[k],
306
+ loading: !1,
307
+ errorText: I
308
+ };
309
+ s.messages = s.messages.map(
310
+ (R, ee) => ee === k ? C : R
311
+ ), (M = (b = s.callbacks).onMessageUpdate) == null || M.call(b, k, C), d(new Error(I));
312
+ } else if (i.message !== void 0) {
313
+ if (i.streamId !== void 0) {
310
314
  if (s.lastStreamId === void 0)
311
- s.lastStreamId = l.streamId;
312
- else if (l.streamId !== s.lastStreamId) {
313
- s.lastStreamId = l.streamId;
315
+ s.lastStreamId = i.streamId;
316
+ else if (i.streamId !== s.lastStreamId) {
317
+ s.lastStreamId = i.streamId;
314
318
  const C = {
315
319
  role: T.BOT,
316
320
  text: "",
@@ -322,22 +326,13 @@ function Ne({ text: e, html: t, context: o }) {
322
326
  const I = s.messages.length - 1, k = s.messages[I], O = {
323
327
  ...k,
324
328
  loading: !1,
325
- text: (k.text || "") + l.message,
326
- sources: l.sources,
327
- done: (E = l.done) != null ? E : k.done
328
- };
329
- s.messages = s.messages.map(
330
- (C, A) => A === I ? O : C
331
- ), (x = (M = s.callbacks).onMessageUpdate) == null || x.call(M, I, O), l.done && a(s.sessionId), s.sessionId = (q = l.session_id) != null ? q : s.sessionId, s.requestId = (G = l.requestId) != null ? G : s.requestId;
332
- } else if (l.error) {
333
- const I = "Failed to connect to the system", k = s.messages.length - 1, C = {
334
- ...s.messages[k],
335
- loading: !1,
336
- errorText: I
329
+ text: (k.text || "") + i.message,
330
+ sources: i.sources,
331
+ done: (x = i.done) != null ? x : k.done
337
332
  };
338
333
  s.messages = s.messages.map(
339
- (A, ee) => ee === k ? C : A
340
- ), (z = (L = s.callbacks).onMessageUpdate) == null || z.call(L, k, C), d(new Error(I));
334
+ (C, R) => R === I ? O : C
335
+ ), (L = (q = s.callbacks).onMessageUpdate) == null || L.call(q, I, O), i.done && r(s.sessionId), s.sessionId = (G = i.session_id) != null ? G : s.sessionId, s.requestId = (z = i.requestId) != null ? z : s.requestId;
341
336
  }
342
337
  },
343
338
  onerror: (g) => {
@@ -345,65 +340,74 @@ function Ne({ text: e, html: t, context: o }) {
345
340
  },
346
341
  openWhenHidden: !0
347
342
  });
348
- } catch (r) {
349
- console.error("Failed to send message: ", r);
343
+ } catch (l) {
350
344
  const p = "Failed to connect to the system", m = s.messages.length - 1, y = s.messages[m], g = {
351
345
  ...y,
352
346
  loading: !1,
353
- errorText: y.done ? void 0 : r.message || p,
347
+ errorText: y.done ? void 0 : l.message || p,
354
348
  done: !0
355
349
  };
356
350
  s.messages = s.messages.map(
357
- (l, E) => E === m ? g : l
358
- ), (f = (i = s.callbacks).onMessageUpdate) == null || f.call(i, m, g), d(r);
351
+ (i, b) => b === m ? g : i
352
+ ), (f = (c = s.callbacks).onMessageUpdate) == null || f.call(c, m, g), d(l);
359
353
  }
360
354
  })();
361
355
  });
362
356
  }
363
- const fe = "Something went wrong initializing the chat", pe = "Chat SDK not initialized";
364
- async function me(e) {
365
- const { endpoint: t } = e, o = `${t}/config`, a = await fetch(o, {
357
+ const pe = "Something went wrong initializing the chat", me = "Chat SDK not initialized";
358
+ async function ke(e) {
359
+ const { endpoint: t } = e, o = `${t}/config`, r = await fetch(o, {
366
360
  method: "GET",
367
361
  headers: {
368
362
  "Content-Type": "application/json"
369
363
  }
370
364
  });
371
- if (!a.ok) {
372
- const i = await a.json();
373
- throw new Error((i == null ? void 0 : i.error) || fe);
365
+ if (!r.ok) {
366
+ const c = await r.json();
367
+ throw new Error((c == null ? void 0 : c.error) || pe);
374
368
  }
375
- return (await a.json()).data;
369
+ return (await r.json()).data;
376
370
  }
377
- async function Re() {
371
+ async function Ne() {
378
372
  const e = new URLSearchParams({
379
- externalId: P()
373
+ externalId: $()
380
374
  }), t = await Q(`/sessions?${e.toString()}`, "GET");
381
375
  if (!t.ok)
382
376
  throw new Error("Unable to load history, please try again later");
383
377
  return t.json();
384
378
  }
385
- async function ke(e) {
379
+ async function Se(e) {
380
+ var u;
386
381
  const t = new URLSearchParams({
387
382
  sessionId: e
388
383
  }), o = await Q(`/session?${t.toString()}`, "GET");
389
384
  if (!o.ok)
390
385
  throw new Error("Unable to load messages, please try again later");
391
- return o.json();
386
+ const r = await o.json();
387
+ return ((u = r == null ? void 0 : r.sessionHistory) != null ? u : []).map((c) => ({
388
+ id: c.id,
389
+ text: c.text,
390
+ role: c.youtubeVideo ? T.BOT : c.role,
391
+ timestamp: c.timestamp,
392
+ video: c.youtubeVideo,
393
+ channel: c.channel,
394
+ done: !0
395
+ }));
392
396
  }
393
397
  async function Q(e, t = "GET", o = null) {
394
- const a = U(), { endpoint: d, token: u } = a || {};
398
+ const r = N(), { endpoint: d, token: u } = r || {};
395
399
  if (!d)
396
- throw new Error(pe);
397
- const i = `${d}${e}`, f = {
400
+ throw new Error(me);
401
+ const c = `${d}${e}`, f = {
398
402
  "Content-Type": "application/json"
399
403
  };
400
- return u && (f.Authorization = `Bearer ${u}`), fetch(i, {
404
+ return u && (f.Authorization = `Bearer ${u}`), fetch(c, {
401
405
  headers: f,
402
406
  method: t,
403
407
  body: o ? JSON.stringify(o) : null
404
408
  });
405
409
  }
406
- function j(e = {}) {
410
+ function Z(e = {}) {
407
411
  return {
408
412
  sessionId: void 0,
409
413
  socket: null,
@@ -421,17 +425,17 @@ function j(e = {}) {
421
425
  pendingRemoteIceCandidates: []
422
426
  };
423
427
  }
424
- let n = j();
425
- const Se = {
428
+ let n = Z();
429
+ const Ie = {
426
430
  iceServers: [{ urls: "stun:stun.l.google.com:19302" }, { urls: "stun:stun1.l.google.com:19302" }]
427
431
  };
428
- function Ue(e) {
432
+ function Me(e) {
429
433
  n.callbacks = { ...n.callbacks, ...e };
430
434
  }
431
- function Z() {
435
+ function j() {
432
436
  n.peerConnection && (n.peerConnection.close(), n.peerConnection = null), n.localStream && (n.localStream.getTracks().forEach((t) => t.stop()), n.localStream = null), n.remoteStream && (n.remoteStream = null), n.remoteAudio && (n.remoteAudio.srcObject = null, n.remoteAudio.parentNode && n.remoteAudio.parentNode.removeChild(n.remoteAudio), n.remoteAudio = null), n.socket && (n.socket.close(), n.socket = null), D();
433
437
  const e = n.callbacks;
434
- n = j(e), console.log("Call session cleaned up");
438
+ n = Z(e);
435
439
  }
436
440
  function S(e) {
437
441
  var t, o;
@@ -444,7 +448,7 @@ function v(e) {
444
448
  function D() {
445
449
  n.pingInterval && (clearInterval(n.pingInterval), n.pingInterval = null);
446
450
  }
447
- function Ie() {
451
+ function Ce() {
448
452
  D(), n.pingInterval = setInterval(() => {
449
453
  if (n.socket && n.socket.readyState === WebSocket.OPEN) {
450
454
  n.pingCount++;
@@ -453,68 +457,60 @@ function Ie() {
453
457
  timestamp: Date.now(),
454
458
  count: n.pingCount
455
459
  };
456
- w(e), console.log(`Sending keep-alive ping #${n.pingCount}`);
460
+ w(e);
457
461
  } else
458
- console.log("Socket not open, stopping ping interval"), D();
462
+ D();
459
463
  }, 1e4);
460
464
  }
461
- function Ce() {
462
- n.lastPongTime = Date.now(), console.log(`Received pong #${n.pingCount}`);
465
+ function he() {
466
+ n.lastPongTime = Date.now();
463
467
  }
464
468
  function w(e) {
465
- if (!n.socket) {
466
- console.error("Failed to send event: no socket instance");
467
- return;
468
- }
469
- if (n.socket.readyState !== WebSocket.OPEN) {
470
- console.error("Failed to send event: socket state not open ", e);
471
- return;
472
- }
473
- n.socket.send(JSON.stringify(e));
469
+ n.socket && n.socket.readyState === WebSocket.OPEN && n.socket.send(JSON.stringify(e));
474
470
  }
475
- async function he() {
471
+ async function we() {
476
472
  try {
477
473
  n.localStream = await navigator.mediaDevices.getUserMedia({
478
474
  audio: !0,
479
475
  video: !1
480
- }), console.log("Got audio media");
476
+ });
481
477
  } catch (e) {
482
- throw console.error(`Failed to get audio media: ${e.message}`), e;
478
+ throw e;
483
479
  }
484
480
  }
485
- function we() {
486
- n.peerConnection = new RTCPeerConnection(Se), n.peerConnection.onicecandidate = (e) => {
481
+ function ye() {
482
+ n.peerConnection = new RTCPeerConnection(Ie), n.peerConnection.onicecandidate = (e) => {
487
483
  if (e.candidate) {
488
484
  const t = JSON.stringify(e.candidate);
489
- n.peerConnection && n.peerConnection.remoteDescription ? (w({
485
+ n.peerConnection && n.peerConnection.remoteDescription ? w({
490
486
  type: "ice",
491
487
  data: {
492
488
  candidate: t
493
489
  }
494
- }), console.log("Sent ICE candidate immediately")) : (n.localIceCandidates.push(t), console.log("Queued local ICE candidate"));
490
+ }) : n.localIceCandidates.push(t);
495
491
  }
496
492
  }, n.peerConnection.ontrack = (e) => {
497
- console.log("Received remote audio stream"), n.remoteStream = e.streams[0], n.remoteAudio || (n.remoteAudio = document.createElement("audio"), n.remoteAudio.autoplay = !0, n.remoteAudio.controls = !1, document.body.appendChild(n.remoteAudio)), n.remoteAudio.srcObject = n.remoteStream, n.remoteAudio.play().then(() => console.log("🔊 remote audio playing")).catch((t) => console.error("❌ playback error:", t));
493
+ n.remoteStream = e.streams[0], n.remoteAudio || (n.remoteAudio = document.createElement("audio"), n.remoteAudio.autoplay = !0, n.remoteAudio.controls = !1, document.body.appendChild(n.remoteAudio)), n.remoteAudio.srcObject = n.remoteStream, n.remoteAudio.play().then(() => {
494
+ }).catch((t) => {
495
+ });
498
496
  }, n.peerConnection.onconnectionstatechange = () => {
499
497
  const e = n.peerConnection.connectionState;
500
- console.log(`Connection state: ${e}`), e === "connected" ? S("connected") : (e === "disconnected" || e === "closed") && (S("disconnected"), X());
498
+ e === "connected" ? S("connected") : (e === "disconnected" || e === "closed") && (S("disconnected"), X());
501
499
  }, n.peerConnection.oniceconnectionstatechange = () => {
502
- console.log(`ICE connection state: ${n.peerConnection.iceConnectionState}`);
503
500
  };
504
501
  }
505
- function ye(e) {
502
+ function be(e) {
506
503
  return new Promise((t, o) => {
507
504
  if (n.socket && (n.socket.readyState === WebSocket.CONNECTING || n.socket.readyState === WebSocket.OPEN)) {
508
- console.log("Socket in connecting/open state, returning."), t(n.socket.readyState === WebSocket.OPEN);
505
+ t(n.socket.readyState === WebSocket.OPEN);
509
506
  return;
510
507
  }
511
- console.log("Initializing socket connection..");
512
- const a = U();
513
- if (!a || !a.endpoint) {
508
+ const r = N();
509
+ if (!r || !r.endpoint) {
514
510
  o(new Error("SDK not initialized. Please initialize SDK first."));
515
511
  return;
516
512
  }
517
- const d = ce(a.endpoint);
513
+ const d = re(r.endpoint);
518
514
  if (!d) {
519
515
  o(
520
516
  new Error(
@@ -523,36 +519,36 @@ function ye(e) {
523
519
  );
524
520
  return;
525
521
  }
526
- const u = P(), i = new URLSearchParams({
522
+ const u = $(), c = new URLSearchParams({
527
523
  externalId: u
528
524
  });
529
- e.sessionId && i.set("sessionId", e.sessionId), a.token && i.set("token", a.token);
530
- const f = `${d}?${i.toString()}`;
531
- n.socket = new WebSocket(f), n.socket.onopen = (r) => {
532
- console.log("Socket connection established: ", r), Ie(), t(!0);
533
- }, n.socket.onmessage = (r) => {
534
- const p = JSON.parse(r.data);
525
+ e.sessionId && c.set("sessionId", e.sessionId), r.token && c.set("token", r.token);
526
+ const f = `${d}?${c.toString()}`;
527
+ n.socket = new WebSocket(f), n.socket.onopen = (l) => {
528
+ Ce(), t(!0);
529
+ }, n.socket.onmessage = (l) => {
530
+ const p = JSON.parse(l.data);
535
531
  Ee(p);
536
- }, n.socket.onerror = (r) => {
537
- console.error("Socket error: ", r), S("error"), v(r.message || "Unable to connect voice"), o(r);
538
- }, n.socket.onclose = (r) => {
539
- console.log("Socket connection closed: ", r), D();
532
+ }, n.socket.onerror = (l) => {
533
+ S("error"), v(l.message || "Unable to connect voice"), o(l);
534
+ }, n.socket.onclose = (l) => {
535
+ D();
540
536
  };
541
537
  });
542
538
  }
543
539
  function Ee(e) {
544
- switch (console.log("Handling socket server event: ", e), e.type) {
540
+ switch (e.type) {
545
541
  case "pong":
546
- Ce();
542
+ he();
547
543
  break;
548
544
  case "answer":
549
- be(e.data);
545
+ Te(e.data);
550
546
  break;
551
547
  case "ice":
552
- Te(e.data);
548
+ ve(e.data);
553
549
  break;
554
550
  case "renegotiationOffer":
555
- ve(e.data);
551
+ De(e.data);
556
552
  break;
557
553
  case "end":
558
554
  X();
@@ -561,61 +557,57 @@ function Ee(e) {
561
557
  S("error"), v(e.error || "Unable to connect voice");
562
558
  break;
563
559
  default:
564
- console.log("Unknown call event type: ", e.type);
565
560
  break;
566
561
  }
567
562
  }
568
- async function be(e) {
563
+ async function Te(e) {
569
564
  try {
570
- if (console.log("Received answer"), n.sessionId = e.sessionId, ge(e.sessionId), n.peerConnection) {
565
+ if (n.sessionId = e.sessionId, fe(e.sessionId), n.peerConnection) {
571
566
  const t = new RTCSessionDescription({
572
567
  type: "answer",
573
568
  sdp: e.sdp
574
569
  });
575
- console.log("Setting remote description answer: ", t), await n.peerConnection.setRemoteDescription(t), console.log("Remote description set");
570
+ await n.peerConnection.setRemoteDescription(t);
576
571
  for (const o of n.localIceCandidates)
577
572
  w({
578
573
  type: "ice",
579
574
  data: {
580
575
  candidate: o
581
576
  }
582
- }), console.log("Sent queued local ICE candidate");
577
+ });
583
578
  n.localIceCandidates = [];
584
579
  for (const o of n.pendingRemoteIceCandidates)
585
580
  try {
586
- const a = new RTCIceCandidate(JSON.parse(o));
587
- await n.peerConnection.addIceCandidate(a), console.log("Added pending remote ICE candidate");
588
- } catch (a) {
589
- console.error(`Failed to add pending ICE candidate: ${a.message}`);
581
+ const r = new RTCIceCandidate(JSON.parse(o));
582
+ await n.peerConnection.addIceCandidate(r);
583
+ } catch (r) {
590
584
  }
591
585
  n.pendingRemoteIceCandidates = [];
592
586
  }
593
587
  } catch (t) {
594
- console.error(`Failed to handle answer: ${t.message}`);
595
588
  }
596
589
  }
597
- async function Te(e) {
590
+ async function ve(e) {
598
591
  try {
599
592
  if (n.peerConnection) {
600
593
  if (!n.peerConnection.remoteDescription) {
601
- n.pendingRemoteIceCandidates.push(e.candidate), console.log("Queued remote ICE candidate - remote description not set");
594
+ n.pendingRemoteIceCandidates.push(e.candidate);
602
595
  return;
603
596
  }
604
597
  const t = new RTCIceCandidate(JSON.parse(e.candidate));
605
- await n.peerConnection.addIceCandidate(t), console.log("Added ICE candidate");
598
+ await n.peerConnection.addIceCandidate(t);
606
599
  }
607
600
  } catch (t) {
608
- console.error(`Failed to add ICE candidate: ${t.message}`);
609
601
  }
610
602
  }
611
- async function ve(e) {
603
+ async function De(e) {
612
604
  try {
613
- if (console.log("Received renegotiation offer"), n.peerConnection) {
605
+ if (n.peerConnection) {
614
606
  const t = new RTCSessionDescription({
615
607
  type: "offer",
616
608
  sdp: e.sdp
617
609
  });
618
- console.log("Setting remote description offer: ", t), await n.peerConnection.setRemoteDescription(t), console.log("Remote description set");
610
+ await n.peerConnection.setRemoteDescription(t);
619
611
  const o = await n.peerConnection.createAnswer();
620
612
  await n.peerConnection.setLocalDescription(o), w({
621
613
  type: "renegotiationAnswer",
@@ -625,43 +617,40 @@ async function ve(e) {
625
617
  });
626
618
  }
627
619
  } catch (t) {
628
- console.error(`Failed to handle renegotiation offer: ${t.message}`);
629
620
  }
630
621
  }
631
- async function Me(e = {}) {
622
+ async function xe(e = {}) {
632
623
  try {
633
- if (n.callStatus === "connecting" || n.callStatus === "connected") {
634
- console.log(`Call already in ${n.callStatus} state`);
624
+ if (n.callStatus === "connecting" || n.callStatus === "connected")
635
625
  return;
636
- }
637
- console.log("Starting audio call..."), S("connecting"), v(null), n.sessionId = e.sessionId, await he(), we(), n.localStream.getTracks().forEach((o) => {
638
- n.peerConnection.addTrack(o, n.localStream), console.log(`Added ${o.kind} track`);
639
- }), await ye(e);
626
+ S("connecting"), v(null), n.sessionId = e.sessionId, await we(), ye(), n.localStream.getTracks().forEach((o) => {
627
+ n.peerConnection.addTrack(o, n.localStream);
628
+ }), await be(e);
640
629
  const t = await n.peerConnection.createOffer();
641
630
  await n.peerConnection.setLocalDescription(t), w({
642
631
  type: "offer",
643
632
  data: {
644
633
  sdp: t.sdp
645
634
  }
646
- }), console.log("Call initiated successfully");
635
+ });
647
636
  } catch (t) {
648
- console.log("error: ", t), console.error(`Failed to start call: ${t.message}`), S("error"), v(t.message || "Unable to connect voice"), Z();
637
+ S("error"), v(t.message || "Unable to connect voice"), j();
649
638
  }
650
639
  }
651
640
  function X() {
652
641
  w({
653
642
  type: "end"
654
- }), n.socket && (n.socket.close(), n.socket = null), S("disconnected"), n.peerConnection && (n.peerConnection.close(), n.peerConnection = null), n.localStream && (n.localStream.getTracks().forEach((e) => e.stop()), n.localStream = null), Z();
643
+ }), n.socket && (n.socket.close(), n.socket = null), S("disconnected"), n.peerConnection && (n.peerConnection.close(), n.peerConnection = null), n.localStream && (n.localStream.getTracks().forEach((e) => e.stop()), n.localStream = null), j();
655
644
  }
656
- function xe() {
645
+ function qe() {
657
646
  if (n.localStream) {
658
647
  const e = n.localStream.getAudioTracks()[0];
659
648
  if (e)
660
- return e.enabled = !e.enabled, n.isMuted = !e.enabled, console.log(`Audio ${n.isMuted ? "muted" : "unmuted"}`), n.isMuted;
649
+ return e.enabled = !e.enabled, n.isMuted = !e.enabled, n.isMuted;
661
650
  }
662
651
  return !1;
663
652
  }
664
- function qe() {
653
+ function Le() {
665
654
  return n.localStream;
666
655
  }
667
656
  function Ge() {
@@ -671,23 +660,23 @@ function Ge() {
671
660
  return;
672
661
  }
673
662
  n.peerConnection.getStats().then((o) => {
674
- o.forEach((a) => {
675
- a.type == "inbound-rtp" && e(a.totalAudioEnergy);
663
+ o.forEach((r) => {
664
+ r.type == "inbound-rtp" && e(r.totalAudioEnergy);
676
665
  }), t(new Error("no inbound-rtp stats found"));
677
666
  }).catch((o) => {
678
667
  t(o);
679
668
  });
680
669
  });
681
670
  }
682
- function Le() {
671
+ function ze() {
683
672
  return new Promise((e, t) => {
684
673
  if (!n.peerConnection) {
685
674
  t(new Error("no peer connection"));
686
675
  return;
687
676
  }
688
677
  n.peerConnection.getStats().then((o) => {
689
- o.forEach((a) => {
690
- a.type == "outbound-rtp" && e(a.totalAudioEnergy);
678
+ o.forEach((r) => {
679
+ r.type == "outbound-rtp" && e(r.totalAudioEnergy);
691
680
  }), t(new Error("no outbound-rtp stats found"));
692
681
  }).catch((o) => {
693
682
  t(o);
@@ -696,20 +685,20 @@ function Le() {
696
685
  }
697
686
  export {
698
687
  T as MESSAGE_ROLES,
699
- me as authenticate,
688
+ ke as authenticate,
700
689
  Ae as disconnect,
701
690
  X as disconnectCall,
702
- Re as getHistory,
691
+ Ne as getHistory,
703
692
  Ge as getInboundAudioEnergy,
704
- qe as getLocalStream,
705
- ke as getMessages,
706
- Le as getOutboundAudioEnergy,
707
- $e as initialize,
708
- Ne as sendMessage,
709
- Ue as setCallCallbacks,
693
+ Le as getLocalStream,
694
+ Se as getMessages,
695
+ ze as getOutboundAudioEnergy,
696
+ Oe as initialize,
697
+ Ue as sendMessage,
698
+ Me as setCallCallbacks,
710
699
  Pe as setCallbacks,
711
- Me as startCall,
712
- Oe as startChat,
713
- xe as toggleMute
700
+ xe as startCall,
701
+ Re as startChat,
702
+ qe as toggleMute
714
703
  };
715
704
  //# sourceMappingURL=origon-chat-sdk.js.map