@deepgram/sdk 5.0.0-alpha.2 → 5.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/LICENSE +1 -1
  2. package/dist/browser/index.global.js +674 -1135
  3. package/dist/cjs/BaseClient.d.ts +7 -7
  4. package/dist/cjs/BaseClient.js +2 -2
  5. package/dist/cjs/Client.d.ts +1 -2
  6. package/dist/cjs/CustomClient.d.ts +9 -1
  7. package/dist/cjs/CustomClient.js +346 -232
  8. package/dist/cjs/api/resources/agent/client/Client.d.ts +1 -2
  9. package/dist/cjs/api/resources/agent/resources/v1/client/Client.d.ts +1 -2
  10. package/dist/cjs/api/resources/agent/resources/v1/client/Socket.d.ts +8 -8
  11. package/dist/cjs/api/resources/agent/resources/v1/client/Socket.js +9 -9
  12. package/dist/cjs/api/resources/agent/resources/v1/resources/settings/client/Client.d.ts +1 -2
  13. package/dist/cjs/api/resources/agent/resources/v1/resources/settings/resources/think/client/Client.d.ts +1 -2
  14. package/dist/cjs/api/resources/agent/resources/v1/resources/settings/resources/think/resources/models/client/Client.d.ts +1 -2
  15. package/dist/cjs/api/resources/agent/resources/v1/types/AgentV1Settings.d.ts +3 -43
  16. package/dist/cjs/api/resources/agent/resources/v1/types/AgentV1SettingsAgentListenProvider.d.ts +26 -0
  17. package/dist/cjs/api/resources/agent/resources/v1/types/AgentV1SettingsAgentListenProvider.js +3 -0
  18. package/dist/cjs/api/resources/agent/resources/v1/types/AgentV1SettingsAgentSpeakEndpointProvider.d.ts +28 -13
  19. package/dist/cjs/api/resources/agent/resources/v1/types/AgentV1SettingsAgentSpeakEndpointProvider.js +19 -17
  20. package/dist/cjs/api/resources/agent/resources/v1/types/AgentV1SettingsAgentSpeakOneItemProvider.d.ts +28 -13
  21. package/dist/cjs/api/resources/agent/resources/v1/types/AgentV1SettingsAgentSpeakOneItemProvider.js +19 -17
  22. package/dist/cjs/api/resources/agent/resources/v1/types/AgentV1SettingsAgentThinkProvider.d.ts +115 -0
  23. package/dist/cjs/api/resources/agent/resources/v1/types/AgentV1SettingsAgentThinkProvider.js +57 -0
  24. package/dist/cjs/api/resources/agent/resources/v1/types/AgentV1UpdateSpeakSpeakProvider.d.ts +18 -3
  25. package/dist/cjs/api/resources/agent/resources/v1/types/AgentV1UpdateSpeakSpeakProvider.js +2 -0
  26. package/dist/cjs/api/resources/agent/resources/v1/types/index.d.ts +2 -0
  27. package/dist/cjs/api/resources/agent/resources/v1/types/index.js +2 -0
  28. package/dist/cjs/api/resources/auth/client/Client.d.ts +1 -2
  29. package/dist/cjs/api/resources/auth/resources/v1/client/Client.d.ts +1 -2
  30. package/dist/cjs/api/resources/auth/resources/v1/resources/tokens/client/Client.d.ts +1 -2
  31. package/dist/cjs/api/resources/listen/client/Client.d.ts +1 -2
  32. package/dist/cjs/api/resources/listen/resources/v1/client/Client.d.ts +1 -2
  33. package/dist/cjs/api/resources/listen/resources/v1/client/Client.js +29 -80
  34. package/dist/cjs/api/resources/listen/resources/v1/client/Socket.d.ts +4 -4
  35. package/dist/cjs/api/resources/listen/resources/v1/client/Socket.js +5 -5
  36. package/dist/cjs/api/resources/listen/resources/v1/resources/media/client/Client.d.ts +1 -2
  37. package/dist/cjs/api/resources/listen/resources/v1/resources/media/client/Client.js +76 -298
  38. package/dist/cjs/api/resources/listen/resources/v1/types/ListenV1Results.d.ts +3 -3
  39. package/dist/cjs/api/resources/listen/resources/v2/client/Client.d.ts +1 -2
  40. package/dist/cjs/api/resources/listen/resources/v2/client/Client.js +11 -26
  41. package/dist/cjs/api/resources/listen/resources/v2/client/Socket.d.ts +2 -2
  42. package/dist/cjs/api/resources/listen/resources/v2/client/Socket.js +3 -3
  43. package/dist/cjs/api/resources/manage/client/Client.d.ts +1 -2
  44. package/dist/cjs/api/resources/manage/resources/v1/client/Client.d.ts +1 -2
  45. package/dist/cjs/api/resources/manage/resources/v1/resources/models/client/Client.d.ts +1 -2
  46. package/dist/cjs/api/resources/manage/resources/v1/resources/models/client/Client.js +3 -4
  47. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/client/Client.d.ts +1 -2
  48. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/client/Client.js +4 -7
  49. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/client/Client.d.ts +1 -2
  50. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/balances/client/Client.d.ts +1 -2
  51. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/breakdown/client/Client.d.ts +1 -2
  52. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/breakdown/client/Client.js +9 -27
  53. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/fields/client/Client.d.ts +1 -2
  54. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/fields/client/Client.js +4 -7
  55. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/purchases/client/Client.d.ts +1 -2
  56. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/purchases/client/Client.js +3 -4
  57. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/keys/client/Client.d.ts +1 -2
  58. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/keys/client/Client.js +3 -4
  59. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/members/client/Client.d.ts +1 -2
  60. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/members/resources/invites/client/Client.d.ts +1 -2
  61. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/members/resources/scopes/client/Client.d.ts +1 -2
  62. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/models/client/Client.d.ts +1 -2
  63. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/models/client/Client.js +3 -4
  64. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/requests/client/Client.d.ts +1 -2
  65. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/requests/client/Client.js +12 -31
  66. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/usage/client/Client.d.ts +1 -2
  67. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/usage/client/Client.js +46 -133
  68. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/breakdown/client/Client.d.ts +1 -2
  69. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/breakdown/client/Client.js +47 -136
  70. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/fields/client/Client.d.ts +1 -2
  71. package/dist/cjs/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/fields/client/Client.js +4 -7
  72. package/dist/cjs/api/resources/read/client/Client.d.ts +1 -2
  73. package/dist/cjs/api/resources/read/resources/v1/client/Client.d.ts +1 -2
  74. package/dist/cjs/api/resources/read/resources/v1/resources/text/client/Client.d.ts +1 -2
  75. package/dist/cjs/api/resources/read/resources/v1/resources/text/client/Client.js +14 -52
  76. package/dist/cjs/api/resources/selfHosted/client/Client.d.ts +1 -2
  77. package/dist/cjs/api/resources/selfHosted/resources/v1/client/Client.d.ts +1 -2
  78. package/dist/cjs/api/resources/selfHosted/resources/v1/resources/distributionCredentials/client/Client.d.ts +1 -2
  79. package/dist/cjs/api/resources/selfHosted/resources/v1/resources/distributionCredentials/client/Client.js +4 -12
  80. package/dist/cjs/api/resources/speak/client/Client.d.ts +1 -2
  81. package/dist/cjs/api/resources/speak/resources/v1/client/Client.d.ts +1 -2
  82. package/dist/cjs/api/resources/speak/resources/v1/client/Client.js +6 -13
  83. package/dist/cjs/api/resources/speak/resources/v1/client/Socket.d.ts +4 -4
  84. package/dist/cjs/api/resources/speak/resources/v1/client/Socket.js +4 -4
  85. package/dist/cjs/api/resources/speak/resources/v1/resources/audio/client/Client.d.ts +1 -2
  86. package/dist/cjs/api/resources/speak/resources/v1/resources/audio/client/Client.js +11 -33
  87. package/dist/cjs/api/types/SpeakV1SampleRate.d.ts +1 -1
  88. package/dist/cjs/api/types/SpeakV1SampleRate.js +1 -1
  89. package/dist/cjs/auth/HeaderAuthProvider.d.ts +14 -8
  90. package/dist/cjs/auth/HeaderAuthProvider.js +19 -9
  91. package/dist/cjs/core/fetcher/EndpointSupplier.d.ts +2 -2
  92. package/dist/cjs/core/fetcher/Fetcher.d.ts +1 -2
  93. package/dist/cjs/core/headers.d.ts +2 -2
  94. package/dist/cjs/core/websocket/ws.d.ts +1 -1
  95. package/dist/cjs/version.d.ts +1 -1
  96. package/dist/cjs/version.js +1 -1
  97. package/dist/esm/BaseClient.d.mts +7 -7
  98. package/dist/esm/BaseClient.mjs +2 -2
  99. package/dist/esm/Client.d.mts +1 -2
  100. package/dist/esm/CustomClient.d.mts +9 -1
  101. package/dist/esm/CustomClient.mjs +347 -233
  102. package/dist/esm/api/resources/agent/client/Client.d.mts +1 -2
  103. package/dist/esm/api/resources/agent/resources/v1/client/Client.d.mts +1 -2
  104. package/dist/esm/api/resources/agent/resources/v1/client/Socket.d.mts +8 -8
  105. package/dist/esm/api/resources/agent/resources/v1/client/Socket.mjs +9 -9
  106. package/dist/esm/api/resources/agent/resources/v1/resources/settings/client/Client.d.mts +1 -2
  107. package/dist/esm/api/resources/agent/resources/v1/resources/settings/resources/think/client/Client.d.mts +1 -2
  108. package/dist/esm/api/resources/agent/resources/v1/resources/settings/resources/think/resources/models/client/Client.d.mts +1 -2
  109. package/dist/esm/api/resources/agent/resources/v1/types/AgentV1Settings.d.mts +3 -43
  110. package/dist/esm/api/resources/agent/resources/v1/types/AgentV1SettingsAgentListenProvider.d.mts +26 -0
  111. package/dist/esm/api/resources/agent/resources/v1/types/AgentV1SettingsAgentListenProvider.mjs +2 -0
  112. package/dist/esm/api/resources/agent/resources/v1/types/AgentV1SettingsAgentSpeakEndpointProvider.d.mts +28 -13
  113. package/dist/esm/api/resources/agent/resources/v1/types/AgentV1SettingsAgentSpeakEndpointProvider.mjs +19 -17
  114. package/dist/esm/api/resources/agent/resources/v1/types/AgentV1SettingsAgentSpeakOneItemProvider.d.mts +28 -13
  115. package/dist/esm/api/resources/agent/resources/v1/types/AgentV1SettingsAgentSpeakOneItemProvider.mjs +19 -17
  116. package/dist/esm/api/resources/agent/resources/v1/types/AgentV1SettingsAgentThinkProvider.d.mts +115 -0
  117. package/dist/esm/api/resources/agent/resources/v1/types/AgentV1SettingsAgentThinkProvider.mjs +54 -0
  118. package/dist/esm/api/resources/agent/resources/v1/types/AgentV1UpdateSpeakSpeakProvider.d.mts +18 -3
  119. package/dist/esm/api/resources/agent/resources/v1/types/AgentV1UpdateSpeakSpeakProvider.mjs +2 -0
  120. package/dist/esm/api/resources/agent/resources/v1/types/index.d.mts +2 -0
  121. package/dist/esm/api/resources/agent/resources/v1/types/index.mjs +2 -0
  122. package/dist/esm/api/resources/auth/client/Client.d.mts +1 -2
  123. package/dist/esm/api/resources/auth/resources/v1/client/Client.d.mts +1 -2
  124. package/dist/esm/api/resources/auth/resources/v1/resources/tokens/client/Client.d.mts +1 -2
  125. package/dist/esm/api/resources/listen/client/Client.d.mts +1 -2
  126. package/dist/esm/api/resources/listen/resources/v1/client/Client.d.mts +1 -2
  127. package/dist/esm/api/resources/listen/resources/v1/client/Client.mjs +29 -80
  128. package/dist/esm/api/resources/listen/resources/v1/client/Socket.d.mts +4 -4
  129. package/dist/esm/api/resources/listen/resources/v1/client/Socket.mjs +5 -5
  130. package/dist/esm/api/resources/listen/resources/v1/resources/media/client/Client.d.mts +1 -2
  131. package/dist/esm/api/resources/listen/resources/v1/resources/media/client/Client.mjs +76 -298
  132. package/dist/esm/api/resources/listen/resources/v1/types/ListenV1Results.d.mts +3 -3
  133. package/dist/esm/api/resources/listen/resources/v2/client/Client.d.mts +1 -2
  134. package/dist/esm/api/resources/listen/resources/v2/client/Client.mjs +11 -26
  135. package/dist/esm/api/resources/listen/resources/v2/client/Socket.d.mts +2 -2
  136. package/dist/esm/api/resources/listen/resources/v2/client/Socket.mjs +3 -3
  137. package/dist/esm/api/resources/manage/client/Client.d.mts +1 -2
  138. package/dist/esm/api/resources/manage/resources/v1/client/Client.d.mts +1 -2
  139. package/dist/esm/api/resources/manage/resources/v1/resources/models/client/Client.d.mts +1 -2
  140. package/dist/esm/api/resources/manage/resources/v1/resources/models/client/Client.mjs +3 -4
  141. package/dist/esm/api/resources/manage/resources/v1/resources/projects/client/Client.d.mts +1 -2
  142. package/dist/esm/api/resources/manage/resources/v1/resources/projects/client/Client.mjs +4 -7
  143. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/client/Client.d.mts +1 -2
  144. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/balances/client/Client.d.mts +1 -2
  145. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/breakdown/client/Client.d.mts +1 -2
  146. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/breakdown/client/Client.mjs +9 -27
  147. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/fields/client/Client.d.mts +1 -2
  148. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/fields/client/Client.mjs +4 -7
  149. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/purchases/client/Client.d.mts +1 -2
  150. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/billing/resources/purchases/client/Client.mjs +3 -4
  151. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/keys/client/Client.d.mts +1 -2
  152. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/keys/client/Client.mjs +3 -4
  153. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/members/client/Client.d.mts +1 -2
  154. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/members/resources/invites/client/Client.d.mts +1 -2
  155. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/members/resources/scopes/client/Client.d.mts +1 -2
  156. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/models/client/Client.d.mts +1 -2
  157. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/models/client/Client.mjs +3 -4
  158. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/requests/client/Client.d.mts +1 -2
  159. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/requests/client/Client.mjs +12 -31
  160. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/usage/client/Client.d.mts +1 -2
  161. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/usage/client/Client.mjs +46 -133
  162. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/breakdown/client/Client.d.mts +1 -2
  163. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/breakdown/client/Client.mjs +47 -136
  164. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/fields/client/Client.d.mts +1 -2
  165. package/dist/esm/api/resources/manage/resources/v1/resources/projects/resources/usage/resources/fields/client/Client.mjs +4 -7
  166. package/dist/esm/api/resources/read/client/Client.d.mts +1 -2
  167. package/dist/esm/api/resources/read/resources/v1/client/Client.d.mts +1 -2
  168. package/dist/esm/api/resources/read/resources/v1/resources/text/client/Client.d.mts +1 -2
  169. package/dist/esm/api/resources/read/resources/v1/resources/text/client/Client.mjs +14 -52
  170. package/dist/esm/api/resources/selfHosted/client/Client.d.mts +1 -2
  171. package/dist/esm/api/resources/selfHosted/resources/v1/client/Client.d.mts +1 -2
  172. package/dist/esm/api/resources/selfHosted/resources/v1/resources/distributionCredentials/client/Client.d.mts +1 -2
  173. package/dist/esm/api/resources/selfHosted/resources/v1/resources/distributionCredentials/client/Client.mjs +4 -12
  174. package/dist/esm/api/resources/speak/client/Client.d.mts +1 -2
  175. package/dist/esm/api/resources/speak/resources/v1/client/Client.d.mts +1 -2
  176. package/dist/esm/api/resources/speak/resources/v1/client/Client.mjs +6 -13
  177. package/dist/esm/api/resources/speak/resources/v1/client/Socket.d.mts +4 -4
  178. package/dist/esm/api/resources/speak/resources/v1/client/Socket.mjs +4 -4
  179. package/dist/esm/api/resources/speak/resources/v1/resources/audio/client/Client.d.mts +1 -2
  180. package/dist/esm/api/resources/speak/resources/v1/resources/audio/client/Client.mjs +11 -33
  181. package/dist/esm/api/types/SpeakV1SampleRate.d.mts +1 -1
  182. package/dist/esm/api/types/SpeakV1SampleRate.mjs +1 -1
  183. package/dist/esm/auth/HeaderAuthProvider.d.mts +14 -8
  184. package/dist/esm/auth/HeaderAuthProvider.mjs +19 -9
  185. package/dist/esm/core/fetcher/EndpointSupplier.d.mts +2 -2
  186. package/dist/esm/core/fetcher/Fetcher.d.mts +1 -2
  187. package/dist/esm/core/headers.d.mts +2 -2
  188. package/dist/esm/core/websocket/ws.d.mts +1 -1
  189. package/dist/esm/version.d.mts +1 -1
  190. package/dist/esm/version.mjs +1 -1
  191. package/package.json +11 -10
