@origonai/web-chat-sdk 1.0.11 → 1.0.12

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,5 +1,5 @@
1
- import { fetchEventSource as ge } from "@microsoft/fetch-event-source";
2
- function j() {
1
+ import { fetchEventSource as Ie } from "@microsoft/fetch-event-source";
2
+ function re() {
3
3
  const e = Date.now(), n = new Uint8Array(16);
4
4
  crypto.getRandomValues(n), n[0] = e >> 40 & 255, n[1] = e >> 32 & 255, n[2] = e >> 24 & 255, n[3] = e >> 16 & 255, n[4] = e >> 8 & 255, n[5] = e & 255, n[6] = n[6] & 15 | 112, n[8] = n[8] & 63 | 128;
5
5
  const o = [...n].map((r) => r.toString(16).padStart(2, "0")).join("");
@@ -8,25 +8,25 @@ function j() {
8
8
  20
9
9
  )}-${o.slice(20)}`;
10
10
  }
11
- function fe() {
11
+ function he() {
12
12
  if (localStorage.getItem("chatDeviceId"))
13
13
  return localStorage.getItem("chatDeviceId");
14
- const e = j();
14
+ const e = re();
15
15
  return localStorage.setItem("chatDeviceId", e), e;
16
16
  }
17
- async function pe(e) {
17
+ async function we(e) {
18
18
  return new Promise((n) => setTimeout(n, e));
19
19
  }
20
- function me(e) {
20
+ function Ce(e) {
21
21
  let n;
22
22
  try {
23
23
  const o = new URL(e);
24
- n = `https://${o.hostname}${o.pathname}/sse`;
24
+ n = `https://${o.hostname}${o.pathname}/sse${o.search}`;
25
25
  } catch (o) {
26
26
  }
27
27
  return n;
28
28
  }
