@botpress/webchat-client 0.2.0 → 0.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.
@@ -1,5 +1,5 @@
1
1
 
2
- > @botpress/webchat-client@0.2.0 build /home/runner/work/genisys/genisys/packages/webchat-client
2
+ > @botpress/webchat-client@0.3.0 build /home/runner/work/genisys/genisys/packages/webchat-client
3
3
  > openapi-ts && vite build
4
4
 
5
5
  ⏳ Generating from raw OpenAPI specification
@@ -11,19 +11,19 @@ rendering chunks...
11
11
 
12
12
  [vite:dts] Start generate declaration files...
13
13
  computing gzip size...
14
- dist/webchat-client.js  0.17 kB │ gzip: 0.13 kB
15
14
  dist/webchat-client8.js  0.19 kB │ gzip: 0.16 kB
15
+ dist/webchat-client.js  0.21 kB │ gzip: 0.14 kB
16
16
  dist/webchat-client4.js  0.29 kB │ gzip: 0.18 kB
17
17
  dist/webchat-client6.js  0.30 kB │ gzip: 0.22 kB
18
18
  dist/webchat-client7.js  0.45 kB │ gzip: 0.26 kB
19
19
  dist/webchat-client9.js  2.63 kB │ gzip: 1.15 kB
20
20
  dist/webchat-client3.js  3.30 kB │ gzip: 0.58 kB
21
- dist/webchat-client2.js  4.75 kB │ gzip: 1.31 kB
21
+ dist/webchat-client2.js  5.31 kB │ gzip: 1.50 kB
22
22
  dist/webchat-client10.js  8.58 kB │ gzip: 2.91 kB
23
23
  dist/webchat-client5.js 10.93 kB │ gzip: 3.47 kB
24
24
  [vite:dts] Start rollup declaration files...
25
25
  Analysis will use the bundled TypeScript version 5.4.2
26
26
  *** The target project appears to use TypeScript 5.6.2 which is newer than the bundled compiler engine; consider upgrading API Extractor.
27
- [vite:dts] Declaration files built in 5323ms.
27
+ [vite:dts] Declaration files built in 4849ms.
28
28
 
29
- ✓ built in 5.65s
29
+ ✓ built in 5.14s
package/dist/index.d.ts CHANGED
@@ -196,7 +196,7 @@ export declare type Client = {
196
196
  addMessageFeedback: (params: MessageIdParam & ClientTypes_2.AddMessageFeedbackBody) => Promise<ClientTypes_2.AddMessageFeedbackResponse>;
197
197
  removeMessageFeedback: (params: MessageIdParam) => Promise<ClientTypes_2.RemoveMessageFeedbackResponse>;
198
198
  generateUserKey: (params: ClientTypes_2.GenerateUserKeyBody & {
199
- adminKey: string;
199
+ adminSecret: string;
200
200
  }) => Promise<ClientTypes_2.GenerateUserKeyResponse>;
201
201
  };
202
202
 
@@ -356,6 +356,11 @@ declare namespace ClientTypes_2 {
356
356
  CreateFileError,
357
357
  CreateFileResponses,
358
358
  CreateFileResponse,
359
+ InitializeConversationData,
360
+ InitializeConversationErrors,
361
+ InitializeConversationError,
362
+ InitializeConversationResponses,
363
+ InitializeConversationResponse,
359
364
  ClientOptions,
360
365
  Options,
361
366
  deleteConversation,
@@ -382,7 +387,8 @@ declare namespace ClientTypes_2 {
382
387
  generateUserKey_2 as generateUserKey,
383
388
  getEvent,
384
389
  createEvent,
385
- createFile
390
+ createFile,
391
+ initializeConversation
386
392
  }
387
393
  }
388
394
 
@@ -888,10 +894,10 @@ export declare type CreateMessageResponses = {
888
894
  };
889
895
  };
890
896
 
