@glydeunity/voice-sdk 1.0.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.
@@ -0,0 +1,3091 @@
1
+ function Te(o, e) {
2
+ for (var t = 0; t < e.length; t++) {
3
+ const n = e[t];
4
+ if (typeof n != "string" && !Array.isArray(n)) {
5
+ for (const r in n)
6
+ if (r !== "default" && !(r in o)) {
7
+ const s = Object.getOwnPropertyDescriptor(n, r);
8
+ s && Object.defineProperty(o, r, s.get ? s : {
9
+ enumerable: !0,
10
+ get: () => n[r]
11
+ });
12
+ }
13
+ }
14
+ }
15
+ return Object.freeze(Object.defineProperty(o, Symbol.toStringTag, { value: "Module" }));
16
+ }
17
+ class C extends Error {
18
+ constructor(e) {
19
+ super(e), this.__dgError = !0, this.name = "DeepgramError";
20
+ }
21
+ }
22
+ function w(o) {
23
+ return typeof o == "object" && o !== null && "__dgError" in o;
24
+ }
25
+ class Be extends C {
26
+ constructor(e, t) {
27
+ super(e), this.name = "DeepgramApiError", this.status = t;
28
+ }
29
+ toJSON() {
30
+ return {
31
+ name: this.name,
32
+ message: this.message,
33
+ status: this.status
34
+ };
35
+ }
36
+ }
37
+ class ie extends C {
38
+ constructor(e, t) {
39
+ super(e), this.name = "DeepgramUnknownError", this.originalError = t;
40
+ }
41
+ }
42
+ class F extends C {
43
+ constructor() {
44
+ super("You are attempting to use an old format for a newer SDK version. Read more here: https://dpgr.am/js-v3"), this.name = "DeepgramVersionError";
45
+ }
46
+ }
47
+ class Me extends C {
48
+ constructor(e, t = {}) {
49
+ super(e), this.name = "DeepgramWebSocketError", this.originalEvent = t.originalEvent, this.statusCode = t.statusCode, this.requestId = t.requestId, this.responseHeaders = t.responseHeaders, this.url = t.url, this.readyState = t.readyState;
50
+ }
51
+ toJSON() {
52
+ return {
53
+ name: this.name,
54
+ message: this.message,
55
+ statusCode: this.statusCode,
56
+ requestId: this.requestId,
57
+ responseHeaders: this.responseHeaders,
58
+ url: this.url,
59
+ readyState: this.readyState,
60
+ originalEvent: this.originalEvent ? {
61
+ type: this.originalEvent.type,
62
+ timeStamp: this.originalEvent.timeStamp
63
+ } : void 0
64
+ };
65
+ }
66
+ }
67
+ var Q = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
68
+ function Oe(o) {
69
+ return o && o.__esModule && Object.prototype.hasOwnProperty.call(o, "default") ? o.default : o;
70
+ }
71
+ var ee = { exports: {} }, ve;
72
+ function Le() {
73
+ if (ve) return ee.exports;
74
+ ve = 1;
75
+ var o = typeof Reflect == "object" ? Reflect : null, e = o && typeof o.apply == "function" ? o.apply : function(u, h, y) {
76
+ return Function.prototype.apply.call(u, h, y);
77
+ }, t;
78
+ o && typeof o.ownKeys == "function" ? t = o.ownKeys : Object.getOwnPropertySymbols ? t = function(u) {
79
+ return Object.getOwnPropertyNames(u).concat(Object.getOwnPropertySymbols(u));
80
+ } : t = function(u) {
81
+ return Object.getOwnPropertyNames(u);
82
+ };
83
+ function n(l) {
84
+ console && console.warn && console.warn(l);
85
+ }
86
+ var r = Number.isNaN || function(u) {
87
+ return u !== u;
88
+ };
89
+ function s() {
90
+ s.init.call(this);
91
+ }
92
+ ee.exports = s, ee.exports.once = v, s.EventEmitter = s, s.prototype._events = void 0, s.prototype._eventsCount = 0, s.prototype._maxListeners = void 0;
93
+ var i = 10;
94
+ function c(l) {
95
+ if (typeof l != "function")
96
+ throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof l);
97
+ }
98
+ Object.defineProperty(s, "defaultMaxListeners", {
99
+ enumerable: !0,
100
+ get: function() {
101
+ return i;
102
+ },
103
+ set: function(l) {
104
+ if (typeof l != "number" || l < 0 || r(l))
105
+ throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + l + ".");
106
+ i = l;
107
+ }
108
+ }), s.init = function() {
109
+ (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) && (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0;
110
+ }, s.prototype.setMaxListeners = function(u) {
111
+ if (typeof u != "number" || u < 0 || r(u))
112
+ throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + u + ".");
113
+ return this._maxListeners = u, this;
114
+ };
115
+ function p(l) {
116
+ return l._maxListeners === void 0 ? s.defaultMaxListeners : l._maxListeners;
117
+ }
118
+ s.prototype.getMaxListeners = function() {
119
+ return p(this);
120
+ }, s.prototype.emit = function(u) {
121
+ for (var h = [], y = 1; y < arguments.length; y++) h.push(arguments[y]);
122
+ var m = u === "error", O = this._events;
123
+ if (O !== void 0)
124
+ m = m && O.error === void 0;
125
+ else if (!m)
126
+ return !1;
127
+ if (m) {
128
+ var U;
129
+ if (h.length > 0 && (U = h[0]), U instanceof Error)
130
+ throw U;
131
+ var L = new Error("Unhandled error." + (U ? " (" + U.message + ")" : ""));
132
+ throw L.context = U, L;
133
+ }
134
+ var A = O[u];
135
+ if (A === void 0)
136
+ return !1;
137
+ if (typeof A == "function")
138
+ e(A, this, h);
139
+ else
140
+ for (var Y = A.length, $ = D(A, Y), y = 0; y < Y; ++y)
141
+ e($[y], this, h);
142
+ return !0;
143
+ };
144
+ function g(l, u, h, y) {
145
+ var m, O, U;
146
+ if (c(h), O = l._events, O === void 0 ? (O = l._events = /* @__PURE__ */ Object.create(null), l._eventsCount = 0) : (O.newListener !== void 0 && (l.emit(
147
+ "newListener",
148
+ u,
149
+ h.listener ? h.listener : h
150
+ ), O = l._events), U = O[u]), U === void 0)
151
+ U = O[u] = h, ++l._eventsCount;
152
+ else if (typeof U == "function" ? U = O[u] = y ? [h, U] : [U, h] : y ? U.unshift(h) : U.push(h), m = p(l), m > 0 && U.length > m && !U.warned) {
153
+ U.warned = !0;
154
+ var L = new Error("Possible EventEmitter memory leak detected. " + U.length + " " + String(u) + " listeners added. Use emitter.setMaxListeners() to increase limit");
155
+ L.name = "MaxListenersExceededWarning", L.emitter = l, L.type = u, L.count = U.length, n(L);
156
+ }
157
+ return l;
158
+ }
159
+ s.prototype.addListener = function(u, h) {
160
+ return g(this, u, h, !1);
161
+ }, s.prototype.on = s.prototype.addListener, s.prototype.prependListener = function(u, h) {
162
+ return g(this, u, h, !0);
163
+ };
164
+ function f() {
165
+ if (!this.fired)
166
+ return this.target.removeListener(this.type, this.wrapFn), this.fired = !0, arguments.length === 0 ? this.listener.call(this.target) : this.listener.apply(this.target, arguments);
167
+ }
168
+ function b(l, u, h) {
169
+ var y = { fired: !1, wrapFn: void 0, target: l, type: u, listener: h }, m = f.bind(y);
170
+ return m.listener = h, y.wrapFn = m, m;
171
+ }
172
+ s.prototype.once = function(u, h) {
173
+ return c(h), this.on(u, b(this, u, h)), this;
174
+ }, s.prototype.prependOnceListener = function(u, h) {
175
+ return c(h), this.prependListener(u, b(this, u, h)), this;
176
+ }, s.prototype.removeListener = function(u, h) {
177
+ var y, m, O, U, L;
178
+ if (c(h), m = this._events, m === void 0)
179
+ return this;
180
+ if (y = m[u], y === void 0)
181
+ return this;
182
+ if (y === h || y.listener === h)
183
+ --this._eventsCount === 0 ? this._events = /* @__PURE__ */ Object.create(null) : (delete m[u], m.removeListener && this.emit("removeListener", u, y.listener || h));
184
+ else if (typeof y != "function") {
185
+ for (O = -1, U = y.length - 1; U >= 0; U--)
186
+ if (y[U] === h || y[U].listener === h) {
187
+ L = y[U].listener, O = U;
188
+ break;
189
+ }
190
+ if (O < 0)
191
+ return this;
192
+ O === 0 ? y.shift() : q(y, O), y.length === 1 && (m[u] = y[0]), m.removeListener !== void 0 && this.emit("removeListener", u, L || h);
193
+ }
194
+ return this;
195
+ }, s.prototype.off = s.prototype.removeListener, s.prototype.removeAllListeners = function(u) {
196
+ var h, y, m;
197
+ if (y = this._events, y === void 0)
198
+ return this;
199
+ if (y.removeListener === void 0)
200
+ return arguments.length === 0 ? (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0) : y[u] !== void 0 && (--this._eventsCount === 0 ? this._events = /* @__PURE__ */ Object.create(null) : delete y[u]), this;
201
+ if (arguments.length === 0) {
202
+ var O = Object.keys(y), U;
203
+ for (m = 0; m < O.length; ++m)
204
+ U = O[m], U !== "removeListener" && this.removeAllListeners(U);
205
+ return this.removeAllListeners("removeListener"), this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0, this;
206
+ }
207
+ if (h = y[u], typeof h == "function")
208
+ this.removeListener(u, h);
209
+ else if (h !== void 0)
210
+ for (m = h.length - 1; m >= 0; m--)
211
+ this.removeListener(u, h[m]);
212
+ return this;
213
+ };
214
+ function I(l, u, h) {
215
+ var y = l._events;
216
+ if (y === void 0)
217
+ return [];
218
+ var m = y[u];
219
+ return m === void 0 ? [] : typeof m == "function" ? h ? [m.listener || m] : [m] : h ? H(m) : D(m, m.length);
220
+ }
221
+ s.prototype.listeners = function(u) {
222
+ return I(this, u, !0);
223
+ }, s.prototype.rawListeners = function(u) {
224
+ return I(this, u, !1);
225
+ }, s.listenerCount = function(l, u) {
226
+ return typeof l.listenerCount == "function" ? l.listenerCount(u) : N.call(l, u);
227
+ }, s.prototype.listenerCount = N;
228
+ function N(l) {
229
+ var u = this._events;
230
+ if (u !== void 0) {
231
+ var h = u[l];
232
+ if (typeof h == "function")
233
+ return 1;
234
+ if (h !== void 0)
235
+ return h.length;
236
+ }
237
+ return 0;
238
+ }
239
+ s.prototype.eventNames = function() {
240
+ return this._eventsCount > 0 ? t(this._events) : [];
241
+ };
242
+ function D(l, u) {
243
+ for (var h = new Array(u), y = 0; y < u; ++y)
244
+ h[y] = l[y];
245
+ return h;
246
+ }
247
+ function q(l, u) {
248
+ for (; u + 1 < l.length; u++)
249
+ l[u] = l[u + 1];
250
+ l.pop();
251
+ }
252
+ function H(l) {
253
+ for (var u = new Array(l.length), h = 0; h < u.length; ++h)
254
+ u[h] = l[h].listener || l[h];
255
+ return u;
256
+ }
257
+ function v(l, u) {
258
+ return new Promise(function(h, y) {
259
+ function m(U) {
260
+ l.removeListener(u, O), y(U);
261
+ }
262
+ function O() {
263
+ typeof l.removeListener == "function" && l.removeListener("error", m), h([].slice.call(arguments));
264
+ }
265
+ S(l, u, O, { once: !0 }), u !== "error" && _(l, m, { once: !0 });
266
+ });
267
+ }
268
+ function _(l, u, h) {
269
+ typeof l.on == "function" && S(l, "error", u, h);
270
+ }
271
+ function S(l, u, h, y) {
272
+ if (typeof l.on == "function")
273
+ y.once ? l.once(u, h) : l.on(u, h);
274
+ else if (typeof l.addEventListener == "function")
275
+ l.addEventListener(u, function m(O) {
276
+ y.once && l.removeEventListener(u, m), h(O);
277
+ });
278
+ else
279
+ throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof l);
280
+ }
281
+ return ee.exports;
282
+ }
283
+ var Ie = Le(), te = { exports: {} }, be;
284
+ function Pe() {
285
+ return be || (be = 1, (function(o, e) {
286
+ var t = typeof globalThis < "u" && globalThis || typeof self < "u" && self || typeof Q < "u" && Q, n = (function() {
287
+ function s() {
288
+ this.fetch = !1, this.DOMException = t.DOMException;
289
+ }
290
+ return s.prototype = t, new s();
291
+ })();
292
+ (function(s) {
293
+ (function(i) {
294
+ var c = typeof s < "u" && s || typeof self < "u" && self || // eslint-disable-next-line no-undef
295
+ typeof Q < "u" && Q || {}, p = {
296
+ searchParams: "URLSearchParams" in c,
297
+ iterable: "Symbol" in c && "iterator" in Symbol,
298
+ blob: "FileReader" in c && "Blob" in c && (function() {
299
+ try {
300
+ return new Blob(), !0;
301
+ } catch {
302
+ return !1;
303
+ }
304
+ })(),
305
+ formData: "FormData" in c,
306
+ arrayBuffer: "ArrayBuffer" in c
307
+ };
308
+ function g(a) {
309
+ return a && DataView.prototype.isPrototypeOf(a);
310
+ }
311
+ if (p.arrayBuffer)
312
+ var f = [
313
+ "[object Int8Array]",
314
+ "[object Uint8Array]",
315
+ "[object Uint8ClampedArray]",
316
+ "[object Int16Array]",
317
+ "[object Uint16Array]",
318
+ "[object Int32Array]",
319
+ "[object Uint32Array]",
320
+ "[object Float32Array]",
321
+ "[object Float64Array]"
322
+ ], b = ArrayBuffer.isView || function(a) {
323
+ return a && f.indexOf(Object.prototype.toString.call(a)) > -1;
324
+ };
325
+ function I(a) {
326
+ if (typeof a != "string" && (a = String(a)), /[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(a) || a === "")
327
+ throw new TypeError('Invalid character in header field name: "' + a + '"');
328
+ return a.toLowerCase();
329
+ }
330
+ function N(a) {
331
+ return typeof a != "string" && (a = String(a)), a;
332
+ }
333
+ function D(a) {
334
+ var d = {
335
+ next: function() {
336
+ var j = a.shift();
337
+ return { done: j === void 0, value: j };
338
+ }
339
+ };
340
+ return p.iterable && (d[Symbol.iterator] = function() {
341
+ return d;
342
+ }), d;
343
+ }
344
+ function q(a) {
345
+ this.map = {}, a instanceof q ? a.forEach(function(d, j) {
346
+ this.append(j, d);
347
+ }, this) : Array.isArray(a) ? a.forEach(function(d) {
348
+ if (d.length != 2)
349
+ throw new TypeError("Headers constructor: expected name/value pair to be length 2, found" + d.length);
350
+ this.append(d[0], d[1]);
351
+ }, this) : a && Object.getOwnPropertyNames(a).forEach(function(d) {
352
+ this.append(d, a[d]);
353
+ }, this);
354
+ }
355
+ q.prototype.append = function(a, d) {
356
+ a = I(a), d = N(d);
357
+ var j = this.map[a];
358
+ this.map[a] = j ? j + ", " + d : d;
359
+ }, q.prototype.delete = function(a) {
360
+ delete this.map[I(a)];
361
+ }, q.prototype.get = function(a) {
362
+ return a = I(a), this.has(a) ? this.map[a] : null;
363
+ }, q.prototype.has = function(a) {
364
+ return this.map.hasOwnProperty(I(a));
365
+ }, q.prototype.set = function(a, d) {
366
+ this.map[I(a)] = N(d);
367
+ }, q.prototype.forEach = function(a, d) {
368
+ for (var j in this.map)
369
+ this.map.hasOwnProperty(j) && a.call(d, this.map[j], j, this);
370
+ }, q.prototype.keys = function() {
371
+ var a = [];
372
+ return this.forEach(function(d, j) {
373
+ a.push(j);
374
+ }), D(a);
375
+ }, q.prototype.values = function() {
376
+ var a = [];
377
+ return this.forEach(function(d) {
378
+ a.push(d);
379
+ }), D(a);
380
+ }, q.prototype.entries = function() {
381
+ var a = [];
382
+ return this.forEach(function(d, j) {
383
+ a.push([j, d]);
384
+ }), D(a);
385
+ }, p.iterable && (q.prototype[Symbol.iterator] = q.prototype.entries);
386
+ function H(a) {
387
+ if (!a._noBody) {
388
+ if (a.bodyUsed)
389
+ return Promise.reject(new TypeError("Already read"));
390
+ a.bodyUsed = !0;
391
+ }
392
+ }
393
+ function v(a) {
394
+ return new Promise(function(d, j) {
395
+ a.onload = function() {
396
+ d(a.result);
397
+ }, a.onerror = function() {
398
+ j(a.error);
399
+ };
400
+ });
401
+ }
402
+ function _(a) {
403
+ var d = new FileReader(), j = v(d);
404
+ return d.readAsArrayBuffer(a), j;
405
+ }
406
+ function S(a) {
407
+ var d = new FileReader(), j = v(d), R = /charset=([A-Za-z0-9_-]+)/.exec(a.type), x = R ? R[1] : "utf-8";
408
+ return d.readAsText(a, x), j;
409
+ }
410
+ function l(a) {
411
+ for (var d = new Uint8Array(a), j = new Array(d.length), R = 0; R < d.length; R++)
412
+ j[R] = String.fromCharCode(d[R]);
413
+ return j.join("");
414
+ }
415
+ function u(a) {
416
+ if (a.slice)
417
+ return a.slice(0);
418
+ var d = new Uint8Array(a.byteLength);
419
+ return d.set(new Uint8Array(a)), d.buffer;
420
+ }
421
+ function h() {
422
+ return this.bodyUsed = !1, this._initBody = function(a) {
423
+ this.bodyUsed = this.bodyUsed, this._bodyInit = a, a ? typeof a == "string" ? this._bodyText = a : p.blob && Blob.prototype.isPrototypeOf(a) ? this._bodyBlob = a : p.formData && FormData.prototype.isPrototypeOf(a) ? this._bodyFormData = a : p.searchParams && URLSearchParams.prototype.isPrototypeOf(a) ? this._bodyText = a.toString() : p.arrayBuffer && p.blob && g(a) ? (this._bodyArrayBuffer = u(a.buffer), this._bodyInit = new Blob([this._bodyArrayBuffer])) : p.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(a) || b(a)) ? this._bodyArrayBuffer = u(a) : this._bodyText = a = Object.prototype.toString.call(a) : (this._noBody = !0, this._bodyText = ""), this.headers.get("content-type") || (typeof a == "string" ? this.headers.set("content-type", "text/plain;charset=UTF-8") : this._bodyBlob && this._bodyBlob.type ? this.headers.set("content-type", this._bodyBlob.type) : p.searchParams && URLSearchParams.prototype.isPrototypeOf(a) && this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8"));
424
+ }, p.blob && (this.blob = function() {
425
+ var a = H(this);
426
+ if (a)
427
+ return a;
428
+ if (this._bodyBlob)
429
+ return Promise.resolve(this._bodyBlob);
430
+ if (this._bodyArrayBuffer)
431
+ return Promise.resolve(new Blob([this._bodyArrayBuffer]));
432
+ if (this._bodyFormData)
433
+ throw new Error("could not read FormData body as blob");
434
+ return Promise.resolve(new Blob([this._bodyText]));
435
+ }), this.arrayBuffer = function() {
436
+ if (this._bodyArrayBuffer) {
437
+ var a = H(this);
438
+ return a || (ArrayBuffer.isView(this._bodyArrayBuffer) ? Promise.resolve(
439
+ this._bodyArrayBuffer.buffer.slice(
440
+ this._bodyArrayBuffer.byteOffset,
441
+ this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength
442
+ )
443
+ ) : Promise.resolve(this._bodyArrayBuffer));
444
+ } else {
445
+ if (p.blob)
446
+ return this.blob().then(_);
447
+ throw new Error("could not read as ArrayBuffer");
448
+ }
449
+ }, this.text = function() {
450
+ var a = H(this);
451
+ if (a)
452
+ return a;
453
+ if (this._bodyBlob)
454
+ return S(this._bodyBlob);
455
+ if (this._bodyArrayBuffer)
456
+ return Promise.resolve(l(this._bodyArrayBuffer));
457
+ if (this._bodyFormData)
458
+ throw new Error("could not read FormData body as text");
459
+ return Promise.resolve(this._bodyText);
460
+ }, p.formData && (this.formData = function() {
461
+ return this.text().then(U);
462
+ }), this.json = function() {
463
+ return this.text().then(JSON.parse);
464
+ }, this;
465
+ }
466
+ var y = ["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"];
467
+ function m(a) {
468
+ var d = a.toUpperCase();
469
+ return y.indexOf(d) > -1 ? d : a;
470
+ }
471
+ function O(a, d) {
472
+ if (!(this instanceof O))
473
+ throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
474
+ d = d || {};
475
+ var j = d.body;
476
+ if (a instanceof O) {
477
+ if (a.bodyUsed)
478
+ throw new TypeError("Already read");
479
+ this.url = a.url, this.credentials = a.credentials, d.headers || (this.headers = new q(a.headers)), this.method = a.method, this.mode = a.mode, this.signal = a.signal, !j && a._bodyInit != null && (j = a._bodyInit, a.bodyUsed = !0);
480
+ } else
481
+ this.url = String(a);
482
+ if (this.credentials = d.credentials || this.credentials || "same-origin", (d.headers || !this.headers) && (this.headers = new q(d.headers)), this.method = m(d.method || this.method || "GET"), this.mode = d.mode || this.mode || null, this.signal = d.signal || this.signal || (function() {
483
+ if ("AbortController" in c) {
484
+ var E = new AbortController();
485
+ return E.signal;
486
+ }
487
+ })(), this.referrer = null, (this.method === "GET" || this.method === "HEAD") && j)
488
+ throw new TypeError("Body not allowed for GET or HEAD requests");
489
+ if (this._initBody(j), (this.method === "GET" || this.method === "HEAD") && (d.cache === "no-store" || d.cache === "no-cache")) {
490
+ var R = /([?&])_=[^&]*/;
491
+ if (R.test(this.url))
492
+ this.url = this.url.replace(R, "$1_=" + (/* @__PURE__ */ new Date()).getTime());
493
+ else {
494
+ var x = /\?/;
495
+ this.url += (x.test(this.url) ? "&" : "?") + "_=" + (/* @__PURE__ */ new Date()).getTime();
496
+ }
497
+ }
498
+ }
499
+ O.prototype.clone = function() {
500
+ return new O(this, { body: this._bodyInit });
501
+ };
502
+ function U(a) {
503
+ var d = new FormData();
504
+ return a.trim().split("&").forEach(function(j) {
505
+ if (j) {
506
+ var R = j.split("="), x = R.shift().replace(/\+/g, " "), E = R.join("=").replace(/\+/g, " ");
507
+ d.append(decodeURIComponent(x), decodeURIComponent(E));
508
+ }
509
+ }), d;
510
+ }
511
+ function L(a) {
512
+ var d = new q(), j = a.replace(/\r?\n[\t ]+/g, " ");
513
+ return j.split("\r").map(function(R) {
514
+ return R.indexOf(`
515
+ `) === 0 ? R.substr(1, R.length) : R;
516
+ }).forEach(function(R) {
517
+ var x = R.split(":"), E = x.shift().trim();
518
+ if (E) {
519
+ var Z = x.join(":").trim();
520
+ try {
521
+ d.append(E, Z);
522
+ } catch (le) {
523
+ console.warn("Response " + le.message);
524
+ }
525
+ }
526
+ }), d;
527
+ }
528
+ h.call(O.prototype);
529
+ function A(a, d) {
530
+ if (!(this instanceof A))
531
+ throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
532
+ if (d || (d = {}), this.type = "default", this.status = d.status === void 0 ? 200 : d.status, this.status < 200 || this.status > 599)
533
+ throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");
534
+ this.ok = this.status >= 200 && this.status < 300, this.statusText = d.statusText === void 0 ? "" : "" + d.statusText, this.headers = new q(d.headers), this.url = d.url || "", this._initBody(a);
535
+ }
536
+ h.call(A.prototype), A.prototype.clone = function() {
537
+ return new A(this._bodyInit, {
538
+ status: this.status,
539
+ statusText: this.statusText,
540
+ headers: new q(this.headers),
541
+ url: this.url
542
+ });
543
+ }, A.error = function() {
544
+ var a = new A(null, { status: 200, statusText: "" });
545
+ return a.ok = !1, a.status = 0, a.type = "error", a;
546
+ };
547
+ var Y = [301, 302, 303, 307, 308];
548
+ A.redirect = function(a, d) {
549
+ if (Y.indexOf(d) === -1)
550
+ throw new RangeError("Invalid status code");
551
+ return new A(null, { status: d, headers: { location: a } });
552
+ }, i.DOMException = c.DOMException;
553
+ try {
554
+ new i.DOMException();
555
+ } catch {
556
+ i.DOMException = function(d, j) {
557
+ this.message = d, this.name = j;
558
+ var R = Error(d);
559
+ this.stack = R.stack;
560
+ }, i.DOMException.prototype = Object.create(Error.prototype), i.DOMException.prototype.constructor = i.DOMException;
561
+ }
562
+ function $(a, d) {
563
+ return new Promise(function(j, R) {
564
+ var x = new O(a, d);
565
+ if (x.signal && x.signal.aborted)
566
+ return R(new i.DOMException("Aborted", "AbortError"));
567
+ var E = new XMLHttpRequest();
568
+ function Z() {
569
+ E.abort();
570
+ }
571
+ E.onload = function() {
572
+ var T = {
573
+ statusText: E.statusText,
574
+ headers: L(E.getAllResponseHeaders() || "")
575
+ };
576
+ x.url.indexOf("file://") === 0 && (E.status < 200 || E.status > 599) ? T.status = 200 : T.status = E.status, T.url = "responseURL" in E ? E.responseURL : T.headers.get("X-Request-URL");
577
+ var J = "response" in E ? E.response : E.responseText;
578
+ setTimeout(function() {
579
+ j(new A(J, T));
580
+ }, 0);
581
+ }, E.onerror = function() {
582
+ setTimeout(function() {
583
+ R(new TypeError("Network request failed"));
584
+ }, 0);
585
+ }, E.ontimeout = function() {
586
+ setTimeout(function() {
587
+ R(new TypeError("Network request timed out"));
588
+ }, 0);
589
+ }, E.onabort = function() {
590
+ setTimeout(function() {
591
+ R(new i.DOMException("Aborted", "AbortError"));
592
+ }, 0);
593
+ };
594
+ function le(T) {
595
+ try {
596
+ return T === "" && c.location.href ? c.location.href : T;
597
+ } catch {
598
+ return T;
599
+ }
600
+ }
601
+ if (E.open(x.method, le(x.url), !0), x.credentials === "include" ? E.withCredentials = !0 : x.credentials === "omit" && (E.withCredentials = !1), "responseType" in E && (p.blob ? E.responseType = "blob" : p.arrayBuffer && (E.responseType = "arraybuffer")), d && typeof d.headers == "object" && !(d.headers instanceof q || c.Headers && d.headers instanceof c.Headers)) {
602
+ var ge = [];
603
+ Object.getOwnPropertyNames(d.headers).forEach(function(T) {
604
+ ge.push(I(T)), E.setRequestHeader(T, N(d.headers[T]));
605
+ }), x.headers.forEach(function(T, J) {
606
+ ge.indexOf(J) === -1 && E.setRequestHeader(J, T);
607
+ });
608
+ } else
609
+ x.headers.forEach(function(T, J) {
610
+ E.setRequestHeader(J, T);
611
+ });
612
+ x.signal && (x.signal.addEventListener("abort", Z), E.onreadystatechange = function() {
613
+ E.readyState === 4 && x.signal.removeEventListener("abort", Z);
614
+ }), E.send(typeof x._bodyInit > "u" ? null : x._bodyInit);
615
+ });
616
+ }
617
+ return $.polyfill = !0, c.fetch || (c.fetch = $, c.Headers = q, c.Request = O, c.Response = A), i.Headers = q, i.Request = O, i.Response = A, i.fetch = $, Object.defineProperty(i, "__esModule", { value: !0 }), i;
618
+ })({});
619
+ })(n), n.fetch.ponyfill = !0, delete n.fetch.polyfill;
620
+ var r = t.fetch ? t : n;
621
+ e = r.fetch, e.default = r.fetch, e.fetch = r.fetch, e.Headers = r.Headers, e.Request = r.Request, e.Response = r.Response, o.exports = e;
622
+ })(te, te.exports)), te.exports;
623
+ }
624
+ var pe = Pe();
625
+ const Ee = /* @__PURE__ */ Oe(pe), Ne = /* @__PURE__ */ Te({
626
+ __proto__: null,
627
+ default: Ee
628
+ }, [pe]);
629
+ var de, me;
630
+ function De() {
631
+ if (me) return de;
632
+ me = 1;
633
+ var o = function(_) {
634
+ return e(_) && !t(_);
635
+ };
636
+ function e(v) {
637
+ return !!v && typeof v == "object";
638
+ }
639
+ function t(v) {
640
+ var _ = Object.prototype.toString.call(v);
641
+ return _ === "[object RegExp]" || _ === "[object Date]" || s(v);
642
+ }
643
+ var n = typeof Symbol == "function" && Symbol.for, r = n ? /* @__PURE__ */ Symbol.for("react.element") : 60103;
644
+ function s(v) {
645
+ return v.$$typeof === r;
646
+ }
647
+ function i(v) {
648
+ return Array.isArray(v) ? [] : {};
649
+ }
650
+ function c(v, _) {
651
+ return _.clone !== !1 && _.isMergeableObject(v) ? q(i(v), v, _) : v;
652
+ }
653
+ function p(v, _, S) {
654
+ return v.concat(_).map(function(l) {
655
+ return c(l, S);
656
+ });
657
+ }
658
+ function g(v, _) {
659
+ if (!_.customMerge)
660
+ return q;
661
+ var S = _.customMerge(v);
662
+ return typeof S == "function" ? S : q;
663
+ }
664
+ function f(v) {
665
+ return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(v).filter(function(_) {
666
+ return Object.propertyIsEnumerable.call(v, _);
667
+ }) : [];
668
+ }
669
+ function b(v) {
670
+ return Object.keys(v).concat(f(v));
671
+ }
672
+ function I(v, _) {
673
+ try {
674
+ return _ in v;
675
+ } catch {
676
+ return !1;
677
+ }
678
+ }
679
+ function N(v, _) {
680
+ return I(v, _) && !(Object.hasOwnProperty.call(v, _) && Object.propertyIsEnumerable.call(v, _));
681
+ }
682
+ function D(v, _, S) {
683
+ var l = {};
684
+ return S.isMergeableObject(v) && b(v).forEach(function(u) {
685
+ l[u] = c(v[u], S);
686
+ }), b(_).forEach(function(u) {
687
+ N(v, u) || (I(v, u) && S.isMergeableObject(_[u]) ? l[u] = g(u, S)(v[u], _[u], S) : l[u] = c(_[u], S));
688
+ }), l;
689
+ }
690
+ function q(v, _, S) {
691
+ S = S || {}, S.arrayMerge = S.arrayMerge || p, S.isMergeableObject = S.isMergeableObject || o, S.cloneUnlessOtherwiseSpecified = c;
692
+ var l = Array.isArray(_), u = Array.isArray(v), h = l === u;
693
+ return h ? l ? S.arrayMerge(v, _, S) : D(v, _, S) : c(_, S);
694
+ }
695
+ q.all = function(_, S) {
696
+ if (!Array.isArray(_))
697
+ throw new Error("first argument should be an array");
698
+ return _.reduce(function(l, u) {
699
+ return q(l, u, S);
700
+ }, {});
701
+ };
702
+ var H = q;
703
+ return de = H, de;
704
+ }
705
+ var Fe = De();
706
+ const K = /* @__PURE__ */ Oe(Fe), Se = typeof process < "u" && process.versions && process.versions.node ? process.versions.node : "unknown", qe = typeof process < "u" && process.versions && process.versions.bun ? process.versions.bun : "unknown", Re = typeof window < "u" && window.navigator && window.navigator.userAgent ? window.navigator.userAgent : "unknown", ce = () => Re !== "unknown", He = () => Se !== "unknown", ke = () => qe !== "unknown";
707
+ function we(o = {}, e = {}) {
708
+ return K(e, o);
709
+ }
710
+ function Je(o, e) {
711
+ Object.keys(e).forEach((t) => {
712
+ Array.isArray(e[t]) ? e[t].forEach((r) => {
713
+ o.append(t, String(r));
714
+ }) : o.append(t, String(e[t]));
715
+ });
716
+ }
717
+ const We = () => typeof Headers > "u" ? pe.Headers : Headers, oe = (o) => !!(o && o.url), he = (o) => !!(o && o.text), _e = (o) => !!(Ge(o) || ze(o)), ze = (o) => o != null && Buffer.isBuffer(o), Ge = (o) => o == null || ce() ? !1 : typeof o == "object" && typeof o.pipe == "function" && typeof o.read == "function" && typeof o._readableState == "object", Ve = (o) => ((t) => t.toLowerCase().replace(/^http/, "ws"))(o), Ke = (o) => {
718
+ var e, t, n, r, s, i;
719
+ const c = {};
720
+ return o._experimentalCustomFetch && (c.global = {
721
+ fetch: {
722
+ client: o._experimentalCustomFetch
723
+ }
724
+ }), o = K(o, c), !((e = o.restProxy) === null || e === void 0) && e.url && (c.global = {
725
+ fetch: {
726
+ options: {
727
+ proxy: {
728
+ url: (t = o.restProxy) === null || t === void 0 ? void 0 : t.url
729
+ }
730
+ }
731
+ }
732
+ }), o = K(o, c), !((n = o.global) === null || n === void 0) && n.url && (c.global = {
733
+ fetch: {
734
+ options: {
735
+ url: o.global.url
736
+ }
737
+ },
738
+ websocket: {
739
+ options: {
740
+ url: o.global.url
741
+ }
742
+ }
743
+ }), o = K(o, c), !((r = o.global) === null || r === void 0) && r.headers && (c.global = {
744
+ fetch: {
745
+ options: {
746
+ headers: (s = o.global) === null || s === void 0 ? void 0 : s.headers
747
+ }
748
+ },
749
+ websocket: {
750
+ options: {
751
+ _nodeOnlyHeaders: (i = o.global) === null || i === void 0 ? void 0 : i.headers
752
+ }
753
+ }
754
+ }), o = K(o, c), o;
755
+ }, je = "4.11.3", $e = () => He() ? `node/${Se}` : ke() ? `bun/${qe}` : ce() ? `javascript ${Re}` : "unknown", ae = {
756
+ "Content-Type": "application/json",
757
+ "X-Client-Info": `@deepgram/sdk; ${ce() ? "browser" : "server"}; v${je}`,
758
+ "User-Agent": `@deepgram/sdk/${je} ${$e()}`
759
+ }, ue = "https://api.deepgram.com", xe = "wss://agent.deepgram.com", Xe = {
760
+ fetch: { options: { url: ue, headers: ae } },
761
+ websocket: {
762
+ options: { url: Ve(ue), _nodeOnlyHeaders: ae }
763
+ }
764
+ }, Ye = {
765
+ fetch: { options: { url: ue, headers: ae } },
766
+ websocket: {
767
+ options: { url: xe, _nodeOnlyHeaders: ae }
768
+ }
769
+ }, Ze = {
770
+ global: Xe,
771
+ agent: Ye
772
+ };
773
+ var G;
774
+ (function(o) {
775
+ o[o.connecting = 0] = "connecting", o[o.open = 1] = "open", o[o.closing = 2] = "closing", o[o.closed = 3] = "closed";
776
+ })(G || (G = {}));
777
+ var z;
778
+ (function(o) {
779
+ o.Connecting = "connecting", o.Open = "open", o.Closing = "closing", o.Closed = "closed";
780
+ })(z || (z = {}));
781
+ const Ce = () => {
782
+ };
783
+ class X extends Ie.EventEmitter {
784
+ /**
785
+ * Constructs a new instance of the DeepgramClient class with the provided options.
786
+ *
787
+ * @param options - The options to configure the DeepgramClient instance.
788
+ * @param options.key - The Deepgram API key to use for authentication. If not provided, the `DEEPGRAM_API_KEY` environment variable will be used.
789
+ * @param options.accessToken - The Deepgram access token to use for authentication. If not provided, the `DEEPGRAM_ACCESS_TOKEN` environment variable will be used.
790
+ * @param options.global - Global options that apply to all requests made by the DeepgramClient instance.
791
+ * @param options.global.fetch - Options to configure the fetch requests made by the DeepgramClient instance.
792
+ * @param options.global.fetch.options - Additional options to pass to the fetch function, such as `url` and `headers`.
793
+ * @param options.namespace - Options specific to a particular namespace within the DeepgramClient instance.
794
+ */
795
+ constructor(e) {
796
+ if (super(), this.factory = void 0, this.key = void 0, this.accessToken = void 0, this.namespace = "global", this.version = "v1", this.baseUrl = ue, this.logger = Ce, typeof e.accessToken == "function" ? (this.factory = e.accessToken, this.accessToken = this.factory()) : this.accessToken = e.accessToken, typeof e.key == "function" ? (this.factory = e.key, this.key = this.factory()) : this.key = e.key, !this.key && !this.accessToken && (this.accessToken = process.env.DEEPGRAM_ACCESS_TOKEN, this.accessToken || (this.key = process.env.DEEPGRAM_API_KEY)), !this.key && !this.accessToken)
797
+ throw new C("A deepgram API key or access token is required.");
798
+ e = Ke(e), this.options = we(e, Ze);
799
+ }
800
+ /**
801
+ * Sets the version for the current instance of the Deepgram API and returns the instance.
802
+ *
803
+ * @param version - The version to set for the Deepgram API instance. Defaults to "v1" if not provided.
804
+ * @returns The current instance of the AbstractClient with the updated version.
805
+ */
806
+ v(e = "v1") {
807
+ return this.version = e, this;
808
+ }
809
+ /**
810
+ * Gets the namespace options for the current instance of the AbstractClient.
811
+ * The namespace options include the default options merged with the global options,
812
+ * and the API key for the current instance.
813
+ *
814
+ * @returns The namespace options for the current instance.
815
+ */
816
+ get namespaceOptions() {
817
+ const e = we(this.options[this.namespace], this.options.global);
818
+ return Object.assign(Object.assign({}, e), { key: this.key });
819
+ }
820
+ /**
821
+ * Generates a URL for an API endpoint with optional query parameters and transcription options.
822
+ *
823
+ * @param endpoint - The API endpoint URL, which may contain placeholders for fields.
824
+ * @param fields - An optional object containing key-value pairs to replace placeholders in the endpoint URL.
825
+ * @param transcriptionOptions - Optional transcription options to include as query parameters in the URL.
826
+ * @returns A URL object representing the constructed API request URL.
827
+ */
828
+ getRequestUrl(e, t = { version: this.version }, n) {
829
+ t.version = this.version, e = e.replace(/:(\w+)/g, function(s, i) {
830
+ return t[i];
831
+ });
832
+ const r = new URL(e, this.baseUrl);
833
+ return n && Je(r.searchParams, n), r;
834
+ }
835
+ /**
836
+ * Logs the message.
837
+ *
838
+ * For customized logging, `this.logger` can be overridden.
839
+ */
840
+ log(e, t, n) {
841
+ this.logger(e, t, n);
842
+ }
843
+ }
844
+ var Qe = function(o, e, t, n) {
845
+ function r(s) {
846
+ return s instanceof t ? s : new t(function(i) {
847
+ i(s);
848
+ });
849
+ }
850
+ return new (t || (t = Promise))(function(s, i) {
851
+ function c(f) {
852
+ try {
853
+ g(n.next(f));
854
+ } catch (b) {
855
+ i(b);
856
+ }
857
+ }
858
+ function p(f) {
859
+ try {
860
+ g(n.throw(f));
861
+ } catch (b) {
862
+ i(b);
863
+ }
864
+ }
865
+ function g(f) {
866
+ f.done ? s(f.value) : r(f.value).then(c, p);
867
+ }
868
+ g((n = n.apply(o, e || [])).next());
869
+ });
870
+ };
871
+ const et = typeof WebSocket < "u";
872
+ class ye extends X {
873
+ constructor(e) {
874
+ super(e), this.conn = null, this.sendBuffer = [], this.reconnect = Ce;
875
+ const { key: t, websocket: { options: n, client: r } } = this.namespaceOptions;
876
+ this.proxy ? this.baseUrl = n.proxy.url : this.baseUrl = n.url, r ? this.transport = r : this.transport = null, n._nodeOnlyHeaders ? this.headers = n._nodeOnlyHeaders : this.headers = {}, "Authorization" in this.headers || (this.accessToken ? this.headers.Authorization = `Bearer ${this.accessToken}` : this.headers.Authorization = `Token ${t}`);
877
+ }
878
+ /**
879
+ * Connects the socket, unless already connected.
880
+ *
881
+ * @protected Can only be called from within the class.
882
+ */
883
+ connect(e, t) {
884
+ if (this.conn)
885
+ return;
886
+ this.reconnect = (i = e) => {
887
+ this.connect(i, t);
888
+ };
889
+ const n = this.getRequestUrl(t, {}, e), r = this.accessToken, s = this.key;
890
+ if (!r && !s)
891
+ throw new Error("No key or access token provided for WebSocket connection.");
892
+ if (this.transport) {
893
+ this.conn = new this.transport(n, void 0, {
894
+ headers: this.headers
895
+ }), this.setupConnection();
896
+ return;
897
+ }
898
+ if (ke()) {
899
+ import("./browser-C7NgeXQY.js").then((i) => i.b).then(({ default: i }) => {
900
+ this.conn = new i(n, {
901
+ headers: this.headers
902
+ }), console.log("Using WS package"), this.setupConnection();
903
+ });
904
+ return;
905
+ }
906
+ if (et) {
907
+ this.conn = new WebSocket(n, r ? ["bearer", r] : ["token", s]), this.setupConnection();
908
+ return;
909
+ }
910
+ this.conn = new tt(n, void 0, {
911
+ close: () => {
912
+ this.conn = null;
913
+ }
914
+ }), import("./browser-C7NgeXQY.js").then((i) => i.b).then(({ default: i }) => {
915
+ this.conn = new i(n, void 0, {
916
+ headers: this.headers
917
+ }), this.setupConnection();
918
+ });
919
+ }
920
+ /**
921
+ * Disconnects the socket from the client.
922
+ *
923
+ * @param code A numeric status code to send on disconnect.
924
+ * @param reason A custom reason for the disconnect.
925
+ */
926
+ disconnect(e, t) {
927
+ this.conn && (this.conn.onclose = function() {
928
+ }, e ? this.conn.close(e, t ?? "") : this.conn.close(), this.conn = null);
929
+ }
930
+ /**
931
+ * Returns the current connection state of the WebSocket connection.
932
+ *
933
+ * @returns The current connection state of the WebSocket connection.
934
+ */
935
+ connectionState() {
936
+ switch (this.conn && this.conn.readyState) {
937
+ case G.connecting:
938
+ return z.Connecting;
939
+ case G.open:
940
+ return z.Open;
941
+ case G.closing:
942
+ return z.Closing;
943
+ default:
944
+ return z.Closed;
945
+ }
946
+ }
947
+ /**
948
+ * Returns the current ready state of the WebSocket connection.
949
+ *
950
+ * @returns The current ready state of the WebSocket connection.
951
+ */
952
+ getReadyState() {
953
+ var e, t;
954
+ return (t = (e = this.conn) === null || e === void 0 ? void 0 : e.readyState) !== null && t !== void 0 ? t : G.closed;
955
+ }
956
+ /**
957
+ * Returns `true` is the connection is open.
958
+ */
959
+ isConnected() {
960
+ return this.connectionState() === z.Open;
961
+ }
962
+ /**
963
+ * Sends data to the Deepgram API via websocket connection
964
+ * @param data Audio data to send to Deepgram
965
+ *
966
+ * Conforms to RFC #146 for Node.js - does not send an empty byte.
967
+ * @see https://github.com/deepgram/deepgram-python-sdk/issues/146
968
+ */
969
+ send(e) {
970
+ const t = () => Qe(this, void 0, void 0, function* () {
971
+ var n;
972
+ if (e instanceof Blob) {
973
+ if (e.size === 0) {
974
+ this.log("warn", "skipping `send` for zero-byte blob", e);
975
+ return;
976
+ }
977
+ e = yield e.arrayBuffer();
978
+ }
979
+ if (typeof e != "string" && !e?.byteLength) {
980
+ this.log("warn", "skipping `send` for zero-byte payload", e);
981
+ return;
982
+ }
983
+ (n = this.conn) === null || n === void 0 || n.send(e);
984
+ });
985
+ this.isConnected() ? t() : this.sendBuffer.push(t);
986
+ }
987
+ /**
988
+ * Determines whether the current instance should proxy requests.
989
+ * @returns {boolean} true if the current instance should proxy requests; otherwise, false
990
+ */
991
+ get proxy() {
992
+ var e;
993
+ return this.key === "proxy" && !!(!((e = this.namespaceOptions.websocket.options.proxy) === null || e === void 0) && e.url);
994
+ }
995
+ /**
996
+ * Extracts enhanced error information from a WebSocket error event.
997
+ * This method attempts to capture additional debugging information such as
998
+ * status codes, request IDs, and response headers when available.
999
+ *
1000
+ * @example
1001
+ * ```typescript
1002
+ * // Enhanced error information is now available in error events:
1003
+ * connection.on(LiveTranscriptionEvents.Error, (err) => {
1004
+ * console.error("WebSocket Error:", err.message);
1005
+ *
1006
+ * // Access HTTP status code (e.g., 502, 403, etc.)
1007
+ * if (err.statusCode) {
1008
+ * console.error(`HTTP Status Code: ${err.statusCode}`);
1009
+ * }
1010
+ *
1011
+ * // Access Deepgram request ID for support tickets
1012
+ * if (err.requestId) {
1013
+ * console.error(`Deepgram Request ID: ${err.requestId}`);
1014
+ * }
1015
+ *
1016
+ * // Access WebSocket URL and connection state
1017
+ * if (err.url) {
1018
+ * console.error(`WebSocket URL: ${err.url}`);
1019
+ * }
1020
+ *
1021
+ * if (err.readyState !== undefined) {
1022
+ * const stateNames = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
1023
+ * console.error(`Connection State: ${stateNames[err.readyState]}`);
1024
+ * }
1025
+ *
1026
+ * // Access response headers for additional debugging
1027
+ * if (err.responseHeaders) {
1028
+ * console.error("Response Headers:", err.responseHeaders);
1029
+ * }
1030
+ *
1031
+ * // Access the enhanced error object for detailed debugging
1032
+ * if (err.error?.name === 'DeepgramWebSocketError') {
1033
+ * console.error("Enhanced Error Details:", err.error.toJSON());
1034
+ * }
1035
+ * });
1036
+ * ```
1037
+ *
1038
+ * @param event - The error event from the WebSocket
1039
+ * @param conn - The WebSocket connection object
1040
+ * @returns Enhanced error information object
1041
+ */
1042
+ extractErrorInformation(e, t) {
1043
+ var n;
1044
+ const r = {};
1045
+ if (t && (r.readyState = t.readyState, r.url = typeof t.url == "string" ? t.url : (n = t.url) === null || n === void 0 ? void 0 : n.toString()), t && typeof t == "object") {
1046
+ const s = t;
1047
+ if (s._req && s._req.res && (r.statusCode = s._req.res.statusCode, s._req.res.headers)) {
1048
+ r.responseHeaders = Object.assign({}, s._req.res.headers);
1049
+ const i = s._req.res.headers["dg-request-id"] || s._req.res.headers["x-dg-request-id"];
1050
+ i && (r.requestId = i);
1051
+ }
1052
+ if (e && "target" in e && e.target) {
1053
+ const i = e.target;
1054
+ i.url && (r.url = i.url), i.readyState !== void 0 && (r.readyState = i.readyState);
1055
+ }
1056
+ }
1057
+ return r;
1058
+ }
1059
+ /**
1060
+ * Creates an enhanced error object with additional debugging information.
1061
+ * This method provides backward compatibility by including both the original
1062
+ * error event and enhanced error information.
1063
+ *
1064
+ * @param event - The original error event
1065
+ * @param enhancedInfo - Additional error information extracted from the connection
1066
+ * @returns An object containing both original and enhanced error information
1067
+ */
1068
+ createEnhancedError(e, t) {
1069
+ const n = new Me(e.message || "WebSocket connection error", Object.assign({ originalEvent: e }, t));
1070
+ return Object.assign(Object.assign({}, e), {
1071
+ // Enhanced error information
1072
+ error: n,
1073
+ // Additional fields for easier access
1074
+ statusCode: t.statusCode,
1075
+ requestId: t.requestId,
1076
+ responseHeaders: t.responseHeaders,
1077
+ url: t.url,
1078
+ readyState: t.readyState,
1079
+ // Enhanced message with more context
1080
+ message: this.buildEnhancedErrorMessage(e, t)
1081
+ });
1082
+ }
1083
+ /**
1084
+ * Builds an enhanced error message with additional context information.
1085
+ *
1086
+ * @param event - The original error event
1087
+ * @param enhancedInfo - Additional error information
1088
+ * @returns A more descriptive error message
1089
+ */
1090
+ buildEnhancedErrorMessage(e, t) {
1091
+ let n = e.message || "WebSocket connection error";
1092
+ const r = [];
1093
+ if (t.statusCode && r.push(`Status: ${t.statusCode}`), t.requestId && r.push(`Request ID: ${t.requestId}`), t.readyState !== void 0) {
1094
+ const i = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"][t.readyState] || `Unknown(${t.readyState})`;
1095
+ r.push(`Ready State: ${i}`);
1096
+ }
1097
+ return t.url && r.push(`URL: ${t.url}`), r.length > 0 && (n += ` (${r.join(", ")})`), n;
1098
+ }
1099
+ /**
1100
+ * Sets up the standard connection event handlers (open, close, error) for WebSocket connections.
1101
+ * This method abstracts the common connection event registration pattern used across all live clients.
1102
+ *
1103
+ * @param events - Object containing the event constants for the specific client type
1104
+ * @param events.Open - Event constant for connection open
1105
+ * @param events.Close - Event constant for connection close
1106
+ * @param events.Error - Event constant for connection error
1107
+ * @protected
1108
+ */
1109
+ setupConnectionEvents(e) {
1110
+ this.conn && (this.conn.onopen = () => {
1111
+ this.emit(e.Open, this);
1112
+ }, this.conn.onclose = (t) => {
1113
+ this.emit(e.Close, t);
1114
+ }, this.conn.onerror = (t) => {
1115
+ const n = this.extractErrorInformation(t, this.conn || void 0), r = this.createEnhancedError(t, n);
1116
+ this.emit(e.Error, r);
1117
+ });
1118
+ }
1119
+ }
1120
+ class tt {
1121
+ constructor(e, t, n) {
1122
+ this.binaryType = "arraybuffer", this.onclose = () => {
1123
+ }, this.onerror = () => {
1124
+ }, this.onmessage = () => {
1125
+ }, this.onopen = () => {
1126
+ }, this.readyState = G.connecting, this.send = () => {
1127
+ }, this.url = null, this.url = e.toString(), this.close = n.close;
1128
+ }
1129
+ }
1130
+ var Ae = function(o, e, t, n) {
1131
+ function r(s) {
1132
+ return s instanceof t ? s : new t(function(i) {
1133
+ i(s);
1134
+ });
1135
+ }
1136
+ return new (t || (t = Promise))(function(s, i) {
1137
+ function c(f) {
1138
+ try {
1139
+ g(n.next(f));
1140
+ } catch (b) {
1141
+ i(b);
1142
+ }
1143
+ }
1144
+ function p(f) {
1145
+ try {
1146
+ g(n.throw(f));
1147
+ } catch (b) {
1148
+ i(b);
1149
+ }
1150
+ }
1151
+ function g(f) {
1152
+ f.done ? s(f.value) : r(f.value).then(c, p);
1153
+ }
1154
+ g((n = n.apply(o, e || [])).next());
1155
+ });
1156
+ };
1157
+ const rt = (o) => {
1158
+ let e;
1159
+ return o ? e = o : typeof fetch > "u" ? e = Ee : e = fetch, (...t) => e(...t);
1160
+ }, nt = ({ apiKey: o, customFetch: e, accessToken: t }) => {
1161
+ const n = rt(e), r = We();
1162
+ return (s, i) => Ae(void 0, void 0, void 0, function* () {
1163
+ const c = new r(i?.headers);
1164
+ return c.has("Authorization") || c.set("Authorization", t ? `Bearer ${t}` : `Token ${o}`), n(s, Object.assign(Object.assign({}, i), { headers: c }));
1165
+ });
1166
+ }, st = () => Ae(void 0, void 0, void 0, function* () {
1167
+ return typeof Response > "u" ? (yield Promise.resolve().then(() => Ne)).Response : Response;
1168
+ });
1169
+ var W = function(o, e, t, n) {
1170
+ function r(s) {
1171
+ return s instanceof t ? s : new t(function(i) {
1172
+ i(s);
1173
+ });
1174
+ }
1175
+ return new (t || (t = Promise))(function(s, i) {
1176
+ function c(f) {
1177
+ try {
1178
+ g(n.next(f));
1179
+ } catch (b) {
1180
+ i(b);
1181
+ }
1182
+ }
1183
+ function p(f) {
1184
+ try {
1185
+ g(n.throw(f));
1186
+ } catch (b) {
1187
+ i(b);
1188
+ }
1189
+ }
1190
+ function g(f) {
1191
+ f.done ? s(f.value) : r(f.value).then(c, p);
1192
+ }
1193
+ g((n = n.apply(o, e || [])).next());
1194
+ });
1195
+ };
1196
+ class V extends X {
1197
+ /**
1198
+ * Constructs a new instance of the `AbstractRestClient` class with the provided options.
1199
+ *
1200
+ * @param options - The client options to use for this instance.
1201
+ * @throws {DeepgramError} If the client is being used in a browser and no proxy is provided.
1202
+ */
1203
+ constructor(e) {
1204
+ if (super(e), ce() && !this.proxy)
1205
+ throw new C("Due to CORS we are unable to support REST-based API calls to our API from the browser. Please consider using a proxy: https://dpgr.am/js-proxy for more information.");
1206
+ const { accessToken: t, key: n, fetch: r } = this;
1207
+ this.fetch = nt({ accessToken: t, apiKey: n, customFetch: r }), this.proxy ? this.baseUrl = this.namespaceOptions.fetch.options.proxy.url : this.baseUrl = this.namespaceOptions.fetch.options.url;
1208
+ }
1209
+ /**
1210
+ * Constructs an error message from the provided error object.
1211
+ *
1212
+ * @param err - The error object to extract the error message from.
1213
+ * @returns The constructed error message.
1214
+ */
1215
+ _getErrorMessage(e) {
1216
+ return e.msg || e.message || e.error_description || e.error || JSON.stringify(e);
1217
+ }
1218
+ /**
1219
+ * Handles an error that occurred during a request.
1220
+ *
1221
+ * @param error - The error that occurred during the request.
1222
+ * @param reject - The rejection function to call with the error.
1223
+ * @returns A Promise that resolves when the error has been handled.
1224
+ */
1225
+ _handleError(e, t) {
1226
+ return W(this, void 0, void 0, function* () {
1227
+ const n = yield st();
1228
+ e instanceof n ? e.json().then((r) => {
1229
+ t(new Be(this._getErrorMessage(r), e.status || 500));
1230
+ }).catch((r) => {
1231
+ t(new ie(this._getErrorMessage(r), r));
1232
+ }) : t(new ie(this._getErrorMessage(e), e));
1233
+ });
1234
+ }
1235
+ /**
1236
+ * Constructs the options object to be used for a fetch request.
1237
+ *
1238
+ * @param method - The HTTP method to use for the request, such as "GET", "POST", "PUT", "PATCH", or "DELETE".
1239
+ * @param bodyOrOptions - For "POST", "PUT", and "PATCH" requests, the request body as a string, Buffer, or Readable stream. For "GET" and "DELETE" requests, the fetch options to use.
1240
+ * @param options - Additional fetch options to use for the request.
1241
+ * @returns The constructed fetch options object.
1242
+ */
1243
+ _getRequestOptions(e, t, n) {
1244
+ let r = { method: e };
1245
+ return e === "GET" || e === "DELETE" ? r = Object.assign(Object.assign({}, r), t) : r = Object.assign(Object.assign({ duplex: "half", body: t }, r), n), K(this.namespaceOptions.fetch.options, r, { clone: !1 });
1246
+ }
1247
+ _handleRequest(e, t, n, r) {
1248
+ return W(this, void 0, void 0, function* () {
1249
+ return new Promise((s, i) => {
1250
+ const c = this.fetch;
1251
+ c(t, this._getRequestOptions(e, n, r)).then((p) => {
1252
+ if (!p.ok)
1253
+ throw p;
1254
+ s(p);
1255
+ }).catch((p) => this._handleError(p, i));
1256
+ });
1257
+ });
1258
+ }
1259
+ /**
1260
+ * Handles an HTTP GET request using the provided URL and optional request options.
1261
+ *
1262
+ * @param url - The URL to send the GET request to.
1263
+ * @param options - Additional fetch options to use for the GET request.
1264
+ * @returns A Promise that resolves to the Response object for the GET request.
1265
+ */
1266
+ get(e, t) {
1267
+ return W(this, void 0, void 0, function* () {
1268
+ return this._handleRequest("GET", e, t);
1269
+ });
1270
+ }
1271
+ /**
1272
+ * Handles an HTTP POST request using the provided URL, request body, and optional request options.
1273
+ *
1274
+ * @param url - The URL to send the POST request to.
1275
+ * @param body - The request body as a string, Buffer, or Readable stream.
1276
+ * @param options - Additional fetch options to use for the POST request.
1277
+ * @returns A Promise that resolves to the Response object for the POST request.
1278
+ */
1279
+ post(e, t, n) {
1280
+ return W(this, void 0, void 0, function* () {
1281
+ return this._handleRequest("POST", e, t, n);
1282
+ });
1283
+ }
1284
+ /**
1285
+ * Handles an HTTP PUT request using the provided URL, request body, and optional request options.
1286
+ *
1287
+ * @param url - The URL to send the PUT request to.
1288
+ * @param body - The request body as a string, Buffer, or Readable stream.
1289
+ * @param options - Additional fetch options to use for the PUT request.
1290
+ * @returns A Promise that resolves to the Response object for the PUT request.
1291
+ */
1292
+ put(e, t, n) {
1293
+ return W(this, void 0, void 0, function* () {
1294
+ return this._handleRequest("PUT", e, t, n);
1295
+ });
1296
+ }
1297
+ /**
1298
+ * Handles an HTTP PATCH request using the provided URL, request body, and optional request options.
1299
+ *
1300
+ * @param url - The URL to send the PATCH request to.
1301
+ * @param body - The request body as a string, Buffer, or Readable stream.
1302
+ * @param options - Additional fetch options to use for the PATCH request.
1303
+ * @returns A Promise that resolves to the Response object for the PATCH request.
1304
+ */
1305
+ patch(e, t, n) {
1306
+ return W(this, void 0, void 0, function* () {
1307
+ return this._handleRequest("PATCH", e, t, n);
1308
+ });
1309
+ }
1310
+ /**
1311
+ * Handles an HTTP DELETE request using the provided URL and optional request options.
1312
+ *
1313
+ * @param url - The URL to send the DELETE request to.
1314
+ * @param options - Additional fetch options to use for the DELETE request.
1315
+ * @returns A Promise that resolves to the Response object for the DELETE request.
1316
+ */
1317
+ delete(e, t) {
1318
+ return W(this, void 0, void 0, function* () {
1319
+ return this._handleRequest("DELETE", e, t);
1320
+ });
1321
+ }
1322
+ /**
1323
+ * Determines whether the current instance should proxy requests.
1324
+ * @returns {boolean} true if the current instance should proxy requests; otherwise, false
1325
+ */
1326
+ get proxy() {
1327
+ var e;
1328
+ return this.key === "proxy" && !!(!((e = this.namespaceOptions.fetch.options.proxy) === null || e === void 0) && e.url);
1329
+ }
1330
+ }
1331
+ var P;
1332
+ (function(o) {
1333
+ o.Open = "Open", o.Close = "Close", o.Error = "Error", o.Audio = "Audio", o.Welcome = "Welcome", o.SettingsApplied = "SettingsApplied", o.ConversationText = "ConversationText", o.UserStartedSpeaking = "UserStartedSpeaking", o.AgentThinking = "AgentThinking", o.FunctionCallRequest = "FunctionCallRequest", o.AgentStartedSpeaking = "AgentStartedSpeaking", o.AgentAudioDone = "AgentAudioDone", o.InjectionRefused = "InjectionRefused", o.PromptUpdated = "PromptUpdated", o.SpeakUpdated = "SpeakUpdated", o.Unhandled = "Unhandled";
1334
+ })(P || (P = {}));
1335
+ class it extends ye {
1336
+ constructor(e, t = "/:version/agent/converse") {
1337
+ var n, r, s, i;
1338
+ super(e), this.namespace = "agent", this.baseUrl = (i = (s = (r = (n = e.agent) === null || n === void 0 ? void 0 : n.websocket) === null || r === void 0 ? void 0 : r.options) === null || s === void 0 ? void 0 : s.url) !== null && i !== void 0 ? i : xe, this.connect({}, t);
1339
+ }
1340
+ /**
1341
+ * Sets up the connection event handlers.
1342
+ * This method is responsible for handling the various events that can occur on the WebSocket connection, such as opening, closing, and receiving messages.
1343
+ * - When the connection is opened, it emits the `AgentEvents.Open` event.
1344
+ * - When the connection is closed, it emits the `AgentEvents.Close` event.
1345
+ * - When an error occurs on the connection, it emits the `AgentEvents.Error` event.
1346
+ * - When a message is received, it parses the message and emits the appropriate event based on the message type.
1347
+ */
1348
+ setupConnection() {
1349
+ this.setupConnectionEvents({
1350
+ Open: P.Open,
1351
+ Close: P.Close,
1352
+ Error: P.Error
1353
+ }), this.conn && (this.conn.onmessage = (e) => {
1354
+ this.handleMessage(e);
1355
+ });
1356
+ }
1357
+ /**
1358
+ * Handles incoming messages from the WebSocket connection.
1359
+ * @param event - The MessageEvent object representing the received message.
1360
+ */
1361
+ handleMessage(e) {
1362
+ var t, n, r, s, i, c;
1363
+ if (typeof e.data == "string")
1364
+ try {
1365
+ const p = JSON.parse(e.data);
1366
+ this.handleTextMessage(p);
1367
+ } catch (p) {
1368
+ this.emit(P.Error, {
1369
+ event: e,
1370
+ data: ((t = e.data) === null || t === void 0 ? void 0 : t.toString().substring(0, 200)) + (((n = e.data) === null || n === void 0 ? void 0 : n.toString().length) > 200 ? "..." : ""),
1371
+ message: "Unable to parse `data` as JSON.",
1372
+ error: p,
1373
+ url: (r = this.conn) === null || r === void 0 ? void 0 : r.url,
1374
+ readyState: (s = this.conn) === null || s === void 0 ? void 0 : s.readyState
1375
+ });
1376
+ }
1377
+ else e.data instanceof Blob ? e.data.arrayBuffer().then((p) => {
1378
+ this.handleBinaryMessage(Buffer.from(p));
1379
+ }) : e.data instanceof ArrayBuffer ? this.handleBinaryMessage(Buffer.from(e.data)) : Buffer.isBuffer(e.data) ? this.handleBinaryMessage(e.data) : (console.log("Received unknown data type", e.data), this.emit(P.Error, {
1380
+ event: e,
1381
+ message: "Received unknown data type.",
1382
+ url: (i = this.conn) === null || i === void 0 ? void 0 : i.url,
1383
+ readyState: (c = this.conn) === null || c === void 0 ? void 0 : c.readyState,
1384
+ dataType: typeof e.data
1385
+ }));
1386
+ }
1387
+ /**
1388
+ * Handles binary messages received from the WebSocket connection.
1389
+ * @param data - The binary data.
1390
+ */
1391
+ handleBinaryMessage(e) {
1392
+ this.emit(P.Audio, e);
1393
+ }
1394
+ /**
1395
+ * Handles text messages received from the WebSocket connection.
1396
+ * @param data - The parsed JSON data.
1397
+ */
1398
+ handleTextMessage(e) {
1399
+ e.type in P ? this.emit(e.type, e) : this.emit(P.Unhandled, e);
1400
+ }
1401
+ /**
1402
+ * To be called with your model configuration BEFORE sending
1403
+ * any audio data.
1404
+ * @param options - The SettingsConfiguration object.
1405
+ */
1406
+ configure(e) {
1407
+ const t = JSON.stringify(Object.assign({ type: "Settings" }, e));
1408
+ this.send(t);
1409
+ }
1410
+ /**
1411
+ * Provide new system prompt to the LLM.
1412
+ * @param prompt - The system prompt to provide.
1413
+ */
1414
+ updatePrompt(e) {
1415
+ this.send(JSON.stringify({ type: "UpdatePrompt", prompt: e }));
1416
+ }
1417
+ /**
1418
+ * Change the speak model.
1419
+ * @param model - The new model to use.
1420
+ */
1421
+ updateSpeak(e) {
1422
+ this.send(JSON.stringify({ type: "UpdateSpeak", speak: e }));
1423
+ }
1424
+ /**
1425
+ * Immediately trigger an agent message. If this message
1426
+ * is sent while the user is speaking, or while the server is in the
1427
+ * middle of sending audio, then the request will be ignored and an InjectionRefused
1428
+ * event will be emitted.
1429
+ * @example "Hold on while I look that up for you."
1430
+ * @example "Are you still on the line?"
1431
+ * @param content - The message to speak.
1432
+ */
1433
+ injectAgentMessage(e) {
1434
+ this.send(JSON.stringify({ type: "InjectAgentMessage", content: e }));
1435
+ }
1436
+ /**
1437
+ * Send a text-based message to the agent as if it came from the user.
1438
+ * This allows you to inject user messages into the conversation for the agent to respond to.
1439
+ * @example "Hello! Can you hear me?"
1440
+ * @example "What's the weather like today?"
1441
+ * @param content - The specific phrase or statement the agent should respond to.
1442
+ */
1443
+ injectUserMessage(e) {
1444
+ this.send(JSON.stringify({ type: "InjectUserMessage", content: e }));
1445
+ }
1446
+ /**
1447
+ * Respond to a function call request.
1448
+ * @param response - The response to the function call request.
1449
+ */
1450
+ functionCallResponse(e) {
1451
+ this.send(JSON.stringify(Object.assign({ type: "FunctionCallResponse" }, e)));
1452
+ }
1453
+ /**
1454
+ * Send a keepalive to avoid closing the websocket while you
1455
+ * are not transmitting audio. This should be sent at least
1456
+ * every 8 seconds.
1457
+ */
1458
+ keepAlive() {
1459
+ this.send(JSON.stringify({ type: "KeepAlive" }));
1460
+ }
1461
+ }
1462
+ var ot = function(o, e, t, n) {
1463
+ function r(s) {
1464
+ return s instanceof t ? s : new t(function(i) {
1465
+ i(s);
1466
+ });
1467
+ }
1468
+ return new (t || (t = Promise))(function(s, i) {
1469
+ function c(f) {
1470
+ try {
1471
+ g(n.next(f));
1472
+ } catch (b) {
1473
+ i(b);
1474
+ }
1475
+ }
1476
+ function p(f) {
1477
+ try {
1478
+ g(n.throw(f));
1479
+ } catch (b) {
1480
+ i(b);
1481
+ }
1482
+ }
1483
+ function g(f) {
1484
+ f.done ? s(f.value) : r(f.value).then(c, p);
1485
+ }
1486
+ g((n = n.apply(o, e || [])).next());
1487
+ });
1488
+ };
1489
+ class at extends V {
1490
+ constructor() {
1491
+ super(...arguments), this.namespace = "auth";
1492
+ }
1493
+ /**
1494
+ * Generates a new temporary token for the Deepgram API.
1495
+ * @param options Optional configuration options for the token generation. Includes ttl_seconds to set token expiration.
1496
+ * @param endpoint Optional custom endpoint to use for the request. Defaults to ":version/auth/grant".
1497
+ * @returns Object containing the result of the request or an error if one occurred. Result will contain access_token and expires_in properties.
1498
+ */
1499
+ grantToken(e = {}, t = ":version/auth/grant") {
1500
+ return ot(this, void 0, void 0, function* () {
1501
+ try {
1502
+ const n = this.getRequestUrl(t), r = JSON.stringify(e);
1503
+ return { result: yield this.post(n, r, {
1504
+ headers: { "Content-Type": "application/json" }
1505
+ }).then((i) => i.json()), error: null };
1506
+ } catch (n) {
1507
+ if (w(n))
1508
+ return { result: null, error: n };
1509
+ throw n;
1510
+ }
1511
+ });
1512
+ }
1513
+ }
1514
+ var B;
1515
+ (function(o) {
1516
+ o.Open = "open", o.Close = "close", o.Error = "error", o.Transcript = "Results", o.Metadata = "Metadata", o.UtteranceEnd = "UtteranceEnd", o.SpeechStarted = "SpeechStarted", o.Unhandled = "Unhandled";
1517
+ })(B || (B = {}));
1518
+ var M;
1519
+ (function(o) {
1520
+ o.Open = "Open", o.Close = "Close", o.Error = "Error", o.Metadata = "Metadata", o.Flushed = "Flushed", o.Warning = "Warning", o.Audio = "Audio", o.Unhandled = "Unhandled";
1521
+ })(M || (M = {}));
1522
+ class ut extends ye {
1523
+ /**
1524
+ * Constructs a new `ListenLiveClient` instance with the provided options.
1525
+ *
1526
+ * @param options - The `DeepgramClientOptions` to use for the client connection.
1527
+ * @param transcriptionOptions - An optional `LiveSchema` object containing additional configuration options for the live transcription.
1528
+ * @param endpoint - An optional string representing the WebSocket endpoint to connect to. Defaults to `:version/listen`.
1529
+ */
1530
+ constructor(e, t = {}, n = ":version/listen") {
1531
+ super(e), this.namespace = "listen", this.connect(t, n);
1532
+ }
1533
+ /**
1534
+ * Sets up the connection event handlers.
1535
+ * This method is responsible for handling the various events that can occur on the WebSocket connection, such as opening, closing, and receiving messages.
1536
+ * - When the connection is opened, it emits the `LiveTranscriptionEvents.Open` event.
1537
+ * - When the connection is closed, it emits the `LiveTranscriptionEvents.Close` event.
1538
+ * - When an error occurs on the connection, it emits the `LiveTranscriptionEvents.Error` event.
1539
+ * - When a message is received, it parses the message and emits the appropriate event based on the message type, such as `LiveTranscriptionEvents.Metadata`, `LiveTranscriptionEvents.Transcript`, `LiveTranscriptionEvents.UtteranceEnd`, and `LiveTranscriptionEvents.SpeechStarted`.
1540
+ */
1541
+ setupConnection() {
1542
+ this.setupConnectionEvents({
1543
+ Open: B.Open,
1544
+ Close: B.Close,
1545
+ Error: B.Error
1546
+ }), this.conn && (this.conn.onmessage = (e) => {
1547
+ var t, n, r, s;
1548
+ try {
1549
+ const i = JSON.parse(e.data.toString());
1550
+ i.type === B.Metadata ? this.emit(B.Metadata, i) : i.type === B.Transcript ? this.emit(B.Transcript, i) : i.type === B.UtteranceEnd ? this.emit(B.UtteranceEnd, i) : i.type === B.SpeechStarted ? this.emit(B.SpeechStarted, i) : this.emit(B.Unhandled, i);
1551
+ } catch (i) {
1552
+ this.emit(B.Error, {
1553
+ event: e,
1554
+ message: "Unable to parse `data` as JSON.",
1555
+ error: i,
1556
+ url: (t = this.conn) === null || t === void 0 ? void 0 : t.url,
1557
+ readyState: (n = this.conn) === null || n === void 0 ? void 0 : n.readyState,
1558
+ data: ((r = e.data) === null || r === void 0 ? void 0 : r.toString().substring(0, 200)) + (((s = e.data) === null || s === void 0 ? void 0 : s.toString().length) > 200 ? "..." : "")
1559
+ });
1560
+ }
1561
+ });
1562
+ }
1563
+ /**
1564
+ * Sends additional config to the connected session.
1565
+ *
1566
+ * @param config - The configuration options to apply to the LiveClient.
1567
+ * @param config.numerals - We currently only support numerals.
1568
+ */
1569
+ configure(e) {
1570
+ this.send(JSON.stringify({
1571
+ type: "Configure",
1572
+ processors: e
1573
+ }));
1574
+ }
1575
+ /**
1576
+ * Sends a "KeepAlive" message to the server to maintain the connection.
1577
+ */
1578
+ keepAlive() {
1579
+ this.send(JSON.stringify({
1580
+ type: "KeepAlive"
1581
+ }));
1582
+ }
1583
+ /**
1584
+ * Sends a "Finalize" message to flush any transcription sitting in the server's buffer.
1585
+ */
1586
+ finalize() {
1587
+ this.send(JSON.stringify({
1588
+ type: "Finalize"
1589
+ }));
1590
+ }
1591
+ /**
1592
+ * @deprecated Since version 3.4. Will be removed in version 4.0. Use `requestClose` instead.
1593
+ */
1594
+ finish() {
1595
+ this.requestClose();
1596
+ }
1597
+ /**
1598
+ * Requests the server close the connection.
1599
+ */
1600
+ requestClose() {
1601
+ this.send(JSON.stringify({
1602
+ type: "CloseStream"
1603
+ }));
1604
+ }
1605
+ }
1606
+ var re = function(o, e, t, n) {
1607
+ function r(s) {
1608
+ return s instanceof t ? s : new t(function(i) {
1609
+ i(s);
1610
+ });
1611
+ }
1612
+ return new (t || (t = Promise))(function(s, i) {
1613
+ function c(f) {
1614
+ try {
1615
+ g(n.next(f));
1616
+ } catch (b) {
1617
+ i(b);
1618
+ }
1619
+ }
1620
+ function p(f) {
1621
+ try {
1622
+ g(n.throw(f));
1623
+ } catch (b) {
1624
+ i(b);
1625
+ }
1626
+ }
1627
+ function g(f) {
1628
+ f.done ? s(f.value) : r(f.value).then(c, p);
1629
+ }
1630
+ g((n = n.apply(o, e || [])).next());
1631
+ });
1632
+ };
1633
+ class ct extends V {
1634
+ constructor() {
1635
+ super(...arguments), this.namespace = "listen";
1636
+ }
1637
+ /**
1638
+ * Transcribes audio from a URL synchronously.
1639
+ *
1640
+ * @param source - The URL source object containing the audio URL to transcribe.
1641
+ * @param options - An optional `PrerecordedSchema` object containing additional options for the transcription.
1642
+ * @param endpoint - An optional endpoint string to use for the transcription request.
1643
+ * @returns A `DeepgramResponse` object containing the transcription result or an error.
1644
+ */
1645
+ transcribeUrl(e, t, n = ":version/listen") {
1646
+ var r, s;
1647
+ return re(this, void 0, void 0, function* () {
1648
+ try {
1649
+ let i;
1650
+ if (oe(e))
1651
+ i = JSON.stringify(e);
1652
+ else
1653
+ throw new C("Unknown transcription source type");
1654
+ if (t !== void 0 && "callback" in t)
1655
+ throw new C("Callback cannot be provided as an option to a synchronous transcription. Use `transcribeUrlCallback` or `transcribeFileCallback` instead.");
1656
+ if (!((r = t?.keyterm) === null || r === void 0) && r.length && !(!((s = t.model) === null || s === void 0) && s.startsWith("nova-3")))
1657
+ throw new C("Keyterms are only supported with the Nova 3 models.");
1658
+ const c = this.getRequestUrl(n, {}, Object.assign({}, t));
1659
+ return { result: yield this.post(c, i).then((g) => g.json()), error: null };
1660
+ } catch (i) {
1661
+ if (w(i))
1662
+ return { result: null, error: i };
1663
+ throw i;
1664
+ }
1665
+ });
1666
+ }
1667
+ /**
1668
+ * Transcribes audio from a file asynchronously.
1669
+ *
1670
+ * @param source - The file source object containing the audio file to transcribe.
1671
+ * @param options - An optional `PrerecordedSchema` object containing additional options for the transcription.
1672
+ * @param endpoint - An optional endpoint string to use for the transcription request.
1673
+ * @returns A `DeepgramResponse` object containing the transcription result or an error.
1674
+ */
1675
+ transcribeFile(e, t, n = ":version/listen") {
1676
+ return re(this, void 0, void 0, function* () {
1677
+ try {
1678
+ let r;
1679
+ if (_e(e))
1680
+ r = e;
1681
+ else
1682
+ throw new C("Unknown transcription source type");
1683
+ if (t !== void 0 && "callback" in t)
1684
+ throw new C("Callback cannot be provided as an option to a synchronous transcription. Use `transcribeUrlCallback` or `transcribeFileCallback` instead.");
1685
+ const s = this.getRequestUrl(n, {}, Object.assign({}, t));
1686
+ return { result: yield this.post(s, r, {
1687
+ headers: { "Content-Type": "deepgram/audio+video" }
1688
+ }).then((c) => c.json()), error: null };
1689
+ } catch (r) {
1690
+ if (w(r))
1691
+ return { result: null, error: r };
1692
+ throw r;
1693
+ }
1694
+ });
1695
+ }
1696
+ /**
1697
+ * Transcribes audio from a URL asynchronously.
1698
+ *
1699
+ * @param source - The URL source object containing the audio file to transcribe.
1700
+ * @param callback - The callback URL to receive the transcription result.
1701
+ * @param options - An optional `PrerecordedSchema` object containing additional options for the transcription.
1702
+ * @param endpoint - An optional endpoint string to use for the transcription request.
1703
+ * @returns A `DeepgramResponse` object containing the transcription result or an error.
1704
+ */
1705
+ transcribeUrlCallback(e, t, n, r = ":version/listen") {
1706
+ return re(this, void 0, void 0, function* () {
1707
+ try {
1708
+ let s;
1709
+ if (oe(e))
1710
+ s = JSON.stringify(e);
1711
+ else
1712
+ throw new C("Unknown transcription source type");
1713
+ const i = this.getRequestUrl(r, {}, Object.assign(Object.assign({}, n), { callback: t.toString() }));
1714
+ return { result: yield this.post(i, s).then((p) => p.json()), error: null };
1715
+ } catch (s) {
1716
+ if (w(s))
1717
+ return { result: null, error: s };
1718
+ throw s;
1719
+ }
1720
+ });
1721
+ }
1722
+ /**
1723
+ * Transcribes audio from a file asynchronously.
1724
+ *
1725
+ * @param source - The file source object containing the audio file to transcribe.
1726
+ * @param callback - The callback URL to receive the transcription result.
1727
+ * @param options - An optional `PrerecordedSchema` object containing additional options for the transcription.
1728
+ * @param endpoint - An optional endpoint string to use for the transcription request.
1729
+ * @returns A `DeepgramResponse` object containing the transcription result or an error.
1730
+ */
1731
+ transcribeFileCallback(e, t, n, r = ":version/listen") {
1732
+ return re(this, void 0, void 0, function* () {
1733
+ try {
1734
+ let s;
1735
+ if (_e(e))
1736
+ s = e;
1737
+ else
1738
+ throw new C("Unknown transcription source type");
1739
+ const i = this.getRequestUrl(r, {}, Object.assign(Object.assign({}, n), { callback: t.toString() }));
1740
+ return { result: yield this.post(i, s, {
1741
+ headers: { "Content-Type": "deepgram/audio+video" }
1742
+ }).then((p) => p.json()), error: null };
1743
+ } catch (s) {
1744
+ if (w(s))
1745
+ return { result: null, error: s };
1746
+ throw s;
1747
+ }
1748
+ });
1749
+ }
1750
+ }
1751
+ class lt extends X {
1752
+ constructor() {
1753
+ super(...arguments), this.namespace = "listen";
1754
+ }
1755
+ /**
1756
+ * Returns a `ListenRestClient` instance for interacting with the prerecorded listen API.
1757
+ */
1758
+ get prerecorded() {
1759
+ return new ct(this.options);
1760
+ }
1761
+ /**
1762
+ * Returns a `ListenLiveClient` instance for interacting with the live listen API, with the provided transcription options and endpoint.
1763
+ * @param {LiveSchema} [transcriptionOptions={}] - The transcription options to use for the live listen API.
1764
+ * @param {string} [endpoint=":version/listen"] - The endpoint to use for the live listen API.
1765
+ * @returns {ListenLiveClient} - A `ListenLiveClient` instance for interacting with the live listen API.
1766
+ */
1767
+ live(e = {}, t = ":version/listen") {
1768
+ return new ut(this.options, e, t);
1769
+ }
1770
+ }
1771
+ var k = function(o, e, t, n) {
1772
+ function r(s) {
1773
+ return s instanceof t ? s : new t(function(i) {
1774
+ i(s);
1775
+ });
1776
+ }
1777
+ return new (t || (t = Promise))(function(s, i) {
1778
+ function c(f) {
1779
+ try {
1780
+ g(n.next(f));
1781
+ } catch (b) {
1782
+ i(b);
1783
+ }
1784
+ }
1785
+ function p(f) {
1786
+ try {
1787
+ g(n.throw(f));
1788
+ } catch (b) {
1789
+ i(b);
1790
+ }
1791
+ }
1792
+ function g(f) {
1793
+ f.done ? s(f.value) : r(f.value).then(c, p);
1794
+ }
1795
+ g((n = n.apply(o, e || [])).next());
1796
+ });
1797
+ };
1798
+ class dt extends V {
1799
+ constructor() {
1800
+ super(...arguments), this.namespace = "manage";
1801
+ }
1802
+ /**
1803
+ * Retrieves the details of the current authentication token.
1804
+ *
1805
+ * @returns A promise that resolves to an object containing the token details, or an error object if an error occurs.
1806
+ * @see https://developers.deepgram.com/docs/authenticating#test-request
1807
+ */
1808
+ getTokenDetails(e = ":version/auth/token") {
1809
+ return k(this, void 0, void 0, function* () {
1810
+ try {
1811
+ const t = this.getRequestUrl(e);
1812
+ return { result: yield this.get(t).then((r) => r.json()), error: null };
1813
+ } catch (t) {
1814
+ if (w(t))
1815
+ return { result: null, error: t };
1816
+ throw t;
1817
+ }
1818
+ });
1819
+ }
1820
+ /**
1821
+ * Retrieves a list of all projects associated with the authenticated user.
1822
+ *
1823
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects".
1824
+ * @returns A promise that resolves to an object containing the list of projects, or an error object if an error occurs.
1825
+ * @see https://developers.deepgram.com/reference/get-projects
1826
+ */
1827
+ getProjects(e = ":version/projects") {
1828
+ return k(this, void 0, void 0, function* () {
1829
+ try {
1830
+ const t = this.getRequestUrl(e);
1831
+ return { result: yield this.get(t).then((r) => r.json()), error: null };
1832
+ } catch (t) {
1833
+ if (w(t))
1834
+ return { result: null, error: t };
1835
+ throw t;
1836
+ }
1837
+ });
1838
+ }
1839
+ /**
1840
+ * Retrieves the details of a specific project associated with the authenticated user.
1841
+ *
1842
+ * @param projectId - The ID of the project to retrieve.
1843
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId".
1844
+ * @returns A promise that resolves to an object containing the project details, or an error object if an error occurs.
1845
+ * @see https://developers.deepgram.com/reference/get-project
1846
+ */
1847
+ getProject(e, t = ":version/projects/:projectId") {
1848
+ return k(this, void 0, void 0, function* () {
1849
+ try {
1850
+ const n = this.getRequestUrl(t, { projectId: e });
1851
+ return { result: yield this.get(n).then((s) => s.json()), error: null };
1852
+ } catch (n) {
1853
+ if (w(n))
1854
+ return { result: null, error: n };
1855
+ throw n;
1856
+ }
1857
+ });
1858
+ }
1859
+ /**
1860
+ * Updates an existing project associated with the authenticated user.
1861
+ *
1862
+ * @param projectId - The ID of the project to update.
1863
+ * @param options - An object containing the updated project details.
1864
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId".
1865
+ * @returns A promise that resolves to an object containing the response message, or an error object if an error occurs.
1866
+ * @see https://developers.deepgram.com/reference/update-project
1867
+ */
1868
+ updateProject(e, t, n = ":version/projects/:projectId") {
1869
+ return k(this, void 0, void 0, function* () {
1870
+ try {
1871
+ const r = this.getRequestUrl(n, { projectId: e }, t), s = JSON.stringify(t);
1872
+ return { result: yield this.patch(r, s).then((c) => c.json()), error: null };
1873
+ } catch (r) {
1874
+ if (w(r))
1875
+ return { result: null, error: r };
1876
+ throw r;
1877
+ }
1878
+ });
1879
+ }
1880
+ /**
1881
+ * Deletes an existing project associated with the authenticated user.
1882
+ *
1883
+ * @param projectId - The ID of the project to delete.
1884
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId".
1885
+ * @returns A promise that resolves to an object containing the response message, or an error object if an error occurs.
1886
+ * @see https://developers.deepgram.com/reference/delete-project
1887
+ */
1888
+ deleteProject(e, t = ":version/projects/:projectId") {
1889
+ return k(this, void 0, void 0, function* () {
1890
+ try {
1891
+ const n = this.getRequestUrl(t, { projectId: e });
1892
+ return yield this.delete(n), { error: null };
1893
+ } catch (n) {
1894
+ if (w(n))
1895
+ return { error: n };
1896
+ throw n;
1897
+ }
1898
+ });
1899
+ }
1900
+ /**
1901
+ * Retrieves a list of project keys associated with the specified project.
1902
+ *
1903
+ * @param projectId - The ID of the project to retrieve the keys for.
1904
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/keys".
1905
+ * @returns A promise that resolves to an object containing the list of project keys, or an error object if an error occurs.
1906
+ * @see https://developers.deepgram.com/reference/list-keys
1907
+ */
1908
+ getProjectKeys(e, t = ":version/projects/:projectId/keys") {
1909
+ return k(this, void 0, void 0, function* () {
1910
+ try {
1911
+ const n = this.getRequestUrl(t, { projectId: e });
1912
+ return { result: yield this.get(n).then((s) => s.json()), error: null };
1913
+ } catch (n) {
1914
+ if (w(n))
1915
+ return { result: null, error: n };
1916
+ throw n;
1917
+ }
1918
+ });
1919
+ }
1920
+ /**
1921
+ * Retrieves a specific project key associated with the specified project.
1922
+ *
1923
+ * @param projectId - The ID of the project to retrieve the key for.
1924
+ * @param keyId - The ID of the project key to retrieve.
1925
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/keys/:keyId".
1926
+ * @returns A promise that resolves to an object containing the project key, or an error object if an error occurs.
1927
+ * @see https://developers.deepgram.com/reference/get-key
1928
+ */
1929
+ getProjectKey(e, t, n = ":version/projects/:projectId/keys/:keyId") {
1930
+ return k(this, void 0, void 0, function* () {
1931
+ try {
1932
+ const r = this.getRequestUrl(n, { projectId: e, keyId: t });
1933
+ return { result: yield this.get(r).then((i) => i.json()), error: null };
1934
+ } catch (r) {
1935
+ if (w(r))
1936
+ return { result: null, error: r };
1937
+ throw r;
1938
+ }
1939
+ });
1940
+ }
1941
+ /**
1942
+ * Creates a new project key for the specified project.
1943
+ *
1944
+ * @param projectId - The ID of the project to create the key for.
1945
+ * @param options - An object containing the options for creating the project key.
1946
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/keys".
1947
+ * @returns A promise that resolves to an object containing the created project key, or an error object if an error occurs.
1948
+ * @see https://developers.deepgram.com/reference/create-key
1949
+ */
1950
+ createProjectKey(e, t, n = ":version/projects/:projectId/keys") {
1951
+ return k(this, void 0, void 0, function* () {
1952
+ try {
1953
+ const r = this.getRequestUrl(n, { projectId: e }, t), s = JSON.stringify(t);
1954
+ return { result: yield this.post(r, s).then((c) => c.json()), error: null };
1955
+ } catch (r) {
1956
+ if (w(r))
1957
+ return { result: null, error: r };
1958
+ throw r;
1959
+ }
1960
+ });
1961
+ }
1962
+ /**
1963
+ * Deletes the specified project key.
1964
+ *
1965
+ * @param projectId - The ID of the project the key belongs to.
1966
+ * @param keyId - The ID of the key to delete.
1967
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/keys/:keyId".
1968
+ * @returns A promise that resolves to an object containing a null result and an error object if an error occurs.
1969
+ * @see https://developers.deepgram.com/reference/delete-key
1970
+ */
1971
+ deleteProjectKey(e, t, n = ":version/projects/:projectId/keys/:keyId") {
1972
+ return k(this, void 0, void 0, function* () {
1973
+ try {
1974
+ const r = this.getRequestUrl(n, { projectId: e, keyId: t });
1975
+ return yield this.delete(r), { error: null };
1976
+ } catch (r) {
1977
+ if (w(r))
1978
+ return { error: r };
1979
+ throw r;
1980
+ }
1981
+ });
1982
+ }
1983
+ /**
1984
+ * Retrieves the members of the specified project.
1985
+ *
1986
+ * @param projectId - The ID of the project to retrieve members for.
1987
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/members".
1988
+ * @returns A promise that resolves to an object containing the project members and an error object if an error occurs.
1989
+ * @see https://developers.deepgram.com/reference/get-members
1990
+ */
1991
+ getProjectMembers(e, t = ":version/projects/:projectId/members") {
1992
+ return k(this, void 0, void 0, function* () {
1993
+ try {
1994
+ const n = this.getRequestUrl(t, { projectId: e });
1995
+ return { result: yield this.get(n).then((s) => s.json()), error: null };
1996
+ } catch (n) {
1997
+ if (w(n))
1998
+ return { result: null, error: n };
1999
+ throw n;
2000
+ }
2001
+ });
2002
+ }
2003
+ /**
2004
+ * Removes a member from the specified project.
2005
+ *
2006
+ * @param projectId - The ID of the project to remove the member from.
2007
+ * @param memberId - The ID of the member to remove.
2008
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/members/:memberId".
2009
+ * @returns A promise that resolves to an object containing a null error if the operation was successful, or an error object if an error occurred.
2010
+ * @see https://developers.deepgram.com/reference/remove-member
2011
+ */
2012
+ removeProjectMember(e, t, n = ":version/projects/:projectId/members/:memberId") {
2013
+ return k(this, void 0, void 0, function* () {
2014
+ try {
2015
+ const r = this.getRequestUrl(n, { projectId: e, memberId: t });
2016
+ return yield this.delete(r), { error: null };
2017
+ } catch (r) {
2018
+ if (w(r))
2019
+ return { error: r };
2020
+ throw r;
2021
+ }
2022
+ });
2023
+ }
2024
+ /**
2025
+ * Retrieves the scopes for the specified project member.
2026
+ *
2027
+ * @param projectId - The ID of the project to retrieve the member scopes for.
2028
+ * @param memberId - The ID of the member to retrieve the scopes for.
2029
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/members/:memberId/scopes".
2030
+ * @returns A promise that resolves to an object containing the retrieved scopes or an error object if an error occurred.
2031
+ * @see https://developers.deepgram.com/reference/get-member-scopes
2032
+ */
2033
+ getProjectMemberScopes(e, t, n = ":version/projects/:projectId/members/:memberId/scopes") {
2034
+ return k(this, void 0, void 0, function* () {
2035
+ try {
2036
+ const r = this.getRequestUrl(n, { projectId: e, memberId: t });
2037
+ return { result: yield this.get(r).then((i) => i.json()), error: null };
2038
+ } catch (r) {
2039
+ if (w(r))
2040
+ return { result: null, error: r };
2041
+ throw r;
2042
+ }
2043
+ });
2044
+ }
2045
+ /**
2046
+ * Updates the scopes for the specified project member.
2047
+ *
2048
+ * @param projectId - The ID of the project to update the member scopes for.
2049
+ * @param memberId - The ID of the member to update the scopes for.
2050
+ * @param options - An object containing the new scopes to apply to the member.
2051
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/members/:memberId/scopes".
2052
+ * @returns A promise that resolves to an object containing the result of the update operation or an error object if an error occurred.
2053
+ * @see https://developers.deepgram.com/reference/update-scope
2054
+ */
2055
+ updateProjectMemberScope(e, t, n, r = ":version/projects/:projectId/members/:memberId/scopes") {
2056
+ return k(this, void 0, void 0, function* () {
2057
+ try {
2058
+ const s = this.getRequestUrl(r, { projectId: e, memberId: t }, n), i = JSON.stringify(n);
2059
+ return { result: yield this.put(s, i).then((p) => p.json()), error: null };
2060
+ } catch (s) {
2061
+ if (w(s))
2062
+ return { result: null, error: s };
2063
+ throw s;
2064
+ }
2065
+ });
2066
+ }
2067
+ /**
2068
+ * Retrieves the project invites for the specified project.
2069
+ *
2070
+ * @param projectId - The ID of the project to retrieve the invites for.
2071
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/invites".
2072
+ * @returns A promise that resolves to an object containing the result of the get operation or an error object if an error occurred.
2073
+ * @see https://developers.deepgram.com/reference/list-invites
2074
+ */
2075
+ getProjectInvites(e, t = ":version/projects/:projectId/invites") {
2076
+ return k(this, void 0, void 0, function* () {
2077
+ try {
2078
+ const n = this.getRequestUrl(t, { projectId: e });
2079
+ return { result: yield this.get(n).then((s) => s.json()), error: null };
2080
+ } catch (n) {
2081
+ if (w(n))
2082
+ return { result: null, error: n };
2083
+ throw n;
2084
+ }
2085
+ });
2086
+ }
2087
+ /**
2088
+ * Sends a project invite to the specified email addresses.
2089
+ *
2090
+ * @param projectId - The ID of the project to send the invite for.
2091
+ * @param options - An object containing the email addresses to invite and any additional options.
2092
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/invites".
2093
+ * @returns A promise that resolves to an object containing the result of the post operation or an error object if an error occurred.
2094
+ * @see https://developers.deepgram.com/reference/send-invites
2095
+ */
2096
+ sendProjectInvite(e, t, n = ":version/projects/:projectId/invites") {
2097
+ return k(this, void 0, void 0, function* () {
2098
+ try {
2099
+ const r = this.getRequestUrl(n, { projectId: e }, t), s = JSON.stringify(t);
2100
+ return { result: yield this.post(r, s).then((c) => c.json()), error: null };
2101
+ } catch (r) {
2102
+ if (w(r))
2103
+ return { result: null, error: r };
2104
+ throw r;
2105
+ }
2106
+ });
2107
+ }
2108
+ /**
2109
+ * Deletes a project invite for the specified email address.
2110
+ *
2111
+ * @param projectId - The ID of the project to delete the invite for.
2112
+ * @param email - The email address of the invite to delete.
2113
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/invites/:email".
2114
+ * @returns A promise that resolves to an object containing a null result and an error object if an error occurred.
2115
+ * @see https://developers.deepgram.com/reference/delete-invite
2116
+ */
2117
+ deleteProjectInvite(e, t, n = ":version/projects/:projectId/invites/:email") {
2118
+ return k(this, void 0, void 0, function* () {
2119
+ try {
2120
+ const r = this.getRequestUrl(n, { projectId: e, email: t });
2121
+ return yield this.delete(r), { error: null };
2122
+ } catch (r) {
2123
+ if (w(r))
2124
+ return { error: r };
2125
+ throw r;
2126
+ }
2127
+ });
2128
+ }
2129
+ /**
2130
+ * Leaves the specified project.
2131
+ *
2132
+ * @param projectId - The ID of the project to leave.
2133
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/leave".
2134
+ * @returns A promise that resolves to an object containing a null result and an error object if an error occurred.
2135
+ * @see https://developers.deepgram.com/reference/leave-project
2136
+ */
2137
+ leaveProject(e, t = ":version/projects/:projectId/leave") {
2138
+ return k(this, void 0, void 0, function* () {
2139
+ try {
2140
+ const n = this.getRequestUrl(t, { projectId: e });
2141
+ return { result: yield this.delete(n).then((s) => s.json()), error: null };
2142
+ } catch (n) {
2143
+ if (w(n))
2144
+ return { result: null, error: n };
2145
+ throw n;
2146
+ }
2147
+ });
2148
+ }
2149
+ /**
2150
+ * Retrieves a list of usage requests for the specified project.
2151
+ *
2152
+ * @param projectId - The ID of the project to retrieve usage requests for.
2153
+ * @param options - An object containing options to filter the usage requests, such as pagination parameters.
2154
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/requests".
2155
+ * @returns A promise that resolves to an object containing the list of usage requests and an error object if an error occurred.
2156
+ * @see https://developers.deepgram.com/reference/get-all-requests
2157
+ */
2158
+ getProjectUsageRequests(e, t, n = ":version/projects/:projectId/requests") {
2159
+ return k(this, void 0, void 0, function* () {
2160
+ try {
2161
+ const r = this.getRequestUrl(n, { projectId: e }, t);
2162
+ return { result: yield this.get(r).then((i) => i.json()), error: null };
2163
+ } catch (r) {
2164
+ if (w(r))
2165
+ return { result: null, error: r };
2166
+ throw r;
2167
+ }
2168
+ });
2169
+ }
2170
+ /**
2171
+ * Retrieves the details of a specific usage request for the specified project.
2172
+ *
2173
+ * @param projectId - The ID of the project to retrieve the usage request for.
2174
+ * @param requestId - The ID of the usage request to retrieve.
2175
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/requests/:requestId".
2176
+ * @returns A promise that resolves to an object containing the usage request details and an error object if an error occurred.
2177
+ * @see https://developers.deepgram.com/reference/get-request
2178
+ */
2179
+ getProjectUsageRequest(e, t, n = ":version/projects/:projectId/requests/:requestId") {
2180
+ return k(this, void 0, void 0, function* () {
2181
+ try {
2182
+ const r = this.getRequestUrl(n, { projectId: e, requestId: t });
2183
+ return { result: yield this.get(r).then((i) => i.json()), error: null };
2184
+ } catch (r) {
2185
+ if (w(r))
2186
+ return { result: null, error: r };
2187
+ throw r;
2188
+ }
2189
+ });
2190
+ }
2191
+ /**
2192
+ * Retrieves the usage summary for the specified project.
2193
+ *
2194
+ * @param projectId - The ID of the project to retrieve the usage summary for.
2195
+ * @param options - An object containing optional parameters for the request, such as filters and pagination options.
2196
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/usage".
2197
+ * @returns A promise that resolves to an object containing the usage summary and an error object if an error occurred.
2198
+ * @see https://developers.deepgram.com/reference/get-usage
2199
+ */
2200
+ getProjectUsageSummary(e, t, n = ":version/projects/:projectId/usage") {
2201
+ return k(this, void 0, void 0, function* () {
2202
+ try {
2203
+ const r = this.getRequestUrl(n, { projectId: e }, t);
2204
+ return { result: yield this.get(r).then((i) => i.json()), error: null };
2205
+ } catch (r) {
2206
+ if (w(r))
2207
+ return { result: null, error: r };
2208
+ throw r;
2209
+ }
2210
+ });
2211
+ }
2212
+ /**
2213
+ * Retrieves the usage fields for the specified project.
2214
+ *
2215
+ * @param projectId - The ID of the project to retrieve the usage fields for.
2216
+ * @param options - An object containing optional parameters for the request, such as filters and pagination options.
2217
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/usage/fields".
2218
+ * @returns A promise that resolves to an object containing the usage fields and an error object if an error occurred.
2219
+ * @see https://developers.deepgram.com/reference/get-fields
2220
+ */
2221
+ getProjectUsageFields(e, t, n = ":version/projects/:projectId/usage/fields") {
2222
+ return k(this, void 0, void 0, function* () {
2223
+ try {
2224
+ const r = this.getRequestUrl(n, { projectId: e }, t);
2225
+ return { result: yield this.get(r).then((i) => i.json()), error: null };
2226
+ } catch (r) {
2227
+ if (w(r))
2228
+ return { result: null, error: r };
2229
+ throw r;
2230
+ }
2231
+ });
2232
+ }
2233
+ /**
2234
+ * Retrieves the balances for the specified project.
2235
+ *
2236
+ * @param projectId - The ID of the project to retrieve the balances for.
2237
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/balances".
2238
+ * @returns A promise that resolves to an object containing the project balances and an error object if an error occurred.
2239
+ * @see https://developers.deepgram.com/reference/get-all-balances
2240
+ */
2241
+ getProjectBalances(e, t = ":version/projects/:projectId/balances") {
2242
+ return k(this, void 0, void 0, function* () {
2243
+ try {
2244
+ const n = this.getRequestUrl(t, { projectId: e });
2245
+ return { result: yield this.get(n).then((s) => s.json()), error: null };
2246
+ } catch (n) {
2247
+ if (w(n))
2248
+ return { result: null, error: n };
2249
+ throw n;
2250
+ }
2251
+ });
2252
+ }
2253
+ /**
2254
+ * Retrieves the balance for the specified project and balance ID.
2255
+ *
2256
+ * @param projectId - The ID of the project to retrieve the balance for.
2257
+ * @param balanceId - The ID of the balance to retrieve.
2258
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/projects/:projectId/balances/:balanceId".
2259
+ * @returns A promise that resolves to an object containing the project balance and an error object if an error occurred.
2260
+ * @see https://developers.deepgram.com/reference/get-balance
2261
+ */
2262
+ getProjectBalance(e, t, n = ":version/projects/:projectId/balances/:balanceId") {
2263
+ return k(this, void 0, void 0, function* () {
2264
+ try {
2265
+ const r = this.getRequestUrl(n, { projectId: e, balanceId: t });
2266
+ return { result: yield this.get(r).then((i) => i.json()), error: null };
2267
+ } catch (r) {
2268
+ if (w(r))
2269
+ return { result: null, error: r };
2270
+ throw r;
2271
+ }
2272
+ });
2273
+ }
2274
+ /**
2275
+ * Retrieves all models for a given project.
2276
+ *
2277
+ * @param projectId - The ID of the project.
2278
+ * @param endpoint - (optional) The endpoint URL for retrieving models. Defaults to ":version/projects/:projectId/models".
2279
+ * @returns A promise that resolves to a DeepgramResponse containing the GetModelsResponse.
2280
+ * @example
2281
+ * ```typescript
2282
+ * import { createClient } from "@deepgram/sdk";
2283
+ *
2284
+ * const deepgram = createClient(DEEPGRAM_API_KEY);
2285
+ * const { result: models, error } = deepgram.manage.getAllModels("projectId");
2286
+ *
2287
+ * if (error) {
2288
+ * console.error(error);
2289
+ * } else {
2290
+ * console.log(models);
2291
+ * }
2292
+ * ```
2293
+ */
2294
+ getAllModels(e, t = {}, n = ":version/projects/:projectId/models") {
2295
+ return k(this, void 0, void 0, function* () {
2296
+ try {
2297
+ const r = this.getRequestUrl(n, { projectId: e }, t);
2298
+ return { result: yield this.get(r).then((i) => i.json()), error: null };
2299
+ } catch (r) {
2300
+ if (w(r))
2301
+ return { result: null, error: r };
2302
+ throw r;
2303
+ }
2304
+ });
2305
+ }
2306
+ /**
2307
+ * Retrieves a model from the specified project.
2308
+ *
2309
+ * @param projectId - The ID of the project.
2310
+ * @param modelId - The ID of the model.
2311
+ * @param endpoint - (optional) The endpoint URL for the request. Default value is ":version/projects/:projectId/models/:modelId".
2312
+ * @returns A promise that resolves to a DeepgramResponse containing the GetModelResponse.
2313
+ * @example
2314
+ * ```typescript
2315
+ * import { createClient } from "@deepgram/sdk";
2316
+ *
2317
+ * const deepgram = createClient(DEEPGRAM_API_KEY);
2318
+ * const { result: model, error } = deepgram.models.getModel("projectId", "modelId");
2319
+ *
2320
+ * if (error) {
2321
+ * console.error(error);
2322
+ * } else {
2323
+ * console.log(model);
2324
+ * }
2325
+ * ```
2326
+ */
2327
+ getModel(e, t, n = ":version/projects/:projectId/models/:modelId") {
2328
+ return k(this, void 0, void 0, function* () {
2329
+ try {
2330
+ const r = this.getRequestUrl(n, { projectId: e, modelId: t });
2331
+ return { result: yield this.get(r).then((i) => i.json()), error: null };
2332
+ } catch (r) {
2333
+ if (w(r))
2334
+ return { result: null, error: r };
2335
+ throw r;
2336
+ }
2337
+ });
2338
+ }
2339
+ }
2340
+ var Ue = function(o, e, t, n) {
2341
+ function r(s) {
2342
+ return s instanceof t ? s : new t(function(i) {
2343
+ i(s);
2344
+ });
2345
+ }
2346
+ return new (t || (t = Promise))(function(s, i) {
2347
+ function c(f) {
2348
+ try {
2349
+ g(n.next(f));
2350
+ } catch (b) {
2351
+ i(b);
2352
+ }
2353
+ }
2354
+ function p(f) {
2355
+ try {
2356
+ g(n.throw(f));
2357
+ } catch (b) {
2358
+ i(b);
2359
+ }
2360
+ }
2361
+ function g(f) {
2362
+ f.done ? s(f.value) : r(f.value).then(c, p);
2363
+ }
2364
+ g((n = n.apply(o, e || [])).next());
2365
+ });
2366
+ };
2367
+ class ft extends V {
2368
+ constructor() {
2369
+ super(...arguments), this.namespace = "models";
2370
+ }
2371
+ /**
2372
+ * Retrieves a list of all available models.
2373
+ *
2374
+ * @param endpoint - (optional) The endpoint to request.
2375
+ * @returns A promise that resolves with the response from the Deepgram API.
2376
+ * @example
2377
+ * ```typescript
2378
+ * import { createClient } from "@deepgram/sdk";
2379
+ *
2380
+ * const deepgram = createClient(DEEPGRAM_API_KEY);
2381
+ * const { result: models, error } = deepgram.models.getAll();
2382
+ *
2383
+ * if (error) {
2384
+ * console.error(error);
2385
+ * } else {
2386
+ * console.log(models);
2387
+ * }
2388
+ * ```
2389
+ */
2390
+ getAll(e = ":version/models", t = {}) {
2391
+ return Ue(this, void 0, void 0, function* () {
2392
+ try {
2393
+ const n = this.getRequestUrl(e, {}, t);
2394
+ return { result: yield this.get(n).then((s) => s.json()), error: null };
2395
+ } catch (n) {
2396
+ if (w(n))
2397
+ return { result: null, error: n };
2398
+ throw n;
2399
+ }
2400
+ });
2401
+ }
2402
+ /**
2403
+ * Retrieves information about a specific model.
2404
+ *
2405
+ * @param modelId - The UUID of the model to retrieve.
2406
+ * @param endpoint - (optional) The endpoint to request.
2407
+ * @returns A promise that resolves with the response from the Deepgram API.
2408
+ * @example
2409
+ * ```typescript
2410
+ * import { createClient } from "@deepgram/sdk";
2411
+ *
2412
+ * const deepgram = createClient(DEEPGRAM_API_KEY);
2413
+ * const { result: model, error } = deepgram.models.getModel("modelId");
2414
+ *
2415
+ * if (error) {
2416
+ * console.error(error);
2417
+ * } else {
2418
+ * console.log(model);
2419
+ * }
2420
+ * ```
2421
+ */
2422
+ getModel(e, t = ":version/models/:modelId") {
2423
+ return Ue(this, void 0, void 0, function* () {
2424
+ try {
2425
+ const n = this.getRequestUrl(t, { modelId: e });
2426
+ return { result: yield this.get(n).then((s) => s.json()), error: null };
2427
+ } catch (n) {
2428
+ if (w(n))
2429
+ return { result: null, error: n };
2430
+ throw n;
2431
+ }
2432
+ });
2433
+ }
2434
+ }
2435
+ var ne = function(o, e, t, n) {
2436
+ function r(s) {
2437
+ return s instanceof t ? s : new t(function(i) {
2438
+ i(s);
2439
+ });
2440
+ }
2441
+ return new (t || (t = Promise))(function(s, i) {
2442
+ function c(f) {
2443
+ try {
2444
+ g(n.next(f));
2445
+ } catch (b) {
2446
+ i(b);
2447
+ }
2448
+ }
2449
+ function p(f) {
2450
+ try {
2451
+ g(n.throw(f));
2452
+ } catch (b) {
2453
+ i(b);
2454
+ }
2455
+ }
2456
+ function g(f) {
2457
+ f.done ? s(f.value) : r(f.value).then(c, p);
2458
+ }
2459
+ g((n = n.apply(o, e || [])).next());
2460
+ });
2461
+ };
2462
+ class ht extends V {
2463
+ constructor() {
2464
+ super(...arguments), this.namespace = "read";
2465
+ }
2466
+ /**
2467
+ * Analyzes a URL-based audio source synchronously.
2468
+ *
2469
+ * @param source - The URL-based audio source to analyze.
2470
+ * @param options - Optional analysis options.
2471
+ * @param endpoint - The API endpoint to use for the analysis. Defaults to ":version/read".
2472
+ * @returns A promise that resolves to the analysis response, or an error if the analysis fails.
2473
+ */
2474
+ analyzeUrl(e, t, n = ":version/read") {
2475
+ return ne(this, void 0, void 0, function* () {
2476
+ try {
2477
+ let r;
2478
+ if (oe(e))
2479
+ r = JSON.stringify(e);
2480
+ else
2481
+ throw new C("Unknown source type");
2482
+ if (t !== void 0 && "callback" in t)
2483
+ throw new C("Callback cannot be provided as an option to a synchronous transcription. Use `analyzeUrlCallback` or `analyzeTextCallback` instead.");
2484
+ const s = this.getRequestUrl(n, {}, Object.assign({}, t));
2485
+ return { result: yield this.post(s, r).then((c) => c.json()), error: null };
2486
+ } catch (r) {
2487
+ if (w(r))
2488
+ return { result: null, error: r };
2489
+ throw r;
2490
+ }
2491
+ });
2492
+ }
2493
+ /**
2494
+ * Analyzes a text-based audio source synchronously.
2495
+ *
2496
+ * @param source - The text-based audio source to analyze.
2497
+ * @param options - Optional analysis options.
2498
+ * @param endpoint - The API endpoint to use for the analysis. Defaults to ":version/read".
2499
+ * @returns A promise that resolves to the analysis response, or an error if the analysis fails.
2500
+ */
2501
+ analyzeText(e, t, n = ":version/read") {
2502
+ return ne(this, void 0, void 0, function* () {
2503
+ try {
2504
+ let r;
2505
+ if (he(e))
2506
+ r = JSON.stringify(e);
2507
+ else
2508
+ throw new C("Unknown source type");
2509
+ if (t !== void 0 && "callback" in t)
2510
+ throw new C("Callback cannot be provided as an option to a synchronous requests. Use `analyzeUrlCallback` or `analyzeTextCallback` instead.");
2511
+ const s = this.getRequestUrl(n, {}, Object.assign({}, t));
2512
+ return { result: yield this.post(s, r).then((c) => c.json()), error: null };
2513
+ } catch (r) {
2514
+ if (w(r))
2515
+ return { result: null, error: r };
2516
+ throw r;
2517
+ }
2518
+ });
2519
+ }
2520
+ /**
2521
+ * Analyzes a URL-based audio source asynchronously.
2522
+ *
2523
+ * @param source - The URL-based audio source to analyze.
2524
+ * @param callback - The URL to call back with the analysis results.
2525
+ * @param options - Optional analysis options.
2526
+ * @param endpoint - The API endpoint to use for the analysis. Defaults to ":version/read".
2527
+ * @returns A promise that resolves to the analysis response, or an error if the analysis fails.
2528
+ */
2529
+ analyzeUrlCallback(e, t, n, r = ":version/read") {
2530
+ return ne(this, void 0, void 0, function* () {
2531
+ try {
2532
+ let s;
2533
+ if (oe(e))
2534
+ s = JSON.stringify(e);
2535
+ else
2536
+ throw new C("Unknown source type");
2537
+ const i = this.getRequestUrl(r, {}, Object.assign(Object.assign({}, n), { callback: t.toString() }));
2538
+ return { result: yield this.post(i, s).then((p) => p.json()), error: null };
2539
+ } catch (s) {
2540
+ if (w(s))
2541
+ return { result: null, error: s };
2542
+ throw s;
2543
+ }
2544
+ });
2545
+ }
2546
+ /**
2547
+ * Analyzes a text-based audio source asynchronously.
2548
+ *
2549
+ * @param source - The text-based audio source to analyze.
2550
+ * @param callback - The URL to call back with the analysis results.
2551
+ * @param options - Optional analysis options.
2552
+ * @param endpoint - The API endpoint to use for the analysis. Defaults to ":version/read".
2553
+ * @returns A promise that resolves to the analysis response, or an error if the analysis fails.
2554
+ */
2555
+ analyzeTextCallback(e, t, n, r = ":version/read") {
2556
+ return ne(this, void 0, void 0, function* () {
2557
+ try {
2558
+ let s;
2559
+ if (he(e))
2560
+ s = JSON.stringify(e);
2561
+ else
2562
+ throw new C("Unknown source type");
2563
+ const i = this.getRequestUrl(r, {}, Object.assign(Object.assign({}, n), { callback: t.toString() }));
2564
+ return { result: yield this.post(i, s, {
2565
+ headers: { "Content-Type": "deepgram/audio+video" }
2566
+ }).then((p) => p.json()), error: null };
2567
+ } catch (s) {
2568
+ if (w(s))
2569
+ return { result: null, error: s };
2570
+ throw s;
2571
+ }
2572
+ });
2573
+ }
2574
+ }
2575
+ var se = function(o, e, t, n) {
2576
+ function r(s) {
2577
+ return s instanceof t ? s : new t(function(i) {
2578
+ i(s);
2579
+ });
2580
+ }
2581
+ return new (t || (t = Promise))(function(s, i) {
2582
+ function c(f) {
2583
+ try {
2584
+ g(n.next(f));
2585
+ } catch (b) {
2586
+ i(b);
2587
+ }
2588
+ }
2589
+ function p(f) {
2590
+ try {
2591
+ g(n.throw(f));
2592
+ } catch (b) {
2593
+ i(b);
2594
+ }
2595
+ }
2596
+ function g(f) {
2597
+ f.done ? s(f.value) : r(f.value).then(c, p);
2598
+ }
2599
+ g((n = n.apply(o, e || [])).next());
2600
+ });
2601
+ };
2602
+ class pt extends V {
2603
+ constructor() {
2604
+ super(...arguments), this.namespace = "selfhosted";
2605
+ }
2606
+ /**
2607
+ * Lists the self-hosted credentials for a Deepgram project.
2608
+ *
2609
+ * @param projectId - The ID of the Deepgram project.
2610
+ * @returns A promise that resolves to an object containing the list of self-hosted credentials and any error that occurred.
2611
+ * @see https://developers.deepgram.com/reference/list-credentials
2612
+ */
2613
+ listCredentials(e, t = ":version/projects/:projectId/onprem/distribution/credentials") {
2614
+ return se(this, void 0, void 0, function* () {
2615
+ try {
2616
+ const n = this.getRequestUrl(t, { projectId: e });
2617
+ return { result: yield this.get(n).then((s) => s.json()), error: null };
2618
+ } catch (n) {
2619
+ if (w(n))
2620
+ return { result: null, error: n };
2621
+ throw n;
2622
+ }
2623
+ });
2624
+ }
2625
+ /**
2626
+ * Retrieves the self-hosted credentials for a specific Deepgram project and credentials ID.
2627
+ *
2628
+ * @param projectId - The ID of the Deepgram project.
2629
+ * @param credentialsId - The ID of the self-hosted credentials to retrieve.
2630
+ * @returns A promise that resolves to an object containing the self-hosted credentials and any error that occurred.
2631
+ * @see https://developers.deepgram.com/reference/get-credentials
2632
+ */
2633
+ getCredentials(e, t, n = ":version/projects/:projectId/onprem/distribution/credentials/:credentialsId") {
2634
+ return se(this, void 0, void 0, function* () {
2635
+ try {
2636
+ const r = this.getRequestUrl(n, { projectId: e, credentialsId: t });
2637
+ return { result: yield this.get(r).then((i) => i.json()), error: null };
2638
+ } catch (r) {
2639
+ if (w(r))
2640
+ return { result: null, error: r };
2641
+ throw r;
2642
+ }
2643
+ });
2644
+ }
2645
+ /**
2646
+ * Creates self-hosted credentials for a specific Deepgram project.
2647
+ *
2648
+ * @param projectId - The ID of the Deepgram project.
2649
+ * @param options - The options for creating the self-hosted credentials.
2650
+ * @returns A promise that resolves to an object containing the created self-hosted credentials and any error that occurred.
2651
+ * @see https://developers.deepgram.com/reference/create-credentials
2652
+ */
2653
+ createCredentials(e, t, n = ":version/projects/:projectId/onprem/distribution/credentials") {
2654
+ return se(this, void 0, void 0, function* () {
2655
+ try {
2656
+ const r = this.getRequestUrl(n, { projectId: e }), s = JSON.stringify(t);
2657
+ return { result: yield this.post(r, s).then((c) => c.json()), error: null };
2658
+ } catch (r) {
2659
+ if (w(r))
2660
+ return { result: null, error: r };
2661
+ throw r;
2662
+ }
2663
+ });
2664
+ }
2665
+ /**
2666
+ * Deletes self-hosted credentials for a specific Deepgram project.
2667
+ *
2668
+ * @param projectId - The ID of the Deepgram project.
2669
+ * @param credentialsId - The ID of the self-hosted credentials to delete.
2670
+ * @returns A promise that resolves to an object containing a message response and any error that occurred.
2671
+ * @see https://developers.deepgram.com/reference/delete-credentials
2672
+ */
2673
+ deleteCredentials(e, t, n = ":version/projects/:projectId/onprem/distribution/credentials/:credentialsId") {
2674
+ return se(this, void 0, void 0, function* () {
2675
+ try {
2676
+ const r = this.getRequestUrl(n, { projectId: e, credentialsId: t });
2677
+ return { result: yield this.delete(r).then((i) => i.json()), error: null };
2678
+ } catch (r) {
2679
+ if (w(r))
2680
+ return { result: null, error: r };
2681
+ throw r;
2682
+ }
2683
+ });
2684
+ }
2685
+ }
2686
+ class yt extends ye {
2687
+ /**
2688
+ * Constructs a new `SpeakLiveClient` instance with the provided options.
2689
+ *
2690
+ * @param options - The `DeepgramClientOptions` to use for the client connection.
2691
+ * @param speakOptions - An optional `SpeakSchema` object containing additional configuration options for the text-to-speech.
2692
+ * @param endpoint - An optional string representing the WebSocket endpoint to connect to. Defaults to `:version/speak`.
2693
+ */
2694
+ constructor(e, t = {}, n = ":version/speak") {
2695
+ super(e), this.namespace = "speak", this.connect(t, n);
2696
+ }
2697
+ /**
2698
+ * Sets up the connection event handlers.
2699
+ * This method is responsible for handling the various events that can occur on the WebSocket connection, such as opening, closing, and receiving data.
2700
+ * - When the connection is opened, it emits the `LiveTTSEvents.Open` event.
2701
+ * - When the connection is closed, it emits the `LiveTTSEvents.Close` event.
2702
+ * - When an error occurs on the connection, it emits the `LiveTTSEvents.Error` event.
2703
+ * - When a message is received, it parses the message and emits the appropriate event based on the message type, such as `LiveTTSEvents.Metadata`, `LiveTTSEvents.Flushed`, and `LiveTTSEvents.Warning`.
2704
+ */
2705
+ setupConnection() {
2706
+ this.setupConnectionEvents({
2707
+ Open: M.Open,
2708
+ Close: M.Close,
2709
+ Error: M.Error
2710
+ }), this.conn && (this.conn.onmessage = (e) => {
2711
+ this.handleMessage(e);
2712
+ });
2713
+ }
2714
+ /**
2715
+ * Handles text messages received from the WebSocket connection.
2716
+ * @param data - The parsed JSON data.
2717
+ */
2718
+ handleTextMessage(e) {
2719
+ e.type === M.Metadata ? this.emit(M.Metadata, e) : e.type === M.Flushed ? this.emit(M.Flushed, e) : e.type === M.Warning ? this.emit(M.Warning, e) : this.emit(M.Unhandled, e);
2720
+ }
2721
+ /**
2722
+ * Handles binary messages received from the WebSocket connection.
2723
+ * @param data - The binary data.
2724
+ */
2725
+ handleBinaryMessage(e) {
2726
+ this.emit(M.Audio, e);
2727
+ }
2728
+ /**
2729
+ * Sends a text input message to the server.
2730
+ *
2731
+ * @param {string} text - The text to convert to speech.
2732
+ */
2733
+ sendText(e) {
2734
+ this.send(JSON.stringify({
2735
+ type: "Speak",
2736
+ text: e
2737
+ }));
2738
+ }
2739
+ /**
2740
+ * Requests the server flush the current buffer and return generated audio.
2741
+ */
2742
+ flush() {
2743
+ this.send(JSON.stringify({
2744
+ type: "Flush"
2745
+ }));
2746
+ }
2747
+ /**
2748
+ * Requests the server clear the current buffer.
2749
+ */
2750
+ clear() {
2751
+ this.send(JSON.stringify({
2752
+ type: "Clear"
2753
+ }));
2754
+ }
2755
+ /**
2756
+ * Requests the server close the connection.
2757
+ */
2758
+ requestClose() {
2759
+ this.send(JSON.stringify({
2760
+ type: "Close"
2761
+ }));
2762
+ }
2763
+ /**
2764
+ * Handles incoming messages from the WebSocket connection.
2765
+ * @param event - The MessageEvent object representing the received message.
2766
+ */
2767
+ handleMessage(e) {
2768
+ var t, n, r, s, i, c;
2769
+ if (typeof e.data == "string")
2770
+ try {
2771
+ const p = JSON.parse(e.data);
2772
+ this.handleTextMessage(p);
2773
+ } catch (p) {
2774
+ this.emit(M.Error, {
2775
+ event: e,
2776
+ message: "Unable to parse `data` as JSON.",
2777
+ error: p,
2778
+ url: (t = this.conn) === null || t === void 0 ? void 0 : t.url,
2779
+ readyState: (n = this.conn) === null || n === void 0 ? void 0 : n.readyState,
2780
+ data: ((r = e.data) === null || r === void 0 ? void 0 : r.toString().substring(0, 200)) + (((s = e.data) === null || s === void 0 ? void 0 : s.toString().length) > 200 ? "..." : "")
2781
+ });
2782
+ }
2783
+ else e.data instanceof Blob ? e.data.arrayBuffer().then((p) => {
2784
+ this.handleBinaryMessage(Buffer.from(p));
2785
+ }) : e.data instanceof ArrayBuffer ? this.handleBinaryMessage(Buffer.from(e.data)) : Buffer.isBuffer(e.data) ? this.handleBinaryMessage(e.data) : (console.log("Received unknown data type", e.data), this.emit(M.Error, {
2786
+ event: e,
2787
+ message: "Received unknown data type.",
2788
+ url: (i = this.conn) === null || i === void 0 ? void 0 : i.url,
2789
+ readyState: (c = this.conn) === null || c === void 0 ? void 0 : c.readyState,
2790
+ dataType: typeof e.data
2791
+ }));
2792
+ }
2793
+ }
2794
+ var fe = function(o, e, t, n) {
2795
+ function r(s) {
2796
+ return s instanceof t ? s : new t(function(i) {
2797
+ i(s);
2798
+ });
2799
+ }
2800
+ return new (t || (t = Promise))(function(s, i) {
2801
+ function c(f) {
2802
+ try {
2803
+ g(n.next(f));
2804
+ } catch (b) {
2805
+ i(b);
2806
+ }
2807
+ }
2808
+ function p(f) {
2809
+ try {
2810
+ g(n.throw(f));
2811
+ } catch (b) {
2812
+ i(b);
2813
+ }
2814
+ }
2815
+ function g(f) {
2816
+ f.done ? s(f.value) : r(f.value).then(c, p);
2817
+ }
2818
+ g((n = n.apply(o, e || [])).next());
2819
+ });
2820
+ };
2821
+ class gt extends V {
2822
+ constructor() {
2823
+ super(...arguments), this.namespace = "speak";
2824
+ }
2825
+ /**
2826
+ * Sends a request to the Deepgram Text-to-Speech API to generate audio from the provided text source.
2827
+ *
2828
+ * @param source - The text source to be converted to audio.
2829
+ * @param options - Optional configuration options for the text-to-speech request.
2830
+ * @param endpoint - The API endpoint to use for the request. Defaults to ":version/speak".
2831
+ * @returns A promise that resolves to the SpeakRestClient instance, which can be used to retrieve the response headers and body.
2832
+ * @throws {DeepgramError} If the text source type is unknown.
2833
+ * @throws {DeepgramUnknownError} If the request was made before a previous request completed.
2834
+ * @see https://developers.deepgram.com/reference/text-to-speech-api
2835
+ */
2836
+ request(e, t, n = ":version/speak") {
2837
+ return fe(this, void 0, void 0, function* () {
2838
+ let r;
2839
+ if (he(e))
2840
+ r = JSON.stringify(e);
2841
+ else
2842
+ throw new C("Unknown transcription source type");
2843
+ const s = this.getRequestUrl(n, {}, Object.assign({ model: "aura-2-thalia-en" }, t));
2844
+ return this.result = yield this.post(s, r, {
2845
+ headers: { Accept: "audio/*", "Content-Type": "application/json" }
2846
+ }), this;
2847
+ });
2848
+ }
2849
+ /**
2850
+ * Retrieves the response body as a readable stream.
2851
+ *
2852
+ * @returns A promise that resolves to the response body as a readable stream, or `null` if no request has been made yet.
2853
+ * @throws {DeepgramUnknownError} If a request has not been made yet.
2854
+ */
2855
+ getStream() {
2856
+ return fe(this, void 0, void 0, function* () {
2857
+ if (!this.result)
2858
+ throw new ie("Tried to get stream before making request", "");
2859
+ return this.result.body;
2860
+ });
2861
+ }
2862
+ /**
2863
+ * Retrieves the response headers from the previous request.
2864
+ *
2865
+ * @returns A promise that resolves to the response headers, or throws a `DeepgramUnknownError` if no request has been made yet.
2866
+ */
2867
+ getHeaders() {
2868
+ return fe(this, void 0, void 0, function* () {
2869
+ if (!this.result)
2870
+ throw new ie("Tried to get headers before making request", "");
2871
+ return this.result.headers;
2872
+ });
2873
+ }
2874
+ }
2875
+ class vt extends X {
2876
+ constructor() {
2877
+ super(...arguments), this.namespace = "speak";
2878
+ }
2879
+ /**
2880
+ * Returns a `SpeakRestClient` instance for interacting with the rest speak API.
2881
+ */
2882
+ request(e, t, n = ":version/speak") {
2883
+ return new gt(this.options).request(e, t, n);
2884
+ }
2885
+ /**
2886
+ * Returns a `SpeakLiveClient` instance for interacting with the live speak API, with the provided TTS options and endpoint.
2887
+ * @param {SpeakSchema} [ttsOptions={}] - The TTS options to use for the live speak API.
2888
+ * @param {string} [endpoint=":version/speak"] - The endpoint to use for the live speak API.
2889
+ * @returns {SpeakLiveClient} - A `SpeakLiveClient` instance for interacting with the live speak API.
2890
+ */
2891
+ live(e = {}, t = ":version/speak") {
2892
+ return new yt(this.options, e, t);
2893
+ }
2894
+ }
2895
+ class bt extends X {
2896
+ /**
2897
+ * Returns a new instance of the AuthRestClient, which provides access to the Deepgram API's temporary token endpoints.
2898
+ *
2899
+ * @returns {AuthRestClient} A new instance of the AuthRestClient.
2900
+ * @see https://developers.deepgram.com/reference/token-based-auth-api/grant-token
2901
+ */
2902
+ get auth() {
2903
+ return new at(this.options);
2904
+ }
2905
+ /**
2906
+ * Returns a new instance of the ListenClient, which provides access to the Deepgram API's listening functionality.
2907
+ *
2908
+ * @returns {ListenClient} A new instance of the ListenClient.
2909
+ */
2910
+ get listen() {
2911
+ return new lt(this.options);
2912
+ }
2913
+ /**
2914
+ * Returns a new instance of the ManageClient, which provides access to the Deepgram API's management functionality.
2915
+ *
2916
+ * @returns {ManageClient} A new instance of the ManageClient.
2917
+ */
2918
+ get manage() {
2919
+ return new dt(this.options);
2920
+ }
2921
+ /**
2922
+ * Returns a new instance of the ModelsRestClient, which provides access to the Deepgram API's model functionality.
2923
+ *
2924
+ * @returns {ModelsRestClient} A new instance of the ModelsRestClient.
2925
+ */
2926
+ get models() {
2927
+ return new ft(this.options);
2928
+ }
2929
+ /**
2930
+ * Returns a new instance of the SelfHostedRestClient, which provides access to the Deepgram API's self-hosted functionality.
2931
+ *
2932
+ * @returns {OnPremClient} A new instance of the SelfHostedRestClient named as OnPremClient.
2933
+ * @deprecated use selfhosted() instead
2934
+ */
2935
+ get onprem() {
2936
+ return this.selfhosted;
2937
+ }
2938
+ /**
2939
+ * Returns a new instance of the SelfHostedRestClient, which provides access to the Deepgram API's self-hosted functionality.
2940
+ *
2941
+ * @returns {SelfHostedRestClient} A new instance of the SelfHostedRestClient.
2942
+ */
2943
+ get selfhosted() {
2944
+ return new pt(this.options);
2945
+ }
2946
+ /**
2947
+ * Returns a new instance of the ReadClient, which provides access to the Deepgram API's reading functionality.
2948
+ *
2949
+ * @returns {ReadClient} A new instance of the ReadClient.
2950
+ */
2951
+ get read() {
2952
+ return new ht(this.options);
2953
+ }
2954
+ /**
2955
+ * Returns a new instance of the SpeakClient, which provides access to the Deepgram API's speaking functionality.
2956
+ *
2957
+ * @returns {SpeakClient} A new instance of the SpeakClient.
2958
+ */
2959
+ get speak() {
2960
+ return new vt(this.options);
2961
+ }
2962
+ /**
2963
+ * Returns a new instance of the AgentLiveClient, which provides access to Deepgram's Voice Agent API.
2964
+ *
2965
+ * @returns {AgentLiveClient} A new instance of the AgentLiveClient.
2966
+ * @beta
2967
+ */
2968
+ agent(e = "/:version/agent/converse") {
2969
+ return new it(this.options, e);
2970
+ }
2971
+ /**
2972
+ * @deprecated
2973
+ * @see https://dpgr.am/js-v3
2974
+ */
2975
+ get transcription() {
2976
+ throw new F();
2977
+ }
2978
+ /**
2979
+ * @deprecated
2980
+ * @see https://dpgr.am/js-v3
2981
+ */
2982
+ get projects() {
2983
+ throw new F();
2984
+ }
2985
+ /**
2986
+ * @deprecated
2987
+ * @see https://dpgr.am/js-v3
2988
+ */
2989
+ get keys() {
2990
+ throw new F();
2991
+ }
2992
+ /**
2993
+ * @deprecated
2994
+ * @see https://dpgr.am/js-v3
2995
+ */
2996
+ get members() {
2997
+ throw new F();
2998
+ }
2999
+ /**
3000
+ * @deprecated
3001
+ * @see https://dpgr.am/js-v3
3002
+ */
3003
+ get scopes() {
3004
+ throw new F();
3005
+ }
3006
+ /**
3007
+ * @deprecated
3008
+ * @see https://dpgr.am/js-v3
3009
+ */
3010
+ get invitation() {
3011
+ throw new F();
3012
+ }
3013
+ /**
3014
+ * @deprecated
3015
+ * @see https://dpgr.am/js-v3
3016
+ */
3017
+ get usage() {
3018
+ throw new F();
3019
+ }
3020
+ /**
3021
+ * @deprecated
3022
+ * @see https://dpgr.am/js-v3
3023
+ */
3024
+ get billing() {
3025
+ throw new F();
3026
+ }
3027
+ }
3028
+ function mt(o, e) {
3029
+ let t = {};
3030
+ return typeof o == "string" || typeof o == "function" ? t.key = o : typeof o == "object" && (t = o), new bt(t);
3031
+ }
3032
+ class wt {
3033
+ config;
3034
+ _deepgram = null;
3035
+ unityUrl;
3036
+ active = !1;
3037
+ constructor(e) {
3038
+ this.config = e, this.unityUrl = e.unityBaseUrl || "https://api.glydebuddy.com";
3039
+ }
3040
+ /**
3041
+ * Initialize and start the voice session
3042
+ */
3043
+ async start() {
3044
+ if (!this.active)
3045
+ try {
3046
+ const e = await fetch(`${this.unityUrl}/api/unity/voice/auth`, {
3047
+ method: "POST",
3048
+ headers: {
3049
+ "Content-Type": "application/json",
3050
+ "x-publishable-key": this.config.publishableKey
3051
+ },
3052
+ body: JSON.stringify({
3053
+ context_id: this.config.contextId,
3054
+ domain: window.location.hostname
3055
+ })
3056
+ });
3057
+ if (!e.ok) {
3058
+ const s = await e.json();
3059
+ throw new Error(s.message || "Failed to authenticate voice session");
3060
+ }
3061
+ const { data: t } = await e.json(), { token: n, agent_config: r } = t;
3062
+ this.emit({ type: "open", payload: { config: r } }), this._deepgram = mt(n), this._deepgram, console.log("[GlydeVoice] Connected to Deepgram with token", n), console.log("[GlydeVoice] Agent Instructions:", r.instructions), this.active = !0, this.renderUI();
3063
+ } catch (e) {
3064
+ console.error("[GlydeVoice] Error starting session:", e), this.emit({ type: "error", payload: e });
3065
+ }
3066
+ }
3067
+ /**
3068
+ * Stop the voice session
3069
+ */
3070
+ stop() {
3071
+ this.active = !1, this.emit({ type: "close" });
3072
+ }
3073
+ emit(e) {
3074
+ this.config.onEvent && this.config.onEvent(e);
3075
+ }
3076
+ renderUI() {
3077
+ if (!this.config.container) return;
3078
+ const e = typeof this.config.container == "string" ? document.querySelector(this.config.container) : this.config.container;
3079
+ e && (e.innerHTML = `
3080
+ <div style="padding: 20px; border: 1px solid #ccc; border-radius: 8px; background: #fff;">
3081
+ <h3>Glyde Voice Agent</h3>
3082
+ <p>Status: Active</p>
3083
+ <button onclick="this.closest('div').remove()">Close</button>
3084
+ </div>
3085
+ `);
3086
+ }
3087
+ }
3088
+ export {
3089
+ wt as G,
3090
+ Oe as g
3091
+ };