@d-id/client-sdk 1.0.18-beta.9 → 1.0.19

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,586 +1,499 @@
1
- const didApiUrl = "https://api-dev.d-id.com";
2
- const didSocketApiUrl = "wss://notifications-dev.d-id.com";
3
- function getAuthHeader(auth) {
4
- if (auth.type === "bearer") {
5
- return `Bearer ${auth.token}`;
6
- } else if (auth.type === "basic") {
7
- return `Basic ${btoa(`${auth.username}:${auth.password}`)}`;
8
- } else if (auth.type === "key") {
9
- return `Client-Key ${auth.clientKey}`;
10
- } else {
11
- throw new Error(`Unknown auth type: ${auth}`);
12
- }
1
+ const v = "https://api.d-id.com", J = "wss://notifications.d-id.com";
2
+ function q(e) {
3
+ if (e.type === "bearer")
4
+ return `Bearer ${e.token}`;
5
+ if (e.type === "basic")
6
+ return `Basic ${btoa(`${e.username}:${e.password}`)}`;
7
+ if (e.type === "key")
8
+ return `Client-Key ${e.clientKey}`;
9
+ throw new Error(`Unknown auth type: ${e}`);
13
10
  }
14
- function createClient(auth, host = didApiUrl) {
15
- const client = async (url, options) => {
16
- const request = await fetch(host + ((url == null ? void 0 : url.startsWith("/")) ? url : `/${url}`), {
17
- ...options,
11
+ function y(e, i = v) {
12
+ const r = async (t, n) => {
13
+ const a = await fetch(i + (t != null && t.startsWith("/") ? t : `/${t}`), {
14
+ ...n,
18
15
  headers: {
19
- ...options == null ? void 0 : options.headers,
20
- Authorization: getAuthHeader(auth),
16
+ ...n == null ? void 0 : n.headers,
17
+ Authorization: q(e),
21
18
  "Content-Type": "application/json"
22
19
  }
23
20
  });
24
- if (!request.ok) {
25
- let error = await request.text().catch(() => "Failed to fetch");
26
- throw new Error(error);
21
+ if (!a.ok) {
22
+ let c = await a.text().catch(() => "Failed to fetch");
23
+ throw new Error(c);
27
24
  }
28
- return request.json();
25
+ return a.json();
29
26
  };
30
27
  return {
31
- get(url, options) {
32
- return client(url, {
33
- ...options,
28
+ get(t, n) {
29
+ return r(t, {
30
+ ...n,
34
31
  method: "GET"
35
32
  });
36
33
  },
37
- post(url, body, options) {
38
- return client(url, {
39
- ...options,
40
- body: JSON.stringify(body),
34
+ post(t, n, a) {
35
+ return r(t, {
36
+ ...a,
37
+ body: JSON.stringify(n),
41
38
  method: "POST"
42
39
  });
43
40
  },
44
- delete(url, body, options) {
45
- return client(url, {
46
- ...options,
47
- body: JSON.stringify(body),
41
+ delete(t, n, a) {
42
+ return r(t, {
43
+ ...a,
44
+ body: JSON.stringify(n),
48
45
  method: "DELETE"
49
46
  });
50
47
  },
51
- patch(url, body, options) {
52
- return client(url, {
53
- ...options,
54
- body: JSON.stringify(body),
48
+ patch(t, n, a) {
49
+ return r(t, {
50
+ ...a,
51
+ body: JSON.stringify(n),
55
52
  method: "PATCH"
56
53
  });
57
54
  }
58
55
  };
59
56
  }
60
- function createAgentsApi(auth, host = didApiUrl) {
61
- const client = createClient(auth, `${host}/agents`);
57
+ function T(e, i = v) {
58
+ const r = y(e, `${i}/agents`);
62
59
  return {
63
- create(payload, options) {
64
- return client.post(`/`, payload, options);
60
+ create(t, n) {
61
+ return r.post("/", t, n);
65
62
  },
66
- getAgents(tag, options) {
67
- return client.get(`/${tag ? `?tag=${tag}` : ""}`, options).then((agents) => agents ?? []);
63
+ getAgents(t, n) {
64
+ return r.get(`/${t ? `?tag=${t}` : ""}`, n).then((a) => a ?? []);
68
65
  },
69
- getById(id, options) {
70
- return client.get(`/${id}`, options);
66
+ getById(t, n) {
67
+ return r.get(`/${t}`, n);
71
68
  },
72
- delete(id, options) {
73
- return client.delete(`/${id}`, void 0, options);
69
+ delete(t, n) {
70
+ return r.delete(`/${t}`, void 0, n);
74
71
  },
75
- update(id, payload, options) {
76
- return client.patch(`/${id}`, payload, options);
72
+ update(t, n, a) {
73
+ return r.patch(`/${t}`, n, a);
77
74
  },
78
- newChat(agentId, options) {
79
- return client.post(`/${agentId}/chat`, void 0, options);
75
+ newChat(t, n) {
76
+ return r.post(`/${t}/chat`, void 0, n);
80
77
  },
81
- chat(agentId, chatId, payload, options) {
82
- return client.post(`/${agentId}/chat/${chatId}`, payload, options);
78
+ chat(t, n, a, c) {
79
+ return r.post(`/${t}/chat/${n}`, a, c);
83
80
  }
84
81
  };
85
82
  }
86
- function createKnowledgeApi(auth, host = didApiUrl) {
87
- const client = createClient(auth, `${host}/knowledge`);
83
+ function D(e, i = v) {
84
+ const r = y(e, `${i}/knowledge`);
88
85
  return {
89
- createKnowledge(payload, options) {
90
- return client.post(`/`, payload, options);
86
+ createKnowledge(t, n) {
87
+ return r.post("/", t, n);
91
88
  },
92
- getKnowledgeBase(options) {
93
- return client.get(`/`, options);
89
+ getKnowledgeBase(t) {
90
+ return r.get("/", t);
94
91
  },
95
- getKnowledge(knowledgeId, options) {
96
- return client.get(`/${knowledgeId}`, options);
92
+ getKnowledge(t, n) {
93
+ return r.get(`/${t}`, n);
97
94
  },
98
- deleteKnowledge(knowledgeId, options) {
99
- return client.delete(`/${knowledgeId}`, void 0, options);
95
+ deleteKnowledge(t, n) {
96
+ return r.delete(`/${t}`, void 0, n);
100
97
  },
101
- createDocument(knowledgeId, payload, options) {
102
- return client.post(`/${knowledgeId}/documents`, payload, options);
98
+ createDocument(t, n, a) {
99
+ return r.post(`/${t}/documents`, n, a);
103
100
  },
104
- deleteDocument(knowledgeId, documentId, options) {
105
- return client.delete(`/${knowledgeId}/documents/${documentId}`, void 0, options);
101
+ deleteDocument(t, n, a) {
102
+ return r.delete(`/${t}/documents/${n}`, void 0, a);
106
103
  },
107
- getDocuments(knowledgeId, options) {
108
- return client.get(`/${knowledgeId}/documents`, options);
104
+ getDocuments(t, n) {
105
+ return r.get(`/${t}/documents`, n);
109
106
  },
110
- getDocument(knowledgeId, documentId, options) {
111
- return client.get(`/${knowledgeId}/documents/${documentId}`, options);
107
+ getDocument(t, n, a) {
108
+ return r.get(`/${t}/documents/${n}`, a);
112
109
  },
113
- getRecords(knowledgeId, documentId, options) {
114
- return client.get(`/${knowledgeId}/documents/${documentId}/records`, options);
110
+ getRecords(t, n, a) {
111
+ return r.get(`/${t}/documents/${n}/records`, a);
115
112
  },
116
- query(knowledgeId, query, options) {
117
- return client.post(`/${knowledgeId}/query`, {
118
- query
119
- }, options);
113
+ query(t, n, a) {
114
+ return r.post(`/${t}/query`, {
115
+ query: n
116
+ }, a);
120
117
  }
121
118
  };
122
119
  }
123
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
124
- function connect(options) {
125
- return new Promise((resolve, reject) => {
126
- const {
127
- callbacks,
128
- host,
129
- auth
130
- } = options;
120
+ function F(e, i = v) {
121
+ const r = y(e, `${i}/chats/ratings`);
122
+ return {
123
+ create(t, n) {
124
+ return r.post("/", t, n);
125
+ },
126
+ getByKnowledge(t, n) {
127
+ return r.get(`/${t}`, n).then((a) => a ?? []);
128
+ },
129
+ update(t, n, a) {
130
+ return r.patch(`/${t}`, n, a);
131
+ },
132
+ delete(t, n) {
133
+ return r.delete(`/${t}`, n);
134
+ }
135
+ };
136
+ }
137
+ const V = (e) => new Promise((i) => setTimeout(i, e));
138
+ function G(e) {
139
+ return new Promise((i, r) => {
131
140
  const {
132
- onMessage = null,
133
- onOpen = null,
134
- onClose = null,
135
- onError = null
136
- } = callbacks || {};
137
- const socket = new WebSocket(`${host}?authorization=${getAuthHeader(auth)}`);
138
- socket.onmessage = onMessage;
139
- socket.onclose = onClose;
140
- socket.onerror = (e) => {
141
- console.log(e);
142
- onError == null ? void 0 : onError(e);
143
- reject(e);
144
- };
145
- socket.onopen = (e) => {
146
- onOpen == null ? void 0 : onOpen(e);
147
- resolve(socket);
141
+ callbacks: t,
142
+ host: n,
143
+ auth: a
144
+ } = e, {
145
+ onMessage: c = null,
146
+ onOpen: d = null,
147
+ onClose: f = null,
148
+ onError: m = null
149
+ } = t || {}, l = new WebSocket(`${n}?authorization=${q(a)}`);
150
+ l.onmessage = c, l.onclose = f, l.onerror = (s) => {
151
+ console.log(s), m == null || m(s), r(s);
152
+ }, l.onopen = (s) => {
153
+ d == null || d(s), i(l);
148
154
  };
149
155
  });
150
156
  }
151
- async function connectWithRetries(options) {
157
+ async function Q(e) {
152
158
  const {
153
- retries = 1
154
- } = options;
155
- let socket = null;
156
- for (let attempt = 0; (socket == null ? void 0 : socket.readyState) !== WebSocket.OPEN; attempt++) {
159
+ retries: i = 1
160
+ } = e;
161
+ let r = null;
162
+ for (let t = 0; (r == null ? void 0 : r.readyState) !== WebSocket.OPEN; t++)
157
163
  try {
158
- socket = await connect(options);
159
- } catch (e) {
160
- if (attempt === retries) {
161
- throw e;
162
- }
163
- await sleep(attempt * 500);
164
+ r = await G(e);
165
+ } catch (n) {
166
+ if (t === i)
167
+ throw n;
168
+ await V(t * 500);
164
169
  }
165
- }
166
- return socket;
170
+ return r;
167
171
  }
168
- async function SocketManager(auth, host = didSocketApiUrl) {
169
- const messageCallbacks = [];
170
- const socket = await connectWithRetries({
171
- auth,
172
- host,
172
+ async function X(e, i, r = J) {
173
+ const t = i ? [i] : [], n = await Q({
174
+ auth: e,
175
+ host: r,
173
176
  callbacks: {
174
- onMessage: (event) => {
175
- messageCallbacks.forEach((callback) => callback(event));
177
+ onMessage: (a) => {
178
+ const c = JSON.parse(a.data);
179
+ t.forEach((d) => d(c.event, c));
176
180
  }
177
181
  }
178
182
  });
179
183
  return {
180
- socket,
181
- terminate: () => socket.close(),
182
- subscribeToEvents: (callback) => messageCallbacks.push(callback)
183
- };
184
- }
185
- var Providers = /* @__PURE__ */ ((Providers2) => {
186
- Providers2["Amazon"] = "amazon";
187
- Providers2["Microsoft"] = "microsoft";
188
- Providers2["Afflorithmics"] = "afflorithmics";
189
- Providers2["Elevenlabs"] = "elevenlabs";
190
- return Providers2;
191
- })(Providers || {});
192
- var VoiceAccess = /* @__PURE__ */ ((VoiceAccess2) => {
193
- VoiceAccess2["Public"] = "public";
194
- VoiceAccess2["Premium"] = "premium";
195
- VoiceAccess2["Private"] = "private";
196
- return VoiceAccess2;
197
- })(VoiceAccess || {});
198
- var StreamingState = /* @__PURE__ */ ((StreamingState2) => {
199
- StreamingState2["Start"] = "START";
200
- StreamingState2["Stop"] = "STOP";
201
- return StreamingState2;
202
- })(StreamingState || {});
203
- var StreamEvents = /* @__PURE__ */ ((StreamEvents2) => {
204
- StreamEvents2["ChatAnswer"] = "chat/answer";
205
- StreamEvents2["ChatPartial"] = "chat/partial";
206
- StreamEvents2["StreamDone"] = "stream/done";
207
- StreamEvents2["StreamStarted"] = "stream/started";
208
- return StreamEvents2;
209
- })(StreamEvents || {});
210
- var RateState = /* @__PURE__ */ ((RateState2) => {
211
- RateState2["Unrated"] = "Unrated";
212
- RateState2["Positive"] = "Positive";
213
- RateState2["Negative"] = "Negative";
214
- return RateState2;
215
- })(RateState || {});
216
- var Subject = /* @__PURE__ */ ((Subject2) => {
217
- Subject2["KnowledgeProcessing"] = "knowledge/processing";
218
- Subject2["KnowledgeIndexing"] = "knowledge/indexing";
219
- Subject2["KnowledgeFailed"] = "knowledge/error";
220
- Subject2["KnowledgeDone"] = "knowledge/done";
221
- return Subject2;
222
- })(Subject || {});
223
- var KnowledgeType = /* @__PURE__ */ ((KnowledgeType2) => {
224
- KnowledgeType2["Knowledge"] = "knowledge";
225
- KnowledgeType2["Document"] = "document";
226
- KnowledgeType2["Record"] = "record";
227
- return KnowledgeType2;
228
- })(KnowledgeType || {});
229
- var DocumentType = /* @__PURE__ */ ((DocumentType2) => {
230
- DocumentType2["Pdf"] = "pdf";
231
- DocumentType2["Text"] = "text";
232
- DocumentType2["Html"] = "html";
233
- DocumentType2["Word"] = "word";
234
- DocumentType2["Json"] = "json";
235
- DocumentType2["Markdown"] = "markdown";
236
- DocumentType2["Csv"] = "csv";
237
- DocumentType2["Excel"] = "excel";
238
- DocumentType2["Powerpoint"] = "powerpoint";
239
- DocumentType2["Archive"] = "archive";
240
- DocumentType2["Image"] = "image";
241
- DocumentType2["Audio"] = "audio";
242
- DocumentType2["Video"] = "video";
243
- return DocumentType2;
244
- })(DocumentType || {});
245
- var VideoType = /* @__PURE__ */ ((VideoType2) => {
246
- VideoType2["Clip"] = "clip";
247
- VideoType2["Talk"] = "talk";
248
- return VideoType2;
249
- })(VideoType || {});
250
- function createRatingsApi(auth, host = didApiUrl) {
251
- const client = createClient(auth, `${host}/chats/ratings`);
252
- return {
253
- create(payload, options) {
254
- return client.post(`/`, payload, options);
255
- },
256
- getByKnowledge(knowledgeId, options) {
257
- return client.get(`/${knowledgeId}`, options).then((ratings) => ratings ?? []);
258
- },
259
- update(id, payload, options) {
260
- return client.patch(`/${id}`, payload, options);
261
- },
262
- delete(id, options) {
263
- return client.delete(`/${id}`, options);
264
- }
184
+ socket: n,
185
+ terminate: () => n.close(),
186
+ subscribeToEvents: (a) => t.push(a)
265
187
  };
266
188
  }
267
- function getAgentStreamArgs(agent) {
268
- if (agent.presenter.type === VideoType.Clip) {
269
- return {
270
- videoType: VideoType.Clip,
271
- driver_id: agent.presenter.driver_id,
272
- presenter_id: agent.presenter.presenter_id
273
- };
274
- }
275
- return {
276
- videoType: VideoType.Talk,
277
- source_url: agent.presenter.source_url
189
+ var Y = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(Y || {}), Z = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(Z || {}), _ = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(_ || {}), A = /* @__PURE__ */ ((e) => (e.ChatAnswer = "chat/answer", e.ChatPartial = "chat/partial", e.StreamDone = "stream/done", e.StreamStarted = "stream/started", e))(A || {}), O = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(O || {}), L = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(L || {}), j = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(j || {}), ee = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(ee || {}), te = /* @__PURE__ */ ((e) => (e.Pdf = "pdf", e.Text = "text", e.Html = "html", e.Word = "word", e.Json = "json", e.Markdown = "markdown", e.Csv = "csv", e.Excel = "excel", e.Powerpoint = "powerpoint", e.Archive = "archive", e.Image = "image", e.Audio = "audio", e.Video = "video", e))(te || {}), R = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e))(R || {});
190
+ function ne(e) {
191
+ return e.presenter.type === R.Clip ? {
192
+ videoType: R.Clip,
193
+ driver_id: e.presenter.driver_id,
194
+ presenter_id: e.presenter.presenter_id
195
+ } : {
196
+ videoType: R.Talk,
197
+ source_url: e.presenter.source_url
278
198
  };
279
199
  }
280
- function initializeStreamAndChat(agent, options, agentsApi, chat) {
281
- return new Promise(async (resolve, reject) => {
282
- const streamingManager = await createStreamingManager(getAgentStreamArgs(agent), {
283
- ...options,
200
+ function x(e, i, r, t) {
201
+ return new Promise(async (n, a) => {
202
+ const c = await oe(ne(e), {
203
+ ...i,
284
204
  callbacks: {
285
- ...options.callbacks,
286
- onConnectionStateChange: async (state) => {
287
- var _a, _b;
288
- if (state === "connected") {
289
- if (!chat) {
290
- chat = await agentsApi.newChat(agent.id);
291
- }
292
- resolve({
293
- chat,
294
- streamingManager
295
- });
296
- } else if (state === "failed") {
297
- reject(new Error("Cannot create connection"));
298
- }
299
- (_b = (_a = options.callbacks).onConnectionStateChange) == null ? void 0 : _b.call(_a, state);
205
+ ...i.callbacks,
206
+ onConnectionStateChange: async (d) => {
207
+ var f, m;
208
+ d === "connected" ? (t || (t = await r.newChat(e.id)), n({
209
+ chat: t,
210
+ streamingManager: c
211
+ })) : d === "failed" && a(new Error("Cannot create connection")), (m = (f = i.callbacks).onConnectionStateChange) == null || m.call(f, d);
212
+ },
213
+ // TODO remove when webscoket will return partial
214
+ onMessage: (d, f) => {
215
+ var m, l;
216
+ d === A.ChatPartial && ((l = (m = i.callbacks).onChatEvents) == null || l.call(m, L.Partial, {
217
+ content: f,
218
+ event: L.Partial
219
+ }));
300
220
  }
301
221
  }
302
222
  });
303
223
  });
304
224
  }
305
- async function createAgentManager(agentId, options) {
306
- const baseURL = options.baseURL || didApiUrl;
307
- const abortController = new AbortController();
308
- const agentsApi = createAgentsApi(options.auth, baseURL);
309
- const ratingsAPI = createRatingsApi(options.auth, baseURL);
310
- const agent = await agentsApi.getById(agentId);
311
- const socketManager = await SocketManager(options.auth);
225
+ async function ce(e, i) {
226
+ const r = i.baseURL || v, t = new AbortController(), n = T(i.auth, r), a = F(i.auth, r), c = D(i.auth, r), d = await n.getById(e), f = await X(i.auth, i.callbacks.onChatEvents);
312
227
  let {
313
- chat,
314
- streamingManager
315
- } = await initializeStreamAndChat(agent, options, agentsApi);
228
+ chat: m,
229
+ streamingManager: l
230
+ } = await x(d, i, n);
316
231
  return {
317
- agent,
232
+ agent: d,
318
233
  async reconnectToChat() {
319
234
  const {
320
- streamingManager: newStreamingManager
321
- } = await initializeStreamAndChat(agent, options, agentsApi, chat);
322
- streamingManager = newStreamingManager;
235
+ streamingManager: s
236
+ } = await x(d, i, n, m);
237
+ l = s;
323
238
  },
324
239
  terminate() {
325
- abortController.abort();
326
- socketManager.terminate();
327
- return streamingManager.terminate();
328
- },
329
- chatId: chat.id,
330
- async chat(messages) {
331
- const result = await agentsApi.chat(agentId, chat.id, {
332
- sessionId: streamingManager.sessionId,
333
- streamId: streamingManager.streamId,
334
- messages
240
+ return t.abort(), f.terminate(), l.terminate();
241
+ },
242
+ chatId: m.id,
243
+ chat(s) {
244
+ return n.chat(e, m.id, {
245
+ sessionId: l.sessionId,
246
+ streamId: l.streamId,
247
+ messages: s
335
248
  }, {
336
- signal: abortController.signal
249
+ signal: t.signal
337
250
  });
338
- console.log(result);
339
- return result;
340
251
  },
341
- rate(payload, id) {
342
- if (id) {
343
- return ratingsAPI.update(id, payload);
344
- }
345
- return ratingsAPI.create(payload);
252
+ rate(s, g) {
253
+ return g ? a.update(g, s) : a.create(s);
346
254
  },
347
- speak(payload) {
348
- if (!agent) {
349
- throw new Error("Agent not initializated");
350
- }
351
- let completePayload;
352
- if (payload.type === "text") {
353
- completePayload = {
354
- script: {
355
- type: "text",
356
- provider: payload.provider,
357
- input: payload.input,
358
- ssml: payload.ssml || false
359
- }
360
- };
361
- } else if (payload.type === "audio") {
362
- completePayload = {
363
- script: {
364
- type: "audio",
365
- audio_url: payload.audio_url
366
- }
367
- };
368
- }
369
- return streamingManager.speak(completePayload);
370
- },
371
- onChatEvents(callback) {
372
- socketManager.subscribeToEvents(callback);
255
+ deleteRate(s) {
256
+ return a.delete(s);
373
257
  },
374
- onConnectionEvents(callback) {
375
- streamingManager.onCallback("onConnectionStateChange", callback);
258
+ speak(s) {
259
+ let g;
260
+ return s.type === "text" ? g = {
261
+ script: {
262
+ type: "text",
263
+ provider: s.provider,
264
+ input: s.input,
265
+ ssml: s.ssml || !1
266
+ }
267
+ } : s.type === "audio" && (g = {
268
+ script: {
269
+ type: "audio",
270
+ audio_url: s.audio_url
271
+ }
272
+ }), l.speak(g);
376
273
  },
377
- onVideoEvents(callback) {
378
- streamingManager.onCallback("onVideoStateChange", callback);
274
+ getStarterMessages() {
275
+ var s, g;
276
+ return (s = d.knowledge) != null && s.id ? c.getKnowledge((g = d.knowledge) == null ? void 0 : g.id).then((C) => (C == null ? void 0 : C.starter_message) || []) : Promise.resolve([]);
379
277
  }
380
278
  };
381
279
  }
382
- function createApi$1(auth, host) {
383
- const client = createClient(auth, host);
280
+ function re(e, i) {
281
+ const r = y(e, i);
384
282
  return {
385
- createStream(options) {
386
- return client.post("/clips/streams", {
387
- driver_id: options.driver_id,
388
- presenter_id: options.presenter_id,
389
- compatibility_mode: options.compatibility_mode
283
+ createStream(t) {
284
+ return r.post("/clips/streams", {
285
+ driver_id: t.driver_id,
286
+ presenter_id: t.presenter_id,
287
+ compatibility_mode: t.compatibility_mode
390
288
  });
391
289
  },
392
- startConnection(streamId, answer, sessionId) {
393
- return client.post(`/clips/streams/${streamId}/sdp`, {
394
- session_id: sessionId,
395
- answer
290
+ startConnection(t, n, a) {
291
+ return r.post(`/clips/streams/${t}/sdp`, {
292
+ session_id: a,
293
+ answer: n
396
294
  });
397
295
  },
398
- addIceCandidate(streamId, candidate, sessionId) {
399
- return client.post(`/clips/streams/${streamId}/ice`, {
400
- session_id: sessionId,
401
- ...candidate
296
+ addIceCandidate(t, n, a) {
297
+ return r.post(`/clips/streams/${t}/ice`, {
298
+ session_id: a,
299
+ ...n
402
300
  });
403
301
  },
404
- sendStreamRequest(streamId, sessionId, payload) {
405
- return client.post(`/clips/streams/${streamId}`, {
406
- session_id: sessionId,
407
- ...payload
302
+ sendStreamRequest(t, n, a) {
303
+ return r.post(`/clips/streams/${t}`, {
304
+ session_id: n,
305
+ ...a
408
306
  });
409
307
  },
410
- close(streamId, sessionId) {
411
- return client.delete(`/clips/streams/${streamId}`, {
412
- session_id: sessionId
308
+ close(t, n) {
309
+ return r.delete(`/clips/streams/${t}`, {
310
+ session_id: n
413
311
  });
414
312
  }
415
313
  };
416
314
  }
417
- function createApi(auth, host) {
418
- const client = createClient(auth, host);
315
+ function ae(e, i) {
316
+ const r = y(e, i);
419
317
  return {
420
- createStream(streamOptions, options) {
421
- return client.post("/talks/streams", {
422
- source_url: streamOptions.source_url,
423
- driver_url: streamOptions.driver_url,
424
- face: streamOptions.face,
425
- config: streamOptions.config
426
- }, options);
427
- },
428
- startConnection(streamId, answer, sessionId, options) {
429
- return client.post(`/talks/streams/${streamId}/sdp`, {
430
- session_id: sessionId,
431
- answer
432
- }, options);
433
- },
434
- addIceCandidate(streamId, candidate, sessionId, options) {
435
- return client.post(`/talks/streams/${streamId}/ice`, {
436
- session_id: sessionId,
437
- ...candidate
438
- }, options);
439
- },
440
- sendStreamRequest(streamId, sessionId, payload, options) {
441
- return client.post(`/talks/streams/${streamId}`, {
442
- session_id: sessionId,
443
- ...payload
444
- }, options);
445
- },
446
- close(streamId, sessionId, options) {
447
- return client.delete(`/talks/streams/${streamId}`, {
448
- session_id: sessionId
449
- }, options);
318
+ createStream(t, n) {
319
+ return r.post("/talks/streams", {
320
+ source_url: t.source_url,
321
+ driver_url: t.driver_url,
322
+ face: t.face,
323
+ config: t.config
324
+ }, n);
325
+ },
326
+ startConnection(t, n, a, c) {
327
+ return r.post(`/talks/streams/${t}/sdp`, {
328
+ session_id: a,
329
+ answer: n
330
+ }, c);
331
+ },
332
+ addIceCandidate(t, n, a, c) {
333
+ return r.post(`/talks/streams/${t}/ice`, {
334
+ session_id: a,
335
+ ...n
336
+ }, c);
337
+ },
338
+ sendStreamRequest(t, n, a, c) {
339
+ return r.post(`/talks/streams/${t}`, {
340
+ session_id: n,
341
+ ...a
342
+ }, c);
343
+ },
344
+ close(t, n, a) {
345
+ return r.delete(`/talks/streams/${t}`, {
346
+ session_id: n
347
+ }, a);
450
348
  }
451
349
  };
452
350
  }
453
- let _debug = false;
454
- const log = (message, extra) => _debug && console.log(message, extra);
455
- const actualRTCPC = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
456
- async function createStreamingManager(agent, {
457
- debug = false,
458
- callbacks,
459
- auth,
460
- baseURL = didApiUrl
461
- }) {
462
- _debug = debug;
463
- const callbacksObj = {
464
- ...callbacks
465
- };
466
- const {
467
- startConnection,
468
- sendStreamRequest,
469
- close,
470
- createStream,
471
- addIceCandidate
472
- } = agent.videoType === VideoType.Clip ? createApi$1(auth, baseURL) : createApi(auth, baseURL);
473
- const {
474
- id: streamIdFromServer,
475
- offer,
476
- ice_servers,
477
- session_id
478
- } = await createStream(agent);
479
- const peerConnection = new actualRTCPC({
480
- iceServers: ice_servers
351
+ function ie(e, i) {
352
+ return e.map((r, t) => t === 0 ? i ? {
353
+ index: t,
354
+ timestamp: r.timestamp,
355
+ bytesReceived: r.bytesReceived - i.bytesReceived,
356
+ packetsReceived: r.packetsReceived - i.packetsReceived,
357
+ packetsLost: r.packetsLost - i.packetsLost,
358
+ jitter: r.jitter,
359
+ frameWidth: r.frameWidth,
360
+ frameHeight: r.frameHeight,
361
+ frameRate: r.frameRate
362
+ } : {
363
+ index: t,
364
+ timestamp: r.timestamp,
365
+ bytesReceived: r.bytesReceived,
366
+ packetsReceived: r.packetsReceived,
367
+ packetsLost: r.packetsLost,
368
+ jitter: r.jitter,
369
+ frameWidth: r.frameWidth,
370
+ frameHeight: r.frameHeight,
371
+ frameRate: r.frameRate
372
+ } : {
373
+ index: t,
374
+ timestamp: r.timestamp,
375
+ bytesReceived: r.bytesReceived - e[t - 1].bytesReceived,
376
+ packetsReceived: r.packetsReceived - e[t - 1].packetsReceived,
377
+ packetsLost: r.packetsLost - e[t - 1].packetsLost,
378
+ jitter: r.jitter,
379
+ frameWidth: r.frameWidth,
380
+ frameHeight: r.frameHeight,
381
+ frameRate: r.frameRate
481
382
  });
482
- const pcDataChannel = peerConnection.createDataChannel("JanusDataChannel");
483
- if (!session_id) {
383
+ }
384
+ let N = !1;
385
+ const h = (e, i) => N && console.log(e, i), se = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
386
+ async function oe(e, {
387
+ debug: i = !1,
388
+ callbacks: r,
389
+ auth: t,
390
+ baseURL: n = v
391
+ }) {
392
+ N = i;
393
+ const a = {
394
+ ...r
395
+ }, {
396
+ startConnection: c,
397
+ sendStreamRequest: d,
398
+ close: f,
399
+ createStream: m,
400
+ addIceCandidate: l
401
+ } = e.videoType === R.Clip ? re(t, n) : ae(t, n), {
402
+ id: s,
403
+ offer: g,
404
+ ice_servers: C,
405
+ session_id: w
406
+ } = await m(e), u = new se({
407
+ iceServers: C
408
+ }), b = u.createDataChannel("JanusDataChannel"), k = [];
409
+ let $ = 0, E;
410
+ if (!w)
484
411
  throw new Error("Could not create session_id");
485
- }
486
- peerConnection.onicecandidate = (event) => {
487
- log("peerConnection.onicecandidate", event);
488
- if (event.candidate && event.candidate.sdpMid && event.candidate.sdpMLineIndex !== null) {
489
- addIceCandidate(streamIdFromServer, {
490
- candidate: event.candidate.candidate,
491
- sdpMid: event.candidate.sdpMid,
492
- sdpMLineIndex: event.candidate.sdpMLineIndex
493
- }, session_id);
494
- }
495
- };
496
- peerConnection.oniceconnectionstatechange = () => {
497
- var _a;
498
- log("peerConnection.oniceconnectionstatechange => " + peerConnection.iceConnectionState);
499
- (_a = callbacksObj.onConnectionStateChange) == null ? void 0 : _a.call(callbacksObj, peerConnection.iceConnectionState);
500
- };
501
- peerConnection.ontrack = (event) => {
502
- var _a;
503
- log("peerConnection.ontrack", event);
504
- (_a = callbacksObj.onSrcObjectReady) == null ? void 0 : _a.call(callbacksObj, event.streams[0]);
505
- };
506
- pcDataChannel.onmessage = (message) => {
507
- var _a, _b, _c;
508
- if (pcDataChannel.readyState === "open") {
509
- const [event, data] = message.data.split(":");
510
- if (event === StreamEvents.StreamDone) {
511
- (_a = callbacksObj.onVideoStateChange) == null ? void 0 : _a.call(callbacksObj, StreamingState.Stop);
512
- } else if (event === StreamEvents.StreamStarted) {
513
- (_b = callbacksObj.onVideoStateChange) == null ? void 0 : _b.call(callbacksObj, StreamingState.Start);
514
- } else {
515
- (_c = callbacksObj.onMessage) == null ? void 0 : _c.call(callbacksObj, event, decodeURIComponent(data));
516
- }
412
+ u.onicecandidate = (o) => {
413
+ h("peerConnection.onicecandidate", o), o.candidate && o.candidate.sdpMid && o.candidate.sdpMLineIndex !== null && l(s, {
414
+ candidate: o.candidate.candidate,
415
+ sdpMid: o.candidate.sdpMid,
416
+ sdpMLineIndex: o.candidate.sdpMLineIndex
417
+ }, w);
418
+ }, u.oniceconnectionstatechange = () => {
419
+ var o;
420
+ h("peerConnection.oniceconnectionstatechange => " + u.iceConnectionState), (o = a.onConnectionStateChange) == null || o.call(a, u.iceConnectionState);
421
+ }, u.ontrack = (o) => {
422
+ var p;
423
+ h("peerConnection.ontrack", o), (p = a.onSrcObjectReady) == null || p.call(a, o.streams[0]);
424
+ }, b.onmessage = (o) => {
425
+ var p, I, H;
426
+ if (b.readyState === "open") {
427
+ const [M, U] = o.data.split(":");
428
+ if (M === A.StreamStarted)
429
+ $ = k.length, E = setInterval(() => {
430
+ u.getStats().then((K) => {
431
+ K.forEach((S) => {
432
+ S.type === "inbound-rtp" && S.kind === "video" && k.push(S);
433
+ });
434
+ });
435
+ }, 1e3), (p = a.onVideoStateChange) == null || p.call(a, _.Start);
436
+ else if (M === A.StreamDone) {
437
+ clearInterval(E);
438
+ const P = k.slice($);
439
+ if (P) {
440
+ const K = $ === 0 ? void 0 : k[$ - 1], S = ie(P, K);
441
+ $ = k.length, (I = a.onVideoStateChange) == null || I.call(a, _.Stop, S.sort((z, B) => B.packetsLost - z.packetsLost).slice(0, 5));
442
+ }
443
+ } else
444
+ (H = a.onMessage) == null || H.call(a, M, decodeURIComponent(U));
517
445
  }
518
- };
519
- await peerConnection.setRemoteDescription(offer);
520
- log("set remote description OK");
521
- const sessionClientAnswer = await peerConnection.createAnswer();
522
- log("create answer OK");
523
- await peerConnection.setLocalDescription(sessionClientAnswer);
524
- log("set local description OK");
525
- await startConnection(streamIdFromServer, sessionClientAnswer, session_id);
526
- log("start connection OK");
527
- return {
446
+ }, await u.setRemoteDescription(g), h("set remote description OK");
447
+ const W = await u.createAnswer();
448
+ return h("create answer OK"), await u.setLocalDescription(W), h("set local description OK"), await c(s, W, w), h("start connection OK"), {
528
449
  /**
529
450
  * Method to send request to server to get clip or talk depend on you payload
530
451
  * @param payload
531
452
  */
532
- speak(payload) {
533
- return sendStreamRequest(streamIdFromServer, session_id, payload);
453
+ speak(o) {
454
+ return d(s, w, o);
534
455
  },
535
456
  /**
536
457
  * Method to close RTC connection
537
458
  */
538
459
  async terminate() {
539
- var _a, _b;
540
- if (streamIdFromServer) {
541
- if (peerConnection) {
542
- peerConnection.close();
543
- peerConnection.oniceconnectionstatechange = null;
544
- peerConnection.onnegotiationneeded = null;
545
- peerConnection.onicecandidate = null;
546
- peerConnection.ontrack = null;
547
- }
548
- await close(streamIdFromServer, session_id).catch((_) => {
549
- });
550
- (_a = callbacksObj.onConnectionStateChange) == null ? void 0 : _a.call(callbacksObj, "closed");
551
- (_b = callbacksObj.onVideoStateChange) == null ? void 0 : _b.call(callbacksObj, StreamingState.Stop);
552
- }
460
+ var o, p;
461
+ s && (u && (u.close(), u.oniceconnectionstatechange = null, u.onnegotiationneeded = null, u.onicecandidate = null, u.ontrack = null), await f(s, w).catch((I) => {
462
+ }), (o = a.onConnectionStateChange) == null || o.call(a, "closed"), (p = a.onVideoStateChange) == null || p.call(a, _.Stop));
553
463
  },
554
464
  /**
555
465
  * Session identifier information, should be returned in the body of all streaming requests
556
466
  */
557
- sessionId: session_id,
467
+ sessionId: w,
558
468
  /**
559
469
  * Id of current RTC stream
560
470
  */
561
- streamId: streamIdFromServer,
471
+ streamId: s,
562
472
  /**
563
473
  * Method to add callback that will be trigered on supported events
564
474
  * @param eventName
565
475
  * @param callback
566
476
  */
567
- onCallback(eventName, callback) {
568
- callbacksObj[eventName] = callback;
477
+ onCallback(o, p) {
478
+ a[o] = p;
569
479
  }
570
480
  };
571
481
  }
572
482
  export {
573
- DocumentType,
574
- KnowledgeType,
575
- Providers,
576
- RateState,
577
- SocketManager,
578
- Subject,
579
- VoiceAccess,
580
- createAgentManager,
581
- createAgentsApi,
582
- createClient,
583
- createKnowledgeApi,
584
- createStreamingManager,
585
- getAgentStreamArgs
483
+ L as ChatProgress,
484
+ te as DocumentType,
485
+ ee as KnowledgeType,
486
+ Y as Providers,
487
+ O as RateState,
488
+ X as SocketManager,
489
+ A as StreamEvents,
490
+ j as Subject,
491
+ Z as VoiceAccess,
492
+ ce as createAgentManager,
493
+ T as createAgentsApi,
494
+ y as createClient,
495
+ D as createKnowledgeApi,
496
+ F as createRatingsApi,
497
+ oe as createStreamingManager,
498
+ ne as getAgentStreamArgs
586
499
  };