29
- function Se(e) {
29
+ function Ee(e) {
30
30
  let n;
31
31
  try {
32
32
  const o = new URL(e);
@@ -35,7 +35,7 @@ function Se(e) {
35
35
  }
36
36
  return n;
37
37
  }
38
- function ke(e) {
38
+ function ye(e) {
39
39
  let n;
40
40
  try {
41
41
  const o = new URL(e);
@@ -44,7 +44,7 @@ function ke(e) {
44
44
  }
45
45
  return n;
46
46
  }
47
- const y = {
47
+ const v = {
48
48
  ASSISTANT: "assistant",
49
49
  // this can be automated or LLM AI Agent response
50
50
  USER: "user",
@@ -53,13 +53,13 @@ const y = {
53
53
  // this is human supervisor (ex. Samespace Dock agent, or Resolve human agent)
54
54
  SYSTEM: "system"
55
55
  // this is system message, for ex "Agent joined" / "Agent left"
56
- }, ee = 1e4, Ie = 5e3, R = {
56
+ }, ae = 1e4, be = 5e3, P = {
57
57
  MESSAGE: "message",
58
58
  TYPING: "typing",
59
59
  TYPING_STOP: "typingOff",
60
60
  END: "end"
61
61
  };
62
- function he() {
62
+ function ve() {
63
63
  return {
64
64
  socket: null,
65
65
  previouslyConnected: !1,
@@ -69,37 +69,37 @@ function he() {
69
69
  socketConnectionTimeout: null
70
70
  };
71
71
  }
72
- let a = he();
73
- function x() {
74
- a.pingInterval && (clearInterval(a.pingInterval), a.pingInterval = null);
72
+ let c = ve();
73
+ function q() {
74
+ c.pingInterval && (clearInterval(c.pingInterval), c.pingInterval = null);
75
75
  }
76
- function we() {
77
- x(), a.pingInterval = setInterval(() => {
78
- a.socket && a.socket.readyState === WebSocket.OPEN ? q({ type: "ping" }) : x();
79
- }, ee);
76
+ function Te() {
77
+ q(), c.pingInterval = setInterval(() => {
78
+ c.socket && c.socket.readyState === WebSocket.OPEN ? z({ type: "ping" }) : q();
79
+ }, ae);
80
80
  }
81
- function ne() {
82
- x(), a.socketDisconnectedTimeout && (clearTimeout(a.socketDisconnectedTimeout), a.socketDisconnectedTimeout = null), a.socketConnectionTimeout && (clearTimeout(a.socketConnectionTimeout), a.socketConnectionTimeout = null);
81
+ function ce() {
82
+ q(), c.socketDisconnectedTimeout && (clearTimeout(c.socketDisconnectedTimeout), c.socketDisconnectedTimeout = null), c.socketConnectionTimeout && (clearTimeout(c.socketConnectionTimeout), c.socketConnectionTimeout = null);
83
83
  }
84
- function te() {
85
- a.socketDisconnected = !1, N("socket");
84
+ function ie() {
85
+ c.socketDisconnected = !1, M("socket");
86
86
  }
87
- function oe() {
88
- a.socketDisconnected = !0, N("sse");
87
+ function le() {
88
+ c.socketDisconnected = !0, M("sse");
89
89
  }
90
- function Ce(e) {
90
+ function $e(e) {
91
91
  return new Promise((n, o) => {
92
- if (a.socket && (a.socket.readyState === WebSocket.CONNECTING || a.socket.readyState === WebSocket.OPEN)) {
93
- n(a.socket.readyState === WebSocket.OPEN);
92
+ if (c.socket && (c.socket.readyState === WebSocket.CONNECTING || c.socket.readyState === WebSocket.OPEN)) {
93
+ n(c.socket.readyState === WebSocket.OPEN);
94
94
  return;
95
95
  }
96
- const r = b();
96
+ const r = T();
97
97
  if (!r || !r.endpoint) {
98
98
  o(new Error("SDK not initialized. Please initialize SDK first."));
99
99
  return;
100
100
  }
101
- const l = Se(r.endpoint);
102
- if (!l) {
101
+ const g = Ee(r.endpoint);
102
+ if (!g) {
103
103
  o(
104
104
  new Error(
105
105
  "Invalid endpoint while initializing SDK. Please check the endpoint and try again."
@@ -107,74 +107,74 @@ function Ce(e) {
107
107
  );
108
108
  return;
109
109
  }
110
- const d = O(), c = new URLSearchParams({
110
+ const d = x(), a = new URLSearchParams({
111
111
  externalId: d
112
112
  });
113
- e.sessionId && c.set("sessionId", e.sessionId), e.requestId && c.set("requestId", e.requestId), r.token && c.set("token", r.token);
114
- const u = `${l}?${c.toString()}`;
115
- a.socket = new WebSocket(u), a.socket.onopen = () => {
116
- a.previouslyConnected = !0, te(), q({ type: "ping" }), clearTimeout(a.socketConnectionTimeout), we(), n(!0);
117
- }, a.socket.onmessage = (g) => {
118
- const f = JSON.parse(g.data);
119
- Ee(f);
120
- }, a.socket.onerror = (g) => {
121
- N("sse"), o(g);
122
- }, a.socket.onclose = (g) => {
123
- g.target === a.socket && (g.code === 1006 && (a.previouslyConnected ? oe() : h({
113
+ e.sessionId && a.set("sessionId", e.sessionId), e.requestId && a.set("requestId", e.requestId), r.token && a.set("token", r.token);
114
+ const l = `${g}?${a.toString()}`;
115
+ c.socket = new WebSocket(l), c.socket.onopen = () => {
116
+ c.previouslyConnected = !0, ie(), z({ type: "ping" }), clearTimeout(c.socketConnectionTimeout), Te(), n(!0);
117
+ }, c.socket.onmessage = (f) => {
118
+ const u = JSON.parse(f.data);
119
+ Ae(u);
120
+ }, c.socket.onerror = (f) => {
121
+ M("sse"), o(f);
122
+ }, c.socket.onclose = (f) => {
123
+ f.target === c.socket && (f.code === 1006 && (c.previouslyConnected ? le() : C({
124
124
  errorText: "Unable to establish connection",
125
125
  done: !0,
126
126
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
127
- }), clearTimeout(a.socketConnectionTimeout)), a.socket = null, ne());
128
- }, a.previouslyConnected || (a.socketConnectionTimeout = setTimeout(() => {
129
- h({
127
+ }), clearTimeout(c.socketConnectionTimeout)), c.socket = null, ce());
128
+ }, c.previouslyConnected || (c.socketConnectionTimeout = setTimeout(() => {
129
+ C({
130
130
  errorText: "Unable to establish connection",
131
131
  done: !0,
132
132
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
133
133
  }), o(new Error("Socket connection timed out"));
134
- }, Ie));
134
+ }, be));
135
135
  });
136
136
  }
137
- function q(e) {
138
- a.socketDisconnected || !a.socket || a.socket.send(JSON.stringify({ ...e, eventId: e.eventId || j() }));
137
+ function z(e) {
138
+ c.socketDisconnected || !c.socket || c.socket.send(JSON.stringify({ ...e, eventId: e.eventId || re() }));
139
139
  }
140
- function Ee(e) {
140
+ function Ae(e) {
141
141
  switch (e.type) {
142
142
  case "pong": {
143
- a.socketDisconnected && te(), a.socketDisconnectedTimeout && clearTimeout(a.socketDisconnectedTimeout), a.socketDisconnectedTimeout = setTimeout(() => {
144
- oe();
145
- }, ee + 1e3);
143
+ c.socketDisconnected && ie(), c.socketDisconnectedTimeout && clearTimeout(c.socketDisconnectedTimeout), c.socketDisconnectedTimeout = setTimeout(() => {
144
+ le();
145
+ }, ae + 1e3);
146
146
  break;
147
147
  }
148
- case R.TYPING: {
149
- Z(!0);
148
+ case P.TYPING: {
149
+ se(!0);
150
150
  break;
151
151
  }
152
- case R.TYPING_STOP: {
153
- Z(!1);
152
+ case P.TYPING_STOP: {
153
+ se(!1);
154
154
  break;
155
155
  }
156
- case R.MESSAGE: {
156
+ case P.MESSAGE: {
157
157
  const { eventId: n, data: o } = e;
158
- n || h({
158
+ n || C({
159
159
  ...o,
160
160
  done: !0,
161
161
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
162
162
  });
163
163
  break;
164
164
  }
165
- case R.END: {
166
- se();
165
+ case P.END: {
166
+ de();
167
167
  break;
168
168
  }
169
169
  }
170
170
  }
171
- function se() {
172
- a.socket && a.socket.close(1e3), a.previouslyConnected = !1, ne(), a.socket = null, N("sse");
171
+ function de() {
172
+ c.socket && c.socket.close(1e3), c.previouslyConnected = !1, ce(), c.socket = null, M("sse");
173
173
  }
174
- function ye() {
175
- return a.socket !== null && a.socket.readyState === WebSocket.OPEN && !a.socketDisconnected;
174
+ function Ue() {
175
+ return c.socket !== null && c.socket.readyState === WebSocket.OPEN && !c.socketDisconnected;
176
176
  }
177
- function re(e = {}) {
177
+ function ue(e = {}) {
178
178
  return {
179
179
  credentials: void 0,
180
180
  authenticated: !1,
@@ -190,34 +190,35 @@ function re(e = {}) {
190
190
  control: "agent"
191
191
  };
192
192
  }
193
- let s = re();
194
- function Ge(e) {
193
+ let s = ue();
194
+ function Ye(e) {
195
195
  s.callbacks = { ...s.callbacks, ...e };
196
196
  }
197
- function Je(e) {
197
+ function Qe(e) {
198
198
  s.credentials = e, e.token && (s.authenticated = !0);
199
199
  }
200
- function b() {
200
+ function T() {
201
201
  return s.credentials;
202
202
  }
203
- function be(e) {
203
+ function De() {
204
+ return s.configData;
205
+ }
206
+ function Re(e) {
204
207
  var n, o;
205
208
  e && e !== s.sessionId && (s.sessionId = e, (o = (n = s.callbacks).onSessionUpdate) == null || o.call(n, e));
206
209
  }
207
- async function We(e = {}) {
210
+ async function Xe(e = {}) {
208
211
  try {
209
212
  let n = null;
210
- s.authenticated ? n = s.configData : (n = await $e(s.credentials), s.authenticated = !0, s.configData = n);
213
+ s.authenticated ? n = s.configData : (n = await Ne(s.credentials), s.authenticated = !0, s.configData = n);
211
214
  let o = [], r = "agent";
212
- const l = e.fetchSession !== !1;
213
- if (e.sessionId && l) {
214
- const c = await De(e.sessionId);
215
- o = c.messages, r = c.control || "agent";
215
+ const g = e.fetchSession !== !1;
216
+ if (e.sessionId && g) {
217
+ const a = await xe(e.sessionId);
218
+ o = a.messages, r = a.control || "agent";
216
219
  }
217
- const d = new URLSearchParams();
218
- return s.credentials.token || d.set("externalId", O()), s.sseUrl = `${me(
219
- s.credentials.endpoint
220
- )}?${d.toString()}`, s.sessionId = e.sessionId, s.messages = o, s.control = r, r === "human" && Te({ text: "", html: "" }).catch(() => {
220
+ const d = new URL(Ce(s.credentials.endpoint));
221
+ return s.credentials.token || d.searchParams.set("externalId", x()), s.sseUrl = d.toString(), s.sessionId = e.sessionId, s.messages = o, s.control = r, r === "human" && Pe({ text: "", html: "" }).catch(() => {
221
222
  }), {
222
223
  sessionId: s.sessionId,
223
224
  messages: o,
@@ -225,81 +226,84 @@ async function We(e = {}) {
225
226
  configData: n
226
227
  };
227
228
  } catch (n) {
228
- throw ae(), n;
229
+ throw ge(), n;
229
230
  }
230
231
  }
231
- function _e() {
232
- ae();
232
+ function Ze() {
233
+ ge();
233
234
  }
234
- function ae() {
235
- s.abortController && s.abortController.abort(), se();
235
+ function ge() {
236
+ s.abortController && s.abortController.abort(), de();
236
237
  const { callbacks: e, credentials: n } = s;
237
- s = re(e), s.credentials = n;
238
+ s = ue(e), s.credentials = n;
238
239
  }
239
- function O() {
240
+ function x() {
240
241
  var e;
241
- return (e = s.credentials) != null && e.externalId ? s.credentials.externalId : fe();
242
+ return (e = s.credentials) != null && e.externalId ? s.credentials.externalId : he();
242
243
  }
243
- function h(e) {
244
+ function C(e) {
244
245
  var n, o;
245
246
  s.messages = [...s.messages, e], (o = (n = s.callbacks).onMessageAdd) == null || o.call(n, e);
246
247
  }
247
- function Z(e) {
248
+ function se(e) {
248
249
  var n, o;
249
250
  (o = (n = s.callbacks).onTyping) == null || o.call(n, e);
250
251
  }
251
- function N(e) {
252
+ function M(e) {
252
253
  var n, o;
253
254
  s.transport = e, (o = (n = s.callbacks).onTransportUpdate) == null || o.call(n, e);
254
255
  }
255
- function Te({ text: e, html: n, context: o, attachments: r, meta: l }) {
256
- return new Promise((d, c) => {
256
+ function Pe({ text: e, html: n, context: o, attachments: r, mode: g, meta: d, createSystem: a }) {
257
+ return new Promise((l, f) => {
257
258
  (async () => {
258
- var u, g, f;
259
+ var u, S, w;
259
260
  try {
260
- const I = !e && !n && !(r != null && r.length);
261
- if (!I) {
261
+ const m = !e && !n && !(r != null && r.length);
262
+ if (!m) {
262
263
  const p = {
263
- role: y.USER,
264
+ role: v.USER,
264
265
  text: e,
265
266
  html: n,
266
267
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
267
268
  attachments: r,
268
- meta: l
269
+ meta: d,
270
+ createSystem: a
269
271
  };
270
- h(p), await pe(200);
272
+ C(p), await we(200);
271
273
  }
272
- if (s.transport === "socket" && ye()) {
273
- q({
274
+ if (s.transport === "socket" && Ue()) {
275
+ z({
274
276
  type: "message",
275
277
  data: {
276
278
  text: e,
277
279
  html: n
278
280
  }
279
- }), d(s.sessionId);
281
+ }), l(s.sessionId);
280
282
  return;
281
283
  }
282
284
  if (s.control === "agent") {
283
285
  const p = {
284
- role: y.ASSISTANT,
286
+ role: v.ASSISTANT,
285
287
  text: "",
286
288
  loading: !0
287
289
  };
288
- h(p);
290
+ C(p);
289
291
  }
290
- const v = new URL(s.sseUrl);
291
- s.sessionId && v.searchParams.set("sessionId", s.sessionId), s.requestId && v.searchParams.set("requestId", s.requestId), s.lastStreamId = void 0, s.abortController = new AbortController();
292
- const C = {
292
+ const A = new URL(s.sseUrl);
293
+ s.sessionId && A.searchParams.set("sessionId", s.sessionId), s.requestId && A.searchParams.set("requestId", s.requestId), s.lastStreamId = void 0, s.abortController = new AbortController();
294
+ const y = {
293
295
  "Content-Type": "application/json"
294
296
  };
295
- (u = s.credentials) != null && u.token && (C.Authorization = `Bearer ${s.credentials.token}`), await ge(v.toString(), {
297
+ (u = s.credentials) != null && u.token && (y.Authorization = `Bearer ${s.credentials.token}`), await Ie(A.toString(), {
296
298
  method: "POST",
297
- headers: C,
298
- body: I ? l ? JSON.stringify({ meta: l }) : void 0 : JSON.stringify({
299
+ headers: y,
300
+ body: m ? d ? JSON.stringify({ meta: d }) : void 0 : JSON.stringify({
299
301
  message: e,
300
302
  html: n,
301
303
  context: o,
302
- attachments: r
304
+ attachments: r,
305
+ mode: g,
306
+ createSystem: a
303
307
  }),
304
308
  signal: s.abortController.signal,
305
309
  openWhenHidden: !0,
@@ -308,45 +312,49 @@ function Te({ text: e, html: n, context: o, attachments: r, meta: l }) {
308
312
  throw new Error("Failed to send message");
309
313
  },
310
314
  onmessage: (p) => {
311
- var D, A, L, z, F, G, J, W, _, K, H, V, B, Y, Q, X;
315
+ var D, R, F, G, J, W, _, K, B, H, V, Y, Q, X, Z, j, ee, ne, te, oe;
312
316
  const i = JSON.parse(p.data);
313
317
  if (p.event === "connected")
314
- s.sessionId = i.sessionId, s.requestId = i.requestId, i.control && (s.control = i.control, (A = (D = s.callbacks).onControlUpdate) == null || A.call(D, i.control));
318
+ s.sessionId = i.sessionId, s.requestId = i.requestId, i.control && (s.control = i.control, (R = (D = s.callbacks).onControlUpdate) == null || R.call(D, i.control));
315
319
  else if (p.event === "upgrade_to_websocket")
316
- Ce({
320
+ $e({
317
321
  sessionId: s.sessionId,
318
322
  requestId: i.requestId
319
323
  });
320
324
  else if (p.event === "update")
321
- i.control && (s.control = i.control, (z = (L = s.callbacks).onControlUpdate) == null || z.call(L, i.control));
322
- else if (i.error) {
323
- const m = i.error && typeof i.error == "string" ? i.error : "Failed to connect to the system", k = s.messages.length - 1, S = {
325
+ i.control && (s.control = i.control, (G = (F = s.callbacks).onControlUpdate) == null || G.call(F, i.control));
326
+ else if (p.event === "done") {
327
+ const k = s.messages.length - 1, b = {
324
328
  ...s.messages[k],
325
329
  loading: !1,
326
- errorText: m
330
+ done: !0
327
331
  };
328
332
  s.messages = s.messages.map(
329
- ($, ue) => ue === k ? S : $
330
- ), (G = (F = s.callbacks).onMessageUpdate) == null || G.call(F, k, S), c(new Error(m));
331
- } else if (p.event === "done") {
332
- const m = s.messages.length - 1, E = {
333
- ...s.messages[m],
333
+ (I, U) => U === k ? b : I
334
+ ), (W = (J = s.callbacks).onMessageUpdate) == null || W.call(J, k, b), l(s.sessionId);
335
+ } else if (p.event === "tool_call")
336
+ (K = (_ = s.callbacks).onToolCall) == null || K.call(_, i);
337
+ else if (p.event === "tool_response")
338
+ (H = (B = s.callbacks).onToolResponse) == null || H.call(B, i);
339
+ else if (i.error) {
340
+ const k = i.error && typeof i.error == "string" ? i.error : "Failed to connect to the system", h = s.messages.length - 1, I = {
341
+ ...s.messages[h],
334
342
  loading: !1,
335
- done: !0
343
+ errorText: k
336
344
  };
337
345
  s.messages = s.messages.map(
338
- (S, $) => $ === m ? E : S
339
- ), (W = (J = s.callbacks).onMessageUpdate) == null || W.call(J, m, E), d(s.sessionId);
340
- } else if (i.message !== void 0 || ((_ = i.attachments) == null ? void 0 : _.length) > 0) {
341
- if (i.role === y.SUPERVISOR) {
342
- const S = {
343
- role: y.SUPERVISOR,
346
+ (U, ke) => ke === h ? I : U
347
+ ), (Y = (V = s.callbacks).onMessageUpdate) == null || Y.call(V, h, I), f(new Error(k));
348
+ } else if (i.message !== void 0 || ((Q = i.attachments) == null ? void 0 : Q.length) > 0) {
349
+ if (i.role === v.SUPERVISOR) {
350
+ const I = {
351
+ role: v.SUPERVISOR,
344
352
  text: i.message,
345
353
  attachments: i.attachments,
346
354
  sources: i.sources,
347
355
  done: !0
348
356
  };
349
- h(S), d(s.sessionId), s.sessionId = (K = i.sessionId) != null ? K : s.sessionId, s.requestId = (H = i.requestId) != null ? H : s.requestId;
357
+ C(I), l(s.sessionId), s.sessionId = (X = i.sessionId) != null ? X : s.sessionId, s.requestId = (Z = i.requestId) != null ? Z : s.requestId;
350
358
  return;
351
359
  }
352
360
  if (i.streamId !== void 0) {
@@ -354,25 +362,25 @@ function Te({ text: e, html: n, context: o, attachments: r, meta: l }) {
354
362
  s.lastStreamId = i.streamId;
355
363
  else if (i.streamId !== s.lastStreamId) {
356
364
  s.lastStreamId = i.streamId;
357
- const S = {
358
- role: y.ASSISTANT,
365
+ const I = {
366
+ role: v.ASSISTANT,
359
367
  text: "",
360
368
  loading: !0
361
369
  };
362
- h(S);
370
+ C(I);
363
371
  }
364
372
  }
365
- const m = s.messages.length - 1, k = s.messages[m], E = {
366
- ...k,
373
+ const k = s.messages.length - 1, h = s.messages[k], b = {
374
+ ...h,
367
375
  loading: !1,
368
- text: (k.text || "") + i.message,
376
+ text: (h.text || "") + i.message,
369
377
  sources: i.sources,
370
378
  attachments: i.attachments,
371
- done: (V = i.done) != null ? V : k.done
379
+ done: (j = i.done) != null ? j : h.done
372
380
  };
373
381
  s.messages = s.messages.map(
374
- (S, $) => $ === m ? E : S
375
- ), (Y = (B = s.callbacks).onMessageUpdate) == null || Y.call(B, m, E), s.sessionId = (Q = i.sessionId) != null ? Q : s.sessionId, s.requestId = (X = i.requestId) != null ? X : s.requestId;
382
+ (I, U) => U === k ? b : I
383
+ ), (ne = (ee = s.callbacks).onMessageUpdate) == null || ne.call(ee, k, b), s.sessionId = (te = i.sessionId) != null ? te : s.sessionId, s.requestId = (oe = i.requestId) != null ? oe : s.requestId;
376
384
  }
377
385
  },
378
386
  onerror: (p) => {
@@ -380,22 +388,22 @@ function Te({ text: e, html: n, context: o, attachments: r, meta: l }) {
380
388
  },
381
389
  openWhenHidden: !0
382
390
  });
383
- } catch (I) {
384
- const v = "Failed to connect to the system", C = s.messages.length - 1, p = s.messages[C], i = {
391
+ } catch (m) {
392
+ const A = "Failed to connect to the system", y = s.messages.length - 1, p = s.messages[y], i = {
385
393
  ...p,
386
394
  loading: !1,
387
- errorText: p.done ? void 0 : I.message || v,
395
+ errorText: p.done ? void 0 : m.message || A,
388
396
  done: !0
389
397
  };
390
398
  s.messages = s.messages.map(
391
- (D, A) => A === C ? i : D
392
- ), (f = (g = s.callbacks).onMessageUpdate) == null || f.call(g, C, i), c(I);
399
+ (D, R) => R === y ? i : D
400
+ ), (w = (S = s.callbacks).onMessageUpdate) == null || w.call(S, y, i), f(m);
393
401
  }
394
402
  })();
395
403
  });
396
404
  }
397
- const ve = "Something went wrong initializing the chat", M = "Chat SDK not initialized";
398
- async function $e(e) {
405
+ const Oe = "Something went wrong initializing the chat", L = "Chat SDK not initialized";
406
+ async function Ne(e) {
399
407
  const { endpoint: n } = e, o = `${n}/config`, r = await fetch(o, {
400
408
  method: "GET",
401
409
  headers: {
@@ -403,102 +411,135 @@ async function $e(e) {
403
411
  }
404
412
  });
405
413
  if (!r.ok) {
406
- const c = await r.json();
407
- throw new Error((c == null ? void 0 : c.error) || ve);
414
+ const a = await r.json();
415
+ throw new Error((a == null ? void 0 : a.error) || Oe);
408
416
  }
409
417
  return (await r.json()).data;
410
418
  }
411
- async function Ke() {
419
+ async function je() {
412
420
  const e = new URLSearchParams({
413
- externalId: O()
414
- }), n = await ce(`/sessions?${e.toString()}`, "GET");
421
+ externalId: x()
422
+ }), n = await fe(`/sessions?${e.toString()}`, "GET");
415
423
  if (!n.ok)
416
424
  throw new Error("Unable to load history, please try again later");
417
425
  return n.json();
418
426
  }
419
- async function De(e) {
420
- var c;
427
+ async function xe(e) {
428
+ var a;
421
429
  const n = new URLSearchParams({
422
430
  sessionId: e
423
- }), o = await ce(`/session?${n.toString()}`, "GET");
431
+ }), o = await fe(`/session?${n.toString()}`, "GET");
424
432
  if (!o.ok)
425
433
  throw new Error("Unable to load messages, please try again later");
426
- const r = await o.json(), l = r == null ? void 0 : r.control, d = ((c = r == null ? void 0 : r.history) != null ? c : []).map((u) => ({
427
- id: u.id,
428
- text: u.text,
429
- role: u.youtubeVideo ? y.ASSISTANT : u.role,
430
- timestamp: u.timestamp,
431
- video: u.youtubeVideo,
432
- attachments: u.attachments,
433
- channel: u.channel,
434
+ const r = await o.json(), g = r == null ? void 0 : r.control, d = ((a = r == null ? void 0 : r.history) != null ? a : []).map((l) => ({
435
+ id: l.id,
436
+ text: l.text,
437
+ role: l.youtubeVideo ? v.ASSISTANT : l.role,
438
+ timestamp: l.timestamp,
439
+ video: l.youtubeVideo,
440
+ attachments: l.attachments,
441
+ channel: l.channel,
434
442
  done: !0
435
443
  }));
436
- return { control: l, messages: d };
444
+ return { control: g, messages: d };
437
445
  }
438
- function He(e, n, o) {
439
- const r = b(), { endpoint: l, token: d } = r || {};
440
- if (!l) {
441
- const f = new Error(M);
442
- return o && o(f, null), null;
446
+ function Me(e) {
447
+ var u, S;
448
+ const n = De(), o = n == null ? void 0 : n.attachments;
449
+ if (!o)
450
+ return "Attachments are not enabled";
451
+ const r = e.name || "", g = (u = r.split(".").pop()) == null ? void 0 : u.toLowerCase();
452
+ if (!g)
453
+ return "File type is not supported";
454
+ const d = ["images", "documents", "audio", "videos"];
455
+ let a = null, l = null;
456
+ for (const w of d) {
457
+ const m = o[w];
458
+ if ((S = m == null ? void 0 : m.supportedFileTypes) != null && S.includes(g)) {
459
+ a = w, l = m;
460
+ break;
461
+ }
462
+ }
463
+ if (!a)
464
+ return `File type ".${g}" is not supported`;
465
+ if (!l.enabled)
466
+ return `${a.charAt(0).toUpperCase() + a.slice(1)} attachments are not supported`;
467
+ const f = e.size / (1024 * 1024);
468
+ return l.maxSize && f > l.maxSize ? `${r} size exceeds the maximum allowed size of ${l.maxSize}MB` : null;
469
+ }
470
+ function en(e, n, o) {
471
+ const r = T(), { endpoint: g, token: d } = r || {};
472
+ if (!g) {
473
+ const u = new Error(L);
474
+ return o && o(u, null), null;
475
+ }
476
+ if (!d) {
477
+ const u = Me(e);
478
+ if (u)
479
+ return o && o(new Error(u), null), null;
443
480
  }
444
- const c = new XMLHttpRequest(), u = new FormData();
445
- u.append("file", e);
446
- const g = `${l}/upload`;
447
- return c.open("POST", g), d && c.setRequestHeader("Authorization", `Bearer ${d}`), n && c.upload.addEventListener("progress", (f) => {
448
- if (f.lengthComputable) {
449
- const I = f.loaded / f.total * 100;
450
- n(I, f.loaded, f.total);
481
+ const a = new XMLHttpRequest(), l = new FormData();
482
+ l.append("file", e);
483
+ const f = `${g}/upload`;
484
+ return a.open("POST", f), d && a.setRequestHeader("Authorization", `Bearer ${d}`), n && a.upload.addEventListener("progress", (u) => {
485
+ if (u.lengthComputable) {
486
+ const S = u.loaded / u.total * 100;
487
+ n(S, u.loaded, u.total);
451
488
  }
452
- }), c.addEventListener("load", () => {
453
- if (c.status >= 200 && c.status < 300)
489
+ }), a.addEventListener("load", () => {
490
+ if (a.status >= 200 && a.status < 300)
454
491
  try {
455
- const f = JSON.parse(c.responseText);
456
- o && o(null, f);
457
- } catch (f) {
492
+ const u = JSON.parse(a.responseText);
493
+ o && o(null, u);
494
+ } catch (u) {
458
495
  o && o(new Error("Failed to parse response"), null);
459
496
  }
460
497
  else
461
- o && o(new Error(`Upload failed with status ${c.status}`), null);
462
- }), c.addEventListener("error", () => {
498
+ o && o(new Error(`Upload failed with status ${a.status}`), null);
499
+ }), a.addEventListener("error", () => {
463
500
  o && o(new Error("Network error during upload"), null);
464
- }), c.addEventListener("abort", () => {
501
+ }), a.addEventListener("abort", () => {
465
502
  o && o(new Error("Upload aborted"), null);
466
- }), c.send(u), c;
503
+ }), a.send(l), a;
467
504
  }
468
- async function Ve(e) {
469
- const n = b(), { endpoint: o, token: r } = n || {};
505
+ async function nn(e) {
506
+ const n = T(), { endpoint: o, token: r } = n || {};
470
507
  if (!o)
471
- throw new Error(M);
472
- const l = `${o}/delete/${e}`, d = {};
508
+ throw new Error(L);
509
+ const g = `${o}/delete/${e}`, d = {};
473
510
  r && (d.Authorization = `Bearer ${r}`);
474
- const c = await fetch(l, {
511
+ const a = await fetch(g, {
475
512
  method: "DELETE",
476
513
  headers: d
477
514
  });
478
- if (!c.ok)
479
- throw new Error(`Delete failed with status ${c.status}`);
515
+ if (!a.ok)
516
+ throw new Error(`Delete failed with status ${a.status}`);
480
517
  return { success: !0 };
481
518
  }
482
- function Be(e) {
483
- const n = b(), { endpoint: o } = n || {};
519
+ function tn(e) {
520
+ const n = T(), { endpoint: o } = n || {};
484
521
  if (!o)
485
- throw new Error(M);
522
+ throw new Error(L);
486
523
  return `${o}/upload/${e}`;
487
524
  }
488
- async function ce(e, n = "GET", o = null) {
489
- const r = b(), { endpoint: l, token: d } = r || {};
490
- if (!l)
491
- throw new Error(M);
492
- const c = `${l}${e}`, u = {
525
+ async function fe(e, n = "GET", o = null) {
526
+ const r = T(), { endpoint: g, token: d } = r || {};
527
+ if (!g)
528
+ throw new Error(L);
529
+ const a = new URL(g), [l, f] = e.split("?");
530
+ a.pathname = a.pathname.replace(/\/$/, "") + l, f && new URLSearchParams(f).forEach((w, m) => {
531
+ a.searchParams.append(m, w);
532
+ });
533
+ const u = a.toString(), S = {
493
534
  "Content-Type": "application/json"
494
535
  };
495
- return d && (u.Authorization = `Bearer ${d}`), fetch(c, {
496
- headers: u,
536
+ return d && (S.Authorization = `Bearer ${d}`), fetch(u, {
537
+ headers: S,
497
538
  method: n,
498
539
  body: o ? JSON.stringify(o) : null
499
540
  });
500
541
  }
501
- function ie(e = {}) {
542
+ function pe(e = {}) {
502
543
  return {
503
544
  sessionId: void 0,
504
545
  socket: null,
@@ -516,31 +557,31 @@ function ie(e = {}) {
516
557
  pendingRemoteIceCandidates: []
517
558
  };
518
559
  }
519
- let t = ie();
520
- const Ae = {
560
+ let t = pe();
561
+ const Le = {
521
562
  iceServers: [{ urls: "stun:stun.l.google.com:19302" }, { urls: "stun:stun1.l.google.com:19302" }]
522
563
  };
523
- function Ye(e) {
564
+ function on(e) {
524
565
  t.callbacks = { ...t.callbacks, ...e };
525
566
  }
526
- function le() {
527
- t.peerConnection && (t.peerConnection.close(), t.peerConnection = null), t.localStream && (t.localStream.getTracks().forEach((n) => n.stop()), t.localStream = null), t.remoteStream && (t.remoteStream = null), t.remoteAudio && (t.remoteAudio.srcObject = null, t.remoteAudio.parentNode && t.remoteAudio.parentNode.removeChild(t.remoteAudio), t.remoteAudio = null), t.socket && (t.socket.close(), t.socket = null), P();
567
+ function me() {
568
+ t.peerConnection && (t.peerConnection.close(), t.peerConnection = null), t.localStream && (t.localStream.getTracks().forEach((n) => n.stop()), t.localStream = null), t.remoteStream && (t.remoteStream = null), t.remoteAudio && (t.remoteAudio.srcObject = null, t.remoteAudio.parentNode && t.remoteAudio.parentNode.removeChild(t.remoteAudio), t.remoteAudio = null), t.socket && (t.socket.close(), t.socket = null), N();
528
569
  const e = t.callbacks;
529
- t = ie(e);
570
+ t = pe(e);
530
571
  }
531
- function w(e) {
572
+ function E(e) {
532
573
  var n, o;
533
574
  t.callStatus = e, (o = (n = t.callbacks).onCallStatus) == null || o.call(n, e);
534
575
  }
535
- function U(e) {
576
+ function O(e) {
536
577
  var n, o;
537
578
  (o = (n = t.callbacks).onCallError) == null || o.call(n, e);
538
579
  }
539
- function P() {
580
+ function N() {
540
581
  t.pingInterval && (clearInterval(t.pingInterval), t.pingInterval = null);
541
582
  }
542
- function Re() {
543
- P(), t.pingInterval = setInterval(() => {
583
+ function qe() {
584
+ N(), t.pingInterval = setInterval(() => {
544
585
  if (t.socket && t.socket.readyState === WebSocket.OPEN) {
545
586
  t.pingCount++;
546
587
  const e = {
@@ -548,18 +589,18 @@ function Re() {
548
589
  timestamp: Date.now(),
549
590
  count: t.pingCount
550
591
  };
551
- T(e);
592
+ $(e);
552
593
  } else
553
- P();
594
+ N();
554
595
  }, 1e4);
555
596
  }
556
- function Ue() {
597
+ function ze() {
557
598
  t.lastPongTime = Date.now();
558
599
  }
559
- function T(e) {
600
+ function $(e) {
560
601
  t.socket && t.socket.readyState === WebSocket.OPEN && t.socket.send(JSON.stringify(e));
561
602
  }
562
- async function Pe() {
603
+ async function Fe() {
563
604
  try {
564
605
  t.localStream = await navigator.mediaDevices.getUserMedia({
565
606
  audio: !0,
@@ -569,11 +610,11 @@ async function Pe() {
569
610
  throw e;
570
611
  }
571
612
  }
572
- function Oe() {
573
- t.peerConnection = new RTCPeerConnection(Ae), t.peerConnection.onicecandidate = (e) => {
613
+ function Ge() {
614
+ t.peerConnection = new RTCPeerConnection(Le), t.peerConnection.onicecandidate = (e) => {
574
615
  if (e.candidate) {
575
616
  const n = JSON.stringify(e.candidate);
576
- t.peerConnection && t.peerConnection.remoteDescription ? T({
617
+ t.peerConnection && t.peerConnection.remoteDescription ? $({
577
618
  type: "ice",
578
619
  data: {
579
620
  candidate: n
@@ -586,23 +627,23 @@ function Oe() {
586
627
  });
587
628
  }, t.peerConnection.onconnectionstatechange = () => {
588
629
  const e = t.peerConnection.connectionState;
589
- e === "connected" ? w("connected") : (e === "disconnected" || e === "closed") && (w("disconnected"), de());
630
+ e === "connected" ? E("connected") : (e === "disconnected" || e === "closed") && (E("disconnected"), Se());
590
631
  }, t.peerConnection.oniceconnectionstatechange = () => {
591
632
  };
592
633
  }
593
- function Ne(e) {
634
+ function Je(e) {
594
635
  return new Promise((n, o) => {
595
636
  if (t.socket && (t.socket.readyState === WebSocket.CONNECTING || t.socket.readyState === WebSocket.OPEN)) {
596
637
  n(t.socket.readyState === WebSocket.OPEN);
597
638
  return;
598
639
  }
599
- const r = b();
640
+ const r = T();
600
641
  if (!r || !r.endpoint) {
601
642
  o(new Error("SDK not initialized. Please initialize SDK first."));
602
643
  return;
603
644
  }
604
- const l = ke(r.endpoint);
605
- if (!l) {
645
+ const g = ye(r.endpoint);
646
+ if (!g) {
606
647
  o(
607
648
  new Error(
608
649
  "Invalid endpoint while initializing SDK. Please check the endpoint and try again."
@@ -610,54 +651,54 @@ function Ne(e) {
610
651
  );
611
652
  return;
612
653
  }
613
- const d = O(), c = new URLSearchParams({
654
+ const d = x(), a = new URLSearchParams({
614
655
  externalId: d
615
656
  });
616
- e.sessionId && c.set("sessionId", e.sessionId), r.token && c.set("token", r.token);
617
- const u = `${l}?${c.toString()}`;
618
- t.socket = new WebSocket(u), t.socket.onopen = (g) => {
619
- Re(), n(!0);
620
- }, t.socket.onmessage = (g) => {
621
- const f = JSON.parse(g.data);
622
- Me(f);
623
- }, t.socket.onerror = (g) => {
624
- w("error"), U(g.message || "Unable to connect voice"), o(g);
625
- }, t.socket.onclose = (g) => {
626
- P();
657
+ e.sessionId && a.set("sessionId", e.sessionId), r.token && a.set("token", r.token);
658
+ const l = `${g}?${a.toString()}`;
659
+ t.socket = new WebSocket(l), t.socket.onopen = (f) => {
660
+ qe(), n(!0);
661
+ }, t.socket.onmessage = (f) => {
662
+ const u = JSON.parse(f.data);
663
+ We(u);
664
+ }, t.socket.onerror = (f) => {
665
+ E("error"), O(f.message || "Unable to connect voice"), o(f);
666
+ }, t.socket.onclose = (f) => {
667
+ N();
627
668
  };
628
669
  });
629
670
  }
630
- function Me(e) {
671
+ function We(e) {
631
672
  switch (e.type) {
632
673
  case "pong":
633
- Ue();
674
+ ze();
634
675
  break;
635
676
  case "answer":
636
- qe(e.data);
677
+ Ke(e.data);
637
678
  break;
638
679
  case "connected":
639
- xe(e.data);
680
+ _e(e.data);
640
681
  break;
641
682
  case "ice":
642
- Le(e.data);
683
+ Be(e.data);
643
684
  break;
644
685
  case "renegotiationOffer":
645
- ze(e.data);
686
+ He(e.data);
646
687
  break;
647
688
  case "end":
648
- de();
689
+ Se();
649
690
  break;
650
691
  case "error":
651
- w("error"), U(e.error || "Unable to connect voice");
692
+ E("error"), O(e.error || "Unable to connect voice");
652
693
  break;
653
694
  default:
654
695
  break;
655
696
  }
656
697
  }
657
- function xe(e) {
658
- t.sessionId = e.sessionId, be(e.sessionId);
698
+ function _e(e) {
699
+ t.sessionId = e.sessionId, Re(e.sessionId);
659
700
  }
660
- async function qe(e) {
701
+ async function Ke(e) {
661
702
  try {
662
703
  if (t.peerConnection) {
663
704
  const n = new RTCSessionDescription({
@@ -666,7 +707,7 @@ async function qe(e) {
666
707
  });
667
708
  await t.peerConnection.setRemoteDescription(n);
668
709
  for (const o of t.localIceCandidates)
669
- T({
710
+ $({
670
711
  type: "ice",
671
712
  data: {
672
713
  candidate: o
@@ -684,7 +725,7 @@ async function qe(e) {
684
725
  } catch (n) {
685
726
  }
686
727
  }
687
- async function Le(e) {
728
+ async function Be(e) {
688
729
  try {
689
730
  if (t.peerConnection) {
690
731
  if (!t.peerConnection.remoteDescription) {
@@ -697,7 +738,7 @@ async function Le(e) {
697
738
  } catch (n) {
698
739
  }
699
740
  }
700
- async function ze(e) {
741
+ async function He(e) {
701
742
  try {
702
743
  if (t.peerConnection) {
703
744
  const n = new RTCSessionDescription({
@@ -706,7 +747,7 @@ async function ze(e) {
706
747
  });
707
748
  await t.peerConnection.setRemoteDescription(n);
708
749
  const o = await t.peerConnection.createAnswer();
709
- await t.peerConnection.setLocalDescription(o), T({
750
+ await t.peerConnection.setLocalDescription(o), $({
710
751
  type: "renegotiationAnswer",
711
752
  data: {
712
753
  sdp: o.sdp
@@ -716,30 +757,30 @@ async function ze(e) {
716
757
  } catch (n) {
717
758
  }
718
759
  }
719
- async function Qe(e = {}) {
760
+ async function sn(e = {}) {
720
761
  try {
721
762
  if (t.callStatus === "connecting" || t.callStatus === "connected")
722
763
  return;
723
- w("connecting"), U(null), t.sessionId = e.sessionId, await Pe(), Oe(), t.localStream.getTracks().forEach((o) => {
764
+ E("connecting"), O(null), t.sessionId = e.sessionId, await Fe(), Ge(), t.localStream.getTracks().forEach((o) => {
724
765
  t.peerConnection.addTrack(o, t.localStream);
725
- }), await Ne(e);
766
+ }), await Je(e);
726
767
  const n = await t.peerConnection.createOffer();
727
- await t.peerConnection.setLocalDescription(n), T({
768
+ await t.peerConnection.setLocalDescription(n), $({
728
769
  type: "offer",
729
770
  data: {
730
771
  sdp: n.sdp
731
772
  }
732
773
  });
733
774
  } catch (n) {
734
- w("error"), U(n.message || "Unable to connect voice"), le();
775
+ E("error"), O(n.message || "Unable to connect voice"), me();
735
776
  }
736
777
  }
737
- function de() {
738
- T({
778
+ function Se() {
779
+ $({
739
780
  type: "end"
740
- }), t.socket && (t.socket.close(), t.socket = null), w("disconnected"), t.peerConnection && (t.peerConnection.close(), t.peerConnection = null), t.localStream && (t.localStream.getTracks().forEach((e) => e.stop()), t.localStream = null), le();
781
+ }), t.socket && (t.socket.close(), t.socket = null), E("disconnected"), t.peerConnection && (t.peerConnection.close(), t.peerConnection = null), t.localStream && (t.localStream.getTracks().forEach((e) => e.stop()), t.localStream = null), me();
741
782
  }
742
- function Xe() {
783
+ function rn() {
743
784
  if (t.localStream) {
744
785
  const e = t.localStream.getAudioTracks()[0];
745
786
  if (e)
@@ -747,10 +788,10 @@ function Xe() {
747
788
  }
748
789
  return !1;
749
790
  }
750
- function Ze() {
791
+ function an() {
751
792
  return t.localStream;
752
793
  }
753
- function je() {
794
+ function cn() {
754
795
  return new Promise((e, n) => {
755
796
  if (!t.peerConnection) {
756
797
  n(new Error("no peer connection"));
@@ -765,7 +806,7 @@ function je() {
765
806
  });
766
807
  });
767
808
  }
768
- function en() {
809
+ function ln() {
769
810
  return new Promise((e, n) => {
770
811
  if (!t.peerConnection) {
771
812
  n(new Error("no peer connection"));
@@ -781,24 +822,24 @@ function en() {
781
822
  });
782
823
  }
783
824
  export {
784
- y as MESSAGE_ROLES,
785
- $e as authenticate,
786
- Ve as deleteAttachment,
787
- _e as disconnect,
788
- de as disconnectCall,
789
- Be as getAttachment,
790
- Ke as getHistory,
791
- je as getInboundAudioEnergy,
792
- Ze as getLocalStream,
793
- en as getOutboundAudioEnergy,
794
- De as getSession,
795
- Je as initialize,
796
- Te as sendMessage,
797
- Ye as setCallCallbacks,
798
- Ge as setCallbacks,
799
- Qe as startCall,
800
- We as startChat,
801
- Xe as toggleMute,
802
- He as uploadAttachment
825
+ v as MESSAGE_ROLES,
826
+ Ne as authenticate,
827
+ nn as deleteAttachment,
828
+ Ze as disconnect,
829
+ Se as disconnectCall,
830
+ tn as getAttachment,
831
+ je as getHistory,
832
+ cn as getInboundAudioEnergy,
833
+ an as getLocalStream,
834
+ ln as getOutboundAudioEnergy,
835
+ xe as getSession,
836
+ Qe as initialize,
837
+ Pe as sendMessage,
838
+ on as setCallCallbacks,
839
+ Ye as setCallbacks,
840
+ sn as startCall,
841
+ Xe as startChat,
842
+ rn as toggleMute,
843
+ en as uploadAttachment
803
844
  };
804
845
  //# sourceMappingURL=origon-chat-sdk.js.map