@@ -20,11 +20,13 @@ import { V1Socket as AgentV1Socket } from "./api/resources/agent/resources/v1/cl
20
20
  import { V1Socket as ListenV1Socket } from "./api/resources/listen/resources/v1/client/Socket.mjs";
21
21
  import { V2Socket as ListenV2Socket } from "./api/resources/listen/resources/v2/client/Socket.mjs";
22
22
  import { V1Socket as SpeakV1Socket } from "./api/resources/speak/resources/v1/client/Socket.mjs";
23
- import { mergeHeaders, mergeOnlyDefinedHeaders } from "./core/headers.mjs";
23
+ import { mergeHeaders } from "./core/headers.mjs";
24
24
  import { fromJson } from "./core/json.mjs";
25
25
  import * as core from "./core/index.mjs";
26
26
  import * as environments from "./environments.mjs";
27
27
  import { RUNTIME } from "./core/runtime/index.mjs";
28
+ // Default WebSocket connection timeout in milliseconds
29
+ const DEFAULT_CONNECTION_TIMEOUT_MS = 10000;
28
30
  // Import ws library for Node.js (will be undefined in browser)
29
31
  let NodeWebSocket;
30
32
  try {
@@ -37,13 +39,108 @@ catch (_a) {
37
39
  // ws not available (e.g., in browser)
38
40
  NodeWebSocket = undefined;
39
41
  }
42
+ // Helper function to generate UUID that works in both Node.js and browser
43
+ function generateUUID() {
44
+ // Try global crypto.randomUUID first (works in both Node.js 14.18+ and modern browsers)
45
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
46
+ return crypto.randomUUID();
47
+ }
48
+ // Fallback for Node.js: use the crypto module
49
+ if (RUNTIME.type === "node") {
50
+ try {
51
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
52
+ const nodeCrypto = require("crypto");
53
+ return nodeCrypto.randomUUID();
54
+ }
55
+ catch (_a) {
56
+ // Fallback if crypto module is not available
57
+ }
58
+ }
59
+ // Final fallback: manual UUID generation (RFC4122 version 4)
60
+ // This should work everywhere but is less secure than crypto.randomUUID()
61
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
62
+ const r = (Math.random() * 16) | 0;
63
+ const v = c === "x" ? r : (r & 0x3) | 0x8;
64
+ return v.toString(16);
65
+ });
66
+ }
67
+ /**
68
+ * Wrapper auth provider that adds "Token " prefix to API keys.
69
+ * The auto-generated HeaderAuthProvider doesn't add the prefix, so we wrap it here.
70
+ */
71
+ class ApiKeyAuthProviderWrapper {
72
+ constructor(originalProvider) {
73
+ this.originalProvider = originalProvider;
74
+ }
75
+ getAuthRequest(arg) {
76
+ return __awaiter(this, void 0, void 0, function* () {
77
+ var _a, _b;
78
+ const authRequest = yield this.originalProvider.getAuthRequest(arg);
79
+ const authHeader = ((_a = authRequest.headers) === null || _a === void 0 ? void 0 : _a.Authorization) || ((_b = authRequest.headers) === null || _b === void 0 ? void 0 : _b.authorization);
80
+ // If the header doesn't already have a scheme prefix, add "Token " prefix for API keys
81
+ if (authHeader && typeof authHeader === "string") {
82
+ // Only add prefix if it doesn't already have Bearer or Token prefix
83
+ if (!authHeader.startsWith("Bearer ") && !authHeader.startsWith("Token ") && !authHeader.startsWith("token ")) {
84
+ return {
85
+ headers: Object.assign(Object.assign({}, authRequest.headers), { Authorization: `Token ${authHeader}` }),
86
+ };
87
+ }
88
+ }
89
+ return authRequest;
90
+ });
91
+ }
92
+ }
93
+ /**
94
+ * Wrapper auth provider that checks for accessToken first (Bearer scheme)
95
+ * before falling back to the original auth provider (Token scheme for API keys).
96
+ */
97
+ class AccessTokenAuthProviderWrapper {
98
+ constructor(originalProvider, accessToken) {
99
+ this.originalProvider = originalProvider;
100
+ this.accessToken = accessToken;
101
+ }
102
+ getAuthRequest(arg) {
103
+ return __awaiter(this, void 0, void 0, function* () {
104
+ var _a, _b;
105
+ // Check for access token first (highest priority)
106
+ // Access tokens use Bearer scheme, API keys use Token scheme
107
+ const accessToken = (_a = (yield core.Supplier.get(this.accessToken))) !== null && _a !== void 0 ? _a : (_b = process.env) === null || _b === void 0 ? void 0 : _b.DEEPGRAM_ACCESS_TOKEN;
108
+ if (accessToken != null) {
109
+ return {
110
+ headers: { Authorization: `Bearer ${accessToken}` },
111
+ };
112
+ }
113
+ // Fall back to original provider (which handles API keys)
114
+ return this.originalProvider.getAuthRequest(arg);
115
+ });
116
+ }
117
+ }
40
118
  /**
41
119
  * Custom wrapper around DeepgramClient that ensures the custom websocket implementation
42
120
  * from ws.ts is always used, even if the auto-generated code changes.
43
121
  */
