-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathCustomClient.ts
More file actions
1536 lines (1341 loc) · 57.3 KB
/
Copy pathCustomClient.ts
File metadata and controls
1536 lines (1341 loc) · 57.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { DeepgramClient } from "./Client.js";
import { ReconnectingWebSocket } from "./core/websocket/ws.js";
import type { AgentClient } from "./api/resources/agent/client/Client.js";
import type { ListenClient } from "./api/resources/listen/client/Client.js";
import type { SpeakClient } from "./api/resources/speak/client/Client.js";
import { AgentClient as AgentClientImpl } from "./api/resources/agent/client/Client.js";
import { ListenClient as ListenClientImpl } from "./api/resources/listen/client/Client.js";
import { SpeakClient as SpeakClientImpl } from "./api/resources/speak/client/Client.js";
import { V1Client as AgentV1Client } from "./api/resources/agent/resources/v1/client/Client.js";
import { V1Client as ListenV1Client } from "./api/resources/listen/resources/v1/client/Client.js";
import { V2Client as ListenV2Client } from "./api/resources/listen/resources/v2/client/Client.js";
import { V1Client as SpeakV1Client } from "./api/resources/speak/resources/v1/client/Client.js";
import { V1Socket as AgentV1Socket } from "./api/resources/agent/resources/v1/client/Socket.js";
import { V1Socket as ListenV1Socket } from "./api/resources/listen/resources/v1/client/Socket.js";
import { V2Socket as ListenV2Socket } from "./api/resources/listen/resources/v2/client/Socket.js";
import { V1Socket as SpeakV1Socket } from "./api/resources/speak/resources/v1/client/Socket.js";
import { mergeHeaders } from "./core/headers.js";
import { fromJson } from "./core/json.js";
import { BadRequestError } from "./api/errors/index.js";
import * as core from "./core/index.js";
import * as websocketEvents from "./core/websocket/events.js";
import * as environments from "./environments.js";
import { RUNTIME } from "./core/runtime/index.js";
import type {
DeepgramTransport,
DeepgramTransportFactory,
DeepgramTransportMessage,
DeepgramTransportRequest,
} from "./transport.js";
// Default WebSocket connection timeout in milliseconds
const DEFAULT_CONNECTION_TIMEOUT_MS = 10000;
// Keys present in every ConnectArgs interface that control the WebSocket connection itself.
// Every other key in ConnectArgs is treated as an API query parameter.
const WEBSOCKET_OPTION_KEYS = new Set([
"Authorization",
"headers",
"protocols",
"debug",
"reconnectAttempts",
"connectionTimeoutInSeconds",
"abortSignal",
"queryParams",
]);
// ws for Node.js - loaded lazily to support CJS, ESM, and browser builds.
// A static import of "module" (for createRequire) would break the browser bundle,
// so we detect the environment at runtime and use an opaque dynamic import in ESM
// Node so bundlers cannot statically analyse and reject it.
let NodeWebSocket: any;
let _wsInitialized = false;
async function loadNodeWebSocket(): Promise<void> {
if (_wsInitialized) return;
_wsInitialized = true;
try {
if (typeof require !== "undefined") {
// CJS: require is injected as a module-scoped binding
// eslint-disable-next-line @typescript-eslint/no-require-imports
let ws = require("ws");
NodeWebSocket = ws.WebSocket || ws.default || ws;
} else if (typeof process !== "undefined" && process.versions?.node) {
// ESM Node: require is not defined. Wrap import() in new Function so
// bundlers (esbuild, webpack) cannot statically resolve or reject "ws".
// eslint-disable-next-line no-new-func
const dynamicImport = new Function("specifier", "return import(specifier)");
const ws = await dynamicImport("ws");
NodeWebSocket = ws.WebSocket || ws.default || ws;
}
// Browser: process.versions?.node is undefined → NodeWebSocket stays undefined
} catch {
// ws not available or failed to load
NodeWebSocket = undefined;
}
}
// Helper function to generate UUID that works in both Node.js and browser
function generateUUID(): string {
// Try global crypto.randomUUID first (works in both Node.js 14.18+ and modern browsers)
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
// Fallback for Node.js: use the crypto module
if (RUNTIME.type === "node") {
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeCrypto = require("crypto");
return nodeCrypto.randomUUID();
} catch {
// Fallback if crypto module is not available
}
}
// Final fallback: manual UUID generation (RFC4122 version 4)
// This should work everywhere but is less secure than crypto.randomUUID()
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
/**
* Wrapper auth provider that adds "Token " prefix to API keys.
* The auto-generated HeaderAuthProvider doesn't add the prefix, so we wrap it here.
*/
class ApiKeyAuthProviderWrapper implements core.AuthProvider {
private readonly originalProvider: core.AuthProvider;
constructor(originalProvider: core.AuthProvider) {
this.originalProvider = originalProvider;
}
public async getAuthRequest(arg?: { endpointMetadata?: core.EndpointMetadata }): Promise<core.AuthRequest> {
const authRequest = await this.originalProvider.getAuthRequest(arg);
const authHeader = authRequest.headers?.Authorization || authRequest.headers?.authorization;
// If the header doesn't already have a scheme prefix, add "Token " prefix for API keys
if (authHeader && typeof authHeader === "string") {
// Only add prefix if it doesn't already have Bearer or Token prefix
if (!authHeader.startsWith("Bearer ") && !authHeader.startsWith("Token ") && !authHeader.startsWith("token ")) {
return {
headers: {
...authRequest.headers,
Authorization: `Token ${authHeader}`,
},
};
}
}
return authRequest;
}
}
/**
* Wrapper auth provider that checks for accessToken first (Bearer scheme)
* before falling back to the original auth provider (Token scheme for API keys).
*/
class AccessTokenAuthProviderWrapper implements core.AuthProvider {
private readonly originalProvider: core.AuthProvider;
private readonly accessToken?: core.Supplier<string | undefined>;
constructor(originalProvider: core.AuthProvider, accessToken?: core.Supplier<string | undefined>) {
this.originalProvider = originalProvider;
this.accessToken = accessToken;
}
public async getAuthRequest(arg?: { endpointMetadata?: core.EndpointMetadata }): Promise<core.AuthRequest> {
// Check for access token first (highest priority)
// Access tokens use Bearer scheme, API keys use Token scheme
const accessToken = (await core.Supplier.get(this.accessToken)) ?? process.env?.DEEPGRAM_ACCESS_TOKEN;
if (accessToken != null) {
return {
headers: { Authorization: `Bearer ${accessToken}` },
};
}
// Fall back to original provider (which handles API keys)
return this.originalProvider.getAuthRequest(arg);
}
}
export type AgentV1ConnectionArgs = Omit<AgentV1Client.ConnectArgs, "Authorization"> & { Authorization?: string };
export type ListenV1ConnectionArgs = Omit<ListenV1Client.ConnectArgs, "Authorization"> & { Authorization?: string };
export type ListenV2ConnectionArgs = Omit<ListenV2Client.ConnectArgs, "Authorization" | "keyterm"> & {
Authorization?: string;
keyterm?: string | string[];
};
export type SpeakV1ConnectionArgs = Omit<SpeakV1Client.ConnectArgs, "Authorization"> & { Authorization?: string };
export interface AgentV1ClientWithWebSocket extends AgentV1Client {
connect(args?: AgentV1ConnectionArgs): Promise<AgentV1Socket>;
createConnection(args?: AgentV1ConnectionArgs): Promise<AgentV1Socket>;
}
export interface ListenV1ClientWithWebSocket extends ListenV1Client {
connect(args: ListenV1ConnectionArgs): Promise<ListenV1Socket>;
createConnection(args: ListenV1ConnectionArgs): Promise<ListenV1Socket>;
}
export interface ListenV2ClientWithWebSocket extends ListenV2Client {
connect(args: ListenV2ConnectionArgs): Promise<ListenV2Socket>;
createConnection(args: ListenV2ConnectionArgs): Promise<ListenV2Socket>;
}
export interface SpeakV1ClientWithWebSocket extends SpeakV1Client {
connect(args: SpeakV1ConnectionArgs): Promise<SpeakV1Socket>;
createConnection(args: SpeakV1ConnectionArgs): Promise<SpeakV1Socket>;
}
export interface AgentClientWithWebSockets extends AgentClient {
readonly v1: AgentV1ClientWithWebSocket;
}
export interface ListenClientWithWebSockets extends ListenClient {
readonly v1: ListenV1ClientWithWebSocket;
readonly v2: ListenV2ClientWithWebSocket;
}
export interface SpeakClientWithWebSockets extends SpeakClient {
readonly v1: SpeakV1ClientWithWebSocket;
}
/**
* Custom wrapper around DeepgramClient that ensures the custom websocket implementation
* from ws.ts is always used, even if the auto-generated code changes.
*/
export interface CustomDeepgramClientOptions extends DeepgramClient.Options {
accessToken?: core.Supplier<string | undefined>;
transportFactory?: DeepgramTransportFactory;
/**
* Whether the SDK should retry streaming connections at the wrapper level
* after a transport failure. Defaults to `true` for native websocket
* connections. When a `transportFactory` is provided, this is auto-set to
* `false` because custom transports own their own retry/reconnect lifecycle
* — wrapping a self-retrying transport in another retry layer creates
* double-retry storms under burst load. Pass `reconnect: true` together
* with `transportFactory` to opt back into wrapper-level retries.
*/
reconnect?: boolean;
}
export class CustomDeepgramClient extends DeepgramClient {
private _customAgent: AgentClientWithWebSockets | undefined;
private _customListen: ListenClientWithWebSockets | undefined;
private _customSpeak: SpeakClientWithWebSockets | undefined;
private readonly _sessionId: string;
private readonly _reconnect: boolean;
constructor(options: CustomDeepgramClientOptions = {}) {
// Generate a UUID for the session ID
const sessionId = generateUUID();
// Add the session ID to headers so it's included in all REST requests
// Auto-disable wrapper-level reconnect when a custom transportFactory
// is in use: those transports own their retry lifecycle, and stacking
// a second retry layer on top causes storm-on-storm under burst load.
// Callers can still opt back in by explicitly passing reconnect: true.
const reconnect = options.reconnect ?? (options.transportFactory == null);
const optionsWithSessionId: CustomDeepgramClientOptions = {
...options,
reconnect,
headers: {
...options.headers,
"x-deepgram-session-id": sessionId,
},
};
super(optionsWithSessionId);
this._sessionId = sessionId;
this._reconnect = reconnect;
// Always wrap the auth provider to add "Token " prefix to API keys
// The auto-generated HeaderAuthProvider doesn't add the prefix
(this._options as any).authProvider = new ApiKeyAuthProviderWrapper(this._options.authProvider);
// Wrap again to handle accessToken if provided
// This ensures accessToken takes priority over apiKey/env var
if (options.accessToken != null) {
(this._options as any).authProvider = new AccessTokenAuthProviderWrapper(
this._options.authProvider,
options.accessToken
);
}
}
/**
* Get the session ID that was generated for this client instance.
*/
public get sessionId(): string {
return this._sessionId;
}
/**
* Whether the SDK will retry streaming connections at the wrapper level
* after a transport-side failure. Returns `false` when a `transportFactory`
* was supplied without an explicit `reconnect: true` override, signalling
* that the custom transport is expected to manage its own reconnect
* lifecycle.
*/
public get reconnect(): boolean {
return this._reconnect;
}
/**
* Override the agent getter to return a wrapped client that ensures
* the custom websocket implementation is used.
*/
public get agent(): AgentClientWithWebSockets {
if (!this._customAgent) {
// Create a wrapper that ensures custom websocket is used
this._customAgent = new WrappedAgentClient(this._options);
}
return this._customAgent;
}
/**
* Override the listen getter to return a wrapped client that ensures
* the custom websocket implementation is used.
*/
public get listen(): ListenClientWithWebSockets {
if (!this._customListen) {
// Create a wrapper that ensures custom websocket is used
this._customListen = new WrappedListenClient(this._options);
}
return this._customListen;
}
/**
* Override the speak getter to return a wrapped client that ensures
* the custom websocket implementation is used.
*/
public get speak(): SpeakClientWithWebSockets {
if (!this._customSpeak) {
// Create a wrapper that ensures custom websocket is used
this._customSpeak = new WrappedSpeakClient(this._options);
}
return this._customSpeak;
}
}
/**
* Wrapper for AgentClient that ensures custom websocket implementation is used.
*
* This wrapper exists to guarantee that our custom WebSocket implementation
* (from ws.ts) continues to be used even after the SDK code is auto-generated
* by Fern. Without this wrapper, Fern regeneration could overwrite the client
* with a different WebSocket implementation.
*/
class WrappedAgentClient extends AgentClientImpl {
public get v1() {
return new WrappedAgentV1Client(this._options);
}
}
/**
* Wrapper for ListenClient that ensures custom websocket implementation is used.
*
* This wrapper exists to guarantee that our custom WebSocket implementation
* (from ws.ts) continues to be used even after the SDK code is auto-generated
* by Fern. Without this wrapper, Fern regeneration could overwrite the client
* with a different WebSocket implementation.
*/
class WrappedListenClient extends ListenClientImpl {
public get v1() {
return new WrappedListenV1Client(this._options);
}
public get v2() {
return new WrappedListenV2Client(this._options);
}
}
/**
* Wrapper for SpeakClient that ensures custom websocket implementation is used.
*
* This wrapper exists to guarantee that our custom WebSocket implementation
* (from ws.ts) continues to be used even after the SDK code is auto-generated
* by Fern. Without this wrapper, Fern regeneration could overwrite the client
* with a different WebSocket implementation.
*/
class WrappedSpeakClient extends SpeakClientImpl {
public get v1() {
return new WrappedSpeakV1Client(this._options);
}
}
/**
* Helper function to resolve Suppliers in headers to their actual values.
*/
async function resolveHeaders(headers: Record<string, unknown>): Promise<Record<string, unknown>> {
const resolved: Record<string, unknown> = {};
for (const [key, value] of Object.entries(headers)) {
if (value == null) {
continue;
}
// Resolve Supplier if it's a Supplier, otherwise use the value directly
const resolvedValue = await core.Supplier.get(value as any);
if (resolvedValue != null) {
resolved[key] = resolvedValue;
}
}
return resolved;
}
/**
* Builds API query parameters from a ConnectArgs object, excluding all WebSocket
* infrastructure keys. This means any new typed parameter added to ConnectArgs by
* the generator is automatically included without needing manual updates here.
* An explicit `queryParams` override is merged in last.
*/
function buildQueryParams(args: Record<string, unknown>): Record<string, unknown> {
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(args)) {
if (!WEBSOCKET_OPTION_KEYS.has(key) && value != null) {
result[key] = value;
}
}
if (args.queryParams != null && typeof args.queryParams === "object") {
Object.assign(result, args.queryParams);
}
return result;
}
/**
* Nova-3 dropped the legacy `keywords` parameter in favor of `keyterm`, and the API rejects the
* combination with a 400. REST surfaces that error, but the streaming endpoint just closes the
* socket cleanly (code 1000, no reason, no error event) — so it fails silently and the socket
* never opens. Detecting the combination up front lets the client throw the same error REST
* already does, in both Node and the browser.
*
* Exported for unit testing; not part of the public API.
*/
export function isUnsupportedNova3Keywords(model: unknown, keywords: unknown): boolean {
if (typeof model !== "string" || !model.startsWith("nova-3")) {
return false;
}
if (keywords == null) {
return false;
}
if (typeof keywords === "string" && keywords.length === 0) {
return false;
}
if (Array.isArray(keywords) && keywords.length === 0) {
return false;
}
return true;
}
function normalizeProtocols(protocols?: string | string[]): string[] {
if (protocols == null) {
return [];
}
return Array.isArray(protocols) ? protocols : [protocols];
}
function stringifyHeaders(headers: Record<string, unknown>): Record<string, string> {
const result: Record<string, string> = {};
for (const [key, value] of Object.entries(headers)) {
result[key] = String(value);
}
return result;
}
function buildWebSocketUrl(url: string, queryParams: Record<string, unknown>): string {
const queryString = core.url.toQueryString(queryParams, { arrayFormat: "repeat" });
return queryString ? `${url}?${queryString}` : url;
}
function getTransportFactory(options: DeepgramClient.Options): DeepgramTransportFactory | undefined {
return (options as CustomDeepgramClientOptions).transportFactory;
}
function getReconnect(options: DeepgramClient.Options): boolean {
return (options as CustomDeepgramClientOptions).reconnect !== false;
}
class TransportWebSocketAdapter {
private _listeners: ReconnectingWebSocket.ListenersMap = {
error: [],
message: [],
open: [],
close: [],
};
private _retryCount = -1;
private _shouldReconnect = true;
private _connectLock = false;
private _binaryType: BinaryType = "blob";
private _closeCalled = false;
private _messageQueue: DeepgramTransportMessage[] = [];
private _connectTimeout: ReturnType<typeof setTimeout> | undefined;
private _transport: DeepgramTransport | undefined;
private _readyState: ReconnectingWebSocket.ReadyState;
private _ws:
| {
OPEN: typeof ReconnectingWebSocket.OPEN;
readyState: ReconnectingWebSocket.ReadyState;
ping?: (data?: string | ArrayBuffer | Blob | ArrayBufferView) => void;
}
| undefined;
private readonly _factory: DeepgramTransportFactory;
private readonly _request: DeepgramTransportRequest;
// Whether the wrapper should retry after a transport-side failure. False
// signals that the underlying transport owns reconnect — the wrapper
// attempts the connect once and surfaces any error without re-attempting.
private readonly _reconnect: boolean;
constructor(args: {
factory: DeepgramTransportFactory;
request: DeepgramTransportRequest;
startClosed?: boolean;
reconnect?: boolean;
}) {
this._factory = args.factory;
this._request = args.request;
this._reconnect = args.reconnect !== false;
this._readyState = args.startClosed ? ReconnectingWebSocket.ReadyState.CLOSED : ReconnectingWebSocket.ReadyState.CONNECTING;
if (this._request.abortSignal) {
this._request.abortSignal.addEventListener("abort", this._handleAbort, { once: true });
}
if (!args.startClosed) {
void this._connect();
}
}
public static readonly CONNECTING = ReconnectingWebSocket.CONNECTING;
public static readonly OPEN = ReconnectingWebSocket.OPEN;
public static readonly CLOSING = ReconnectingWebSocket.CLOSING;
public static readonly CLOSED = ReconnectingWebSocket.CLOSED;
public readonly CONNECTING: typeof ReconnectingWebSocket.CONNECTING = ReconnectingWebSocket.CONNECTING;
public readonly OPEN: typeof ReconnectingWebSocket.OPEN = ReconnectingWebSocket.OPEN;
public readonly CLOSING: typeof ReconnectingWebSocket.CLOSING = ReconnectingWebSocket.CLOSING;
public readonly CLOSED: typeof ReconnectingWebSocket.CLOSED = ReconnectingWebSocket.CLOSED;
public onclose: ((event: websocketEvents.CloseEvent) => void) | null = null;
public onerror: ((event: websocketEvents.ErrorEvent) => void) | null = null;
public onmessage: ((event: MessageEvent) => void) | null = null;
public onopen: ((event: websocketEvents.Event) => void) | null = null;
get binaryType(): BinaryType {
return this._binaryType;
}
set binaryType(value: BinaryType) {
this._binaryType = value;
}
get retryCount(): number {
return Math.max(this._retryCount, 0);
}
get bufferedAmount(): number {
return this._messageQueue.reduce((acc, message) => {
if (typeof message === "string") {
return acc + message.length;
}
if (message instanceof Blob) {
return acc + message.size;
}
return acc + message.byteLength;
}, 0);
}
get extensions(): string {
return "";
}
get protocol(): string {
return this._request.protocols[0] ?? "";
}
get readyState(): ReconnectingWebSocket.ReadyState {
return this._readyState;
}
get url(): string {
return this._request.url;
}
public close(code = 1000, reason?: string): void {
this._closeCalled = true;
this._shouldReconnect = false;
this._clearConnectTimeout();
this._readyState = ReconnectingWebSocket.ReadyState.CLOSING;
const transport = this._transport;
this._transport = undefined;
this._setTransportHandle(undefined);
if (!transport) {
this._readyState = ReconnectingWebSocket.ReadyState.CLOSED;
return;
}
void transport.close(code, reason);
this._readyState = ReconnectingWebSocket.ReadyState.CLOSED;
}
public reconnect(code?: number, reason?: string): void {
this._shouldReconnect = true;
this._closeCalled = false;
this._retryCount = -1;
this._readyState = ReconnectingWebSocket.ReadyState.CONNECTING;
const transport = this._transport;
this._transport = undefined;
this._setTransportHandle(undefined);
if (transport) {
void transport.close(code, reason);
}
void this._connect();
}
public send(data: DeepgramTransportMessage): void {
if (this._transport?.isOpen()) {
void this._transport.send(data);
return;
}
this._messageQueue.push(data);
}
public addEventListener<T extends keyof websocketEvents.WebSocketEventListenerMap>(
type: T,
listener: websocketEvents.WebSocketEventListenerMap[T],
): void {
if (this._listeners[type]) {
(this._listeners[type] as Array<websocketEvents.WebSocketEventListenerMap[T]>).push(listener);
}
}
public dispatchEvent(event: websocketEvents.Event): boolean {
const listeners = this._listeners[event.type as keyof websocketEvents.WebSocketEventListenerMap];
if (listeners) {
for (const listener of listeners) {
this._callEventListener(event as never, listener as never);
}
}
return true;
}
public removeEventListener<T extends keyof websocketEvents.WebSocketEventListenerMap>(
type: T,
listener: websocketEvents.WebSocketEventListenerMap[T],
): void {
if (this._listeners[type]) {
this._listeners[type] = this._listeners[type].filter((registered) => registered !== listener) as never;
}
}
private _debug(...args: unknown[]): void {
if (this._request.debug) {
// biome-ignore lint/suspicious/noConsole: transport debug logging mirrors websocket debug logging
console.log.apply(console, ["DG-TRANSPORT>", ...args]);
}
}
private _handleAbort = () => {
if (this._closeCalled) {
return;
}
this._debug("abort signal fired");
this._closeCalled = true;
this._shouldReconnect = false;
this._clearConnectTimeout();
const transport = this._transport;
this._transport = undefined;
this._setTransportHandle(undefined);
if (transport) {
void transport.close(1000, "aborted");
}
this._readyState = ReconnectingWebSocket.ReadyState.CLOSED;
this._emitClose(1000, "aborted");
};
private async _connect(): Promise<void> {
if (this._connectLock || !this._shouldReconnect || this._request.abortSignal?.aborted) {
return;
}
// When wrapper-level reconnect is disabled, allow only the initial
// attempt (_retryCount starts at -1 and increments to 0 on first
// _connect). Any subsequent re-entry from _handleError must short out
// so the transport's own retry logic is the single source of truth.
if (!this._reconnect && this._retryCount >= 0) {
this._debug("reconnect disabled, skipping retry");
return;
}
if (this._retryCount >= this._request.reconnectAttempts) {
this._debug("max retries reached", this._retryCount, ">=", this._request.reconnectAttempts);
return;
}
this._connectLock = true;
this._retryCount++;
this._readyState = ReconnectingWebSocket.ReadyState.CONNECTING;
this._clearConnectTimeout();
try {
const transport = await this._factory(this._request.url, this._request.headers, this._request);
if (this._closeCalled || this._request.abortSignal?.aborted) {
this._connectLock = false;
await transport.close(1000, "aborted");
return;
}
this._transport = transport;
this._setTransportHandle(transport);
this._bindTransport(transport);
this._armConnectTimeout();
this._connectLock = false;
if (transport.isOpen()) {
this._handleOpen(transport);
}
} catch (error) {
this._connectLock = false;
this._handleError(error instanceof Error ? error : new Error(String(error)));
}
}
private _bindTransport(transport: DeepgramTransport): void {
transport.onOpen(() => {
if (this._transport !== transport) {
return;
}
this._handleOpen(transport);
});
transport.onMessage((message) => {
if (this._transport !== transport) {
return;
}
this._handleMessage(message);
});
transport.onError((error) => {
if (this._transport !== transport) {
return;
}
this._handleError(error);
});
transport.onClose((event) => {
if (this._transport !== transport) {
return;
}
this._handleClose(event.code ?? 1000, event.reason ?? "");
});
}
private _armConnectTimeout(): void {
const timeoutMs =
this._request.connectionTimeoutInSeconds != null
? this._request.connectionTimeoutInSeconds * 1000
: DEFAULT_CONNECTION_TIMEOUT_MS;
this._connectTimeout = setTimeout(() => {
this._handleError(new Error("TIMEOUT"));
}, timeoutMs);
}
private _clearConnectTimeout(): void {
if (this._connectTimeout != null) {
clearTimeout(this._connectTimeout);
this._connectTimeout = undefined;
}
}
private _handleOpen(transport: DeepgramTransport): void {
if (this._transport !== transport || this._readyState === ReconnectingWebSocket.ReadyState.OPEN) {
return;
}
this._debug("open event");
this._clearConnectTimeout();
this._readyState = ReconnectingWebSocket.ReadyState.OPEN;
const queued = [...this._messageQueue];
this._messageQueue = [];
for (const message of queued) {
void transport.send(message);
}
const event = new websocketEvents.Event("open", this);
if (this.onopen) {
this.onopen(event);
}
this._listeners.open.forEach((listener) => this._callEventListener(event, listener));
}
private _handleMessage(message: DeepgramTransportMessage): void {
const event = { type: "message", data: message, target: this } as unknown as MessageEvent;
if (this.onmessage) {
this.onmessage(event);
}
this._listeners.message.forEach((listener) => this._callEventListener(event, listener));
}
private _handleError(error: Error): void {
this._debug("error event", error.message);
this._clearConnectTimeout();
this._readyState = ReconnectingWebSocket.ReadyState.CLOSED;
const event = new websocketEvents.ErrorEvent(error, this);
if (this.onerror) {
this.onerror(event);
}
this._listeners.error.forEach((listener) => this._callEventListener(event, listener));
const transport = this._transport;
this._transport = undefined;
this._setTransportHandle(undefined);
if (transport) {
void transport.close(1011, error.message);
}
if (this._shouldReconnect && !this._closeCalled) {
void this._connect();
}
}
private _handleClose(code: number, reason: string): void {
this._debug("close event", code, reason);
this._clearConnectTimeout();
this._transport = undefined;
this._readyState = ReconnectingWebSocket.ReadyState.CLOSED;
this._setTransportHandle(undefined);
if (code === 1000) {
this._shouldReconnect = false;
}
this._emitClose(code, reason);
if (this._shouldReconnect && !this._closeCalled) {
void this._connect();
}
}
private _emitClose(code: number, reason: string): void {
const event = new websocketEvents.CloseEvent(code, reason, this);
if (this.onclose) {
this.onclose(event);
}
this._listeners.close.forEach((listener) => this._callEventListener(event, listener));
}
private _setTransportHandle(transport: DeepgramTransport | undefined): void {
if (!transport) {
this._ws = undefined;
return;
}
this._ws = {
OPEN: this.OPEN,
get readyState() {
return transport.isOpen()
? ReconnectingWebSocket.ReadyState.OPEN
: ReconnectingWebSocket.ReadyState.CLOSED;
},
ping: transport.ping
? (data?: string | ArrayBuffer | Blob | ArrayBufferView) => {
void transport.ping?.(data);
}
: undefined,
};
}
private _callEventListener<T extends keyof websocketEvents.WebSocketEventListenerMap>(
event: websocketEvents.WebSocketEventMap[T],
listener: websocketEvents.WebSocketEventListenerMap[T],
): void {
if (typeof listener === "object" && listener && "handleEvent" in listener) {
(listener as { handleEvent: (event: websocketEvents.WebSocketEventMap[T]) => void }).handleEvent(event);
} else {
(listener as (event: websocketEvents.WebSocketEventMap[T]) => void)(event);
}
}
}
/**
* Helper function to get WebSocket class and handle headers/protocols based on runtime.
* In Node.js, use the 'ws' library which supports headers.
* In browser, use Sec-WebSocket-Protocol for authentication since headers aren't supported.
*/
function getWebSocketOptions(headers: Record<string, unknown>, requestedProtocols: string[]): {
WebSocket?: any;
headers?: Record<string, unknown>;
protocols?: string[];
} {
const options: { WebSocket?: any; headers?: Record<string, unknown>; protocols?: string[] } = {};
// Check if we're in a browser environment (browser or web-worker)
const isBrowser = RUNTIME.type === "browser" || RUNTIME.type === "web-worker";
// Extract session ID header
const sessionIdHeader = headers["x-deepgram-session-id"] || headers["X-Deepgram-Session-Id"];
// In Node.js, ensure we use the 'ws' library which supports headers
if (RUNTIME.type === "node" && NodeWebSocket) {
options.WebSocket = NodeWebSocket;
options.headers = headers;
if (requestedProtocols.length > 0) {
options.protocols = requestedProtocols;
}
} else if (isBrowser) {
// In browser, native WebSocket doesn't support custom headers
// Extract Authorization header and use Sec-WebSocket-Protocol instead
const authHeader = headers.Authorization || headers.authorization;
const browserHeaders: Record<string, unknown> = { ...headers };
// Remove Authorization and session ID from headers since they won't work in browser
delete browserHeaders.Authorization;
delete browserHeaders.authorization;
delete browserHeaders["x-deepgram-session-id"];
delete browserHeaders["X-Deepgram-Session-Id"];
options.headers = browserHeaders;
// Build protocols array for browser WebSocket
const protocols = [...requestedProtocols];
// If we have an Authorization header, extract the token and format as protocols
// Deepgram expects:
// - For API keys: Sec-WebSocket-Protocol: token,API_KEY_GOES_HERE
// - For Bearer tokens: Sec-WebSocket-Protocol: bearer,TOKEN_GOES_HERE
// The comma separates multiple protocols, so we pass them as an array
if (authHeader && typeof authHeader === "string") {
if (authHeader.startsWith("Token ")) {
// API key: "Token API_KEY" -> ["token", "API_KEY"]
const apiKey = authHeader.substring(6); // Remove "Token " prefix
protocols.push("token", apiKey);
} else if (authHeader.startsWith("Bearer ")) {
// Access token: "Bearer TOKEN" -> ["bearer", "TOKEN"]
const token = authHeader.substring(7); // Remove "Bearer " prefix
protocols.push("bearer", token);
} else {
// Fallback: use the entire header value if it doesn't match expected format
protocols.push(authHeader);
}
}
// Add session ID as a protocol for browser WebSocket
if (sessionIdHeader && typeof sessionIdHeader === "string") {
protocols.push("x-deepgram-session-id", sessionIdHeader);
}
if (protocols.length > 0) {
options.protocols = protocols;
}
} else {
// Fallback for other environments
options.headers = headers;
if (requestedProtocols.length > 0) {
options.protocols = requestedProtocols;
}
}
return options;
}
/**
* Helper function to setup binary-aware message handling for WebSocket sockets.
* Handles both text (JSON) and binary messages correctly.
*/
function setupBinaryHandling(socket: ReconnectingWebSocket, eventHandlers: { message?: (data: any) => void }): (event: MessageEvent) => void {
const binaryAwareHandler = (event: MessageEvent) => {
// Handle both text (JSON) and binary messages
if (typeof event.data === "string") {
try {
const data = fromJson(event.data);
eventHandlers.message?.(data);
} catch (error) {
// If JSON parsing fails, pass the raw string
eventHandlers.message?.(event.data);
}
} else {
// Binary data - pass through as-is
eventHandlers.message?.(event.data);
}
};
// Remove the original handler and add our binary-aware one
const socketAny = socket as any;
if (socketAny._listeners?.message) {
// Remove all message listeners
socketAny._listeners.message.forEach((listener: any) => {
socket.removeEventListener("message", listener);
});
}
// Add our binary-aware handler
socket.addEventListener("message", binaryAwareHandler);