@opencx/widget-core 4.0.25 → 4.0.27

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.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import j from "openapi-fetch";
2
- import L from "lodash.isequal";
1
+ import L from "openapi-fetch";
2
+ import N from "lodash.isequal";
3
3
  import { v4 as z } from "uuid";
4
4
  const F = (h) => {
5
5
  console.log(h.error);
6
- }, N = (h) => {
7
- const i = j({
6
+ }, B = (h) => {
7
+ const i = L({
8
8
  baseUrl: h.baseUrl
9
9
  }), a = {
10
10
  onRequest: h.onRequest,
@@ -27,7 +27,7 @@ class M {
27
27
  }, this.createOpenAPIClient = ({
28
28
  baseUrl: e,
29
29
  headers: t
30
- }) => N({
30
+ }) => B({
31
31
  baseUrl: e,
32
32
  onRequest: ({ request: n }) => {
33
33
  Object.entries(t).forEach(([o, r]) => {
@@ -73,7 +73,7 @@ class M {
73
73
  abortSignal: t,
74
74
  onProgress: n
75
75
  }) => new Promise((o, r) => {
76
- var C;
76
+ var S;
77
77
  const c = new FormData();
78
78
  c.append("file", e);
79
79
  const u = new XMLHttpRequest();
@@ -83,18 +83,18 @@ class M {
83
83
  r(new DOMException("Aborted", "AbortError"));
84
84
  return;
85
85
  }
86
- u.upload.addEventListener("progress", (_) => {
87
- if (_.lengthComputable && n) {
88
- const v = Math.round(_.loaded / _.total * 100);
86
+ u.upload.addEventListener("progress", (f) => {
87
+ if (f.lengthComputable && n) {
88
+ const v = Math.round(f.loaded / f.total * 100);
89
89
  n(v);
90
90
  }
91
91
  }), u.addEventListener("load", () => {
92
92
  if (u.status >= 200 && u.status < 300)
93
93
  try {
94
- const _ = JSON.parse(u.responseText);
95
- o(_);
96
- } catch (_) {
97
- r(new Error(`Failed to parse response: ${_}`));
94
+ const f = JSON.parse(u.responseText);
95
+ o(f);
96
+ } catch (f) {
97
+ r(new Error(`Failed to parse response: ${f}`));
98
98
  }
99
99
  else
100
100
  r(new Error(`Upload failed with status: ${u.status}`));
@@ -103,8 +103,8 @@ class M {
103
103
  }), u.addEventListener("timeout", () => {
104
104
  r(new Error("Upload timed out"));
105
105
  });
106
- const { baseUrl: p } = this.constructClientOptions(this.userToken), f = `${p}/backend/widget/v2/upload`;
107
- u.open("POST", f), u.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((C = this.config.user) == null ? void 0 : C.token) ? u.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : console.error("User token not set"), u.send(c);
106
+ const { baseUrl: p } = this.constructClientOptions(this.userToken), g = `${p}/backend/widget/v2/upload`;
107
+ u.open("POST", g), u.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((S = this.config.user) == null ? void 0 : S.token) ? u.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : console.error("User token not set"), u.send(c);
108
108
  }), this.vote = async (e) => await this.client.POST("/backend/widget/v2/chat/vote", { body: e }), this.resolveSession = async (e, t) => await this.client.POST("/backend/widget/v2/session/resolve", {
109
109
  body: e,
110
110
  signal: t
@@ -117,13 +117,13 @@ class M {
117
117
  this.client = this.createOpenAPIClient({ baseUrl: a, headers: l });
118
118
  }
119
119
  }
120
- function B(h, i) {
120
+ function H(h, i) {
121
121
  console.error(`Missing case for ${h} in ${i}`);
122
122
  }
123
123
  class y {
124
124
  constructor(i) {
125
125
  this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (a) => {
126
- L(this.state, a) || (this.state = a, this.notifySubscribers(a));
126
+ N(this.state, a) || (this.state = a, this.notifySubscribers(a));
127
127
  }, this.setPartial = (a) => {
128
128
  if (a == null) return;
129
129
  const l = { ...this.state, ...a };
@@ -172,7 +172,7 @@ class O {
172
172
  };
173
173
  }
174
174
  }
175
- function H(h) {
175
+ function R(h) {
176
176
  try {
177
177
  const i = h();
178
178
  return i instanceof Promise ? i.then((a) => ({ data: a })).catch((a) => ({ error: a })) : { data: i };
@@ -220,11 +220,11 @@ class q {
220
220
  lastMessageTimestamp: n ? void 0 : r
221
221
  });
222
222
  if (c != null && c.session && (this.sessionCtx.sessionState.setPartial({ session: c.session }), this.sessionCtx.setSessions([c.session])), c != null && c.history && c.history.length > 0) {
223
- const p = this.messageCtx.state.get().messages, S = c.history.map(this.mapHistoryToMessage).filter((f) => f !== null).filter(
224
- (f) => !p.some((b) => b.id === f.id)
223
+ const p = this.messageCtx.state.get().messages, w = c.history.map(this.mapHistoryToMessage).filter((g) => g !== null).filter(
224
+ (g) => !p.some((C) => C.id === g.id)
225
225
  );
226
226
  this.messageCtx.state.setPartial({
227
- messages: [...p, ...S]
227
+ messages: [...p, ...w]
228
228
  });
229
229
  }
230
230
  this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
@@ -321,7 +321,7 @@ class q {
321
321
  case "none":
322
322
  return null;
323
323
  default:
324
- return B(
324
+ return H(
325
325
  e.systemMessagePayload,
326
326
  this.constructSystemMessage.name
327
327
  ), null;
@@ -330,7 +330,7 @@ class q {
330
330
  const t = e.result;
331
331
  if (t === null || typeof t != "object") return t;
332
332
  if ("responseBodyText" in t && typeof t.responseBodyText == "string") {
333
- const n = t.responseBodyText, o = H(() => JSON.parse(n)).data;
333
+ const n = t.responseBodyText, o = R(() => JSON.parse(n)).data;
334
334
  if (o) return o;
335
335
  }
336
336
  return e.result;
@@ -348,7 +348,7 @@ class V {
348
348
  var s;
349
349
  return !!(!((s = this.state.get().contact) != null && s.token) && this.config.collectUserData);
350
350
  }, this.autoCreateUnverifiedUserIfNotExists = async () => {
351
- var s, e, t, n, o, r, c, u, p, S, f, b, C, _;
351
+ var s, e, t, n, o, r, c, u, p, w, g, C, S, f;
352
352
  if (!((s = this.config.user) != null && s.token)) {
353
353
  if (this.config.collectUserData && !((t = (e = this.config.user) == null ? void 0 : e.data) != null && t.email)) {
354
354
  if ((n = this.config.extraDataCollectionFields) != null && n.length)
@@ -365,9 +365,9 @@ class V {
365
365
  }
366
366
  }
367
367
  await this.createUnverifiedContact({
368
- email: (S = (p = this.config.user) == null ? void 0 : p.data) == null ? void 0 : S.email,
369
- non_verified_name: (b = (f = this.config.user) == null ? void 0 : f.data) == null ? void 0 : b.name,
370
- non_verified_custom_data: (_ = (C = this.config.user) == null ? void 0 : C.data) == null ? void 0 : _.customData
368
+ email: (w = (p = this.config.user) == null ? void 0 : p.data) == null ? void 0 : w.email,
369
+ non_verified_name: (C = (g = this.config.user) == null ? void 0 : g.data) == null ? void 0 : C.name,
370
+ non_verified_custom_data: (f = (S = this.config.user) == null ? void 0 : S.data) == null ? void 0 : f.customData
371
371
  });
372
372
  }
373
373
  }, this.createUnverifiedContact = async (s, e) => {
@@ -472,11 +472,18 @@ class $ {
472
472
  this.sessionsRefresher.startPolling(async () => {
473
473
  this.sessionsState.get().didStartInitialFetch === !1 && this.sessionsState.setPartial({ didStartInitialFetch: !0 }), await this.refreshSessions(), this.sessionsState.get().isInitialFetchLoading === !0 && this.sessionsState.setPartial({ isInitialFetchLoading: !1 });
474
474
  }, this.sessionsPollingIntervalSeconds * 1e3);
475
- }, this.createSession = async () => {
475
+ }, this.getParsedCustomData = () => Object.fromEntries(
476
+ Object.entries(this.config.sessionCustomData || {}).map(
477
+ ([s, e]) => {
478
+ var t;
479
+ return typeof e == "string" ? [s, e] : typeof e == "boolean" ? [s, e] : typeof e == "number" ? [s, e] : [s, ((t = R(() => JSON.stringify(e))) == null ? void 0 : t.data) || ""];
480
+ }
481
+ )
482
+ ), this.createSession = async () => {
476
483
  var o;
477
484
  this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
478
485
  const s = (o = this.contactCtx.state.get().contact) == null ? void 0 : o.externalId, e = {
479
- ...this.config.sessionCustomData,
486
+ ...this.getParsedCustomData(),
480
487
  ...s ? { external_id: s } : {}
481
488
  }, { data: t, error: n } = await this.api.createSession({
482
489
  customData: Object.keys(e).length > 0 ? e : void 0
@@ -546,12 +553,13 @@ class K {
546
553
  this.state = new y({
547
554
  messages: [],
548
555
  isSendingMessage: !1,
556
+ isSendingMessageToAI: !1,
549
557
  lastAIResMightSolveUserIssue: !1,
550
558
  isInitialFetchLoading: !1
551
559
  }), this.sendMessageAbortController = new AbortController(), this.reset = () => {
552
560
  this.sendMessageAbortController.abort("Resetting chat"), this.state.reset();
553
561
  }, this.sendMessage = async (s) => {
554
- var e, t, n, o, r, c, u, p, S, f;
562
+ var e, t, n, o, r, c, u, p, w;
555
563
  try {
556
564
  if (!s.content.trim() && (!s.attachments || s.attachments.length === 0)) {
557
565
  console.warn(
@@ -559,21 +567,25 @@ class K {
559
567
  );
560
568
  return;
561
569
  }
562
- const b = this.state.get().isSendingMessage, C = ((e = this.sessionCtx.sessionState.get().session) == null ? void 0 : e.assignee.kind) === "ai", _ = this.state.get().messages, v = _.length > 0 ? _[_.length - 1] : void 0;
563
- if (C && b || // If last message is from user, then bot response did not arrive yet
564
- C && (v == null ? void 0 : v.type) === "USER") {
570
+ const g = this.sessionCtx.sessionState.get().session, S = (g == null ? void 0 : g.assignee.kind) === "ai", f = this.state.get().isSendingMessageToAI, v = this.state.get().messages.at(-1);
571
+ if (f || // If last message is from user, then bot response did not arrive yet
572
+ S && (v == null ? void 0 : v.type) === "USER") {
565
573
  console.warn("Cannot send messages while awaiting AI response");
566
574
  return;
567
575
  }
568
- this.sendMessageAbortController = new AbortController(), this.state.setPartial({ lastAIResMightSolveUserIssue: !1 }), this.state.setPartial({ isSendingMessage: !0 });
569
- const P = this.state.get().messages, A = !((t = this.sessionCtx.sessionState.get().session) != null && t.id) && P.length === 0 && ((n = this.config.advancedInitialMessages) == null ? void 0 : n.some((g) => g.persistent)), T = A ? (this.config.advancedInitialMessages || []).filter((g) => g.persistent).map(
570
- (g) => ({
576
+ this.sendMessageAbortController = new AbortController(), this.state.setPartial({
577
+ lastAIResMightSolveUserIssue: !1,
578
+ isSendingMessage: !0,
579
+ isSendingMessageToAI: !!S || !g
580
+ });
581
+ const P = this.state.get().messages, A = !((e = this.sessionCtx.sessionState.get().session) != null && e.id) && P.length === 0 && ((t = this.config.advancedInitialMessages) == null ? void 0 : t.some((_) => _.persistent)), T = A ? (this.config.advancedInitialMessages || []).filter((_) => _.persistent).map(
582
+ (_) => ({
571
583
  id: k(),
572
584
  component: "bot_message",
573
585
  type: "AI",
574
586
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
575
587
  data: {
576
- message: g.message
588
+ message: _.message
577
589
  }
578
590
  })
579
591
  ) : [], I = this.toUserMessage(
@@ -586,14 +598,14 @@ class K {
586
598
  ...P,
587
599
  I
588
600
  ]
589
- }), !((o = this.sessionCtx.sessionState.get().session) != null && o.id)) {
601
+ }), !((n = this.sessionCtx.sessionState.get().session) != null && n.id)) {
590
602
  if (!await this.sessionCtx.createSession()) {
591
603
  console.error("Failed to create session");
592
604
  return;
593
605
  }
594
606
  this.sessionCtx.refreshSessions();
595
607
  }
596
- const E = (r = this.sessionCtx.sessionState.get().session) == null ? void 0 : r.id;
608
+ const E = (o = this.sessionCtx.sessionState.get().session) == null ? void 0 : o.id;
597
609
  if (!E) return;
598
610
  const { data: m } = await this.api.sendMessage(
599
611
  {
@@ -612,43 +624,46 @@ class K {
612
624
  },
613
625
  language: this.config.language,
614
626
  exit_mode_prompt: s.exitModePrompt,
615
- initial_messages: A ? T.map((g) => ({
616
- uuid: g.id,
617
- content: g.data.message
627
+ initial_messages: A ? T.map((_) => ({
628
+ uuid: _.id,
629
+ content: _.data.message
618
630
  })) : void 0
619
631
  },
620
632
  this.sendMessageAbortController.signal
621
633
  );
622
634
  if (m != null && m.success) {
623
- const g = this.toBotMessage(m);
624
- if (g) {
635
+ const _ = this.toBotMessage(m);
636
+ if (_) {
625
637
  const x = this.state.get().messages;
626
638
  if (!!x.some(
627
- (D) => D.id === g.id
639
+ (j) => j.id === _.id
628
640
  )) {
629
641
  this.state.setPartial({
630
- lastAIResMightSolveUserIssue: ((c = m.autopilotResponse) == null ? void 0 : c.mightSolveUserIssue) || ((u = m.uiResponse) == null ? void 0 : u.mightSolveUserIssue)
642
+ lastAIResMightSolveUserIssue: ((r = m.autopilotResponse) == null ? void 0 : r.mightSolveUserIssue) || ((c = m.uiResponse) == null ? void 0 : c.mightSolveUserIssue)
631
643
  });
632
644
  return;
633
645
  }
634
646
  this.state.setPartial({
635
- messages: [...x, g],
636
- lastAIResMightSolveUserIssue: ((p = m.autopilotResponse) == null ? void 0 : p.mightSolveUserIssue) || ((S = m.uiResponse) == null ? void 0 : S.mightSolveUserIssue)
647
+ messages: [...x, _],
648
+ lastAIResMightSolveUserIssue: ((u = m.autopilotResponse) == null ? void 0 : u.mightSolveUserIssue) || ((p = m.uiResponse) == null ? void 0 : p.mightSolveUserIssue)
637
649
  });
638
650
  }
639
651
  m.session && this.sessionCtx.sessionState.setPartial({ session: m.session });
640
652
  } else {
641
- const g = this.toBotErrorMessage(
642
- ((f = m == null ? void 0 : m.error) == null ? void 0 : f.message) || "Unknown error occurred"
653
+ const _ = this.toBotErrorMessage(
654
+ ((w = m == null ? void 0 : m.error) == null ? void 0 : w.message) || "Unknown error occurred"
643
655
  ), x = this.state.get().messages;
644
656
  this.state.setPartial({
645
- messages: [...x, g]
657
+ messages: [...x, _]
646
658
  });
647
659
  }
648
- } catch (b) {
649
- this.sendMessageAbortController.signal.aborted || console.error("Failed to send message:", b);
660
+ } catch (g) {
661
+ this.sendMessageAbortController.signal.aborted || console.error("Failed to send message:", g);
650
662
  } finally {
651
- this.state.setPartial({ isSendingMessage: !1 });
663
+ this.state.setPartial({
664
+ isSendingMessage: !1,
665
+ isSendingMessageToAI: !1
666
+ });
652
667
  }
653
668
  }, this.toUserMessage = (s, e) => {
654
669
  const t = (() => {
@@ -740,7 +755,7 @@ class G {
740
755
  }), this.registerRoutingListener();
741
756
  }
742
757
  }
743
- class W {
758
+ class J {
744
759
  constructor({
745
760
  storage: i,
746
761
  config: a
@@ -755,7 +770,7 @@ class W {
755
770
  }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId(this.config.token)), this.storage = i, this.config = a;
756
771
  }
757
772
  }
758
- const w = class w {
773
+ const b = class b {
759
774
  constructor({
760
775
  config: i,
761
776
  storage: a,
@@ -764,11 +779,11 @@ const w = class w {
764
779
  }) {
765
780
  if (this.modes = [], this.resetChat = () => {
766
781
  this.sessionCtx.reset(), this.messageCtx.reset();
767
- }, !w.pollingIntervalsSeconds)
782
+ }, !b.pollingIntervalsSeconds)
768
783
  throw Error(
769
784
  "Widget polling values are not defined, did you call WidgetCtx.initialize()"
770
785
  );
771
- this.config = i, this.org = d, this.api = new M({ config: i }), this.storageCtx = a ? new W({ storage: a, config: i }) : void 0, this.modes = l, this.contactCtx = new V({
786
+ this.config = i, this.org = d, this.api = new M({ config: i }), this.storageCtx = a ? new J({ storage: a, config: i }) : void 0, this.modes = l, this.contactCtx = new V({
772
787
  api: this.api,
773
788
  config: this.config,
774
789
  storageCtx: this.storageCtx
@@ -776,7 +791,7 @@ const w = class w {
776
791
  config: this.config,
777
792
  api: this.api,
778
793
  contactCtx: this.contactCtx,
779
- sessionsPollingIntervalSeconds: w.pollingIntervalsSeconds.sessions
794
+ sessionsPollingIntervalSeconds: b.pollingIntervalsSeconds.sessions
780
795
  }), this.messageCtx = new K({
781
796
  config: this.config,
782
797
  api: this.api,
@@ -792,7 +807,7 @@ const w = class w {
792
807
  config: this.config,
793
808
  sessionCtx: this.sessionCtx,
794
809
  messageCtx: this.messageCtx,
795
- sessionPollingIntervalSeconds: w.pollingIntervalsSeconds.session
810
+ sessionPollingIntervalSeconds: b.pollingIntervalsSeconds.session
796
811
  }), this.routerCtx = new G({
797
812
  config: this.config,
798
813
  contactCtx: this.contactCtx,
@@ -801,7 +816,7 @@ const w = class w {
801
816
  });
802
817
  }
803
818
  };
804
- w.pollingIntervalsSeconds = null, w.initialize = async ({
819
+ b.pollingIntervalsSeconds = null, b.initialize = async ({
805
820
  config: i,
806
821
  storage: a
807
822
  }) => {
@@ -811,10 +826,10 @@ w.pollingIntervalsSeconds = null, w.initialize = async ({
811
826
  }).getExternalWidgetConfig();
812
827
  if (!l.data)
813
828
  throw new Error("Failed to fetch widget config");
814
- return w.pollingIntervalsSeconds = {
829
+ return b.pollingIntervalsSeconds = {
815
830
  session: ((d = l.data) == null ? void 0 : d.sessionPollingIntervalSeconds) || 10,
816
831
  sessions: ((s = l.data) == null ? void 0 : s.sessionsPollingIntervalSeconds) || 60
817
- }, new w({
832
+ }, new b({
818
833
  config: i,
819
834
  storage: a,
820
835
  modes: ((e = l.data) == null ? void 0 : e.modes) || [],
@@ -824,8 +839,8 @@ w.pollingIntervalsSeconds = null, w.initialize = async ({
824
839
  }
825
840
  });
826
841
  };
827
- let U = w;
828
- const J = {
842
+ let U = b;
843
+ const W = {
829
844
  write_a_message_placeholder: "اكتب رسالة...",
830
845
  your_issue_has_been_resolved: "تم حل مشكلتك!",
831
846
  new_conversation: "محادثة جديدة",
@@ -1065,9 +1080,9 @@ const J = {
1065
1080
  no_conversations_yet: "Henüz konuşma yok",
1066
1081
  back_to_conversations: "Konuşmalara geri dön",
1067
1082
  closed_conversations: "Kapatılan konuşmalar"
1068
- }, R = {
1083
+ }, D = {
1069
1084
  en: Q,
1070
- ar: J,
1085
+ ar: W,
1071
1086
  nl: ne,
1072
1087
  fr: se,
1073
1088
  de: Z,
@@ -1081,19 +1096,19 @@ const J = {
1081
1096
  ro: le,
1082
1097
  da: X,
1083
1098
  sv: ce
1084
- }, de = Object.keys(R);
1099
+ }, de = Object.keys(D);
1085
1100
  function pe(h) {
1086
1101
  return de.includes(h);
1087
1102
  }
1088
1103
  function fe(h, i, a) {
1089
1104
  var l;
1090
- return ((l = a == null ? void 0 : a[i]) == null ? void 0 : l[h]) || R[i][h] || "";
1105
+ return ((l = a == null ? void 0 : a[i]) == null ? void 0 : l[h]) || D[i][h] || "";
1091
1106
  }
1092
1107
  export {
1093
1108
  y as PrimitiveState,
1094
1109
  U as WidgetCtx,
1095
1110
  fe as getTranslation,
1096
- B as isExhaustive,
1111
+ H as isExhaustive,
1097
1112
  pe as isSupportedLanguage
1098
1113
  };
1099
1114
  //# sourceMappingURL=index.js.map