44
122
  export class CustomDeepgramClient extends DeepgramClient {
45
123
  constructor(options = {}) {
46
- super(options);
124
+ // Generate a UUID for the session ID
125
+ const sessionId = generateUUID();
126
+ // Add the session ID to headers so it's included in all REST requests
127
+ const optionsWithSessionId = Object.assign(Object.assign({}, options), { headers: Object.assign(Object.assign({}, options.headers), { "x-deepgram-session-id": sessionId }) });
128
+ super(optionsWithSessionId);
129
+ this._sessionId = sessionId;
130
+ // Always wrap the auth provider to add "Token " prefix to API keys
131
+ // The auto-generated HeaderAuthProvider doesn't add the prefix
132
+ this._options.authProvider = new ApiKeyAuthProviderWrapper(this._options.authProvider);
133
+ // Wrap again to handle accessToken if provided
134
+ // This ensures accessToken takes priority over apiKey/env var
135
+ if (options.accessToken != null) {
136
+ this._options.authProvider = new AccessTokenAuthProviderWrapper(this._options.authProvider, options.accessToken);
137
+ }
138
+ }
139
+ /**
140
+ * Get the session ID that was generated for this client instance.
141
+ */
142
+ get sessionId() {
143
+ return this._sessionId;
47
144
  }
48
145
  /**
49
146
  * Override the agent getter to return a wrapped client that ensures
@@ -81,6 +178,11 @@ export class CustomDeepgramClient extends DeepgramClient {
81
178
  }
82
179
  /**
83
180
  * Wrapper for AgentClient that ensures custom websocket implementation is used.
181
+ *
182
+ * This wrapper exists to guarantee that our custom WebSocket implementation
183
+ * (from ws.ts) continues to be used even after the SDK code is auto-generated
184
+ * by Fern. Without this wrapper, Fern regeneration could overwrite the client
185
+ * with a different WebSocket implementation.
84
186
  */
85
187
  class WrappedAgentClient extends AgentClientImpl {
86
188
  get v1() {
@@ -89,6 +191,11 @@ class WrappedAgentClient extends AgentClientImpl {
89
191
  }
90
192
  /**
91
193
  * Wrapper for ListenClient that ensures custom websocket implementation is used.
194
+ *
195
+ * This wrapper exists to guarantee that our custom WebSocket implementation
196
+ * (from ws.ts) continues to be used even after the SDK code is auto-generated
197
+ * by Fern. Without this wrapper, Fern regeneration could overwrite the client
198
+ * with a different WebSocket implementation.
92
199
  */
93
200
  class WrappedListenClient extends ListenClientImpl {
94
201
  get v1() {
@@ -100,12 +207,36 @@ class WrappedListenClient extends ListenClientImpl {
100
207
  }
101
208
  /**
102
209
  * Wrapper for SpeakClient that ensures custom websocket implementation is used.
210
+ *
211
+ * This wrapper exists to guarantee that our custom WebSocket implementation
212
+ * (from ws.ts) continues to be used even after the SDK code is auto-generated
213
+ * by Fern. Without this wrapper, Fern regeneration could overwrite the client
214
+ * with a different WebSocket implementation.
103
215
  */
104
216
  class WrappedSpeakClient extends SpeakClientImpl {
105
217
  get v1() {
106
218
  return new WrappedSpeakV1Client(this._options);
107
219
  }
108
220
  }
221
+ /**
222
+ * Helper function to resolve Suppliers in headers to their actual values.
223
+ */
224
+ function resolveHeaders(headers) {
225
+ return __awaiter(this, void 0, void 0, function* () {
226
+ const resolved = {};
227
+ for (const [key, value] of Object.entries(headers)) {
228
+ if (value == null) {
229
+ continue;
230
+ }
231
+ // Resolve Supplier if it's a Supplier, otherwise use the value directly
232
+ const resolvedValue = yield core.Supplier.get(value);
233
+ if (resolvedValue != null) {
234
+ resolved[key] = resolvedValue;
235
+ }
236
+ }
237
+ return resolved;
238
+ });
239
+ }
109
240
  /**
110
241
  * Helper function to get WebSocket class and handle headers/protocols based on runtime.
111
242
  * In Node.js, use the 'ws' library which supports headers.
@@ -115,6 +246,8 @@ function getWebSocketOptions(headers) {
115
246
  const options = {};
116
247
  // Check if we're in a browser environment (browser or web-worker)
117
248
  const isBrowser = RUNTIME.type === "browser" || RUNTIME.type === "web-worker";
249
+ // Extract session ID header
250
+ const sessionIdHeader = headers["x-deepgram-session-id"] || headers["X-Deepgram-Session-Id"];
118
251
  // In Node.js, ensure we use the 'ws' library which supports headers
119
252
  if (RUNTIME.type === "node" && NodeWebSocket) {
120
253
  options.WebSocket = NodeWebSocket;
@@ -125,10 +258,14 @@ function getWebSocketOptions(headers) {
125
258
  // Extract Authorization header and use Sec-WebSocket-Protocol instead
126
259
  const authHeader = headers.Authorization || headers.authorization;
127
260
  const browserHeaders = Object.assign({}, headers);
128
- // Remove Authorization from headers since it won't work in browser
261
+ // Remove Authorization and session ID from headers since they won't work in browser
129
262
  delete browserHeaders.Authorization;
130
263
  delete browserHeaders.authorization;
264
+ delete browserHeaders["x-deepgram-session-id"];
265
+ delete browserHeaders["X-Deepgram-Session-Id"];
131
266
  options.headers = browserHeaders;
267
+ // Build protocols array for browser WebSocket
268
+ const protocols = [];
132
269
  // If we have an Authorization header, extract the token and format as protocols
133
270
  // Deepgram expects:
134
271
  // - For API keys: Sec-WebSocket-Protocol: token,API_KEY_GOES_HERE
@@ -138,18 +275,25 @@ function getWebSocketOptions(headers) {
138
275
  if (authHeader.startsWith("Token ")) {
139
276
  // API key: "Token API_KEY" -> ["token", "API_KEY"]
140
277
  const apiKey = authHeader.substring(6); // Remove "Token " prefix
141
- options.protocols = ["token", apiKey];
278
+ protocols.push("token", apiKey);
142
279
  }
143
280
  else if (authHeader.startsWith("Bearer ")) {
144
281
  // Access token: "Bearer TOKEN" -> ["bearer", "TOKEN"]
145
282
  const token = authHeader.substring(7); // Remove "Bearer " prefix
146
- options.protocols = ["bearer", token];
283
+ protocols.push("bearer", token);
147
284
  }
148
285
  else {
149
286
  // Fallback: use the entire header value if it doesn't match expected format
150
- options.protocols = [authHeader];
287
+ protocols.push(authHeader);
151
288
  }
152
289
  }
290
+ // Add session ID as a protocol for browser WebSocket
291
+ if (sessionIdHeader && typeof sessionIdHeader === "string") {
292
+ protocols.push("x-deepgram-session-id", sessionIdHeader);
293
+ }
294
+ if (protocols.length > 0) {
295
+ options.protocols = protocols;
296
+ }
153
297
  }
154
298
  else {
155
299
  // Fallback for other environments
@@ -157,32 +301,108 @@ function getWebSocketOptions(headers) {
157
301
  }
158
302
  return options;
159
303
  }
304
+ /**
305
+ * Helper function to setup binary-aware message handling for WebSocket sockets.
306
+ * Handles both text (JSON) and binary messages correctly.
307
+ */
308
+ function setupBinaryHandling(socket, eventHandlers) {
309
+ var _a;
310
+ const binaryAwareHandler = (event) => {
311
+ var _a, _b, _c;
312
+ // Handle both text (JSON) and binary messages
313
+ if (typeof event.data === "string") {
314
+ try {
315
+ const data = fromJson(event.data);
316
+ (_a = eventHandlers.message) === null || _a === void 0 ? void 0 : _a.call(eventHandlers, data);
317
+ }
318
+ catch (error) {
319
+ // If JSON parsing fails, pass the raw string
320
+ (_b = eventHandlers.message) === null || _b === void 0 ? void 0 : _b.call(eventHandlers, event.data);
321
+ }
322
+ }
323
+ else {
324
+ // Binary data - pass through as-is
325
+ (_c = eventHandlers.message) === null || _c === void 0 ? void 0 : _c.call(eventHandlers, event.data);
326
+ }
327
+ };
328
+ // Remove the original handler and add our binary-aware one
329
+ const socketAny = socket;
330
+ if ((_a = socketAny._listeners) === null || _a === void 0 ? void 0 : _a.message) {
331
+ // Remove all message listeners
332
+ socketAny._listeners.message.forEach((listener) => {
333
+ socket.removeEventListener("message", listener);
334
+ });
335
+ }
336
+ // Add our binary-aware handler
337
+ socket.addEventListener("message", binaryAwareHandler);
338
+ return binaryAwareHandler;
339
+ }
340
+ /**
341
+ * Helper function to reset socket connection state before connecting.
342
+ * Ensures _connectLock is reset if the socket is in CLOSED state.
343
+ */
344
+ function resetSocketConnectionState(socket) {
345
+ if (socket.readyState === socket.CLOSED) {
346
+ // Force a fresh reconnect to ensure _connectLock is reset
347
+ socket._connectLock = false;
348
+ socket._shouldReconnect = true;
349
+ }
350
+ }
351
+ /**
352
+ * Helper function to create a WebSocket connection with common setup logic.
353
+ * Handles authentication, header merging, and WebSocket configuration.
354
+ * This reduces duplication across all Wrapped*Client classes.
355
+ */
356
+ function createWebSocketConnection(_a) {
357
+ return __awaiter(this, arguments, void 0, function* ({ options, urlPath, environmentKey, queryParams, headers, debug, reconnectAttempts, }) {
358
+ var _b, _c, _d, _e, _f, _g;
359
+ // Get Authorization from authProvider (cast to any to access internal property)
360
+ const authRequest = yield ((_b = options.authProvider) === null || _b === void 0 ? void 0 : _b.getAuthRequest());
361
+ // Merge headers from options (which includes session ID), auth headers, and request headers
362
+ const mergedHeaders = mergeHeaders((_c = options.headers) !== null && _c !== void 0 ? _c : {}, (_d = authRequest === null || authRequest === void 0 ? void 0 : authRequest.headers) !== null && _d !== void 0 ? _d : {}, headers);
363
+ // Resolve any Suppliers in headers to actual values
364
+ const _headers = yield resolveHeaders(mergedHeaders);
365
+ // Get WebSocket options with proper header handling
366
+ const wsOptions = getWebSocketOptions(_headers);
367
+ // Get the appropriate base URL for the environment
368
+ const baseUrl = (_e = (yield core.Supplier.get(options.baseUrl))) !== null && _e !== void 0 ? _e : ((_f = (yield core.Supplier.get(options.environment))) !== null && _f !== void 0 ? _f : environments.DeepgramEnvironment.Production)[environmentKey];
369
+ // Create and return the ReconnectingWebSocket
370
+ return new ReconnectingWebSocket({
371
+ url: core.url.join(baseUrl, urlPath),
372
+ protocols: (_g = wsOptions.protocols) !== null && _g !== void 0 ? _g : [],
373
+ queryParameters: queryParams,
374
+ headers: wsOptions.headers,
375
+ options: {
376
+ WebSocket: wsOptions.WebSocket,
377
+ debug: debug !== null && debug !== void 0 ? debug : false,
378
+ maxRetries: reconnectAttempts !== null && reconnectAttempts !== void 0 ? reconnectAttempts : 30,
379
+ startClosed: true,
380
+ connectionTimeout: DEFAULT_CONNECTION_TIMEOUT_MS,
381
+ },
382
+ });
383
+ });
384
+ }
160
385
  /**
161
386
  * Wrapper for Agent V1Client that overrides connect to use custom websocket.
387
+ *
388
+ * This wrapper ensures that the connect() method uses our custom ReconnectingWebSocket
389
+ * implementation instead of any auto-generated WebSocket handling. This guarantees
390
+ * consistent behavior across Fern regenerations and allows us to customize
391
+ * connection setup, authentication, and header handling.
162
392
  */
163
393
  class WrappedAgentV1Client extends AgentV1Client {
164
394
  connect() {
165
395
  return __awaiter(this, arguments, void 0, function* (args = {}) {
166
- var _a, _b, _c, _d, _e;
167
396
  const { headers, debug, reconnectAttempts } = args;
168
- // Get Authorization from authProvider (matching the working version)
169
- const authRequest = yield ((_a = this._options.authProvider) === null || _a === void 0 ? void 0 : _a.getAuthRequest());
170
- const _headers = mergeHeaders((_b = authRequest === null || authRequest === void 0 ? void 0 : authRequest.headers) !== null && _b !== void 0 ? _b : {}, headers);
171
- // Get WebSocket options with proper header handling
172
- const wsOptions = getWebSocketOptions(_headers);
173
- // Explicitly use the custom ReconnectingWebSocket from ws.ts
174
- const socket = new ReconnectingWebSocket({
175
- url: core.url.join((_c = (yield core.Supplier.get(this._options.baseUrl))) !== null && _c !== void 0 ? _c : ((_d = (yield core.Supplier.get(this._options.environment))) !== null && _d !== void 0 ? _d : environments.DeepgramEnvironment.Production).agent, "/v1/agent/converse"),
176
- protocols: (_e = wsOptions.protocols) !== null && _e !== void 0 ? _e : [],
177
- queryParameters: {},
178
- headers: wsOptions.headers,
179
- options: {
180
- WebSocket: wsOptions.WebSocket,
181
- debug: debug !== null && debug !== void 0 ? debug : false,
182
- maxRetries: reconnectAttempts !== null && reconnectAttempts !== void 0 ? reconnectAttempts : 30,
183
- startClosed: true,
184
- connectionTimeout: 10000, // Increase timeout to 10 seconds
185
- },
397
+ // Use shared connection helper
398
+ const socket = yield createWebSocketConnection({
399
+ options: this._options,
400
+ urlPath: "/v1/agent/converse",
401
+ environmentKey: 'agent',
402
+ queryParams: {},
403
+ headers,
404
+ debug,
405
+ reconnectAttempts,
186
406
  });
187
407
  return new WrappedAgentV1Socket({ socket });
188
408
  });
@@ -190,6 +410,11 @@ class WrappedAgentV1Client extends AgentV1Client {
190
410
  }
191
411
  /**
192
412
  * Wrapper for Agent V1Socket that handles binary messages correctly.
413
+ *
414
+ * This wrapper ensures that both text (JSON) and binary WebSocket messages are
415
+ * handled properly. The auto-generated socket class may not handle binary data
416
+ * correctly, so we override the message handling to support both formats.
417
+ * This is critical for audio and other binary data streaming.
193
418
  */
194
419
  class WrappedAgentV1Socket extends AgentV1Socket {
195
420
  constructor(args) {
@@ -197,50 +422,10 @@ class WrappedAgentV1Socket extends AgentV1Socket {
197
422
  this.setupBinaryHandling();
198
423
  }
199
424
  setupBinaryHandling() {
200
- var _a;
201
- // Create a binary-aware message handler
202
- this.binaryAwareHandler = (event) => {
203
- var _a, _b, _c, _d, _e, _f;
204
- // Handle both text (JSON) and binary messages
205
- if (typeof event.data === "string") {
206
- try {
207
- const data = fromJson(event.data);
208
- (_b = (_a = this.eventHandlers).message) === null || _b === void 0 ? void 0 : _b.call(_a, data);
209
- }
210
- catch (error) {
211
- // If JSON parsing fails, pass the raw string
212
- (_d = (_c = this.eventHandlers).message) === null || _d === void 0 ? void 0 : _d.call(_c, event.data);
213
- }
214
- }
215
- else {
216
- // Binary data - pass through as-is
217
- (_f = (_e = this.eventHandlers).message) === null || _f === void 0 ? void 0 : _f.call(_e, event.data);
218
- }
219
- };
220
- // Remove the original handler and add our binary-aware one
221
- // The original handler was added in super() constructor
222
- // We need to replace it
223
- const socketAny = this.socket;
224
- if ((_a = socketAny._listeners) === null || _a === void 0 ? void 0 : _a.message) {
225
- // Remove all message listeners
226
- socketAny._listeners.message.forEach((listener) => {
227
- this.socket.removeEventListener("message", listener);
228
- });
229
- }
230
- // Add our binary-aware handler
231
- if (this.binaryAwareHandler) {
232
- this.socket.addEventListener("message", this.binaryAwareHandler);
233
- }
425
+ this.binaryAwareHandler = setupBinaryHandling(this.socket, this.eventHandlers);
234
426
  }
235
427
  connect() {
236
- // Ensure socket is ready to connect - if _connectLock is stuck, force reconnect
237
- // by closing and reconnecting
238
- if (this.socket.readyState === this.socket.CLOSED) {
239
- // Force a fresh reconnect to ensure _connectLock is reset
240
- this.socket._connectLock = false;
241
- this.socket._shouldReconnect = true;
242
- }
243
- // Call parent connect, but then ensure our binary handler is still active
428
+ resetSocketConnectionState(this.socket);
244
429
  super.connect();
245
430
  // Re-setup binary handling in case connect() re-registered handlers
246
431
  this.setupBinaryHandling();
@@ -249,11 +434,15 @@ class WrappedAgentV1Socket extends AgentV1Socket {
249
434
  }
250
435
  /**
251
436
  * Wrapper for Listen V1Client that overrides connect to use custom websocket.
437
+ *
438
+ * This wrapper ensures that the connect() method uses our custom ReconnectingWebSocket
439
+ * implementation instead of any auto-generated WebSocket handling. This guarantees
440
+ * consistent behavior across Fern regenerations and allows us to customize
441
+ * connection setup, authentication, and header handling.
252
442
  */
253
443
  class WrappedListenV1Client extends ListenV1Client {
254
444
  connect(args) {
255
445
  return __awaiter(this, void 0, void 0, function* () {
256
- var _a, _b, _c;
257
446
  // Extract all the args (same as the original implementation)
258
447
  const { callback, callback_method: callbackMethod, channels, diarize, dictation, encoding, endpointing, extra, interim_results: interimResults, keyterm, keywords, language, mip_opt_out: mipOptOut, model, multichannel, numerals, profanity_filter: profanityFilter, punctuate, redact, replace, sample_rate: sampleRate, search, smart_format: smartFormat, tag, utterance_end_ms: utteranceEndMs, vad_events: vadEvents, version, headers, debug, reconnectAttempts, } = args;
259
448
  // Build query params (same as original)
@@ -311,24 +500,15 @@ class WrappedListenV1Client extends ListenV1Client {
311
500
  _queryParams.vad_events = vadEvents;
312
501
  if (version != null)
313
502
  _queryParams.version = version;
314
- // Get Authorization from authProvider (matching the working version)
315
- const authRequest = yield this._options.authProvider.getAuthRequest();
316
- const _headers = mergeHeaders(authRequest.headers, headers);
317
- // Get WebSocket options with proper header handling
318
- const wsOptions = getWebSocketOptions(_headers);
319
- // Explicitly use the custom ReconnectingWebSocket from ws.ts
320
- const socket = new ReconnectingWebSocket({
321
- url: core.url.join((_a = (yield core.Supplier.get(this._options.baseUrl))) !== null && _a !== void 0 ? _a : ((_b = (yield core.Supplier.get(this._options.environment))) !== null && _b !== void 0 ? _b : environments.DeepgramEnvironment.Production).production, "/v1/listen"),
322
- protocols: (_c = wsOptions.protocols) !== null && _c !== void 0 ? _c : [],
323
- queryParameters: _queryParams,
324
- headers: wsOptions.headers,
325
- options: {
326
- WebSocket: wsOptions.WebSocket,
327
- debug: debug !== null && debug !== void 0 ? debug : false,
328
- maxRetries: reconnectAttempts !== null && reconnectAttempts !== void 0 ? reconnectAttempts : 30,
329
- startClosed: true,
330
- connectionTimeout: 10000, // Increase timeout to 10 seconds
331
- },
503
+ // Use shared connection helper
504
+ const socket = yield createWebSocketConnection({
505
+ options: this._options,
506
+ urlPath: "/v1/listen",
507
+ environmentKey: 'production',
508
+ queryParams: _queryParams,
509
+ headers,
510
+ debug,
511
+ reconnectAttempts,
332
512
  });
333
513
  return new WrappedListenV1Socket({ socket });
334
514
  });
@@ -336,6 +516,11 @@ class WrappedListenV1Client extends ListenV1Client {
336
516
  }
337
517
  /**
338
518
  * Wrapper for Listen V1Socket that handles binary messages correctly.
519
+ *
520
+ * This wrapper ensures that both text (JSON) and binary WebSocket messages are
521
+ * handled properly. The auto-generated socket class may not handle binary data
522
+ * correctly, so we override the message handling to support both formats.
523
+ * This is critical for audio and other binary data streaming.
339
524
  */
340
525
  class WrappedListenV1Socket extends ListenV1Socket {
341
526
  constructor(args) {
@@ -343,44 +528,10 @@ class WrappedListenV1Socket extends ListenV1Socket {
343
528
  this.setupBinaryHandling();
344
529
  }
345
530
  setupBinaryHandling() {
346
- var _a;
347
- // Create a binary-aware message handler
348
- this.binaryAwareHandler = (event) => {
349
- var _a, _b, _c, _d, _e, _f;
350
- // Handle both text (JSON) and binary messages
351
- if (typeof event.data === "string") {
352
- try {
353
- const data = fromJson(event.data);
354
- (_b = (_a = this.eventHandlers).message) === null || _b === void 0 ? void 0 : _b.call(_a, data);
355
- }
356
- catch (error) {
357
- // If JSON parsing fails, pass the raw string
358
- (_d = (_c = this.eventHandlers).message) === null || _d === void 0 ? void 0 : _d.call(_c, event.data);
359
- }
360
- }
361
- else {
362
- // Binary data - pass through as-is
363
- (_f = (_e = this.eventHandlers).message) === null || _f === void 0 ? void 0 : _f.call(_e, event.data);
364
- }
365
- };
366
- // Remove the original handler and add our binary-aware one
367
- const socketAny = this.socket;
368
- if ((_a = socketAny._listeners) === null || _a === void 0 ? void 0 : _a.message) {
369
- socketAny._listeners.message.forEach((listener) => {
370
- this.socket.removeEventListener("message", listener);
371
- });
372
- }
373
- if (this.binaryAwareHandler) {
374
- this.socket.addEventListener("message", this.binaryAwareHandler);
375
- }
531
+ this.binaryAwareHandler = setupBinaryHandling(this.socket, this.eventHandlers);
376
532
  }
377
533
  connect() {
378
- // Ensure socket is ready to connect - if _connectLock is stuck, force reconnect
379
- if (this.socket.readyState === this.socket.CLOSED) {
380
- // Force a fresh reconnect to ensure _connectLock is reset
381
- this.socket._connectLock = false;
382
- this.socket._shouldReconnect = true;
383
- }
534
+ resetSocketConnectionState(this.socket);
384
535
  super.connect();
385
536
  this.setupBinaryHandling();
386
537
  return this;
@@ -388,11 +539,15 @@ class WrappedListenV1Socket extends ListenV1Socket {
388
539
  }
389
540
  /**
390
541
  * Wrapper for Listen V2Client that overrides connect to use custom websocket.
542
+ *
543
+ * This wrapper ensures that the connect() method uses our custom ReconnectingWebSocket
544
+ * implementation instead of any auto-generated WebSocket handling. This guarantees
545
+ * consistent behavior across Fern regenerations and allows us to customize
546
+ * connection setup, authentication, and header handling.
391
547
  */
392
548
  class WrappedListenV2Client extends ListenV2Client {
393
549
  connect(args) {
394
550
  return __awaiter(this, void 0, void 0, function* () {
395
- var _a, _b, _c, _d, _e;
396
551
  const { model, encoding, sample_rate: sampleRate, eager_eot_threshold: eagerEotThreshold, eot_threshold: eotThreshold, eot_timeout_ms: eotTimeoutMs, keyterm, mip_opt_out: mipOptOut, tag, headers, debug, reconnectAttempts, } = args;
397
552
  const _queryParams = {};
398
553
  _queryParams.model = model;
@@ -412,31 +567,28 @@ class WrappedListenV2Client extends ListenV2Client {
412
567
  _queryParams.mip_opt_out = mipOptOut;
413
568
  if (tag != null)
414
569
  _queryParams.tag = tag;
415
- // Get Authorization from authProvider (matching the working version)
416
- const authRequest = yield ((_a = this._options.authProvider) === null || _a === void 0 ? void 0 : _a.getAuthRequest());
417
- const _headers = mergeHeaders((_b = authRequest === null || authRequest === void 0 ? void 0 : authRequest.headers) !== null && _b !== void 0 ? _b : {}, headers);
418
- // Get WebSocket options with proper header handling
419
- const wsOptions = getWebSocketOptions(_headers);
420
- // Explicitly use the custom ReconnectingWebSocket from ws.ts
421
- const socket = new ReconnectingWebSocket({
422
- url: core.url.join((_c = (yield core.Supplier.get(this._options.baseUrl))) !== null && _c !== void 0 ? _c : ((_d = (yield core.Supplier.get(this._options.environment))) !== null && _d !== void 0 ? _d : environments.DeepgramEnvironment.Production).production, "/v2/listen"),
423
- protocols: (_e = wsOptions.protocols) !== null && _e !== void 0 ? _e : [],
424
- queryParameters: _queryParams,
425
- headers: wsOptions.headers,
426
- options: {
427
- WebSocket: wsOptions.WebSocket,
428
- debug: debug !== null && debug !== void 0 ? debug : false,
429
- maxRetries: reconnectAttempts !== null && reconnectAttempts !== void 0 ? reconnectAttempts : 30,
430
- startClosed: true,
431
- connectionTimeout: 10000, // Increase timeout to 10 seconds
432
- },
570
+ // Use shared connection helper
571
+ const socket = yield createWebSocketConnection({
572
+ options: this._options,
573
+ urlPath: "/v2/listen",
574
+ environmentKey: 'production',
575
+ queryParams: _queryParams,
576
+ headers,
577
+ debug,
578
+ reconnectAttempts,
433
579
  });
434
580
  return new WrappedListenV2Socket({ socket });
435
581
  });
436
582
  }
437
583
  }
438
584
  /**
439
- * Wrapper for Listen V2Socket that handles binary messages correctly.
585
+ * Wrapper for Listen V2Socket that handles binary messages correctly and adds ping support.
586
+ *
587
+ * This wrapper ensures that both text (JSON) and binary WebSocket messages are
588
+ * handled properly. The auto-generated socket class may not handle binary data
589
+ * correctly, so we override the message handling to support both formats.
590
+ * Additionally, this wrapper adds a ping() method for sending WebSocket ping
591
+ * frames to keep connections alive (Node.js only).
440
592
  */
441
593
  class WrappedListenV2Socket extends ListenV2Socket {
442
594
  constructor(args) {
@@ -444,56 +596,56 @@ class WrappedListenV2Socket extends ListenV2Socket {
444
596
  this.setupBinaryHandling();
445
597
  }
446
598
  setupBinaryHandling() {
447
- var _a;
448
- // Create a binary-aware message handler
449
- this.binaryAwareHandler = (event) => {
450
- var _a, _b, _c, _d, _e, _f;
451
- // Handle both text (JSON) and binary messages
452
- if (typeof event.data === "string") {
453
- try {
454
- const data = fromJson(event.data);
455
- (_b = (_a = this.eventHandlers).message) === null || _b === void 0 ? void 0 : _b.call(_a, data);
456
- }
457
- catch (error) {
458
- // If JSON parsing fails, pass the raw string
459
- (_d = (_c = this.eventHandlers).message) === null || _d === void 0 ? void 0 : _d.call(_c, event.data);
460
- }
461
- }
462
- else {
463
- // Binary data - pass through as-is
464
- (_f = (_e = this.eventHandlers).message) === null || _f === void 0 ? void 0 : _f.call(_e, event.data);
465
- }
466
- };
467
- // Remove the original handler and add our binary-aware one
468
- const socketAny = this.socket;
469
- if ((_a = socketAny._listeners) === null || _a === void 0 ? void 0 : _a.message) {
470
- socketAny._listeners.message.forEach((listener) => {
471
- this.socket.removeEventListener("message", listener);
472
- });
473
- }
474
- if (this.binaryAwareHandler) {
475
- this.socket.addEventListener("message", this.binaryAwareHandler);
476
- }
599
+ this.binaryAwareHandler = setupBinaryHandling(this.socket, this.eventHandlers);
477
600
  }
478
601
  connect() {
479
- // Ensure socket is ready to connect - if _connectLock is stuck, force reconnect
480
- if (this.socket.readyState === this.socket.CLOSED) {
481
- // Force a fresh reconnect to ensure _connectLock is reset
482
- this.socket._connectLock = false;
483
- this.socket._shouldReconnect = true;
484
- }
602
+ resetSocketConnectionState(this.socket);
485
603
  super.connect();
486
604
  this.setupBinaryHandling();
487
605
  return this;
488
606
  }
607
+ /**
608
+ * Send a WebSocket ping frame to keep the connection alive.
609
+ *
610
+ * In Node.js, this uses the native WebSocket ping() method from the 'ws' library.
611
+ * In browsers, WebSocket ping/pong is handled automatically by the browser and
612
+ * cannot be manually triggered, so this method will throw an error.
613
+ *
614
+ * @param data Optional data to send with the ping (Node.js only)
615
+ * @throws Error if not in Node.js environment or WebSocket is not connected
616
+ */
617
+ ping(data) {
618
+ const ws = this.socket._ws;
619
+ if (!ws) {
620
+ throw new Error("WebSocket is not connected. Call connect() and waitForOpen() first.");
621
+ }
622
+ if (ws.readyState !== ws.OPEN) {
623
+ throw new Error("WebSocket is not in OPEN state.");
624
+ }
625
+ // Check if we're in Node.js and the WebSocket has a ping method (from 'ws' library)
626
+ if (RUNTIME.type === "node" && typeof ws.ping === "function") {
627
+ // Call the native ping method from the 'ws' library
628
+ ws.ping(data);
629
+ }
630
+ else {
631
+ // In browsers, WebSocket ping/pong is automatic and not exposed to JavaScript
632
+ throw new Error("WebSocket ping is not supported in browser environments. " +
633
+ "Browser WebSocket connections handle ping/pong automatically. " +
634
+ "If you need keepalive in the browser, consider sending periodic audio data or using a timer.");
635
+ }
636
+ }
489
637
  }
490
638
  /**
491
639
  * Wrapper for Speak V1Client that overrides connect to use custom websocket.
640
+ *
641
+ * This wrapper ensures that the connect() method uses our custom ReconnectingWebSocket
642
+ * implementation instead of any auto-generated WebSocket handling. This guarantees
643
+ * consistent behavior across Fern regenerations and allows us to customize
644
+ * connection setup, authentication, and header handling.
492
645
  */
493
646
  class WrappedSpeakV1Client extends SpeakV1Client {
494
647
  connect(args) {
495
648
  return __awaiter(this, void 0, void 0, function* () {
496
- var _a, _b, _c;
497
649
  const { encoding, mip_opt_out: mipOptOut, model, sample_rate: sampleRate, headers, debug, reconnectAttempts, } = args;
498
650
  const _queryParams = {};
499
651
  if (encoding != null)
@@ -504,24 +656,15 @@ class WrappedSpeakV1Client extends SpeakV1Client {
504
656
  _queryParams.model = model;
505
657
  if (sampleRate != null)
506
658
  _queryParams.sample_rate = sampleRate;
507
- // Get Authorization from authProvider (matching the working version)
508
- const authRequest = yield this._options.authProvider.getAuthRequest();
509
- const _headers = mergeHeaders(authRequest.headers, headers);
510
- // Get WebSocket options with proper header handling
511
- const wsOptions = getWebSocketOptions(_headers);
512
- // Explicitly use the custom ReconnectingWebSocket from ws.ts
513
- const socket = new ReconnectingWebSocket({
514
- url: core.url.join((_a = (yield core.Supplier.get(this._options.baseUrl))) !== null && _a !== void 0 ? _a : ((_b = (yield core.Supplier.get(this._options.environment))) !== null && _b !== void 0 ? _b : environments.DeepgramEnvironment.Production).production, "/v1/speak"),
515
- protocols: (_c = wsOptions.protocols) !== null && _c !== void 0 ? _c : [],
516
- queryParameters: _queryParams,
517
- headers: wsOptions.headers,
518
- options: {
519
- WebSocket: wsOptions.WebSocket,
520
- debug: debug !== null && debug !== void 0 ? debug : false,
521
- maxRetries: reconnectAttempts !== null && reconnectAttempts !== void 0 ? reconnectAttempts : 30,
522
- startClosed: true,
523
- connectionTimeout: 10000, // Increase timeout to 10 seconds
524
- },
659
+ // Use shared connection helper
660
+ const socket = yield createWebSocketConnection({
661
+ options: this._options,
662
+ urlPath: "/v1/speak",
663
+ environmentKey: 'production',
664
+ queryParams: _queryParams,
665
+ headers,
666
+ debug,
667
+ reconnectAttempts,
525
668
  });
526
669
  return new WrappedSpeakV1Socket({ socket });
527
670
  });
@@ -529,6 +672,11 @@ class WrappedSpeakV1Client extends SpeakV1Client {
529
672
  }
530
673
  /**
531
674
  * Wrapper for Speak V1Socket that handles binary messages correctly.
675
+ *
676
+ * This wrapper ensures that both text (JSON) and binary WebSocket messages are
677
+ * handled properly. The auto-generated socket class may not handle binary data
678
+ * correctly, so we override the message handling to support both formats.
679
+ * This is critical for audio and other binary data streaming.
532
680
  */
533
681
  class WrappedSpeakV1Socket extends SpeakV1Socket {
534
682
  constructor(args) {
@@ -536,44 +684,10 @@ class WrappedSpeakV1Socket extends SpeakV1Socket {
536
684
  this.setupBinaryHandling();
537
685
  }
538
686
  setupBinaryHandling() {
539
- var _a;
540
- // Create a binary-aware message handler
541
- this.binaryAwareHandler = (event) => {
542
- var _a, _b, _c, _d, _e, _f;
543
- // Handle both text (JSON) and binary messages
544
- if (typeof event.data === "string") {
545
- try {
546
- const data = fromJson(event.data);
547
- (_b = (_a = this.eventHandlers).message) === null || _b === void 0 ? void 0 : _b.call(_a, data);
548
- }
549
- catch (error) {
550
- // If JSON parsing fails, pass the raw string
551
- (_d = (_c = this.eventHandlers).message) === null || _d === void 0 ? void 0 : _d.call(_c, event.data);
552
- }
553
- }
554
- else {
555
- // Binary data - pass through as-is
556
- (_f = (_e = this.eventHandlers).message) === null || _f === void 0 ? void 0 : _f.call(_e, event.data);
557
- }
558
- };
559
- // Remove the original handler and add our binary-aware one
560
- const socketAny = this.socket;
561
- if ((_a = socketAny._listeners) === null || _a === void 0 ? void 0 : _a.message) {
562
- socketAny._listeners.message.forEach((listener) => {
563
- this.socket.removeEventListener("message", listener);
564
- });
565
- }
566
- if (this.binaryAwareHandler) {
567
- this.socket.addEventListener("message", this.binaryAwareHandler);
568
- }
687
+ this.binaryAwareHandler = setupBinaryHandling(this.socket, this.eventHandlers);
569
688
  }
570
689
  connect() {
571
- // Ensure socket is ready to connect - if _connectLock is stuck, force reconnect
572
- if (this.socket.readyState === this.socket.CLOSED) {
573
- // Force a fresh reconnect to ensure _connectLock is reset
574
- this.socket._connectLock = false;
575
- this.socket._shouldReconnect = true;
576
- }
690
+ resetSocketConnectionState(this.socket);
577
691
  super.connect();
578
692
  this.setupBinaryHandling();
579
693
  return this;