@opencx/widget 2.2.0 → 2.3.0

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.
Files changed (68) hide show
  1. package/README.md +30 -105
  2. package/dist/basic.cjs +3 -3
  3. package/dist/basic.cjs.map +1 -1
  4. package/dist/basic.js +10 -9
  5. package/dist/basic.js.map +1 -1
  6. package/dist/core/client/api.d.ts +21 -7
  7. package/dist/core/client/chat.d.ts +62 -0
  8. package/dist/core/client/chat.test.d.ts +1 -0
  9. package/dist/core/client/client.d.ts +6 -36
  10. package/dist/core/client/config.d.ts +35 -0
  11. package/dist/core/client/config.test.d.ts +1 -0
  12. package/dist/core/client/contact.d.ts +32 -0
  13. package/dist/core/client/contact.test.d.ts +1 -0
  14. package/dist/core/client/index.d.ts +3 -1
  15. package/dist/core/index.d.ts +6 -1
  16. package/dist/core/platform/index.d.ts +1 -10
  17. package/dist/core/types/index.d.ts +24 -2
  18. package/dist/core/types/pub-sub.d.ts +19 -82
  19. package/dist/core/types/schemas-v2.d.ts +687 -0
  20. package/dist/core/utils/create-fetch.d.ts +24 -0
  21. package/dist/index-B7LNpE9i.cjs +18 -0
  22. package/dist/index-B7LNpE9i.cjs.map +1 -0
  23. package/dist/{index-XkXeMM77.js → index-BQfnx4Er.js} +1182 -1310
  24. package/dist/index-BQfnx4Er.js.map +1 -0
  25. package/dist/index.cjs +1 -1
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.js +376 -370
  28. package/dist/index.js.map +1 -1
  29. package/dist/react-bindings/context/ChatContext.d.ts +130 -0
  30. package/dist/react-bindings/hooks/useContact.d.ts +9 -0
  31. package/dist/react-bindings/hooks/usePubsub.d.ts +3 -0
  32. package/dist/react-bindings/hooks/useSendMessage.d.ts +6 -0
  33. package/dist/react-bindings/index.d.ts +3 -0
  34. package/dist/react-lib/hooks/useAbstractChat.d.ts +42 -45
  35. package/dist/react-lib/hooks/useAxiosInstance.d.ts +37 -0
  36. package/dist/react-lib/hooks/useUploadFiles.d.ts +1 -1
  37. package/dist/react-lib/providers/ChatProvider.d.ts +54 -46
  38. package/dist/react-lib/types/index.d.ts +1 -0
  39. package/dist/react.cjs +1 -1
  40. package/dist/react.cjs.map +1 -1
  41. package/dist/react.js +2 -2
  42. package/dist/react.js.map +1 -1
  43. package/dist/schemas-BBAV6Sd_.js +122 -0
  44. package/dist/schemas-BBAV6Sd_.js.map +1 -0
  45. package/dist/schemas-wky4fpbc.cjs +2 -0
  46. package/dist/schemas-wky4fpbc.cjs.map +1 -0
  47. package/dist/src/components/dialog.d.ts +2 -2
  48. package/dist/style.css +1 -1
  49. package/dist-embed/script.js +106 -106
  50. package/dist-embed/script.js.map +1 -1
  51. package/package.json +1 -3
  52. package/dist/core/managers/chathistory-manager.d.ts +0 -61
  53. package/dist/core/managers/session-manager.d.ts +0 -35
  54. package/dist/core/transport/http.transport.d.ts +0 -17
  55. package/dist/core/transport/transport.d.ts +0 -25
  56. package/dist/core/types/transport.d.ts +0 -31
  57. package/dist/history-to-widget-messages-CP0hKjhv.js +0 -195
  58. package/dist/history-to-widget-messages-CP0hKjhv.js.map +0 -1
  59. package/dist/history-to-widget-messages-CdbZolRN.cjs +0 -2
  60. package/dist/history-to-widget-messages-CdbZolRN.cjs.map +0 -1
  61. package/dist/index-XkXeMM77.js.map +0 -1
  62. package/dist/index-xb7Pg6AD.cjs +0 -18
  63. package/dist/index-xb7Pg6AD.cjs.map +0 -1
  64. package/dist/react-lib/hooks/handle-socket-messages.d.ts +0 -27
  65. package/dist/react-lib/hooks/socket.d.ts +0 -11
  66. package/dist/react-lib/hooks/socketState.d.ts +0 -2
  67. package/dist/react-lib/hooks/useBaseClient.d.ts +0 -2
  68. package/dist/react-lib/providers/ClientProvider.d.ts +0 -7
