@origonai/web-chat-sdk 0.1.0 → 0.1.2

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,33 +1,33 @@
1
- import { fetchEventSource as X } from "@microsoft/fetch-event-source";
2
- function ee() {
3
- const e = Date.now(), o = new Uint8Array(16);
4
- crypto.getRandomValues(o), o[0] = e >> 40 & 255, o[1] = e >> 32 & 255, o[2] = e >> 24 & 255, o[3] = e >> 16 & 255, o[4] = e >> 8 & 255, o[5] = e & 255, o[6] = o[6] & 15 | 112, o[8] = o[8] & 63 | 128;
5
- const s = [...o].map((a) => a.toString(16).padStart(2, "0")).join("");
1
+ import { fetchEventSource as _ } from "@microsoft/fetch-event-source";
2
+ function j() {
3
+ const e = Date.now(), t = new Uint8Array(16);
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 s = [...t].map((a) => a.toString(16).padStart(2, "0")).join("");
6
6
  return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(
7
7
  16,
8
8
  20
9
9
  )}-${s.slice(20)}`;
10
10
  }
11
- function ne() {
11
+ function V() {
12
12
  if (localStorage.getItem("chatDeviceId"))
13
13
  return localStorage.getItem("chatDeviceId");
14
- const e = ee();
14
+ const e = j();
15
15
  return localStorage.setItem("chatDeviceId", e), e;
16
16
  }
17
- async function te(e) {
18
- return new Promise((o) => setTimeout(o, e));
17
+ async function Q(e) {
18
+ return new Promise((t) => setTimeout(t, e));
19
19
  }
20
- function oe(e) {
21
- let o;
20
+ function Y(e) {
21
+ let t;
22
22
  try {
23
23
  const s = new URL(e);
24
- o = `wss://${s.hostname}${s.pathname}/audio`;
24
+ t = `wss://${s.hostname}${s.pathname}/audio`;
25
25
  } catch (s) {
26
26
  console.error("getCallServerEndpoint: Invalid base URL: ", e);
27
27
  }
28
- return o;
28
+ return t;
29
29
  }