891
- export declare const createUser: ({ clientId, apiUrl, adminKey, }: {
897
+ export declare const createUser: ({ clientId, apiUrl, adminSecret, }: {
892
898
  clientId: string;
893
899
  apiUrl?: string;
894
- adminKey?: string;
900
+ adminSecret?: string;
895
901
  }) => Promise<{
896
902
  user: ClientTypes_2.User;
897
903
  key: string;
@@ -935,7 +941,7 @@ export declare type CreateUserData = {
935
941
  /**
936
942
  * Admin Key for managing users
937
943
  */
938
- 'x-admin-key'?: string;
944
+ 'x-admin-secret'?: string;
939
945
  };
940
946
  path?: never;
941
947
  query?: never;
@@ -1186,8 +1192,8 @@ declare type File_2 = {
1186
1192
  };
1187
1193
  export { File_2 as File }
1188
1194
 
1189
- export declare const generateUserKey: ({ adminKey, expiresAt, userId, apiUrl, clientId, }: {
1190
- adminKey: string;
1195
+ export declare const generateUserKey: ({ adminSecret, expiresAt, userId, apiUrl, clientId, }: {
1196
+ adminSecret: string;
1191
1197
  expiresAt: number;
1192
1198
  userId: string;
1193
1199
  apiUrl?: string;
@@ -1228,7 +1234,7 @@ export declare type GenerateUserKeyData = {
1228
1234
  /**
1229
1235
  * Admin Key for managing users
1230
1236
  */
1231
- 'x-admin-key'?: string;
1237
+ 'x-admin-secret'?: string;
1232
1238
  };
1233
1239
  path?: never;
1234
1240
  query?: never;
@@ -1501,6 +1507,78 @@ export declare type GetUserResponses = {
1501
1507
  };
1502
1508
  };
1503
1509
 
1510
+ declare type Initialize = {
1511
+ type: 'init';
1512
+ data: {
1513
+ conversation: GetConversationResponse['conversation'];
1514
+ messages: ListConversationMessagesResponse['messages'];
1515
+ participants: ListParticipantsResponse['participants'];
1516
+ user: GetUserResponse['user'] & {
1517
+ userKey?: string;
1518
+ };
1519
+ };
1520
+ };
1521
+
1522
+ export declare const initialize: ({ conversationId, userToken, clientId, apiUrl, }: {
1523
+ conversationId?: string;
1524
+ userToken?: string;
1525
+ apiUrl?: string;
1526
+ clientId: string;
1527
+ }) => <U extends "custom" | "error" | "message_created" | "message_updated" | "typing_started" | "typing_stopped" | "webchat_config" | "webchat_visibility" | "participant_added" | "participant_removed" | "message_status_changed" | "init" | "open">(event: U, callback: (args: Record<"custom" | "error" | "message_created" | "message_updated" | "typing_started" | "typing_stopped" | "webchat_config" | "webchat_visibility" | "participant_added" | "participant_removed" | "message_status_changed" | "init" | "open", any>[U]) => void) => () => void;
1528
+
1529
+ /**
1530
+ * Creates a SSE stream to receive messages and events. The first event will be a payload containing the conversation details.
1531
+ */
1532
+ declare const initializeConversation: <ThrowOnError extends boolean = false>(options?: Options<InitializeConversationData, ThrowOnError>) => RequestResult<{
1533
+ [key: string]: never;
1534
+ }, {
1535
+ [key: string]: never;
1536
+ }, ThrowOnError>;
1537
+
1538
+ export declare type InitializeConversationData = {
1539
+ body?: never;
1540
+ headers?: {
1541
+ /**
1542
+ * Authentication Key
1543
+ */
1544
+ 'x-user-key'?: string;
1545
+ };
1546
+ path?: never;
1547
+ query?: {
1548
+ /**
1549
+ * User id (if not provided with a user key a new user will be created)
1550
+ */
1551
+ userId?: string;
1552
+ /**
1553
+ * Conversation id
1554
+ */
1555
+ conversationId?: string;
1556
+ };
1557
+ url: '/initialize';
1558
+ };
1559
+
1560
+ export declare type InitializeConversationError = InitializeConversationErrors[keyof InitializeConversationErrors];
1561
+
1562
+ export declare type InitializeConversationErrors = {
1563
+ /**
1564
+ * Returns nothing but a stream
1565
+ */
1566
+ default: {
1567
+ [key: string]: never;
1568
+ };
1569
+ };
1570
+
1571
+ export declare type InitializeConversationResponse = InitializeConversationResponses[keyof InitializeConversationResponses];
1572
+
1573
+ export declare type InitializeConversationResponses = {
1574
+ /**
1575
+ * Returns nothing but a stream
1576
+ */
1577
+ 200: {
1578
+ [key: string]: never;
1579
+ };
1580
+ };
1581
+
1504
1582
  export declare type IntegrationError = {
1505
1583
  id: string;
1506
1584
  code: number;
@@ -2827,7 +2905,7 @@ declare interface SerializerOptions<T> {
2827
2905
  style: T;
2828
2906
  }
2829
2907
 
2830
- declare type Signal = MessageCreated | MessageUpdated | WebchatVisibility | WebchatConfig | Custom | TypingStarted | TypingStopped | ParticipantAdded | ParticipantRemoved | MessageStatusChanged;
2908
+ declare type Signal = MessageCreated | MessageUpdated | WebchatVisibility | WebchatConfig | Custom | TypingStarted | TypingStopped | ParticipantAdded | ParticipantRemoved | MessageStatusChanged | Initialize;
2831
2909
 
2832
2910
  declare interface TDataShape {
2833
2911
  body?: unknown;
@@ -1,6 +1,7 @@
1
- import { createClient as t, createUser as a, generateUserKey as c } from "./webchat-client2.js";
1
+ import { createClient as t, createUser as i, generateUserKey as a, initialize as n } from "./webchat-client2.js";
2
2
  export {
3
3
  t as createClient,
4
- a as createUser,
5
- c as generateUserKey
4
+ i as createUser,
5
+ a as generateUserKey,
6
+ n as initialize
6
7
  };
@@ -1,111 +1,130 @@
1
- import { createUser as U, generateUserKey as y, removeMessageFeedback as M, addMessageFeedback as b, getEvent as $, createEvent as R, deleteUser as P, updateUser as k, getUser as T, createFile as _, deleteMessage as x, getMessage as F, updateMessage as I, createMessage as S, listParticipants as A, getParticipant as q, removeParticipant as w, addParticipant as K, listConversationMessages as N, listConversations as J, deleteConversation as L, getConversation as O, createConversation as V } from "./webchat-client3.js";
2
- import { client as i } from "./webchat-client4.js";
3
- import { EventSource as X } from "./webchat-client5.js";
4
- import { throwErrorInterceptor as E } from "./webchat-client6.js";
5
- import { createEventEmitter as Y } from "./webchat-client7.js";
6
- const n = (a) => a.data, v = {
1
+ import { createUser as f, generateUserKey as U, removeMessageFeedback as x, addMessageFeedback as F, getEvent as T, createEvent as k, deleteUser as R, updateUser as S, getUser as w, createFile as I, deleteMessage as K, getMessage as _, updateMessage as q, createMessage as N, listParticipants as O, getParticipant as z, removeParticipant as A, addParticipant as J, listConversationMessages as D, listConversations as L, deleteConversation as V, getConversation as X, createConversation as Y } from "./webchat-client3.js";
2
+ import { client as l } from "./webchat-client4.js";
3
+ import { EventSource as j } from "./webchat-client5.js";
4
+ import { throwErrorInterceptor as y } from "./webchat-client6.js";
5
+ import { createEventEmitter as C } from "./webchat-client7.js";
6
+ const r = (a) => a.data, b = 10, E = 3e3, B = "60000", m = {
7
7
  throwOnError: !0
8
- }, W = async ({
8
+ }, ee = async ({
9
9
  clientId: a,
10
- apiUrl: p,
11
- adminKey: c
10
+ apiUrl: o,
11
+ adminSecret: i
12
12
  }) => {
13
- const t = `${p || i.getConfig().baseUrl}/${a}`;
14
- i.interceptors.response._fns.length === 0 && i.interceptors.response.use(E);
15
- const d = {
16
- ...v,
13
+ const t = `${o || l.getConfig().baseUrl}/${a}`;
14
+ l.interceptors.response._fns.length === 0 && l.interceptors.response.use(y);
15
+ const c = {
16
+ ...m,
17
17
  baseUrl: t
18
18
  };
19
- return U({
20
- ...d,
19
+ return f({
20
+ ...c,
21
21
  body: {},
22
- headers: c ? { "x-admin-key": c } : void 0
23
- }).then(n);
24
- }, Z = async ({
25
- adminKey: a,
26
- expiresAt: p,
27
- userId: c,
22
+ headers: i ? { "x-admin-secret": i } : void 0
23
+ }).then(r);
24
+ }, te = ({
25
+ conversationId: a,
26
+ userToken: o,
27
+ clientId: i,
28
+ apiUrl: t
29
+ }) => {
30
+ let c = 0, n = null;
31
+ const p = C(), e = () => {
32
+ n && n.close();
33
+ const d = `${`${t || l.getConfig().baseUrl}/${i}`}/initialize${a ? `?conversationId=${a}` : ""}`;
34
+ n = M(d, o ? { "x-user-token": o } : {}), n.onopen = () => p.emit("open"), n.onerror = (h) => {
35
+ c < b ? (c++, setTimeout(() => e(), E)) : p.emit("error", h);
36
+ }, n.onmessage = (h) => {
37
+ const g = $(h.data);
38
+ p.emit(g.type, g.data);
39
+ };
40
+ };
41
+ return e(), p.on;
42
+ }, ne = async ({
43
+ adminSecret: a,
44
+ expiresAt: o,
45
+ userId: i,
28
46
  apiUrl: t,
29
- clientId: d
47
+ clientId: c
30
48
  }) => {
31
- const s = { "x-admin-key": a }, m = `${t || i.getConfig().baseUrl}/${d}`, e = {
32
- ...v,
33
- baseUrl: m
49
+ const n = { "x-admin-secret": a }, p = `${t || l.getConfig().baseUrl}/${c}`, e = {
50
+ ...m,
51
+ baseUrl: p
34
52
  };
35
- return y({ ...e, headers: s, body: { id: c, expiresAt: p } }).then(n);
36
- }, ee = ({
53
+ return U({ ...e, headers: n, body: { id: i, expiresAt: o } }).then(r);
54
+ }, re = ({
37
55
  userKey: a,
38
- clientId: p,
39
- apiUrl: c
56
+ clientId: o,
57
+ apiUrl: i
40
58
  }) => {
41
59
  const t = {
42
60
  "x-user-key": a
43
- }, d = `${c || i.getConfig().baseUrl}/${p}`, s = {
44
- ...v,
45
- baseUrl: d
61
+ }, c = `${i || l.getConfig().baseUrl}/${o}`, n = {
62
+ ...m,
63
+ baseUrl: c
46
64
  };
47
- return i.interceptors.response._fns.length === 0 && i.interceptors.response.use(E), {
48
- createConversation: () => V({ ...s, headers: t, body: {} }).then(n),
49
- getConversation: ({ conversationId: e }) => O({ ...s, headers: t, path: { id: e } }).then(n),
50
- deleteConversation: ({ conversationId: e }) => L({ ...s, headers: t, path: { id: e } }).then(n),
51
- listConversations: ({ nextToken: e }) => J({ ...s, headers: t, query: { nextToken: e } }).then(n),
52
- listConversationMessages: ({ conversationId: e, nextToken: r }) => N({
53
- ...s,
65
+ return l.interceptors.response._fns.length === 0 && l.interceptors.response.use(y), {
66
+ createConversation: () => Y({ ...n, headers: t, body: {} }).then(r),
67
+ getConversation: ({ conversationId: e }) => X({ ...n, headers: t, path: { id: e } }).then(r),
68
+ deleteConversation: ({ conversationId: e }) => V({ ...n, headers: t, path: { id: e } }).then(r),
69
+ listConversations: ({ nextToken: e }) => L({ ...n, headers: t, query: { nextToken: e } }).then(r),
70
+ listConversationMessages: ({ conversationId: e, nextToken: s }) => D({
71
+ ...n,
54
72
  headers: t,
55
73
  path: { id: e },
56
- query: { nextToken: r }
57
- }).then(n),
58
- addParticipant: ({ conversationId: e, userId: r }) => K({ ...s, headers: t, path: { id: e }, body: { userId: r } }).then(n),
59
- removeParticipant: ({ conversationId: e, userId: r }) => w({ ...s, headers: t, path: { id: e, userId: r } }).then(n),
60
- getParticipant: ({ conversationId: e, userId: r }) => q({ ...s, headers: t, path: { id: e, userId: r } }).then(n),
61
- listParticipants: ({ conversationId: e, nextToken: r }) => A({ ...s, headers: t, path: { id: e }, query: { nextToken: r } }).then(n),
62
- createMessage: (e) => S({ ...s, headers: t, body: e }).then(n),
63
- updateMessage: ({ messageId: e, ...r }) => I({ ...s, headers: t, path: { id: e }, body: r }).then(n),
64
- getMessage: ({ messageId: e }) => F({ ...s, headers: t, path: { id: e } }).then(n),
65
- deleteMessage: ({ messageId: e }) => x({ ...s, headers: t, path: { id: e } }).then(n),
66
- createFile: (e) => _({ ...s, headers: t, body: e }).then(n),
67
- createUser: (e) => U({ ...s, headers: t, body: e }).then(n),
68
- getUser: () => T({ ...s, headers: t }).then(n),
69
- updateUser: (e) => k({ ...s, headers: t, body: e }).then(n),
70
- deleteUser: () => P({ ...s, headers: t }).then(n),
71
- createEvent: (e) => R({ ...s, headers: t, body: e }).then(n),
72
- getEvent: ({ eventId: e }) => $({ ...s, headers: t, path: { id: e } }).then(n),
73
- addMessageFeedback: ({ messageId: e, ...r }) => b({ ...s, headers: t, path: { id: e }, body: r }).then(n),
74
- removeMessageFeedback: ({ messageId: e }) => M({ ...s, headers: t, path: { id: e } }).then(n),
75
- generateUserKey: ({ adminKey: e, ...r }) => y({ ...s, headers: { "x-admin-key": e }, body: r }).then(n),
74
+ query: { nextToken: s }
75
+ }).then(r),
76
+ addParticipant: ({ conversationId: e, userId: s }) => J({ ...n, headers: t, path: { id: e }, body: { userId: s } }).then(r),
77
+ removeParticipant: ({ conversationId: e, userId: s }) => A({ ...n, headers: t, path: { id: e, userId: s } }).then(r),
78
+ getParticipant: ({ conversationId: e, userId: s }) => z({ ...n, headers: t, path: { id: e, userId: s } }).then(r),
79
+ listParticipants: ({ conversationId: e, nextToken: s }) => O({ ...n, headers: t, path: { id: e }, query: { nextToken: s } }).then(r),
80
+ createMessage: (e) => N({ ...n, headers: t, body: e }).then(r),
81
+ updateMessage: ({ messageId: e, ...s }) => q({ ...n, headers: t, path: { id: e }, body: s }).then(r),
82
+ getMessage: ({ messageId: e }) => _({ ...n, headers: t, path: { id: e } }).then(r),
83
+ deleteMessage: ({ messageId: e }) => K({ ...n, headers: t, path: { id: e } }).then(r),
84
+ createFile: (e) => I({ ...n, headers: t, body: e }).then(r),
85
+ createUser: (e) => f({ ...n, headers: t, body: e }).then(r),
86
+ getUser: () => w({ ...n, headers: t }).then(r),
87
+ updateUser: (e) => S({ ...n, headers: t, body: e }).then(r),
88
+ deleteUser: () => R({ ...n, headers: t }).then(r),
89
+ createEvent: (e) => k({ ...n, headers: t, body: e }).then(r),
90
+ getEvent: ({ eventId: e }) => T({ ...n, headers: t, path: { id: e } }).then(r),
91
+ addMessageFeedback: ({ messageId: e, ...s }) => F({ ...n, headers: t, path: { id: e }, body: s }).then(r),
92
+ removeMessageFeedback: ({ messageId: e }) => x({ ...n, headers: t, path: { id: e } }).then(r),
93
+ generateUserKey: ({ adminSecret: e, ...s }) => U({ ...n, headers: { "x-admin-secret": e }, body: s }).then(r),
76
94
  listenConversation: ({ conversationId: e }) => {
77
- let u = 0, h = null;
78
- const l = Y(), f = () => {
79
- h && h.close();
80
- const C = `${d}/conversations/${e}/listen`;
81
- h = new X(C, {
82
- fetch: (g, o) => fetch(g, {
83
- ...o,
84
- headers: {
85
- ...o == null ? void 0 : o.headers,
86
- ...t,
87
- timeout: "60_000"
88
- }
89
- })
90
- }), h.onopen = () => l.emit("open"), h.onerror = (g) => {
91
- u < 10 ? (u++, setTimeout(() => f(), 3e3)) : l.emit("error", g);
92
- }, h.onmessage = (g) => {
93
- const o = D(g.data);
94
- l.emit(o.type, o.data);
95
+ let s = 0, d = null;
96
+ const h = C(), g = () => {
97
+ d && d.close();
98
+ const P = `${c}/conversations/${e}/listen`;
99
+ d = M(P, t), d.onopen = () => h.emit("open"), d.onerror = (u) => {
100
+ s < b ? (s++, setTimeout(() => g(), E)) : h.emit("error", u);
101
+ }, d.onmessage = (u) => {
102
+ const v = $(u.data);
103
+ h.emit(v.type, v.data);
95
104
  };
96
105
  };
97
- return f(), l.on;
106
+ return g(), h.on;
98
107
  }
99
108
  };
100
- }, D = (a) => {
109
+ }, $ = (a) => {
101
110
  try {
102
111
  return JSON.parse(a);
103
112
  } catch {
104
113
  return a;
105
114
  }
106
- };
115
+ }, M = (a, o) => new j(a, {
116
+ fetch: (i, t) => fetch(i, {
117
+ ...t,
118
+ headers: {
119
+ ...t == null ? void 0 : t.headers,
120
+ ...o,
121
+ timeout: B
122
+ }
123
+ })
124
+ });
107
125
  export {
108
- ee as createClient,
109
- W as createUser,
110
- Z as generateUserKey
126
+ re as createClient,
127
+ ee as createUser,
128
+ ne as generateUserKey,
129
+ te as initialize
111
130
  };
package/package.json CHANGED
@@ -1,15 +1,18 @@
1
1
  {
2
2
  "name": "@botpress/webchat-client",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "",
5
5
  "main": "src/index.ts",
6
6
  "type": "module",
7
7
  "sideEffects": false,
8
+ "repository": {
9
+ "url": "https://github.com/botpress/genisys"
10
+ },
8
11
  "scripts": {
9
12
  "build": "openapi-ts && vite build",
10
13
  "check:lint": "eslint .",
11
14
  "fix:lint": "eslint --fix .",
12
- "check:type": "tsc --noEmit"
15
+ "check:type": "openapi-ts && tsc --noEmit"
13
16
  },
14
17
  "types": "./dist/index.d.ts",
15
18
  "module": "./dist/webchat-client.js",
@@ -26,7 +29,7 @@
26
29
  "eventsource": "^3.0.6"
27
30
  },
28
31
  "devDependencies": {
29
- "@bpinternal/webchat-http-client": "0.4.1",
32
+ "@bpinternal/webchat-http-client": "0.5.1",
30
33
  "@hey-api/client-fetch": "^0.10.0",
31
34
  "@hey-api/openapi-ts": "^0.66.4",
32
35
  "@repo/eslint-config": "workspace:*",
@@ -39,6 +39,10 @@ type Event =
39
39
  data: any
40
40
  }
41
41
 
42
+ const MAX_RETRIES = 10
43
+ const RETRY_INTERVAL = 3000 // ms
44
+ const TIMEOUT = '60000' // ms
45
+
42
46
  export type Client = {
43
47
  createConversation: () => Promise<ClientTypes.CreateConversationResponse>
44
48
  getConversation: (params: ConversationIdParam) => Promise<ClientTypes.GetConversationResponse>
@@ -68,7 +72,7 @@ export type Client = {
68
72
  ) => Promise<ClientTypes.AddMessageFeedbackResponse>
69
73
  removeMessageFeedback: (params: MessageIdParam) => Promise<ClientTypes.RemoveMessageFeedbackResponse>
70
74
  generateUserKey: (
71
- params: ClientTypes.GenerateUserKeyBody & { adminKey: string }
75
+ params: ClientTypes.GenerateUserKeyBody & { adminSecret: string }
72
76
  ) => Promise<ClientTypes.GenerateUserKeyResponse>
73
77
  }
74
78
 
@@ -79,11 +83,11 @@ const baseConfigs = {
79
83
  export const createUser = async ({
80
84
  clientId,
81
85
  apiUrl,
82
- adminKey,
86
+ adminSecret,
83
87
  }: {
84
88
  clientId: string
85
89
  apiUrl?: string
86
- adminKey?: string
90
+ adminSecret?: string
87
91
  }) => {
88
92
  const baseUrl = `${apiUrl || baseClient.getConfig().baseUrl}/${clientId}`
89
93
 
@@ -101,25 +105,68 @@ export const createUser = async ({
101
105
  .createUser({
102
106
  ...configs,
103
107
  body: {},
104
- headers: adminKey ? { 'x-admin-key': adminKey } : undefined,
108
+ headers: adminSecret ? { 'x-admin-secret': adminSecret } : undefined,
105
109
  })
106
110
  .then(extractData)
107
111
  }
108
112
 
113
+ export const initialize = ({
114
+ conversationId,
115
+ userToken,
116
+ clientId,
117
+ apiUrl,
118
+ }: {
119
+ conversationId?: string
120
+ userToken?: string
121
+ apiUrl?: string
122
+ clientId: string
123
+ }) => {
124
+ let retryCount = 0
125
+ let eventSource: EventSource | null = null
126
+ const eventEmitter = createEventEmitter<Record<Event['type'], Event['data']>>()
127
+
128
+ const connect = () => {
129
+ if (eventSource) {
130
+ eventSource.close()
131
+ }
132
+
133
+ const baseUrl = `${apiUrl || baseClient.getConfig().baseUrl}/${clientId}`
134
+ const url = `${baseUrl}/initialize${conversationId ? `?conversationId=${conversationId}` : ''}`
135
+
136
+ eventSource = createNewEventSource(url, userToken ? { 'x-user-token': userToken } : {})
137
+
138
+ eventSource.onopen = () => eventEmitter.emit('open')
139
+ eventSource.onerror = (err) => {
140
+ if (retryCount < MAX_RETRIES) {
141
+ retryCount++
142
+ setTimeout(() => connect(), RETRY_INTERVAL)
143
+ } else {
144
+ eventEmitter.emit('error', err)
145
+ }
146
+ }
147
+ eventSource.onmessage = (ev) => {
148
+ const event = safeJsonParse(ev.data) as Signal
149
+ eventEmitter.emit(event.type, event.data)
150
+ }
151
+ }
152
+ connect()
153
+ return eventEmitter.on
154
+ }
155
+
109
156
  export const generateUserKey = async ({
110
- adminKey,
157
+ adminSecret,
111
158
  expiresAt,
112
159
  userId,
113
160
  apiUrl,
114
161
  clientId,
115
162
  }: {
116
- adminKey: string
163
+ adminSecret: string
117
164
  expiresAt: number
118
165
  userId: string
119
166
  apiUrl?: string
120
167
  clientId: string
121
168
  }) => {
122
- const headers = { 'x-admin-key': adminKey }
169
+ const headers = { 'x-admin-secret': adminSecret }
123
170
 
124
171
  const baseUrl = `${apiUrl || baseClient.getConfig().baseUrl}/${clientId}`
125
172
  const configs = {
@@ -197,11 +244,9 @@ export const createClient = ({
197
244
  sdk.addMessageFeedback({ ...configs, headers, path: { id: messageId }, body }).then(extractData),
198
245
  removeMessageFeedback: ({ messageId }) =>
199
246
  sdk.removeMessageFeedback({ ...configs, headers, path: { id: messageId } }).then(extractData),
200
- generateUserKey: ({ adminKey, ...body }) =>
201
- sdk.generateUserKey({ ...configs, headers: { 'x-admin-key': adminKey }, body }).then(extractData),
247
+ generateUserKey: ({ adminSecret, ...body }) =>
248
+ sdk.generateUserKey({ ...configs, headers: { 'x-admin-secret': adminSecret }, body }).then(extractData),
202
249
  listenConversation: ({ conversationId }) => {
203
- const MAX_RETRIES = 10
204
- const RETRY_INTERVAL = 3000 // ms
205
250
  let retryCount = 0
206
251
  let eventSource: EventSource | null = null
207
252
  const eventEmitter = createEventEmitter<Record<Event['type'], Event['data']>>()
@@ -213,17 +258,7 @@ export const createClient = ({
213
258
 
214
259
  const url = `${baseUrl}/conversations/${conversationId}/listen`
215
260
 
216
- eventSource = new EventSource(url, {
217
- fetch: (input, init) =>
218
- fetch(input, {
219
- ...init,
220
- headers: {
221
- ...init?.headers,
222
- ...headers,
223
- timeout: '60_000',
224
- },
225
- }),
226
- })
261
+ eventSource = createNewEventSource(url, headers)
227
262
 
228
263
  eventSource.onopen = () => eventEmitter.emit('open')
229
264
  eventSource.onerror = (err) => {
@@ -254,3 +289,17 @@ const safeJsonParse = (data: any) => {
254
289
  return data
255
290
  }
256
291
  }
292
+
293
+ const createNewEventSource = (url: string, headers: Record<string, string>) => {
294
+ return new EventSource(url, {
295
+ fetch: (input, init) =>
296
+ fetch(input, {
297
+ ...init,
298
+ headers: {
299
+ ...init?.headers,
300
+ ...headers,
301
+ timeout: TIMEOUT,
302
+ },
303
+ }),
304
+ })
305
+ }
@@ -8,6 +8,7 @@ import type { WebchatVisibility } from './webchatVisibility'
8
8
  import type { ParticipantAdded } from './participantAdded'
9
9
  import type { ParticipantRemoved } from './participantRemoved'
10
10
  import type { MessageStatusChanged } from './messageStatusChanged'
11
+ import type { Initialize } from './initialize'
11
12
 
12
13
  export type Signal =
13
14
  | MessageCreated
@@ -20,3 +21,4 @@ export type Signal =
20
21
  | ParticipantAdded
21
22
  | ParticipantRemoved
22
23
  | MessageStatusChanged
24
+ | Initialize
@@ -0,0 +1,18 @@
1
+ import type {
2
+ GetConversationResponse,
3
+ GetUserResponse,
4
+ ListConversationMessagesResponse,
5
+ ListParticipantsResponse,
6
+ } from '../../../gen/client'
7
+
8
+ export type Initialize = {
9
+ type: 'init'
10
+ data: {
11
+ conversation: GetConversationResponse['conversation']
12
+ messages: ListConversationMessagesResponse['messages']
13
+ participants: ListParticipantsResponse['participants']
14
+ user: GetUserResponse['user'] & {
15
+ userKey?: string
16
+ }
17
+ }
18
+ }
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@ export {
2
2
  createClient,
3
3
  createUser,
4
4
  generateUserKey,
5
+ initialize,
5
6
  type Client,
6
7
  type UserCredentials,
7
8
  type IntegrationError,