@origonai/web-chat-sdk 1.0.10 → 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,33 +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
- if (e.sessionId) {
213
- const d = await De(e.sessionId);
214
- o = d.messages, r = d.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";
215
219
  }
216
- const l = new URLSearchParams();
217
- return s.credentials.token || l.set("externalId", O()), s.sseUrl = `${me(
218
- s.credentials.endpoint
219
- )}?${l.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(() => {
220
222
  }), {
221
223
  sessionId: s.sessionId,
222
224
  messages: o,
@@ -224,81 +226,84 @@ async function We(e = {}) {
224
226
  configData: n
225
227
  };
226
228
  } catch (n) {
227
- throw ae(), n;
229
+ throw ge(), n;
228
230
  }
229
231
  }
230
- function _e() {
231
- ae();
232
+ function Ze() {
233
+ ge();
232
234
  }
233
- function ae() {
234
- s.abortController && s.abortController.abort(), se();
235
+ function ge() {
236
+ s.abortController && s.abortController.abort(), de();
235
237
  const { callbacks: e, credentials: n } = s;
236
- s = re(e), s.credentials = n;
238
+ s = ue(e), s.credentials = n;
237
239
  }
238
- function O() {
240
+ function x() {
239
241
  var e;
240
- return (e = s.credentials) != null && e.externalId ? s.credentials.externalId : fe();
242
+ return (e = s.credentials) != null && e.externalId ? s.credentials.externalId : he();
241
243
  }
242
- function h(e) {
244
+ function C(e) {
243
245
  var n, o;
244
246
  s.messages = [...s.messages, e], (o = (n = s.callbacks).onMessageAdd) == null || o.call(n, e);
245
247
  }
246
- function Z(e) {
248
+ function se(e) {
247
249
  var n, o;
248
250
  (o = (n = s.callbacks).onTyping) == null || o.call(n, e);
249
251
  }
250
- function N(e) {
252
+ function M(e) {
251
253
  var n, o;
252
254
  s.transport = e, (o = (n = s.callbacks).onTransportUpdate) == null || o.call(n, e);
253
255
  }
254
- function Te({ text: e, html: n, context: o, attachments: r, meta: l }) {
255
- 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) => {
256
258
  (async () => {
257
- var u, g, f;
259
+ var u, S, w;
258
260
  try {
259
- const I = !e && !n && !(r != null && r.length);
260
- if (!I) {
261
+ const m = !e && !n && !(r != null && r.length);
262
+ if (!m) {
261
263
  const p = {
262
- role: y.USER,
264
+ role: v.USER,
263
265
  text: e,
264
266
  html: n,
265
267
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
266
268
  attachments: r,
267
- meta: l
269
+ meta: d,
270
+ createSystem: a
268
271
  };
269
- h(p), await pe(200);
272
+ C(p), await we(200);
270
273
  }
271
- if (s.transport === "socket" && ye()) {
272
- q({
274
+ if (s.transport === "socket" && Ue()) {
275
+ z({
273
276
  type: "message",
274
277
  data: {
275
278
  text: e,
276
279
  html: n
277
280
  }
278
- }), d(s.sessionId);
281
+ }), l(s.sessionId);
279
282
  return;
280
283
  }
281
284
  if (s.control === "agent") {
282
285
  const p = {
283
- role: y.ASSISTANT,
286
+ role: v.ASSISTANT,
284
287
  text: "",
285
288
  loading: !0
286
289
  };
287
- h(p);
290
+ C(p);
288
291
  }
289
- const v = new URL(s.sseUrl);
290
- s.sessionId && v.searchParams.set("sessionId", s.sessionId), s.requestId && v.searchParams.set("requestId", s.requestId), s.lastStreamId = void 0, s.abortController = new AbortController();
291
- 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 = {
292
295
  "Content-Type": "application/json"
293
296
  };
294
- (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(), {
295
298
  method: "POST",
296
- headers: C,
297
- 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({
298
301
  message: e,
299
302
  html: n,
300
303
  context: o,
301
- attachments: r
304
+ attachments: r,
305
+ mode: g,
306
+ createSystem: a
302
307
  }),
303
308
  signal: s.abortController.signal,
304
309
  openWhenHidden: !0,
@@ -307,45 +312,49 @@ function Te({ text: e, html: n, context: o, attachments: r, meta: l }) {
307
312
  throw new Error("Failed to send message");
308
313
  },
309
314
  onmessage: (p) => {
310
- 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;
311
316
  const i = JSON.parse(p.data);
312
317
  if (p.event === "connected")
313
- 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));
314
319
  else if (p.event === "upgrade_to_websocket")
315
- Ce({
320
+ $e({
316
321
  sessionId: s.sessionId,
317
322
  requestId: i.requestId
318
323
  });
319
324
  else if (p.event === "update")
320
- i.control && (s.control = i.control, (z = (L = s.callbacks).onControlUpdate) == null || z.call(L, i.control));
321
- else if (i.error) {
322
- 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 = {
323
328
  ...s.messages[k],
324
329
  loading: !1,
325
- errorText: m
330
+ done: !0
326
331
  };
327
332
  s.messages = s.messages.map(
328
- ($, ue) => ue === k ? S : $
329
- ), (G = (F = s.callbacks).onMessageUpdate) == null || G.call(F, k, S), c(new Error(m));
330
- } else if (p.event === "done") {
331
- const m = s.messages.length - 1, E = {
332
- ...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],
333
342
  loading: !1,
334
- done: !0
343
+ errorText: k
335
344
  };
336
345
  s.messages = s.messages.map(
337
- (S, $) => $ === m ? E : S
338
- ), (W = (J = s.callbacks).onMessageUpdate) == null || W.call(J, m, E), d(s.sessionId);
339
- } else if (i.message !== void 0 || ((_ = i.attachments) == null ? void 0 : _.length) > 0) {
340
- if (i.role === y.SUPERVISOR) {
341
- const S = {
342
- 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,
343
352
  text: i.message,
344
353
  attachments: i.attachments,
345
354
  sources: i.sources,
346
355
  done: !0
347
356
  };
348
- 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;
349
358
  return;
350
359
  }
351
360
  if (i.streamId !== void 0) {
@@ -353,25 +362,25 @@ function Te({ text: e, html: n, context: o, attachments: r, meta: l }) {
353
362
  s.lastStreamId = i.streamId;
354
363
  else if (i.streamId !== s.lastStreamId) {
355
364
  s.lastStreamId = i.streamId;
356
- const S = {
357
- role: y.ASSISTANT,
365
+ const I = {
366
+ role: v.ASSISTANT,
358
367
  text: "",
359
368
  loading: !0
360
369
  };
361
- h(S);
370
+ C(I);
362
371
  }
363
372
  }
364
- const m = s.messages.length - 1, k = s.messages[m], E = {
365
- ...k,
373
+ const k = s.messages.length - 1, h = s.messages[k], b = {
374
+ ...h,
366
375
  loading: !1,
367
- text: (k.text || "") + i.message,
376
+ text: (h.text || "") + i.message,
368
377
  sources: i.sources,
369
378
  attachments: i.attachments,
370
- done: (V = i.done) != null ? V : k.done
379
+ done: (j = i.done) != null ? j : h.done
371
380
  };
372
381
  s.messages = s.messages.map(
373
- (S, $) => $ === m ? E : S
374
- ), (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;
375
384
  }
376
385
  },
377
386
  onerror: (p) => {
@@ -379,22 +388,22 @@ function Te({ text: e, html: n, context: o, attachments: r, meta: l }) {
379
388
  },
380
389
  openWhenHidden: !0
381
390
  });
382
- } catch (I) {
383
- 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 = {
384
393
  ...p,
385
394
  loading: !1,
386
- errorText: p.done ? void 0 : I.message || v,
395
+ errorText: p.done ? void 0 : m.message || A,
387
396
  done: !0
388
397
  };
389
398
  s.messages = s.messages.map(
390
- (D, A) => A === C ? i : D
391
- ), (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);
392
401
  }
393
402
  })();
394
403
  });
395
404
  }
396
- const ve = "Something went wrong initializing the chat", M = "Chat SDK not initialized";
397
- async function $e(e) {
405
+ const Oe = "Something went wrong initializing the chat", L = "Chat SDK not initialized";
406
+ async function Ne(e) {
398
407
  const { endpoint: n } = e, o = `${n}/config`, r = await fetch(o, {
399
408
  method: "GET",
400
409
  headers: {
@@ -402,102 +411,135 @@ async function $e(e) {
402
411
  }
403
412
  });
404
413
  if (!r.ok) {
405
- const c = await r.json();
406
- 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);
407
416
  }
408
417
  return (await r.json()).data;
409
418
  }
410
- async function Ke() {
419
+ async function je() {
411
420
  const e = new URLSearchParams({
412
- externalId: O()
413
- }), n = await ce(`/sessions?${e.toString()}`, "GET");
421
+ externalId: x()
422
+ }), n = await fe(`/sessions?${e.toString()}`, "GET");
414
423
  if (!n.ok)
415
424
  throw new Error("Unable to load history, please try again later");
416
425
  return n.json();
417
426
  }
418
- async function De(e) {
419
- var c;
427
+ async function xe(e) {
428
+ var a;
420
429
  const n = new URLSearchParams({
421
430
  sessionId: e
422
- }), o = await ce(`/session?${n.toString()}`, "GET");
431
+ }), o = await fe(`/session?${n.toString()}`, "GET");
423
432
  if (!o.ok)
424
433
  throw new Error("Unable to load messages, please try again later");
425
- const r = await o.json(), l = r == null ? void 0 : r.control, d = ((c = r == null ? void 0 : r.history) != null ? c : []).map((u) => ({
426
- id: u.id,
427
- text: u.text,
428
- role: u.youtubeVideo ? y.ASSISTANT : u.role,
429
- timestamp: u.timestamp,
430
- video: u.youtubeVideo,
431
- attachments: u.attachments,
432
- 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,
433
442
  done: !0
434
443
  }));
435
- return { control: l, messages: d };
444
+ return { control: g, messages: d };
436
445
  }
437
- function He(e, n, o) {
438
- const r = b(), { endpoint: l, token: d } = r || {};
439
- if (!l) {
440
- const f = new Error(M);
441
- 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;
442
480
  }
443
- const c = new XMLHttpRequest(), u = new FormData();
444
- u.append("file", e);
445
- const g = `${l}/upload`;
446
- return c.open("POST", g), d && c.setRequestHeader("Authorization", `Bearer ${d}`), n && c.upload.addEventListener("progress", (f) => {
447
- if (f.lengthComputable) {
448
- const I = f.loaded / f.total * 100;
449
- 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);
450
488
  }
451
- }), c.addEventListener("load", () => {
452
- if (c.status >= 200 && c.status < 300)
489
+ }), a.addEventListener("load", () => {
490
+ if (a.status >= 200 && a.status < 300)
453
491
  try {
454
- const f = JSON.parse(c.responseText);
455
- o && o(null, f);
456
- } catch (f) {
492
+ const u = JSON.parse(a.responseText);
493
+ o && o(null, u);
494
+ } catch (u) {
457
495
  o && o(new Error("Failed to parse response"), null);
458
496
  }
459
497
  else
460
- o && o(new Error(`Upload failed with status ${c.status}`), null);
461
- }), c.addEventListener("error", () => {
498
+ o && o(new Error(`Upload failed with status ${a.status}`), null);
499
+ }), a.addEventListener("error", () => {
462
500
  o && o(new Error("Network error during upload"), null);
463
- }), c.addEventListener("abort", () => {
501
+ }), a.addEventListener("abort", () => {
464
502
  o && o(new Error("Upload aborted"), null);
465
- }), c.send(u), c;
503
+ }), a.send(l), a;
466
504
  }
467
- async function Ve(e) {
468
- const n = b(), { endpoint: o, token: r } = n || {};
505
+ async function nn(e) {
506
+ const n = T(), { endpoint: o, token: r } = n || {};
469
507
  if (!o)
470
- throw new Error(M);
471
- const l = `${o}/delete/${e}`, d = {};
508
+ throw new Error(L);
509
+ const g = `${o}/delete/${e}`, d = {};
472
510
  r && (d.Authorization = `Bearer ${r}`);
473
- const c = await fetch(l, {
511
+ const a = await fetch(g, {
474
512
  method: "DELETE",
475
513
  headers: d
476
514
  });
477
- if (!c.ok)
478
- throw new Error(`Delete failed with status ${c.status}`);
515
+ if (!a.ok)
516
+ throw new Error(`Delete failed with status ${a.status}`);
479
517
  return { success: !0 };
480
518
  }
481
- function Be(e) {
482
- const n = b(), { endpoint: o } = n || {};
519
+ function tn(e) {
520
+ const n = T(), { endpoint: o } = n || {};
483
521
  if (!o)
484
- throw new Error(M);
522
+ throw new Error(L);
485
523
  return `${o}/upload/${e}`;
486
524
  }
487
- async function ce(e, n = "GET", o = null) {
488
- const r = b(), { endpoint: l, token: d } = r || {};
489
- if (!l)
490
- throw new Error(M);
491
- 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 = {
492
534
  "Content-Type": "application/json"
493
535
  };
494
- return d && (u.Authorization = `Bearer ${d}`), fetch(c, {
495
- headers: u,
536
+ return d && (S.Authorization = `Bearer ${d}`), fetch(u, {
537
+ headers: S,
496
538
  method: n,
497
539
  body: o ? JSON.stringify(o) : null
498
540
  });
499
541
  }
500
- function ie(e = {}) {
542
+ function pe(e = {}) {
501
543
  return {
502
544
  sessionId: void 0,
503
545
  socket: null,
@@ -515,31 +557,31 @@ function ie(e = {}) {
515
557
  pendingRemoteIceCandidates: []
516
558
  };
517
559
  }
518
- let t = ie();
519
- const Ae = {
560
+ let t = pe();
561
+ const Le = {
520
562
  iceServers: [{ urls: "stun:stun.l.google.com:19302" }, { urls: "stun:stun1.l.google.com:19302" }]
521
563
  };
522
- function Ye(e) {
564
+ function on(e) {
523
565
  t.callbacks = { ...t.callbacks, ...e };
524
566
  }
525
- function le() {
526
- 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();
527
569
  const e = t.callbacks;
528
- t = ie(e);
570
+ t = pe(e);
529
571
  }
530
- function w(e) {
572
+ function E(e) {
531
573
  var n, o;
532
574
  t.callStatus = e, (o = (n = t.callbacks).onCallStatus) == null || o.call(n, e);
533
575
  }
534
- function U(e) {
576
+ function O(e) {
535
577
  var n, o;
536
578
  (o = (n = t.callbacks).onCallError) == null || o.call(n, e);
537
579
  }
538
- function P() {
580
+ function N() {
539
581
  t.pingInterval && (clearInterval(t.pingInterval), t.pingInterval = null);
540
582
  }
541
- function Re() {
542
- P(), t.pingInterval = setInterval(() => {
583
+ function qe() {
584
+ N(), t.pingInterval = setInterval(() => {
543
585
  if (t.socket && t.socket.readyState === WebSocket.OPEN) {
544
586
  t.pingCount++;
545
587
  const e = {
@@ -547,18 +589,18 @@ function Re() {
547
589
  timestamp: Date.now(),
548
590
  count: t.pingCount
549
591
  };
550
- T(e);
592
+ $(e);
551
593
  } else
552
- P();
594
+ N();
553
595
  }, 1e4);
554
596
  }
555
- function Ue() {
597
+ function ze() {
556
598
  t.lastPongTime = Date.now();
557
599
  }
558
- function T(e) {
600
+ function $(e) {
559
601
  t.socket && t.socket.readyState === WebSocket.OPEN && t.socket.send(JSON.stringify(e));
560
602
  }
561
- async function Pe() {
603
+ async function Fe() {
562
604
  try {
563
605
  t.localStream = await navigator.mediaDevices.getUserMedia({
564
606
  audio: !0,
@@ -568,11 +610,11 @@ async function Pe() {
568
610
  throw e;
569
611
  }
570
612
  }
571
- function Oe() {
572
- t.peerConnection = new RTCPeerConnection(Ae), t.peerConnection.onicecandidate = (e) => {
613
+ function Ge() {
614
+ t.peerConnection = new RTCPeerConnection(Le), t.peerConnection.onicecandidate = (e) => {
573
615
  if (e.candidate) {
574
616
  const n = JSON.stringify(e.candidate);
575
- t.peerConnection && t.peerConnection.remoteDescription ? T({
617
+ t.peerConnection && t.peerConnection.remoteDescription ? $({
576
618
  type: "ice",
577
619
  data: {
578
620
  candidate: n
@@ -585,23 +627,23 @@ function Oe() {
585
627
  });
586
628
  }, t.peerConnection.onconnectionstatechange = () => {
587
629
  const e = t.peerConnection.connectionState;
588
- e === "connected" ? w("connected") : (e === "disconnected" || e === "closed") && (w("disconnected"), de());
630
+ e === "connected" ? E("connected") : (e === "disconnected" || e === "closed") && (E("disconnected"), Se());
589
631
  }, t.peerConnection.oniceconnectionstatechange = () => {
590
632
  };
591
633
  }
592
- function Ne(e) {
634
+ function Je(e) {
593
635
  return new Promise((n, o) => {
594
636
  if (t.socket && (t.socket.readyState === WebSocket.CONNECTING || t.socket.readyState === WebSocket.OPEN)) {
595
637
  n(t.socket.readyState === WebSocket.OPEN);
596
638
  return;
597
639
  }
598
- const r = b();
640
+ const r = T();
599
641
  if (!r || !r.endpoint) {
600
642
  o(new Error("SDK not initialized. Please initialize SDK first."));
601
643
  return;
602
644
  }
603
- const l = ke(r.endpoint);
604
- if (!l) {
645
+ const g = ye(r.endpoint);
646
+ if (!g) {
605
647
  o(
606
648
  new Error(
607
649
  "Invalid endpoint while initializing SDK. Please check the endpoint and try again."
@@ -609,54 +651,54 @@ function Ne(e) {
609
651
  );
610
652
  return;
611
653
  }
612
- const d = O(), c = new URLSearchParams({
654
+ const d = x(), a = new URLSearchParams({
613
655
  externalId: d
614
656
  });
615
- e.sessionId && c.set("sessionId", e.sessionId), r.token && c.set("token", r.token);
616
- const u = `${l}?${c.toString()}`;
617
- t.socket = new WebSocket(u), t.socket.onopen = (g) => {
618
- Re(), n(!0);
619
- }, t.socket.onmessage = (g) => {
620
- const f = JSON.parse(g.data);
621
- Me(f);
622
- }, t.socket.onerror = (g) => {
623
- w("error"), U(g.message || "Unable to connect voice"), o(g);
624
- }, t.socket.onclose = (g) => {
625
- 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();
626
668
  };
627
669
  });
628
670
  }
629
- function Me(e) {
671
+ function We(e) {
630
672
  switch (e.type) {
631
673
  case "pong":
632
- Ue();
674
+ ze();
633
675
  break;
634
676
  case "answer":
635
- qe(e.data);
677
+ Ke(e.data);
636
678
  break;
637
679
  case "connected":
638
- xe(e.data);
680
+ _e(e.data);
639
681
  break;
640
682
  case "ice":
641
- Le(e.data);
683
+ Be(e.data);
642
684
  break;
643
685
  case "renegotiationOffer":
644
- ze(e.data);
686
+ He(e.data);
645
687
  break;
646
688
  case "end":
647
- de();
689
+ Se();
648
690
  break;
649
691
  case "error":
650
- w("error"), U(e.error || "Unable to connect voice");
692
+ E("error"), O(e.error || "Unable to connect voice");
651
693
  break;
652
694
  default:
653
695
  break;
654
696
  }
655
697
  }
656
- function xe(e) {
657
- t.sessionId = e.sessionId, be(e.sessionId);
698
+ function _e(e) {
699
+ t.sessionId = e.sessionId, Re(e.sessionId);
658
700
  }
659
- async function qe(e) {
701
+ async function Ke(e) {
660
702
  try {
661
703
  if (t.peerConnection) {
662
704
  const n = new RTCSessionDescription({
@@ -665,7 +707,7 @@ async function qe(e) {
665
707
  });
666
708
  await t.peerConnection.setRemoteDescription(n);
667
709
  for (const o of t.localIceCandidates)
668
- T({
710
+ $({
669
711
  type: "ice",
670
712
  data: {
671
713
  candidate: o
@@ -683,7 +725,7 @@ async function qe(e) {
683
725
  } catch (n) {
684
726
  }
685
727
  }
686
- async function Le(e) {
728
+ async function Be(e) {
687
729
  try {
688
730
  if (t.peerConnection) {
689
731
  if (!t.peerConnection.remoteDescription) {
@@ -696,7 +738,7 @@ async function Le(e) {
696
738
  } catch (n) {
697
739
  }
698
740
  }
699
- async function ze(e) {
741
+ async function He(e) {
700
742
  try {
701
743
  if (t.peerConnection) {
702
744
  const n = new RTCSessionDescription({
@@ -705,7 +747,7 @@ async function ze(e) {
705
747
  });
706
748
  await t.peerConnection.setRemoteDescription(n);
707
749
  const o = await t.peerConnection.createAnswer();
708
- await t.peerConnection.setLocalDescription(o), T({
750
+ await t.peerConnection.setLocalDescription(o), $({
709
751
  type: "renegotiationAnswer",
710
752
  data: {
711
753
  sdp: o.sdp
@@ -715,30 +757,30 @@ async function ze(e) {
715
757
  } catch (n) {
716
758
  }
717
759
  }
718
- async function Qe(e = {}) {
760
+ async function sn(e = {}) {
719
761
  try {
720
762
  if (t.callStatus === "connecting" || t.callStatus === "connected")
721
763
  return;
722
- 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) => {
723
765
  t.peerConnection.addTrack(o, t.localStream);
724
- }), await Ne(e);
766
+ }), await Je(e);
725
767
  const n = await t.peerConnection.createOffer();
726
- await t.peerConnection.setLocalDescription(n), T({
768
+ await t.peerConnection.setLocalDescription(n), $({
727
769
  type: "offer",
728
770
  data: {
729
771
  sdp: n.sdp
730
772
  }
731
773
  });
732
774
  } catch (n) {
733
- w("error"), U(n.message || "Unable to connect voice"), le();
775
+ E("error"), O(n.message || "Unable to connect voice"), me();
734
776
  }
735
777
  }
736
- function de() {
737
- T({
778
+ function Se() {
779
+ $({
738
780
  type: "end"
739
- }), 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();
740
782
  }
741
- function Xe() {
783
+ function rn() {
742
784
  if (t.localStream) {
743
785
  const e = t.localStream.getAudioTracks()[0];
744
786
  if (e)
@@ -746,10 +788,10 @@ function Xe() {
746
788
  }
747
789
  return !1;
748
790
  }
749
- function Ze() {
791
+ function an() {
750
792
  return t.localStream;
751
793
  }
752
- function je() {
794
+ function cn() {
753
795
  return new Promise((e, n) => {
754
796
  if (!t.peerConnection) {
755
797
  n(new Error("no peer connection"));
@@ -764,7 +806,7 @@ function je() {
764
806
  });
765
807
  });
766
808
  }
767
- function en() {
809
+ function ln() {
768
810
  return new Promise((e, n) => {
769
811
  if (!t.peerConnection) {
770
812
  n(new Error("no peer connection"));
@@ -780,24 +822,24 @@ function en() {
780
822
  });
781
823
  }
782
824
  export {
783
- y as MESSAGE_ROLES,
784
- $e as authenticate,
785
- Ve as deleteAttachment,
786
- _e as disconnect,
787
- de as disconnectCall,
788
- Be as getAttachment,
789
- Ke as getHistory,
790
- je as getInboundAudioEnergy,
791
- Ze as getLocalStream,
792
- en as getOutboundAudioEnergy,
793
- De as getSession,
794
- Je as initialize,
795
- Te as sendMessage,
796
- Ye as setCallCallbacks,
797
- Ge as setCallbacks,
798
- Qe as startCall,
799
- We as startChat,
800
- Xe as toggleMute,
801
- 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
802
844
  };
803
845
  //# sourceMappingURL=origon-chat-sdk.js.map