package/dist/index.js CHANGED
@@ -1,445 +1,451 @@
1
- var y = Object.defineProperty;
2
- var f = (n) => {
3
- throw TypeError(n);
1
+ var P = Object.defineProperty;
2
+ var O = (t) => {
3
+ throw TypeError(t);
4
4
  };
5
- var w = (n, e, s) => e in n ? y(n, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : n[e] = s;
6
- var i = (n, e, s) => w(n, typeof e != "symbol" ? e + "" : e, s), m = (n, e, s) => e.has(n) || f("Cannot " + s);
7
- var a = (n, e, s) => (m(n, e, "read from private field"), s ? s.call(n) : e.get(n)), d = (n, e, s) => e.has(n) ? f("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(n) : e.set(n, s), p = (n, e, s, t) => (m(n, e, "write to private field"), t ? t.call(n, s) : e.set(n, s), s);
8
- import { S as I, A as v, m as k, g as E } from "./history-to-widget-messages-CP0hKjhv.js";
9
- class g {
10
- constructor() {
11
- i(this, "subscribers", /* @__PURE__ */ new Map());
5
+ var v = (t, e, s) => e in t ? P(t, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : t[e] = s;
6
+ var E = (t, e, s) => v(t, typeof e != "symbol" ? e + "" : e, s), U = (t, e, s) => e.has(t) || O("Cannot " + s);
7
+ var d = (t, e, s) => (U(t, e, "read from private field"), s ? s.call(t) : e.get(t)), y = (t, e, s) => e.has(t) ? O("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(t) : e.set(t, s), f = (t, e, s, r) => (U(t, e, "write to private field"), r ? r.call(t, s) : e.set(t, s), s);
8
+ import { g as w } from "./schemas-BBAV6Sd_.js";
9
+ import { A as V, M as K, b as Q, a as W, S as Y, d as Z, e as ee, c as te, f as se, s as re } from "./schemas-BBAV6Sd_.js";
10
+ var g;
11
+ class S {
12
+ constructor(e) {
13
+ E(this, "subscribers", /* @__PURE__ */ new Set());
14
+ y(this, g);
15
+ E(this, "initialState");
16
+ f(this, g, e), this.initialState = e;
12
17
  }
13
18
  /**
14
- * Subscribe to an event
15
- * @param event Event name to subscribe to
16
- * @param callback Function to call when event is published
19
+ * Subscribe to state changes
20
+ * @param callback Function to call when state changes
17
21
  * @returns Unsubscribe function
18
22
  */
19
- subscribe(e, s) {
20
- return this.subscribers.has(e) || this.subscribers.set(e, /* @__PURE__ */ new Set()), this.subscribers.get(e).add(s), () => {
21
- const t = this.subscribers.get(e);
22
- t && (t.delete(s), t.size === 0 && this.subscribers.delete(e));
23
+ subscribe(e) {
24
+ return this.subscribers.add(e), () => {
25
+ this.subscribers.delete(e);
23
26
  };
24
27
  }
25
28
  /**
26
- * Publish an event with data
27
- * @param event Event name to publish
28
- * @param data Data to send with the event
29
+ * Get the current state
29
30
  */
30
- publish(e, s) {
31
- const t = this.subscribers.get(e);
32
- t && t.forEach((r) => r(s));
31
+ getState() {
32
+ return d(this, g);
33
33
  }
34
34
  /**
35
- * Clear all subscriptions
35
+ * Set the state and notify subscribers if the state changes
36
+ * @param newState The new state to set
36
37
  */
37
- clear() {
38
- this.subscribers.clear();
38
+ setState(e) {
39
+ d(this, g) !== e && (f(this, g, e), this.subscribers.forEach((s) => s(e)));
39
40
  }
40
- }
41
- class T {
42
- constructor() {
43
- i(this, "unsubscribers", []);
41
+ setStatePartial(e) {
42
+ const s = { ...d(this, g), ...e };
43
+ this.setState(s);
44
44
  }
45
45
  /**
46
- * Add an unsubscribe function to be called during cleanup
46
+ * Clear all subscriptions
47
47
  */
48
- addUnsubscriber(e) {
49
- this.unsubscribers.push(e);
48
+ clear() {
49
+ this.subscribers.clear();
50
50
  }
51
- /**
52
- * Dispose of all subscriptions and perform cleanup
53
- */
54
- dispose() {
55
- this.unsubscribers.forEach((e) => e()), this.unsubscribers = [], this.cleanup();
51
+ reset() {
52
+ this.setState(this.initialState);
56
53
  }
57
- }
58
- class C {
59
- constructor(e) {
60
- this.options = e;
54
+ getSnapshot() {
55
+ return d(this, g);
61
56
  }
62
- async createSession() {
63
- const e = await fetch(`${this.options.apiUrl}/sessions`, {
64
- method: "POST",
65
- headers: {
66
- Authorization: `Bearer ${this.options.token}`,
67
- "Content-Type": "application/json"
68
- }
69
- });
70
- if (!e.ok)
71
- throw new Error("Failed to create session");
72
- return e.json();
57
+ get state() {
58
+ return d(this, g);
73
59
  }
74
- async fetchSession(e) {
75
- const s = await fetch(
76
- `${this.options.apiUrl}/sessions/${e}`,
77
- {
78
- headers: {
79
- Authorization: `Bearer ${this.options.token}`
60
+ }
61
+ g = new WeakMap();
62
+ function $(t) {
63
+ return new S(t);
64
+ }
65
+ const I = 1e4, T = 5e3;
66
+ function C(t) {
67
+ var e, s, r;
68
+ return t.sender.kind === "user" ? {
69
+ id: t.publicId || w(),
70
+ type: "FROM_USER",
71
+ content: t.content.text || "",
72
+ deliveredAt: ((e = t.sentAt) == null ? void 0 : e.toISOString()) || null,
73
+ attachments: t.attachments || void 0,
74
+ timestamp: (s = t.sentAt) == null ? void 0 : s.toISOString()
75
+ } : {
76
+ id: t.publicId || w(),
77
+ type: "FROM_BOT",
78
+ component: t.type,
79
+ data: {
80
+ text: t.content.text
81
+ },
82
+ timestamp: (r = t.sentAt) == null ? void 0 : r.toISOString(),
83
+ attachments: t.attachments || void 0
84
+ };
85
+ }
86
+ function A(t, e, s) {
87
+ const r = [];
88
+ return r.push(
89
+ setInterval(async () => {
90
+ const n = e.getState();
91
+ if (n != null && n.id)
92
+ try {
93
+ const a = await t.getSession(n.id);
94
+ a && e.setState(a);
95
+ } catch (a) {
96
+ console.error("Error polling session:", a);
80
97
  }
98
+ }, I)
99
+ ), r.push(
100
+ setInterval(async () => {
101
+ const n = e.getState();
102
+ if (n != null && n.id)
103
+ try {
104
+ const a = await t.getSessionHistory(n.id);
105
+ if (a) {
106
+ const l = a.map(C);
107
+ s.setStatePartial({
108
+ messages: l,
109
+ lastUpdated: Date.now()
110
+ });
111
+ }
112
+ } catch (a) {
113
+ console.error("Error polling messages:", a);
114
+ }
115
+ }, T)
116
+ ), () => r.forEach(clearInterval);
117
+ }
118
+ function L(t) {
119
+ const e = new S({
120
+ lastUpdated: null,
121
+ messages: [],
122
+ keyboard: null
123
+ }), s = new S(null);
124
+ let r = null;
125
+ async function n() {
126
+ const o = await t.api.createSession();
127
+ return s.setState(o), r || (r = A(t.api, s, e)), o;
128
+ }
129
+ async function a() {
130
+ var i;
131
+ const o = s.getState();
132
+ if (o != null && o.id)
133
+ try {
134
+ r && (r(), r = null), s.setState(null), e.setState({
135
+ lastUpdated: null,
136
+ messages: [],
137
+ keyboard: null
138
+ }), (i = t.onSessionDestroy) == null || i.call(t);
139
+ } catch (u) {
140
+ throw console.error("Error clearing session:", u), u;
81
141
  }
82
- );
83
- if (!s.ok)
84
- throw new Error("Failed to fetch session");
85
- return s.json();
86
- }
87
- async ping() {
88
- if (!(await fetch(`${this.options.apiUrl}/ping`, {
89
- headers: {
90
- Authorization: `Bearer ${this.options.token}`
91
- }
92
- })).ok)
93
- throw new Error("Failed to ping API");
94
142
  }
95
- async getMessages(e) {
96
- const s = e ? `${this.options.apiUrl}/messages/${e}` : `${this.options.apiUrl}/messages`, t = await fetch(s, {
97
- headers: {
98
- Authorization: `Bearer ${this.options.token}`
143
+ function l() {
144
+ r && (r(), r = null), e.setState({
145
+ lastUpdated: null,
146
+ messages: [],
147
+ keyboard: null
148
+ }), s.setState(null), e.clear(), s.clear();
149
+ }
150
+ return {
151
+ chatState: e,
152
+ sessionState: s,
153
+ sendMessage: async (o) => {
154
+ const i = s.getState();
155
+ if (!(i != null && i.id))
156
+ throw new Error("No active session");
157
+ const u = {
158
+ ...o,
159
+ session_id: i.id
160
+ };
161
+ try {
162
+ e.setStatePartial({
163
+ messages: [
164
+ ...e.getState().messages,
165
+ {
166
+ id: o.id || w(),
167
+ type: "FROM_USER",
168
+ content: o.content.text,
169
+ deliveredAt: (/* @__PURE__ */ new Date()).toISOString(),
170
+ attachments: o.attachments,
171
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
172
+ }
173
+ ]
174
+ }), await t.api.handleMessage(u);
175
+ } catch (m) {
176
+ throw console.error("Error sending message:", m), m;
99
177
  }
100
- });
101
- if (!t.ok)
102
- throw new Error("Failed to fetch messages");
103
- return t.json();
104
- }
105
- async sendMessage(e) {
106
- if (!(await fetch(`${this.options.apiUrl}/messages`, {
107
- method: "POST",
108
- headers: {
109
- Authorization: `Bearer ${this.options.token}`,
110
- "Content-Type": "application/json"
111
- },
112
- body: JSON.stringify(e)
113
- })).ok)
114
- throw new Error("Failed to send message");
115
- }
178
+ },
179
+ createSession: n,
180
+ clearSession: a,
181
+ cleanup: l
182
+ };
116
183
  }
117
- var o;
118
- class M extends g {
119
- constructor(s, t) {
120
- super();
121
- d(this, o, null);
122
- i(this, "clearSession", () => {
123
- if (a(this, o)) {
124
- const s = a(this, o).id;
125
- p(this, o, null), this.publish("session:closed", { sessionId: s });
184
+ function N(t) {
185
+ var l;
186
+ const e = `${t.botToken}:contact:${(l = t.user) == null ? void 0 : l.external_id}`;
187
+ let s = null;
188
+ if (t.platform.storage) {
189
+ const c = t.platform.storage.getItem(e);
190
+ if (c)
191
+ try {
192
+ s = JSON.parse(c);
193
+ } catch (o) {
194
+ console.error("Error parsing stored contact:", o);
126
195
  }
127
- });
128
- this.httpClient = s, t && this.setSession(t);
129
- }
130
- get currentSession() {
131
- return a(this, o) ? {
132
- ...a(this, o),
133
- isSessionClosed: a(this, o).status !== I.OPEN,
134
- isAssignedToAi: a(this, o).assignee_id === 555,
135
- isAssignedToHuman: a(this, o).assignee_id !== 555,
136
- isPendingHuman: a(this, o).assignee_id === 555 && a(this, o).ai_closure_type === v.handed_off
137
- } : null;
138
- }
139
- setSession(s) {
140
- p(this, o, s), this.publish("session:updated", s);
141
- }
142
- async createSession() {
143
- try {
144
- const s = await this.httpClient.createSession();
145
- return this.setSession(s), this.publish("session:created", s), s;
146
- } catch (s) {
147
- throw this.publish("session:error", { error: s }), s;
148
- }
149
- }
150
- async getOrCreateSession() {
151
- const s = this.currentSession;
152
- return s || this.createSession();
153
- }
154
- async refreshSession(s) {
155
- try {
156
- const t = await this.httpClient.fetchSession(s);
157
- if (t)
158
- return this.setSession(t), t;
159
- } catch (t) {
160
- this.publish("session:error", { error: t }), console.error("Failed to refresh session:", t);
161
- }
162
- return null;
163
- }
164
- cleanup() {
165
- p(this, o, null), this.clear();
166
- }
167
- }
168
- o = new WeakMap();
169
- class b {
170
- constructor() {
171
- i(this, "env", {
172
- platform: this.detectPlatform()
173
- });
174
- i(this, "date", {
175
- now: () => Date.now(),
176
- toISOString: (e) => new Date(e).toISOString()
177
- });
178
196
  }
179
- detectPlatform() {
180
- return typeof window < "u" ? "browser" : "server";
181
- }
182
- }
183
- var c;
184
- class _ extends g {
185
- constructor(s) {
186
- super();
187
- d(this, c, {
188
- connected: !1
189
- });
190
- this.options = s;
191
- }
192
- setState(s) {
193
- p(this, c, { ...a(this, c), ...s }), "connected" in s && this.publish("transport:status", {
194
- status: s.connected ? "connected" : "disconnected"
195
- });
196
- }
197
- isConnected() {
198
- return a(this, c).connected;
197
+ const r = new S(s);
198
+ t.platform.storage && r.subscribe((c) => {
199
+ var o, i;
200
+ c ? (o = t.platform.storage) == null || o.setItem(e, JSON.stringify(c)) : (i = t.platform.storage) == null || i.removeItem(e);
201
+ });
202
+ function n() {
203
+ const c = r.getState();
204
+ return !(c != null && c.id) && t.collectUserData ? {
205
+ should: !0,
206
+ reason: "No contact id and collectUserData is true"
207
+ } : {
208
+ should: !1
209
+ };
199
210
  }
200
- getState() {
201
- return { ...a(this, c) };
211
+ function a() {
212
+ r.clear(), r.setState(null);
202
213
  }
214
+ return {
215
+ shouldCollectData: n,
216
+ cleanup: a,
217
+ contactState: r
218
+ };
203
219
  }
204
- c = new WeakMap();
205
- class O extends _ {
206
- constructor(s, t = new b()) {
207
- super(s);
208
- i(this, "pollingInterval");
209
- this.httpOptions = s, this.platform = t;
210
- }
211
- async connect() {
212
- this.setState({ connected: !0 }), this.startPolling();
213
- }
214
- disconnect() {
215
- this.pollingInterval && clearInterval(this.pollingInterval), this.setState({ connected: !1 });
216
- }
217
- async sendMessage(s) {
218
- if (!this.isConnected()) {
219
- const t = new Error("Transport not connected");
220
- throw this.publish("transport:error", { error: t }), t;
221
- }
220
+ function k(t = {}) {
221
+ const e = [], s = [], r = [], n = async (a, l = {}) => {
222
+ let c = {
223
+ ...t,
224
+ ...l,
225
+ headers: {
226
+ ...t.headers,
227
+ ...l.headers
228
+ }
229
+ };
222
230
  try {
223
- await this.httpOptions.api.sendMessage(s);
224
- } catch (t) {
225
- throw this.publish("transport:error", { error: t }), t;
231
+ for (const m of e)
232
+ c = await m(c);
233
+ const o = c.params ? "?" + new URLSearchParams(c.params).toString() : "", i = c.baseURL ? `${c.baseURL}${a}${o}`.replace(/([^:]\/)\/+/g, "$1") : `${a}${o}`;
234
+ let u = await fetch(i, c);
235
+ for (const m of s)
236
+ u = await m(u);
237
+ return u;
238
+ } catch (o) {
239
+ let i = o;
240
+ for (const u of r)
241
+ i = await u(i);
242
+ throw i;
226
243
  }
227
- }
228
- startPolling() {
229
- this.pollingInterval && clearInterval(this.pollingInterval), this.pollingInterval = setInterval(async () => {
230
- if (this.isConnected())
231
- try {
232
- const s = await this.httpOptions.sessionManager.getOrCreateSession();
233
- (await this.httpOptions.api.getMessages(s.id)).forEach((r) => {
234
- this.publish("transport:message:received", r);
235
- });
236
- } catch (s) {
237
- this.publish("transport:error", { error: s });
238
- }
239
- }, this.httpOptions.pollingInterval);
240
- }
244
+ };
245
+ return n.interceptors = {
246
+ request: {
247
+ use: (a) => (e.push(a), e.length - 1),
248
+ eject: (a) => {
249
+ e.splice(a, 1);
250
+ }
251
+ },
252
+ response: {
253
+ use: (a, l) => (s.push(a), l && r.push(l), s.length - 1),
254
+ eject: (a) => {
255
+ s.splice(a, 1), r.splice(a, 1);
256
+ }
257
+ }
258
+ }, n;
241
259
  }
242
- class U extends T {
243
- constructor(s, t = new b()) {
244
- super();
245
- i(this, "messagingTransport");
246
- i(this, "options");
247
- i(this, "api");
248
- i(this, "session");
249
- i(this, "events", new g());
250
- i(this, "messages", []);
251
- i(this, "keyboard", null);
252
- i(this, "pollingInterval");
253
- i(this, "heartbeatInterval");
254
- this.platform = t, this.options = {
255
- ...s,
256
- apiUrl: s.apiUrl ?? "https://api-v2.opencopilot.so/backend",
257
- socketUrl: s.socketUrl ?? "https://api-v2.opencopilot.so",
258
- transport: s.transport ?? "socket",
259
- pollingInterval: s.pollingInterval ?? 3e3,
260
- headers: {
261
- "X-Bot-Token": s.token,
262
- ...s.headers
263
- },
264
- queryParams: {},
265
- pathParams: {},
266
- bot: {},
267
- debug: !1,
268
- language: "en",
269
- user: {}
270
- }, this.api = new C({
271
- apiUrl: this.options.apiUrl,
272
- token: this.options.token
273
- }), this.session = new M(this.api), this.initializeTransport(), this.startMessagePolling(), this.startHeartbeat();
274
- }
275
- startMessagePolling() {
276
- this.pollingInterval && clearInterval(this.pollingInterval), this.pollingInterval = setInterval(async () => {
277
- const s = this.session.currentSession;
278
- if (!s) return;
279
- const t = this.messages[this.messages.length - 1];
280
- if (t != null && t.timestamp)
281
- try {
282
- const r = await this.api.getMessages(s.id);
283
- if (r && r.length > 0) {
284
- const l = r.map((h) => ({
285
- message: h.content.text,
286
- type: "message",
287
- publicId: h.id,
288
- agent_avatar: null,
289
- agent_id: null,
290
- agent_name: null,
291
- created_at: h.timestamp,
292
- from_user: !1,
293
- handoff_happened_during_office_hours: !1,
294
- session_id: h.session_id,
295
- updated_at: null,
296
- attachments: h.attachments
297
- }));
298
- this.appendMessages(k(l));
299
- }
300
- } catch (r) {
301
- console.error("Error polling messages:", r), this.events.publish("client:error", r);
302
- }
303
- }, 20 * 1e3);
304
- }
305
- startHeartbeat() {
306
- this.heartbeatInterval && clearInterval(this.heartbeatInterval);
307
- const s = async () => {
308
- this.session.currentSession;
309
- };
310
- s(), this.heartbeatInterval = setInterval(s, 50 * 1e3);
311
- }
312
- appendMessages(s) {
313
- const t = s.filter(
314
- (r) => !this.messages.some((l) => l.id === r.id)
315
- );
316
- this.messages.push(...t);
317
- }
318
- handleIncomingMessage(s) {
319
- this.messages.push(s), this.refreshSession();
320
- }
321
- async refreshSession() {
322
- this.session.currentSession && await this.session.getOrCreateSession();
323
- }
324
- initializeTransport() {
325
- const s = {
326
- api: this.api,
327
- sessionManager: this.session,
328
- coreOptions: this.options
260
+ var h;
261
+ class _ {
262
+ constructor(e) {
263
+ y(this, h);
264
+ this.options = e;
265
+ const s = this.options.coreOptions.user, r = {
266
+ claim: "",
267
+ value: ""
329
268
  };
330
- this.options.transport === "http" && (this.messagingTransport = new O(
331
- {
332
- ...s,
333
- pollingInterval: this.options.pollingInterval
334
- },
335
- this.platform
336
- ));
337
- }
338
- async sendMessage({
339
- content: s,
340
- user: t,
341
- ...r
342
- }) {
343
- const l = await this.session.getOrCreateSession(), h = E(), S = {
344
- type: "FROM_USER",
345
- id: h,
346
- content: s.text,
347
- user: t,
348
- deliveredAt: null,
349
- attachments: r.attachments
269
+ s != null && s.email ? (r.claim = "email", r.value = s.email) : s != null && s.phone && (r.claim = "phone", r.value = s.phone);
270
+ const n = {
271
+ "X-Bot-Token": this.options.token,
272
+ "X-Consumer-Id": `${r.claim}:${r.value}`
350
273
  };
351
- this.messages.push(S), this.keyboard && this.setKeyboard(null), await this.messagingTransport.sendMessage({
352
- id: h,
353
- content: { text: s.text },
354
- session_id: l.id,
355
- bot_token: this.options.token,
356
- headers: this.options.headers,
357
- pathParams: this.options.pathParams,
358
- queryParams: this.options.queryParams,
359
- user: t,
360
- language: r.language ?? this.options.language,
361
- attachments: r.attachments,
362
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
363
- });
364
- }
365
- setKeyboard(s) {
366
- this.keyboard = s;
274
+ this.options.coreOptions.contactToken && (n.Authorization = `Bearer ${this.options.coreOptions.contactToken}`), f(this, h, k({
275
+ baseURL: `${this.options.apiUrl}/widget/v2`,
276
+ headers: n
277
+ }));
367
278
  }
368
- handleKeyboardOption(s) {
369
- this.sendMessage({
370
- content: { text: s }
371
- }), this.setKeyboard(null);
279
+ async me() {
280
+ return (await d(this, h).call(this, "/me")).json();
372
281
  }
373
- getMessages() {
374
- return this.messages;
282
+ async widgetPrelude() {
283
+ return (await d(this, h).call(this, "/prelude")).json();
375
284
  }
376
- clearChat() {
377
- this.messages = [], this.keyboard = null, this.session.clearSession();
378
- }
379
- async connect() {
380
- await this.messagingTransport.connect();
285
+ async handleMessage(e) {
286
+ return (await d(this, h).call(this, "/chat/send", {
287
+ method: "POST",
288
+ body: JSON.stringify(e)
289
+ })).json();
381
290
  }
382
- async disconnect() {
383
- this.messagingTransport.disconnect();
291
+ async getSessionHistory(e, s) {
292
+ const r = new URLSearchParams({
293
+ lastMessageTimestamp: s || ""
294
+ }), n = `/session/history/${e}?${r.toString()}`;
295
+ return (await d(this, h).call(this, n, {
296
+ method: "GET"
297
+ })).json();
384
298
  }
385
- setTransport(s) {
386
- this.messagingTransport.disconnect(), this.messagingTransport = s, this.connect();
299
+ async createSession() {
300
+ return (await d(this, h).call(this, "/create-session", {
301
+ method: "POST"
302
+ })).json();
387
303
  }
388
- get state() {
389
- return {
390
- connected: this.messagingTransport.isConnected(),
391
- session: this.session.currentSession,
392
- messages: this.messages,
393
- keyboard: this.keyboard
394
- };
304
+ async getSession(e) {
305
+ return (await d(this, h).call(this, `/session/${e}`, {
306
+ method: "GET"
307
+ })).json();
395
308
  }
396
- cleanup() {
397
- this.pollingInterval && clearInterval(this.pollingInterval), this.heartbeatInterval && clearInterval(this.heartbeatInterval), this.messagingTransport.disconnect(), this.session.clear(), this.events.clear(), this.messages = [], this.keyboard = null;
309
+ async createContact(e) {
310
+ return (await d(this, h).call(this, "/contact/upsert", {
311
+ method: "POST",
312
+ body: JSON.stringify(e)
313
+ })).json();
398
314
  }
399
315
  }
400
- class u extends Error {
316
+ h = new WeakMap();
317
+ class p extends Error {
401
318
  constructor(e) {
402
319
  super(e), this.name = "OpenCXError";
403
320
  }
404
321
  }
405
- class $ extends u {
322
+ class R extends p {
406
323
  constructor(e = "Connection failed") {
407
324
  super(e), this.name = "ConnectionError";
408
325
  }
409
326
  }
410
- class F extends u {
327
+ class j extends p {
411
328
  constructor(e = "Authentication failed") {
412
329
  super(e), this.name = "AuthenticationError";
413
330
  }
414
331
  }
415
- class P extends u {
332
+ class x extends p {
416
333
  constructor(e = "Session error occurred") {
417
334
  super(e), this.name = "SessionError";
418
335
  }
419
336
  }
420
- class z extends P {
337
+ class q extends x {
421
338
  constructor(e = "Session not defined") {
422
339
  super(e), this.name = "SessionNotDefinedError";
423
340
  }
424
341
  }
425
- class H extends u {
342
+ class B extends p {
426
343
  constructor(e = "Transport error occurred") {
427
344
  super(e), this.name = "TransportError";
428
345
  }
429
346
  }
430
- class B extends u {
347
+ class H extends p {
431
348
  constructor(e = "File upload failed") {
432
349
  super(e), this.name = "FileUploadError";
433
350
  }
434
351
  }
352
+ function G() {
353
+ return {
354
+ env: {
355
+ platform: typeof window < "u" ? "browser" : "server"
356
+ },
357
+ date: {
358
+ now: () => Date.now(),
359
+ toISOString: (e) => new Date(e).toISOString()
360
+ }
361
+ };
362
+ }
363
+ const D = {
364
+ messageArrived: "https://cloud.opencopilot.so/sfx/notification3.mp3"
365
+ }, b = {
366
+ headerStyle: "basic",
367
+ primaryColor: "hsl(211,65%,59%)",
368
+ triggerOffset: "20px"
369
+ };
370
+ function X(t) {
371
+ var s, r, n, a, l, c, o, i, u, m;
372
+ const e = {
373
+ ...t,
374
+ apiUrl: t.apiUrl ?? "https://api-v2.opencopilot.so/backend",
375
+ socketUrl: t.socketUrl ?? "https://api-v2.opencopilot.so",
376
+ transport: t.transport ?? "socket",
377
+ pollingInterval: t.pollingInterval ?? 3e3,
378
+ headers: {
379
+ ...t.headers ?? {},
380
+ "X-Bot-Token": t.token
381
+ },
382
+ queryParams: t.queryParams ?? {},
383
+ pathParams: t.pathParams ?? {},
384
+ bot: {
385
+ name: ((s = t.bot) == null ? void 0 : s.name) ?? "Bot",
386
+ avatarUrl: (r = t.bot) == null ? void 0 : r.avatarUrl,
387
+ id: ((n = t.bot) == null ? void 0 : n.id) ?? null,
388
+ is_ai: ((a = t.bot) == null ? void 0 : a.is_ai) ?? !0
389
+ },
390
+ contactToken: t.contactToken,
391
+ debug: t.debug ?? !1,
392
+ language: t.language ?? "en",
393
+ user: t.user ?? {},
394
+ soundEffectFiles: {
395
+ messageArrived: ((l = t.soundEffectFiles) == null ? void 0 : l.messageArrived) ?? D.messageArrived
396
+ },
397
+ theme: {
398
+ headerStyle: ((c = t.theme) == null ? void 0 : c.headerStyle) ?? b.headerStyle,
399
+ primaryColor: ((o = t.theme) == null ? void 0 : o.primaryColor) ?? b.primaryColor,
400
+ triggerOffset: ((i = t.theme) == null ? void 0 : i.triggerOffset) ?? b.triggerOffset
401
+ },
402
+ settings: {
403
+ persistSession: ((u = t.settings) == null ? void 0 : u.persistSession) ?? !1,
404
+ useSoundEffects: ((m = t.settings) == null ? void 0 : m.useSoundEffects) ?? !1
405
+ }
406
+ };
407
+ return {
408
+ getConfig: () => e,
409
+ getApiConfig: () => ({
410
+ apiUrl: e.apiUrl,
411
+ token: e.token,
412
+ headers: e.headers,
413
+ queryParams: e.queryParams,
414
+ pathParams: e.pathParams
415
+ }),
416
+ getBotConfig: () => e.bot,
417
+ getThemeConfig: () => e.theme,
418
+ getSettings: () => e.settings,
419
+ getSoundEffects: () => e.soundEffectFiles,
420
+ getUser: () => e.user,
421
+ getLanguage: () => e.language,
422
+ getDebugMode: () => e.debug
423
+ };
424
+ }
435
425
  export {
436
- U as ApiClient,
437
- F as AuthenticationError,
438
- $ as ConnectionError,
439
- B as FileUploadError,
440
- u as OpenCXError,
441
- P as SessionError,
442
- z as SessionNotDefinedError,
443
- H as TransportError
426
+ V as AIClosureType,
427
+ _ as ApiCaller,
428
+ j as AuthenticationError,
429
+ R as ConnectionError,
430
+ H as FileUploadError,
431
+ K as MessageTypeEnum,
432
+ p as OpenCXError,
433
+ S as PubSub,
434
+ Q as SentimentEnum,
435
+ W as SessionChannel,
436
+ x as SessionError,
437
+ q as SessionNotDefinedError,
438
+ Y as SessionStatus,
439
+ B as TransportError,
440
+ Z as chatAttachmentSchema,
441
+ ee as chatHistoryMessageSchema,
442
+ te as chatSessionSchema,
443
+ se as consumerSchema,
444
+ L as createChat,
445
+ X as createConfig,
446
+ N as createContact,
447
+ G as createDefaultPlatform,
448
+ $ as createPubSub,
449
+ re as structuredSocketMessageSchema
444
450
  };
445
451
  //# sourceMappingURL=index.js.map