30
- const k = {
30
+ const E = {
31
31
  BOT: "assistant",
32
32
  // this can be automated or LLM AI Agent response
33
33
  USER: "user",
@@ -37,7 +37,7 @@ const k = {
37
37
  SYSTEM: "system"
38
38
  // this is system message, for ex "Agent joined" / "Agent left"
39
39
  };
40
- function _(e = {}) {
40
+ function L(e = {}) {
41
41
  return {
42
42
  credentials: void 0,
43
43
  authenticated: !1,
@@ -46,159 +46,141 @@ function _(e = {}) {
46
46
  requestId: void 0,
47
47
  sseUrl: void 0,
48
48
  abortController: void 0,
49
- liveAgent: !1,
50
49
  lastStreamId: void 0,
51
50
  messages: [],
52
51
  callbacks: e
53
52
  };
54
53
  }
55
- let t = _();
56
- function ye(e) {
57
- t.callbacks = { ...t.callbacks, ...e };
54
+ let o = L();
55
+ function pe(e) {
56
+ o.callbacks = { ...o.callbacks, ...e };
58
57
  }
59
- function be(e) {
60
- console.log("Initializing chat...", e), t.credentials = e, e.token && (t.authenticated = !0);
58
+ function me(e) {
59
+ console.log("Initializing chat...", e), o.credentials = e, e.token && (o.authenticated = !0);
61
60
  }
62
- function se() {
63
- return t.credentials;
61
+ function J() {
62
+ return o.credentials;
64
63
  }
65
- function ae(e) {
66
- var o, s;
67
- e && e !== t.sessionId && (t.sessionId = e, (s = (o = t.callbacks).onSessionUpdate) == null || s.call(o, e));
64
+ function Z(e) {
65
+ var t, s;
66
+ e && e !== o.sessionId && (o.sessionId = e, (s = (t = o.callbacks).onSessionUpdate) == null || s.call(t, e));
68
67
  }
69
- async function Ee(e = {}) {
70
- var o;
68
+ async function Se(e = {}) {
69
+ var t;
71
70
  try {
72
- console.log("startChat: ", e, t);
71
+ console.log("startChat: ", e, o);
73
72
  let s = null;
74
- t.authenticated ? s = t.configData : (s = await le(t.credentials), t.authenticated = !0, t.configData = s);
73
+ o.authenticated ? s = o.configData : (s = await ne(o.credentials), o.authenticated = !0, o.configData = s);
75
74
  let a = [];
76
75
  if (e.sessionId) {
77
- const g = await de(e.sessionId);
78
- a = ((o = g == null ? void 0 : g.sessionHistory) != null ? o : []).map((r) => ({
76
+ const u = await te(e.sessionId);
77
+ a = ((t = u == null ? void 0 : u.sessionHistory) != null ? t : []).map((r) => ({
79
78
  id: r.id,
80
79
  text: r.text,
81
- role: r.youtubeVideo ? k.BOT : r.role,
80
+ role: r.youtubeVideo ? E.BOT : r.role,
82
81
  timestamp: r.timestamp,
83
82
  video: r.youtubeVideo,
84
83
  channel: r.channel,
85
84
  done: !0
86
85
  }));
87
86
  }
88
- const u = new URLSearchParams({
89
- externalId: A()
87
+ const l = new URLSearchParams({
88
+ externalId: $()
90
89
  });
91
- return t.sseUrl = `${t.credentials.endpoint}?${u.toString()}`, t.sessionId = e.sessionId, t.messages = a, console.log("Chat initiated successfully"), {
92
- sessionId: t.sessionId,
90
+ return o.sseUrl = `${o.credentials.endpoint}?${l.toString()}`, o.sessionId = e.sessionId, o.messages = a, console.log("Chat initiated successfully"), {
91
+ sessionId: o.sessionId,
93
92
  messages: a,
94
93
  configData: s
95
94
  };
96
95
  } catch (s) {
97
- throw console.error(`Failed to start chat: ${s.message}`), K(), s;
96
+ throw console.error(`Failed to start chat: ${s.message}`), z(), s;
98
97
  }
99
98
  }
100
- function ve() {
101
- K();
99
+ function Ce() {
100
+ z();
102
101
  }
103
- function K() {
104
- t.abortController && t.abortController.abort();
105
- const { callbacks: e, credentials: o } = t;
106
- t = _(e), t.credentials = o, console.log("Chat session cleaned up");
102
+ function z() {
103
+ o.abortController && o.abortController.abort();
104
+ const { callbacks: e, credentials: t } = o;
105
+ o = L(e), o.credentials = t, console.log("Chat session cleaned up");
107
106
  }
108
- function A() {
107
+ function $() {
109
108
  var e;
110
- return (e = t.credentials) != null && e.externalId ? t.credentials.externalId : ne();
109
+ return (e = o.credentials) != null && e.externalId ? o.credentials.externalId : V();
111
110
  }
112
- function Ae({ text: e, html: o }) {
111
+ function Ie({ text: e, html: t }) {
113
112
  return new Promise((s, a) => {
114
113
  (async () => {
115
- var u, g, r, h, l, w, T;
114
+ var l, u, r, k, i, w, M;
116
115
  try {
117
- const y = {
118
- role: k.USER,
116
+ const S = {
117
+ role: E.USER,
119
118
  text: e,
120
- html: o,
119
+ html: t,
121
120
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
122
121
  };
123
- if (t.messages = [...t.messages, y], (g = (u = t.callbacks).onMessagesUpdate) == null || g.call(u, [...t.messages]), await te(200), t.liveAgent)
124
- s(t.sessionId);
125
- else {
126
- const d = {
127
- role: k.BOT,
128
- text: "",
129
- loading: !0
130
- };
131
- t.messages = [...t.messages, d], (h = (r = t.callbacks).onMessagesUpdate) == null || h.call(r, [...t.messages]);
132
- }
133
- const C = new URL(t.sseUrl);
134
- t.sessionId && C.searchParams.set("sessionId", t.sessionId), t.requestId && C.searchParams.set("requestId", t.requestId), t.lastStreamId = void 0, t.abortController = new AbortController();
135
- const I = {
122
+ o.messages = [...o.messages, S], (u = (l = o.callbacks).onMessageAdd) == null || u.call(l, S), await Q(200);
123
+ const y = {
124
+ role: E.BOT,
125
+ text: "",
126
+ loading: !0
127
+ };
128
+ o.messages = [...o.messages, y], (k = (r = o.callbacks).onMessageAdd) == null || k.call(r, y);
129
+ const g = new URL(o.sseUrl);
130
+ o.sessionId && g.searchParams.set("sessionId", o.sessionId), o.requestId && g.searchParams.set("requestId", o.requestId), o.lastStreamId = void 0, o.abortController = new AbortController();
131
+ const h = {
136
132
  "Content-Type": "application/json"
137
133
  };
138
- (l = t.credentials) != null && l.token && (I.Authorization = `Bearer ${t.credentials.token}`), await X(C.toString(), {
134
+ (i = o.credentials) != null && i.token && (h.Authorization = `Bearer ${o.credentials.token}`), await _(g.toString(), {
139
135
  method: "POST",
140
- headers: I,
136
+ headers: h,
141
137
  body: JSON.stringify({
142
138
  message: e,
143
- html: o
139
+ html: t
144
140
  }),
145
- signal: t.abortController.signal,
141
+ signal: o.abortController.signal,
146
142
  onopen: async (d) => {
147
143
  if (!d.ok)
148
144
  throw console.error("Failed to send message bad response: ", d), new Error("Failed to send message");
149
145
  },
150
146
  onmessage: (d) => {
151
- var R, $, O, U, P, x, D, M, N, L, q, F, J, z, G, W, B, H;
147
+ var b, O, x, P, U, D, N, q, F;
152
148
  console.log("Event: ", d);
153
- const i = JSON.parse(d.data);
154
- if (i.status === "connected")
155
- t.sessionId = i.sessionId, t.requestId = i.requestId, t.liveAgent && s(t.sessionId);
156
- else if (i.agent) {
157
- t.liveAgent = !0;
158
- const { type: f, data: c } = i.agent;
159
- switch (f) {
160
- case "typing":
161
- ($ = (R = t.callbacks).onTyping) == null || $.call(R, !0), (U = (O = t.callbacks).onLiveAgentMode) == null || U.call(O, !0);
162
- break;
163
- case "typingOff":
164
- (x = (P = t.callbacks).onTyping) == null || x.call(P, !1), (M = (D = t.callbacks).onLiveAgentMode) == null || M.call(D, !0);
165
- break;
166
- case "message":
167
- if (c.role !== k.USER) {
168
- t.messages = t.messages.filter((b) => !b.loading), t.messages = [...t.messages, c];
169
- const m = c.action === "ended" || c.action === "left";
170
- m && (t.liveAgent = !1), (L = (N = t.callbacks).onMessagesUpdate) == null || L.call(N, [...t.messages]), (F = (q = t.callbacks).onLiveAgentMode) == null || F.call(q, !m);
171
- }
172
- (c.action === "ended" || c.action === "left") && (t.liveAgent = !1);
173
- break;
174
- default:
175
- break;
149
+ const c = JSON.parse(d.data);
150
+ if (c.status === "connected")
151
+ o.sessionId = c.sessionId, o.requestId = c.requestId;
152
+ else if (c.message !== void 0) {
153
+ if (c.streamId !== void 0) {
154
+ if (o.lastStreamId === void 0)
155
+ o.lastStreamId = c.streamId;
156
+ else if (c.streamId !== o.lastStreamId) {
157
+ o.lastStreamId = c.streamId;
158
+ const p = {
159
+ role: E.BOT,
160
+ text: "",
161
+ loading: !0
162
+ };
163
+ o.messages = [...o.messages, p], (O = (b = o.callbacks).onMessageAdd) == null || O.call(b, p);
164
+ }
176
165
  }
177
- } else if (i.message !== void 0) {
178
- let f = t.messages;
179
- i.streamId !== void 0 && (t.lastStreamId === void 0 ? t.lastStreamId = i.streamId : i.streamId !== t.lastStreamId && (t.lastStreamId = i.streamId, f = [
166
+ const C = o.messages.length - 1, f = o.messages[C], T = {
180
167
  ...f,
181
- {
182
- role: k.BOT,
183
- text: "",
184
- loading: !0
185
- }
186
- ])), t.messages = f.map((c, m) => {
187
- var b;
188
- return m === f.length - 1 ? {
189
- ...c,
190
- loading: !1,
191
- text: (c.text || "") + i.message,
192
- done: (b = i.done) != null ? b : c.done
193
- } : c;
194
- }), (z = (J = t.callbacks).onMessagesUpdate) == null || z.call(J, [...t.messages]), i.done && s(t.sessionId), t.sessionId = (G = i.session_id) != null ? G : t.sessionId, t.requestId = (W = i.requestId) != null ? W : t.requestId;
195
- } else if (i.error) {
196
- const f = "Failed to connect to the system";
197
- t.messages = t.messages.map((c, m) => m === t.messages.length - 1 ? {
198
- ...c,
199
168
  loading: !1,
200
- errorText: f
201
- } : c), (H = (B = t.callbacks).onMessagesUpdate) == null || H.call(B, [...t.messages]), a(new Error(f));
169
+ text: (f.text || "") + c.message,
170
+ done: (x = c.done) != null ? x : f.done
171
+ };
172
+ o.messages = o.messages.map(
173
+ (p, R) => R === C ? T : p
174
+ ), (U = (P = o.callbacks).onMessageUpdate) == null || U.call(P, C, T), c.done && s(o.sessionId), o.sessionId = (D = c.session_id) != null ? D : o.sessionId, o.requestId = (N = c.requestId) != null ? N : o.requestId;
175
+ } else if (c.error) {
176
+ const C = "Failed to connect to the system", f = o.messages.length - 1, p = {
177
+ ...o.messages[f],
178
+ loading: !1,
179
+ errorText: C
180
+ };
181
+ o.messages = o.messages.map(
182
+ (R, K) => K === f ? p : R
183
+ ), (F = (q = o.callbacks).onMessageUpdate) == null || F.call(q, f, p), a(new Error(C));
202
184
  }
203
185
  },
204
186
  onerror: (d) => {
@@ -206,30 +188,24 @@ function Ae({ text: e, html: o }) {
206
188
  },
207
189
  openWhenHidden: !0
208
190
  });
209
- } catch (y) {
210
- console.error("Failed to send message: ", y);
211
- const C = "Failed to connect to the system";
212
- t.messages = t.messages.map((I, d) => d === t.messages.length - 1 ? {
213
- ...I,
191
+ } catch (S) {
192
+ console.error("Failed to send message: ", S);
193
+ const y = "Failed to connect to the system", g = o.messages.length - 1, h = o.messages[g], d = {
194
+ ...h,
214
195
  loading: !1,
215
- errorText: C,
196
+ errorText: h.done ? void 0 : S.message || y,
216
197
  done: !0
217
- } : I), (T = (w = t.callbacks).onMessagesUpdate) == null || T.call(w, [...t.messages]), a(y);
198
+ };
199
+ o.messages = o.messages.map(
200
+ (c, b) => b === g ? d : c
201
+ ), (M = (w = o.callbacks).onMessageUpdate) == null || M.call(w, g, d), a(S);
218
202
  }
219
203
  })();
220
204
  });
221
205
  }
222
- const re = "Something went wrong initializing the chat", ie = "Chat SDK not initialized";
223
- let j = {
224
- endpoint: null
225
- };
226
- function ce(e) {
227
- j = {
228
- endpoint: e.endpoint
229
- };
230
- }
231
- async function le(e) {
232
- const { endpoint: o } = e, s = `${o}/config`, a = await fetch(s, {
206
+ const X = "Something went wrong initializing the chat", ee = "Chat SDK not initialized";
207
+ async function ne(e) {
208
+ const { endpoint: t } = e, s = `${t}/config`, a = await fetch(s, {
233
209
  method: "GET",
234
210
  headers: {
235
211
  "Content-Type": "application/json"
@@ -237,41 +213,40 @@ async function le(e) {
237
213
  });
238
214
  if (!a.ok) {
239
215
  const r = await a.json();
240
- throw new Error((r == null ? void 0 : r.error) || re);
216
+ throw new Error((r == null ? void 0 : r.error) || X);
241
217
  }
242
- const g = (await a.json()).data;
243
- return ce({ endpoint: o }), g;
218
+ return (await a.json()).data;
244
219
  }
245
- async function Te() {
220
+ async function he() {
246
221
  const e = new URLSearchParams({
247
- externalId: A()
248
- }), o = await V(`/sessions?${e.toString()}`, "GET");
249
- if (!o.ok)
222
+ externalId: $()
223
+ }), t = await G(`/sessions?${e.toString()}`, "GET");
224
+ if (!t.ok)
250
225
  throw new Error("Unable to load history, please try again later");
251
- return o.json();
226
+ return t.json();
252
227
  }
253
- async function de(e) {
254
- const o = new URLSearchParams({
228
+ async function te(e) {
229
+ const t = new URLSearchParams({
255
230
  sessionId: e
256
- }), s = await V(`/session?${o.toString()}`, "GET");
231
+ }), s = await G(`/session?${t.toString()}`, "GET");
257
232
  if (!s.ok)
258
233
  throw new Error("Unable to load messages, please try again later");
259
234
  return s.json();
260
235
  }
261
- async function V(e, o = "GET", s = null) {
262
- const { endpoint: a } = j;
263
- if (!a)
264
- throw new Error(ie);
265
- const u = `${a}${e}`;
266
- return fetch(u, {
236
+ async function G(e, t = "GET", s = null) {
237
+ const a = J();
238
+ if (!(a != null && a.endpoint))
239
+ throw new Error(ee);
240
+ const l = `${endpoint}${e}`;
241
+ return fetch(l, {
267
242
  headers: {
268
243
  "Content-Type": "application/json"
269
244
  },
270
- method: o,
245
+ method: t,
271
246
  body: s ? JSON.stringify(s) : null
272
247
  });
273
248
  }
274
- function Q(e = {}) {
249
+ function W(e = {}) {
275
250
  return {
276
251
  sessionId: void 0,
277
252
  socket: null,
@@ -289,31 +264,31 @@ function Q(e = {}) {
289
264
  pendingRemoteIceCandidates: []
290
265
  };
291
266
  }
292
- let n = Q();
293
- const ue = {
267
+ let n = W();
268
+ const oe = {
294
269
  iceServers: [{ urls: "stun:stun.l.google.com:19302" }, { urls: "stun:stun1.l.google.com:19302" }]
295
270
  };
296
- function Re(e) {
271
+ function ke(e) {
297
272
  n.callbacks = { ...n.callbacks, ...e };
298
273
  }
299
- function Y() {
300
- n.peerConnection && (n.peerConnection.close(), n.peerConnection = null), n.localStream && (n.localStream.getTracks().forEach((o) => o.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), v();
274
+ function B() {
275
+ 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), A();
301
276
  const e = n.callbacks;
302
- n = Q(e), console.log("Call session cleaned up");
277
+ n = W(e), console.log("Call session cleaned up");
303
278
  }
304
- function p(e) {
305
- var o, s;
306
- n.callStatus = e, (s = (o = n.callbacks).onCallStatus) == null || s.call(o, e);
279
+ function m(e) {
280
+ var t, s;
281
+ n.callStatus = e, (s = (t = n.callbacks).onCallStatus) == null || s.call(t, e);
307
282
  }
308
- function E(e) {
309
- var o, s;
310
- (s = (o = n.callbacks).onCallError) == null || s.call(o, e);
283
+ function v(e) {
284
+ var t, s;
285
+ (s = (t = n.callbacks).onCallError) == null || s.call(t, e);
311
286
  }
312
- function v() {
287
+ function A() {
313
288
  n.pingInterval && (clearInterval(n.pingInterval), n.pingInterval = null);
314
289
  }
315
- function ge() {
316
- v(), n.pingInterval = setInterval(() => {
290
+ function se() {
291
+ A(), n.pingInterval = setInterval(() => {
317
292
  if (n.socket && n.socket.readyState === WebSocket.OPEN) {
318
293
  n.pingCount++;
319
294
  const e = {
@@ -321,15 +296,15 @@ function ge() {
321
296
  timestamp: Date.now(),
322
297
  count: n.pingCount
323
298
  };
324
- S(e), console.log(`Sending keep-alive ping #${n.pingCount}`);
299
+ I(e), console.log(`Sending keep-alive ping #${n.pingCount}`);
325
300
  } else
326
- console.log("Socket not open, stopping ping interval"), v();
301
+ console.log("Socket not open, stopping ping interval"), A();
327
302
  }, 1e4);
328
303
  }
329
- function fe() {
304
+ function ae() {
330
305
  n.lastPongTime = Date.now(), console.log(`Received pong #${n.pingCount}`);
331
306
  }
332
- function S(e) {
307
+ function I(e) {
333
308
  if (!n.socket) {
334
309
  console.error("Failed to send event: no socket instance");
335
310
  return;
@@ -340,7 +315,7 @@ function S(e) {
340
315
  }
341
316
  n.socket.send(JSON.stringify(e));
342
317
  }
343
- async function pe() {
318
+ async function re() {
344
319
  try {
345
320
  n.localStream = await navigator.mediaDevices.getUserMedia({
346
321
  audio: !0,
@@ -350,40 +325,40 @@ async function pe() {
350
325
  throw console.error(`Failed to get audio media: ${e.message}`), e;
351
326
  }
352
327
  }
353
- function me() {
354
- n.peerConnection = new RTCPeerConnection(ue), n.peerConnection.onicecandidate = (e) => {
328
+ function ce() {
329
+ n.peerConnection = new RTCPeerConnection(oe), n.peerConnection.onicecandidate = (e) => {
355
330
  if (e.candidate) {
356
- const o = JSON.stringify(e.candidate);
357
- n.peerConnection && n.peerConnection.remoteDescription ? (S({
331
+ const t = JSON.stringify(e.candidate);
332
+ n.peerConnection && n.peerConnection.remoteDescription ? (I({
358
333
  type: "ice",
359
334
  data: {
360
- candidate: o
335
+ candidate: t
361
336
  }
362
- }), console.log("Sent ICE candidate immediately")) : (n.localIceCandidates.push(o), console.log("Queued local ICE candidate"));
337
+ }), console.log("Sent ICE candidate immediately")) : (n.localIceCandidates.push(t), console.log("Queued local ICE candidate"));
363
338
  }
364
339
  }, n.peerConnection.ontrack = (e) => {
365
- 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((o) => console.error("❌ playback error:", o));
340
+ 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));
366
341
  }, n.peerConnection.onconnectionstatechange = () => {
367
342
  const e = n.peerConnection.connectionState;
368
- console.log(`Connection state: ${e}`), e === "connected" ? p("connected") : (e === "disconnected" || e === "closed") && (p("disconnected"), Z());
343
+ console.log(`Connection state: ${e}`), e === "connected" ? m("connected") : (e === "disconnected" || e === "closed") && (m("disconnected"), H());
369
344
  }, n.peerConnection.oniceconnectionstatechange = () => {
370
345
  console.log(`ICE connection state: ${n.peerConnection.iceConnectionState}`);
371
346
  };
372
347
  }
373
- function Se(e) {
374
- return new Promise((o, s) => {
348
+ function ie(e) {
349
+ return new Promise((t, s) => {
375
350
  if (n.socket && (n.socket.readyState === WebSocket.CONNECTING || n.socket.readyState === WebSocket.OPEN)) {
376
- console.log("Socket in connecting/open state, returning."), o(n.socket.readyState === WebSocket.OPEN);
351
+ console.log("Socket in connecting/open state, returning."), t(n.socket.readyState === WebSocket.OPEN);
377
352
  return;
378
353
  }
379
354
  console.log("Initializing socket connection..");
380
- const a = se();
355
+ const a = J();
381
356
  if (!a || !a.endpoint) {
382
357
  s(new Error("SDK not initialized. Please initialize SDK first."));
383
358
  return;
384
359
  }
385
- const u = oe(a.endpoint);
386
- if (!u) {
360
+ const l = Y(a.endpoint);
361
+ if (!l) {
387
362
  s(
388
363
  new Error(
389
364
  "Invalid endpoint while initializing SDK. Please check the endpoint and try again."
@@ -391,58 +366,58 @@ function Se(e) {
391
366
  );
392
367
  return;
393
368
  }
394
- const g = A(), r = new URLSearchParams({
395
- externalId: g
369
+ const u = $(), r = new URLSearchParams({
370
+ externalId: u
396
371
  });
397
372
  e.sessionId && r.set("sessionId", e.sessionId), a.token && r.set("token", a.token);
398
- const h = `${u}?${r.toString()}`;
399
- n.socket = new WebSocket(h), n.socket.onopen = (l) => {
400
- console.log("Socket connection established: ", l), ge(), o(!0);
401
- }, n.socket.onmessage = (l) => {
402
- const w = JSON.parse(l.data);
403
- Ce(w);
404
- }, n.socket.onerror = (l) => {
405
- console.error("Socket error: ", l), p("error"), E(l.message || "Unable to connect voice"), s(l);
406
- }, n.socket.onclose = (l) => {
407
- console.log("Socket connection closed: ", l), v();
373
+ const k = `${l}?${r.toString()}`;
374
+ n.socket = new WebSocket(k), n.socket.onopen = (i) => {
375
+ console.log("Socket connection established: ", i), se(), t(!0);
376
+ }, n.socket.onmessage = (i) => {
377
+ const w = JSON.parse(i.data);
378
+ le(w);
379
+ }, n.socket.onerror = (i) => {
380
+ console.error("Socket error: ", i), m("error"), v(i.message || "Unable to connect voice"), s(i);
381
+ }, n.socket.onclose = (i) => {
382
+ console.log("Socket connection closed: ", i), A();
408
383
  };
409
384
  });
410
385
  }
411
- function Ce(e) {
386
+ function le(e) {
412
387
  switch (console.log("Handling socket server event: ", e), e.type) {
413
388
  case "pong":
414
- fe();
389
+ ae();
415
390
  break;
416
391
  case "answer":
417
- Ie(e.data);
392
+ de(e.data);
418
393
  break;
419
394
  case "ice":
420
- ke(e.data);
395
+ ue(e.data);
421
396
  break;
422
397
  case "renegotiationOffer":
423
- he(e.data);
398
+ ge(e.data);
424
399
  break;
425
400
  case "end":
426
- Z();
401
+ H();
427
402
  break;
428
403
  case "error":
429
- p("error"), E(e.error || "Unable to connect voice");
404
+ m("error"), v(e.error || "Unable to connect voice");
430
405
  break;
431
406
  default:
432
407
  console.log("Unknown call event type: ", e.type);
433
408
  break;
434
409
  }
435
410
  }
436
- async function Ie(e) {
411
+ async function de(e) {
437
412
  try {
438
- if (console.log("Received answer"), n.sessionId = e.sessionId, ae(e.sessionId), n.peerConnection) {
439
- const o = new RTCSessionDescription({
413
+ if (console.log("Received answer"), n.sessionId = e.sessionId, Z(e.sessionId), n.peerConnection) {
414
+ const t = new RTCSessionDescription({
440
415
  type: "answer",
441
416
  sdp: e.sdp
442
417
  });
443
- console.log("Setting remote description answer: ", o), await n.peerConnection.setRemoteDescription(o), console.log("Remote description set");
418
+ console.log("Setting remote description answer: ", t), await n.peerConnection.setRemoteDescription(t), console.log("Remote description set");
444
419
  for (const s of n.localIceCandidates)
445
- S({
420
+ I({
446
421
  type: "ice",
447
422
  data: {
448
423
  candidate: s
@@ -458,70 +433,70 @@ async function Ie(e) {
458
433
  }
459
434
  n.pendingRemoteIceCandidates = [];
460
435
  }
461
- } catch (o) {
462
- console.error(`Failed to handle answer: ${o.message}`);
436
+ } catch (t) {
437
+ console.error(`Failed to handle answer: ${t.message}`);
463
438
  }
464
439
  }
465
- async function ke(e) {
440
+ async function ue(e) {
466
441
  try {
467
442
  if (n.peerConnection) {
468
443
  if (!n.peerConnection.remoteDescription) {
469
444
  n.pendingRemoteIceCandidates.push(e.candidate), console.log("Queued remote ICE candidate - remote description not set");
470
445
  return;
471
446
  }
472
- const o = new RTCIceCandidate(JSON.parse(e.candidate));
473
- await n.peerConnection.addIceCandidate(o), console.log("Added ICE candidate");
447
+ const t = new RTCIceCandidate(JSON.parse(e.candidate));
448
+ await n.peerConnection.addIceCandidate(t), console.log("Added ICE candidate");
474
449
  }
475
- } catch (o) {
476
- console.error(`Failed to add ICE candidate: ${o.message}`);
450
+ } catch (t) {
451
+ console.error(`Failed to add ICE candidate: ${t.message}`);
477
452
  }
478
453
  }
479
- async function he(e) {
454
+ async function ge(e) {
480
455
  try {
481
456
  if (console.log("Received renegotiation offer"), n.peerConnection) {
482
- const o = new RTCSessionDescription({
457
+ const t = new RTCSessionDescription({
483
458
  type: "offer",
484
459
  sdp: e.sdp
485
460
  });
486
- console.log("Setting remote description offer: ", o), await n.peerConnection.setRemoteDescription(o), console.log("Remote description set");
461
+ console.log("Setting remote description offer: ", t), await n.peerConnection.setRemoteDescription(t), console.log("Remote description set");
487
462
  const s = await n.peerConnection.createAnswer();
488
- await n.peerConnection.setLocalDescription(s), S({
463
+ await n.peerConnection.setLocalDescription(s), I({
489
464
  type: "renegotiationAnswer",
490
465
  data: {
491
466
  sdp: s.sdp
492
467
  }
493
468
  });
494
469
  }
495
- } catch (o) {
496
- console.error(`Failed to handle renegotiation offer: ${o.message}`);
470
+ } catch (t) {
471
+ console.error(`Failed to handle renegotiation offer: ${t.message}`);
497
472
  }
498
473
  }
499
- async function $e(e = {}) {
474
+ async function we(e = {}) {
500
475
  try {
501
476
  if (n.callStatus === "connecting" || n.callStatus === "connected") {
502
477
  console.log(`Call already in ${n.callStatus} state`);
503
478
  return;
504
479
  }
505
- console.log("Starting audio call..."), p("connecting"), E(null), n.sessionId = e.sessionId, await pe(), me(), n.localStream.getTracks().forEach((s) => {
480
+ console.log("Starting audio call..."), m("connecting"), v(null), n.sessionId = e.sessionId, await re(), ce(), n.localStream.getTracks().forEach((s) => {
506
481
  n.peerConnection.addTrack(s, n.localStream), console.log(`Added ${s.kind} track`);
507
- }), await Se(e);
508
- const o = await n.peerConnection.createOffer();
509
- await n.peerConnection.setLocalDescription(o), S({
482
+ }), await ie(e);
483
+ const t = await n.peerConnection.createOffer();
484
+ await n.peerConnection.setLocalDescription(t), I({
510
485
  type: "offer",
511
486
  data: {
512
- sdp: o.sdp
487
+ sdp: t.sdp
513
488
  }
514
489
  }), console.log("Call initiated successfully");
515
- } catch (o) {
516
- console.log("error: ", o), console.error(`Failed to start call: ${o.message}`), p("error"), E(o.message || "Unable to connect voice"), Y();
490
+ } catch (t) {
491
+ console.log("error: ", t), console.error(`Failed to start call: ${t.message}`), m("error"), v(t.message || "Unable to connect voice"), B();
517
492
  }
518
493
  }
519
- function Z() {
520
- S({
494
+ function H() {
495
+ I({
521
496
  type: "end"
522
- }), n.socket && (n.socket.close(), n.socket = null), p("disconnected"), n.peerConnection && (n.peerConnection.close(), n.peerConnection = null), n.localStream && (n.localStream.getTracks().forEach((e) => e.stop()), n.localStream = null), Y();
497
+ }), n.socket && (n.socket.close(), n.socket = null), m("disconnected"), n.peerConnection && (n.peerConnection.close(), n.peerConnection = null), n.localStream && (n.localStream.getTracks().forEach((e) => e.stop()), n.localStream = null), B();
523
498
  }
524
- function Oe() {
499
+ function ye() {
525
500
  if (n.localStream) {
526
501
  const e = n.localStream.getAudioTracks()[0];
527
502
  if (e)
@@ -529,56 +504,55 @@ function Oe() {
529
504
  }
530
505
  return !1;
531
506
  }
532
- function Ue() {
507
+ function be() {
533
508
  return n.localStream;
534
509
  }
535
- function Pe() {
536
- return new Promise((e, o) => {
510
+ function Ee() {
511
+ return new Promise((e, t) => {
537
512
  if (!n.peerConnection) {
538
- o(new Error("no peer connection"));
513
+ t(new Error("no peer connection"));
539
514
  return;
540
515
  }
541
516
  n.peerConnection.getStats().then((s) => {
542
517
  s.forEach((a) => {
543
518
  a.type == "inbound-rtp" && e(a.totalAudioEnergy);
544
- }), o(new Error("no inbound-rtp stats found"));
519
+ }), t(new Error("no inbound-rtp stats found"));
545
520
  }).catch((s) => {
546
- o(s);
521
+ t(s);
547
522
  });
548
523
  });
549
524
  }
550
- function xe() {
551
- return new Promise((e, o) => {
525
+ function ve() {
526
+ return new Promise((e, t) => {
552
527
  if (!n.peerConnection) {
553
- o(new Error("no peer connection"));
528
+ t(new Error("no peer connection"));
554
529
  return;
555
530
  }
556
531
  n.peerConnection.getStats().then((s) => {
557
532
  s.forEach((a) => {
558
533
  a.type == "outbound-rtp" && e(a.totalAudioEnergy);
559
- }), o(new Error("no outbound-rtp stats found"));
534
+ }), t(new Error("no outbound-rtp stats found"));
560
535
  }).catch((s) => {
561
- o(s);
536
+ t(s);
562
537
  });
563
538
  });
564
539
  }
565
540
  export {
566
- k as MESSAGE_ROLES,
567
- le as authenticate,
568
- ce as configure,
569
- ve as disconnect,
570
- Z as disconnectCall,
571
- Te as getHistory,
572
- Pe as getInboundAudioEnergy,
573
- Ue as getLocalStream,
574
- de as getMessages,
575
- xe as getOutboundAudioEnergy,
576
- be as initialize,
577
- Ae as sendMessage,
578
- Re as setCallCallbacks,
579
- ye as setCallbacks,
580
- $e as startCall,
581
- Ee as startChat,
582
- Oe as toggleMute
541
+ E as MESSAGE_ROLES,
542
+ ne as authenticate,
543
+ Ce as disconnect,
544
+ H as disconnectCall,
545
+ he as getHistory,
546
+ Ee as getInboundAudioEnergy,
547
+ be as getLocalStream,
548
+ te as getMessages,
549
+ ve as getOutboundAudioEnergy,
550
+ me as initialize,
551
+ Ie as sendMessage,
552
+ ke as setCallCallbacks,
553
+ pe as setCallbacks,
554
+ we as startCall,
555
+ Se as startChat,
556
+ ye as toggleMute
583
557
  };
584
558
  //# sourceMappingURL=origon-chat-sdk.js.map