@honeybbq/teamspeak 0.0.1 → 1.0.0-beta.7

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 (393) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +726 -2
  3. package/dist/client/abort.d.ts +5 -0
  4. package/dist/client/abort.d.ts.map +1 -0
  5. package/dist/client/abort.js +23 -0
  6. package/dist/client/abort.js.map +1 -0
  7. package/dist/client/address.d.ts +17 -0
  8. package/dist/client/address.d.ts.map +1 -0
  9. package/dist/client/address.js +66 -0
  10. package/dist/client/address.js.map +1 -0
  11. package/dist/client/api/voice.d.ts +24 -0
  12. package/dist/client/api/voice.d.ts.map +1 -0
  13. package/dist/client/api/voice.js +33 -0
  14. package/dist/client/api/voice.js.map +1 -0
  15. package/dist/client/capabilities.d.ts +68 -0
  16. package/dist/client/capabilities.d.ts.map +1 -0
  17. package/dist/client/capabilities.js +59 -0
  18. package/dist/client/capabilities.js.map +1 -0
  19. package/dist/client/client.d.ts +196 -0
  20. package/dist/client/client.d.ts.map +1 -0
  21. package/dist/client/client.js +1523 -0
  22. package/dist/client/client.js.map +1 -0
  23. package/dist/client/commands.d.ts +66 -0
  24. package/dist/client/commands.d.ts.map +1 -0
  25. package/dist/client/commands.js +162 -0
  26. package/dist/client/commands.js.map +1 -0
  27. package/dist/client/crypto/crypt-ops.d.ts +7 -0
  28. package/dist/client/crypto/crypt-ops.d.ts.map +1 -0
  29. package/dist/client/crypto/crypt-ops.js +2 -0
  30. package/dist/client/crypto/crypt-ops.js.map +1 -0
  31. package/dist/client/crypto/crypt.d.ts +37 -0
  32. package/dist/client/crypto/crypt.d.ts.map +1 -0
  33. package/dist/client/crypto/crypt.js +203 -0
  34. package/dist/client/crypto/crypt.js.map +1 -0
  35. package/dist/client/crypto/eax.d.ts +12 -0
  36. package/dist/client/crypto/eax.d.ts.map +1 -0
  37. package/dist/client/crypto/eax.js +118 -0
  38. package/dist/client/crypto/eax.js.map +1 -0
  39. package/dist/client/crypto/identity.d.ts +97 -0
  40. package/dist/client/crypto/identity.d.ts.map +1 -0
  41. package/dist/client/crypto/identity.js +412 -0
  42. package/dist/client/crypto/identity.js.map +1 -0
  43. package/dist/client/crypto/index.d.ts +7 -0
  44. package/dist/client/crypto/index.d.ts.map +1 -0
  45. package/dist/client/crypto/index.js +5 -0
  46. package/dist/client/crypto/index.js.map +1 -0
  47. package/dist/client/crypto/primitives.d.ts +43 -0
  48. package/dist/client/crypto/primitives.d.ts.map +1 -0
  49. package/dist/client/crypto/primitives.js +116 -0
  50. package/dist/client/crypto/primitives.js.map +1 -0
  51. package/dist/client/diagnostics.d.ts +45 -0
  52. package/dist/client/diagnostics.d.ts.map +1 -0
  53. package/dist/client/diagnostics.js +30 -0
  54. package/dist/client/diagnostics.js.map +1 -0
  55. package/dist/client/discovery/index.d.ts +2 -0
  56. package/dist/client/discovery/index.d.ts.map +1 -0
  57. package/dist/client/discovery/index.js +2 -0
  58. package/dist/client/discovery/index.js.map +1 -0
  59. package/dist/client/discovery/resolver.d.ts +26 -0
  60. package/dist/client/discovery/resolver.d.ts.map +1 -0
  61. package/dist/client/discovery/resolver.js +275 -0
  62. package/dist/client/discovery/resolver.js.map +1 -0
  63. package/dist/client/errors.d.ts +82 -0
  64. package/dist/client/errors.d.ts.map +1 -0
  65. package/dist/client/errors.js +201 -0
  66. package/dist/client/errors.js.map +1 -0
  67. package/dist/client/events.d.ts +3 -0
  68. package/dist/client/events.d.ts.map +1 -0
  69. package/dist/client/events.js +8 -0
  70. package/dist/client/events.js.map +1 -0
  71. package/dist/client/handshake/crypt-handshake.d.ts +17 -0
  72. package/dist/client/handshake/crypt-handshake.d.ts.map +1 -0
  73. package/dist/client/handshake/crypt-handshake.js +128 -0
  74. package/dist/client/handshake/crypt-handshake.js.map +1 -0
  75. package/dist/client/handshake/crypt-init2.d.ts +7 -0
  76. package/dist/client/handshake/crypt-init2.d.ts.map +1 -0
  77. package/dist/client/handshake/crypt-init2.js +37 -0
  78. package/dist/client/handshake/crypt-init2.js.map +1 -0
  79. package/dist/client/handshake/index.d.ts +4 -0
  80. package/dist/client/handshake/index.d.ts.map +1 -0
  81. package/dist/client/handshake/index.js +4 -0
  82. package/dist/client/handshake/index.js.map +1 -0
  83. package/dist/client/handshake/license.d.ts +35 -0
  84. package/dist/client/handshake/license.d.ts.map +1 -0
  85. package/dist/client/handshake/license.js +169 -0
  86. package/dist/client/handshake/license.js.map +1 -0
  87. package/dist/client/handshake.d.ts +27 -0
  88. package/dist/client/handshake.d.ts.map +1 -0
  89. package/dist/client/handshake.js +126 -0
  90. package/dist/client/handshake.js.map +1 -0
  91. package/dist/client/helpers.d.ts +6 -0
  92. package/dist/client/helpers.d.ts.map +1 -0
  93. package/dist/client/helpers.js +13 -0
  94. package/dist/client/helpers.js.map +1 -0
  95. package/dist/client/hooks.d.ts +7 -0
  96. package/dist/client/hooks.d.ts.map +1 -0
  97. package/dist/client/hooks.js +28 -0
  98. package/dist/client/hooks.js.map +1 -0
  99. package/dist/client/index.d.ts +26 -0
  100. package/dist/client/index.d.ts.map +1 -0
  101. package/dist/client/index.js +28 -0
  102. package/dist/client/index.js.map +1 -0
  103. package/dist/client/reconnect.d.ts +12 -0
  104. package/dist/client/reconnect.d.ts.map +1 -0
  105. package/dist/client/reconnect.js +44 -0
  106. package/dist/client/reconnect.js.map +1 -0
  107. package/dist/client/throttle.d.ts +20 -0
  108. package/dist/client/throttle.d.ts.map +1 -0
  109. package/dist/client/throttle.js +83 -0
  110. package/dist/client/throttle.js.map +1 -0
  111. package/dist/client/trace.d.ts +223 -0
  112. package/dist/client/trace.d.ts.map +1 -0
  113. package/dist/client/trace.js +13 -0
  114. package/dist/client/trace.js.map +1 -0
  115. package/dist/client/transfer.d.ts +111 -0
  116. package/dist/client/transfer.d.ts.map +1 -0
  117. package/dist/client/transfer.js +243 -0
  118. package/dist/client/transfer.js.map +1 -0
  119. package/dist/client/transport/generation-window.d.ts +30 -0
  120. package/dist/client/transport/generation-window.d.ts.map +1 -0
  121. package/dist/client/transport/generation-window.js +97 -0
  122. package/dist/client/transport/generation-window.js.map +1 -0
  123. package/dist/client/transport/handler.d.ts +61 -0
  124. package/dist/client/transport/handler.d.ts.map +1 -0
  125. package/dist/client/transport/handler.js +793 -0
  126. package/dist/client/transport/handler.js.map +1 -0
  127. package/dist/client/transport/index.d.ts +6 -0
  128. package/dist/client/transport/index.d.ts.map +1 -0
  129. package/dist/client/transport/index.js +5 -0
  130. package/dist/client/transport/index.js.map +1 -0
  131. package/dist/client/transport/packet.d.ts +36 -0
  132. package/dist/client/transport/packet.d.ts.map +1 -0
  133. package/dist/client/transport/packet.js +55 -0
  134. package/dist/client/transport/packet.js.map +1 -0
  135. package/dist/client/transport/quicklz.d.ts +24 -0
  136. package/dist/client/transport/quicklz.d.ts.map +1 -0
  137. package/dist/client/transport/quicklz.js +179 -0
  138. package/dist/client/transport/quicklz.js.map +1 -0
  139. package/dist/client/types.d.ts +226 -0
  140. package/dist/client/types.d.ts.map +1 -0
  141. package/dist/client/types.js +39 -0
  142. package/dist/client/types.js.map +1 -0
  143. package/dist/core/api/channels.d.ts +182 -0
  144. package/dist/core/api/channels.d.ts.map +1 -0
  145. package/dist/core/api/channels.js +155 -0
  146. package/dist/core/api/channels.js.map +1 -0
  147. package/dist/core/api/clients.d.ts +304 -0
  148. package/dist/core/api/clients.d.ts.map +1 -0
  149. package/dist/core/api/clients.js +260 -0
  150. package/dist/core/api/clients.js.map +1 -0
  151. package/dist/core/api/command.d.ts +305 -0
  152. package/dist/core/api/command.d.ts.map +1 -0
  153. package/dist/core/api/command.js +363 -0
  154. package/dist/core/api/command.js.map +1 -0
  155. package/dist/core/api/files.d.ts +153 -0
  156. package/dist/core/api/files.d.ts.map +1 -0
  157. package/dist/core/api/files.js +181 -0
  158. package/dist/core/api/files.js.map +1 -0
  159. package/dist/core/api/groups.d.ts +248 -0
  160. package/dist/core/api/groups.d.ts.map +1 -0
  161. package/dist/core/api/groups.js +271 -0
  162. package/dist/core/api/groups.js.map +1 -0
  163. package/dist/core/api/moderation.d.ts +205 -0
  164. package/dist/core/api/moderation.d.ts.map +1 -0
  165. package/dist/core/api/moderation.js +209 -0
  166. package/dist/core/api/moderation.js.map +1 -0
  167. package/dist/core/api/parse.d.ts +16 -0
  168. package/dist/core/api/parse.d.ts.map +1 -0
  169. package/dist/core/api/parse.js +40 -0
  170. package/dist/core/api/parse.js.map +1 -0
  171. package/dist/core/api/server.d.ts +310 -0
  172. package/dist/core/api/server.d.ts.map +1 -0
  173. package/dist/core/api/server.js +290 -0
  174. package/dist/core/api/server.js.map +1 -0
  175. package/dist/core/command/command.d.ts +20 -0
  176. package/dist/core/command/command.d.ts.map +1 -0
  177. package/dist/core/command/command.js +112 -0
  178. package/dist/core/command/command.js.map +1 -0
  179. package/dist/core/command/ids.d.ts +125 -0
  180. package/dist/core/command/ids.d.ts.map +1 -0
  181. package/dist/core/command/ids.js +85 -0
  182. package/dist/core/command/ids.js.map +1 -0
  183. package/dist/core/command/parser.d.ts +17 -0
  184. package/dist/core/command/parser.d.ts.map +1 -0
  185. package/dist/core/command/parser.js +65 -0
  186. package/dist/core/command/parser.js.map +1 -0
  187. package/dist/core/command/request.d.ts +61 -0
  188. package/dist/core/command/request.d.ts.map +1 -0
  189. package/dist/core/command/request.js +64 -0
  190. package/dist/core/command/request.js.map +1 -0
  191. package/dist/core/command/responses.d.ts +59 -0
  192. package/dist/core/command/responses.d.ts.map +1 -0
  193. package/dist/core/command/responses.js +74 -0
  194. package/dist/core/command/responses.js.map +1 -0
  195. package/dist/core/command-name.d.ts +333 -0
  196. package/dist/core/command-name.d.ts.map +1 -0
  197. package/dist/core/command-name.js +331 -0
  198. package/dist/core/command-name.js.map +1 -0
  199. package/dist/core/enums.d.ts +146 -0
  200. package/dist/core/enums.d.ts.map +1 -0
  201. package/dist/core/enums.js +132 -0
  202. package/dist/core/enums.js.map +1 -0
  203. package/dist/core/errorcode.d.ts +413 -0
  204. package/dist/core/errorcode.d.ts.map +1 -0
  205. package/dist/core/errorcode.js +410 -0
  206. package/dist/core/errorcode.js.map +1 -0
  207. package/dist/core/errors.d.ts +111 -0
  208. package/dist/core/errors.d.ts.map +1 -0
  209. package/dist/core/errors.js +233 -0
  210. package/dist/core/errors.js.map +1 -0
  211. package/dist/core/events.d.ts +207 -0
  212. package/dist/core/events.d.ts.map +1 -0
  213. package/dist/core/events.js +6 -0
  214. package/dist/core/events.js.map +1 -0
  215. package/dist/core/helpers.d.ts +42 -0
  216. package/dist/core/helpers.d.ts.map +1 -0
  217. package/dist/core/helpers.js +156 -0
  218. package/dist/core/helpers.js.map +1 -0
  219. package/dist/core/index.d.ts +35 -0
  220. package/dist/core/index.d.ts.map +1 -0
  221. package/dist/core/index.js +34 -0
  222. package/dist/core/index.js.map +1 -0
  223. package/dist/core/internal.d.ts +23 -0
  224. package/dist/core/internal.d.ts.map +1 -0
  225. package/dist/core/internal.js +20 -0
  226. package/dist/core/internal.js.map +1 -0
  227. package/dist/core/middleware.d.ts +14 -0
  228. package/dist/core/middleware.d.ts.map +1 -0
  229. package/dist/core/middleware.js +18 -0
  230. package/dist/core/middleware.js.map +1 -0
  231. package/dist/core/notification-name.d.ts +154 -0
  232. package/dist/core/notification-name.d.ts.map +1 -0
  233. package/dist/core/notification-name.js +152 -0
  234. package/dist/core/notification-name.js.map +1 -0
  235. package/dist/core/notifications.d.ts +43 -0
  236. package/dist/core/notifications.d.ts.map +1 -0
  237. package/dist/core/notifications.js +116 -0
  238. package/dist/core/notifications.js.map +1 -0
  239. package/dist/core/permission-name.d.ts +533 -0
  240. package/dist/core/permission-name.d.ts.map +1 -0
  241. package/dist/core/permission-name.js +531 -0
  242. package/dist/core/permission-name.js.map +1 -0
  243. package/dist/core/permission.d.ts +31 -0
  244. package/dist/core/permission.d.ts.map +1 -0
  245. package/dist/core/permission.js +20 -0
  246. package/dist/core/permission.js.map +1 -0
  247. package/dist/core/property-name.d.ts +403 -0
  248. package/dist/core/property-name.d.ts.map +1 -0
  249. package/dist/core/property-name.js +405 -0
  250. package/dist/core/property-name.js.map +1 -0
  251. package/dist/core/reason.d.ts +39 -0
  252. package/dist/core/reason.d.ts.map +1 -0
  253. package/dist/core/reason.js +36 -0
  254. package/dist/core/reason.js.map +1 -0
  255. package/dist/core/reconnect.d.ts +59 -0
  256. package/dist/core/reconnect.d.ts.map +1 -0
  257. package/dist/core/reconnect.js +55 -0
  258. package/dist/core/reconnect.js.map +1 -0
  259. package/dist/core/types.d.ts +110 -0
  260. package/dist/core/types.d.ts.map +1 -0
  261. package/dist/core/types.js +27 -0
  262. package/dist/core/types.js.map +1 -0
  263. package/dist/query/client.d.ts +194 -0
  264. package/dist/query/client.d.ts.map +1 -0
  265. package/dist/query/client.js +967 -0
  266. package/dist/query/client.js.map +1 -0
  267. package/dist/query/errors.d.ts +61 -0
  268. package/dist/query/errors.d.ts.map +1 -0
  269. package/dist/query/errors.js +100 -0
  270. package/dist/query/errors.js.map +1 -0
  271. package/dist/query/index.d.ts +36 -0
  272. package/dist/query/index.d.ts.map +1 -0
  273. package/dist/query/index.js +34 -0
  274. package/dist/query/index.js.map +1 -0
  275. package/dist/query/knownhosts.d.ts +61 -0
  276. package/dist/query/knownhosts.d.ts.map +1 -0
  277. package/dist/query/knownhosts.js +223 -0
  278. package/dist/query/knownhosts.js.map +1 -0
  279. package/dist/query/lines.d.ts +14 -0
  280. package/dist/query/lines.d.ts.map +1 -0
  281. package/dist/query/lines.js +29 -0
  282. package/dist/query/lines.js.map +1 -0
  283. package/dist/query/options.d.ts +187 -0
  284. package/dist/query/options.d.ts.map +1 -0
  285. package/dist/query/options.js +213 -0
  286. package/dist/query/options.js.map +1 -0
  287. package/dist/query/reconnect.d.ts +29 -0
  288. package/dist/query/reconnect.d.ts.map +1 -0
  289. package/dist/query/reconnect.js +87 -0
  290. package/dist/query/reconnect.js.map +1 -0
  291. package/dist/query/ssh.d.ts +345 -0
  292. package/dist/query/ssh.d.ts.map +1 -0
  293. package/dist/query/ssh.js +241 -0
  294. package/dist/query/ssh.js.map +1 -0
  295. package/dist/query/stream.d.ts +38 -0
  296. package/dist/query/stream.d.ts.map +1 -0
  297. package/dist/query/stream.js +70 -0
  298. package/dist/query/stream.js.map +1 -0
  299. package/dist/query/tcp.d.ts +38 -0
  300. package/dist/query/tcp.d.ts.map +1 -0
  301. package/dist/query/tcp.js +53 -0
  302. package/dist/query/tcp.js.map +1 -0
  303. package/dist/query/transport.d.ts +36 -0
  304. package/dist/query/transport.d.ts.map +1 -0
  305. package/dist/query/transport.js +2 -0
  306. package/dist/query/transport.js.map +1 -0
  307. package/dist/query/web.d.ts +54 -0
  308. package/dist/query/web.d.ts.map +1 -0
  309. package/dist/query/web.js +146 -0
  310. package/dist/query/web.js.map +1 -0
  311. package/dist/versions/index.d.ts +3094 -0
  312. package/dist/versions/index.d.ts.map +1 -0
  313. package/dist/versions/index.js +9237 -0
  314. package/dist/versions/index.js.map +1 -0
  315. package/package.json +118 -4
  316. package/src/client/abort.ts +24 -0
  317. package/src/client/address.ts +74 -0
  318. package/src/client/api/voice.ts +61 -0
  319. package/src/client/capabilities.ts +106 -0
  320. package/src/client/client.ts +1809 -0
  321. package/src/client/commands.ts +193 -0
  322. package/src/client/crypto/crypt-ops.ts +6 -0
  323. package/src/client/crypto/crypt.ts +275 -0
  324. package/src/client/crypto/eax.ts +152 -0
  325. package/src/client/crypto/identity.ts +484 -0
  326. package/src/client/crypto/index.ts +21 -0
  327. package/src/client/crypto/primitives.ts +141 -0
  328. package/src/client/diagnostics.ts +58 -0
  329. package/src/client/discovery/index.ts +1 -0
  330. package/src/client/discovery/resolver.ts +325 -0
  331. package/src/client/errors.ts +217 -0
  332. package/src/client/events.ts +12 -0
  333. package/src/client/handshake/crypt-handshake.ts +157 -0
  334. package/src/client/handshake/crypt-init2.ts +48 -0
  335. package/src/client/handshake/index.ts +3 -0
  336. package/src/client/handshake/license.ts +208 -0
  337. package/src/client/handshake.ts +150 -0
  338. package/src/client/helpers.ts +10 -0
  339. package/src/client/hooks.ts +30 -0
  340. package/src/client/index.ts +93 -0
  341. package/src/client/reconnect.ts +43 -0
  342. package/src/client/throttle.ts +92 -0
  343. package/src/client/trace.ts +237 -0
  344. package/src/client/transfer.ts +436 -0
  345. package/src/client/transport/generation-window.ts +108 -0
  346. package/src/client/transport/handler.ts +926 -0
  347. package/src/client/transport/index.ts +14 -0
  348. package/src/client/transport/packet.ts +69 -0
  349. package/src/client/transport/quicklz.ts +209 -0
  350. package/src/client/types.ts +268 -0
  351. package/src/core/api/channels.ts +396 -0
  352. package/src/core/api/clients.ts +654 -0
  353. package/src/core/api/command.ts +563 -0
  354. package/src/core/api/files.ts +405 -0
  355. package/src/core/api/groups.ts +622 -0
  356. package/src/core/api/moderation.ts +525 -0
  357. package/src/core/api/parse.ts +52 -0
  358. package/src/core/api/server.ts +709 -0
  359. package/src/core/command/command.ts +125 -0
  360. package/src/core/command/ids.ts +149 -0
  361. package/src/core/command/parser.ts +68 -0
  362. package/src/core/command/request.ts +119 -0
  363. package/src/core/command/responses.ts +114 -0
  364. package/src/core/command-name.ts +334 -0
  365. package/src/core/enums.ts +167 -0
  366. package/src/core/errorcode.ts +412 -0
  367. package/src/core/errors.ts +258 -0
  368. package/src/core/events.ts +219 -0
  369. package/src/core/helpers.ts +161 -0
  370. package/src/core/index.ts +126 -0
  371. package/src/core/internal.ts +23 -0
  372. package/src/core/middleware.ts +24 -0
  373. package/src/core/notification-name.ts +155 -0
  374. package/src/core/notifications.ts +157 -0
  375. package/src/core/permission-name.ts +538 -0
  376. package/src/core/permission.ts +34 -0
  377. package/src/core/property-name.ts +411 -0
  378. package/src/core/reason.ts +38 -0
  379. package/src/core/reconnect.ts +98 -0
  380. package/src/core/types.ts +138 -0
  381. package/src/query/client.ts +1132 -0
  382. package/src/query/errors.ts +108 -0
  383. package/src/query/index.ts +65 -0
  384. package/src/query/knownhosts.ts +257 -0
  385. package/src/query/lines.ts +28 -0
  386. package/src/query/options.ts +388 -0
  387. package/src/query/reconnect.ts +84 -0
  388. package/src/query/ssh.ts +614 -0
  389. package/src/query/stream.ts +91 -0
  390. package/src/query/tcp.ts +85 -0
  391. package/src/query/transport.ts +35 -0
  392. package/src/query/web.ts +195 -0
  393. package/src/versions/index.ts +10774 -0
@@ -0,0 +1,1809 @@
1
+ import {
2
+ type EventMap,
3
+ type VoiceOptions,
4
+ type WhisperTargets,
5
+ type ClientOptions,
6
+ type DatagramSocket,
7
+ type ResolvedAddr,
8
+ type EventMiddleware,
9
+ type AddrResolver,
10
+ type ServerEvent,
11
+ type ServerEventName,
12
+ } from "./types.js";
13
+ import { ConnectPhase, type ClientTrace } from "./trace.js";
14
+ import { callHook } from "./hooks.js";
15
+ import { puzzleOf } from "./handshake/crypt-handshake.js";
16
+ import {
17
+ type ChannelID,
18
+ type ClientEnterEvent,
19
+ type ClientID,
20
+ type Codec,
21
+ type KickedEvent,
22
+ type CommandMiddleware,
23
+ type CommandOptions,
24
+ type UID,
25
+ asChannelID,
26
+ asClientID,
27
+ type Listener,
28
+ type Logger,
29
+ type ReconnectOptions,
30
+ type Unsubscribe,
31
+ AlreadyConnectedError,
32
+ backoffDelay,
33
+ ClientStatus,
34
+ ErrorCode,
35
+ Reason,
36
+ TeamspeakError,
37
+ noopLogger,
38
+ } from "@honeybbq/teamspeak";
39
+ import { HandshakeError, RemovedError } from "./errors.js";
40
+ import { abortable, abortReason } from "./abort.js";
41
+ import type { Identity } from "./crypto/index.js";
42
+ import { Crypt } from "./crypto/index.js";
43
+ import { RESOLVE_BUDGET_MS, Resolver } from "./discovery/resolver.js";
44
+ import { PacketHandler } from "./transport/handler.js";
45
+ import { PacketType } from "./transport/packet.js";
46
+ import type { Packet } from "./transport/packet.js";
47
+ import { CommandTracker, appendReturnCode } from "./commands.js";
48
+ import {
49
+ buildCommandChain,
50
+ encodeRequest,
51
+ parseServerError,
52
+ resolveBackoffPolicy,
53
+ } from "../core/internal.js";
54
+ import { uploadFileData, downloadFileData, type FileTransferOptions } from "./transfer.js";
55
+ import { buildEventChain } from "./events.js";
56
+ import { processInit1 } from "./handshake/crypt-handshake.js";
57
+ import {
58
+ handleHandshakeInitIV,
59
+ handleHandshakeExpand2,
60
+ defaultClientVersion,
61
+ handleInitServer,
62
+ prepareClientPassword,
63
+ } from "./handshake.js";
64
+ import type { ClientVersion, CommandExecutor, CommandRequest } from "@honeybbq/teamspeak";
65
+ import { handleNotification } from "../core/internal.js";
66
+ import type { NotificationResult } from "../core/internal.js";
67
+ import { parseCommand } from "../core/internal.js";
68
+ import { CommandThrottle } from "./throttle.js";
69
+ import { splitCommandRows, sleep } from "../core/internal.js";
70
+ import { isAutoNicknameMatch } from "./helpers.js";
71
+ import type { FileUploadInfo, FileDownloadInfo } from "@honeybbq/teamspeak";
72
+ import { CommandTimeoutError, NotConnectedError } from "@honeybbq/teamspeak";
73
+ import { responseSpec } from "../core/internal.js";
74
+ import type { Readable, Writable } from "node:stream";
75
+ import type { SocketFactory, FileTransferSocketFactory } from "./types.js";
76
+ import { unknownServerCapabilities, type ServerCapabilities } from "./capabilities.js";
77
+ import { joinHostPort, parseConnectAddress, splitHostPort } from "./address.js";
78
+ import { commandChannel, incomingChannel, type CommandTrace } from "./diagnostics.js";
79
+ import { defaultShouldRetry } from "./reconnect.js";
80
+
81
+ /**
82
+ * What clientinit sends about the connection, with the passwords already in
83
+ * their wire form, `base64(sha1(password))`: hashed once, when the client is
84
+ * made, so the plain text is never held.
85
+ */
86
+ export interface ClientInitOptions {
87
+ readonly serverPasswordHash: string;
88
+ readonly defaultChannel: string;
89
+ readonly defaultChannelPasswordHash: string;
90
+ /** The platform, version and signature, copied so later changes to the option have no effect. */
91
+ readonly version: ClientVersion;
92
+ }
93
+
94
+ /** The signature is Ed25519, 64 bytes; the server verifies it, so only its shape is checked. */
95
+ function normalizeClientVersion(version: ClientVersion | undefined): ClientVersion {
96
+ if (version === undefined) return defaultClientVersion;
97
+ const { platform, version: text, sign } = version;
98
+ for (const [name, value] of [
99
+ ["platform", platform],
100
+ ["version", text],
101
+ ["sign", sign],
102
+ ] as const) {
103
+ if (typeof value !== "string" || value === "") {
104
+ throw new TypeError(`a client version's ${name} is a non-empty string`);
105
+ }
106
+ }
107
+ const raw = Buffer.from(sign, "base64");
108
+ if (raw.length !== 64 || raw.toString("base64") !== sign) {
109
+ throw new RangeError("a client version's sign is the base64 of a 64-byte signature");
110
+ }
111
+ return { platform, version: text, sign };
112
+ }
113
+
114
+ function normalizeClientInitOptions(options: ClientOptions): ClientInitOptions {
115
+ return {
116
+ serverPasswordHash: prepareClientPassword(options.serverPassword ?? ""),
117
+ defaultChannel: options.defaultChannel ?? "",
118
+ defaultChannelPasswordHash: prepareClientPassword(options.defaultChannelPassword ?? ""),
119
+ version: normalizeClientVersion(options.version),
120
+ };
121
+ }
122
+
123
+ /**
124
+ * What the handshake, and the package's own tests, reach inside a Client.
125
+ * Not exported from the package: a Client keeps all of it in private fields,
126
+ * so none of it shows in `util.inspect()`, `JSON.stringify()` or a debugger's
127
+ * property list.
128
+ *
129
+ * @internal
130
+ */
131
+ export interface ClientInternals {
132
+ readonly crypt: Crypt;
133
+ readonly handler: PacketHandler;
134
+ readonly logger: Logger;
135
+ readonly initOptions: ClientInitOptions;
136
+ nickname: string;
137
+ clid: number;
138
+ capabilities: ServerCapabilities;
139
+ /** Mark the attempt in progress connected. */
140
+ markConnected(initServer?: Readonly<Record<string, string>>): void;
141
+ /**
142
+ * The shared secret exists: the attempt moves from its handshake to joining.
143
+ * `serverPublicKey` is the server's `omega`, as it sent it.
144
+ */
145
+ markHandshakeDone(serverPublicKey?: string): void;
146
+ /**
147
+ * Send a command line without waiting for an answer, on the handshake's
148
+ * own path: it needs an open socket, not a connected session.
149
+ */
150
+ execNoWait(command: string): Promise<void>;
151
+ /** Handle a packet as if the current handler had received it. */
152
+ handlePacket(packet: Packet): void;
153
+ }
154
+
155
+ let internalsOf: (client: Client) => ClientInternals;
156
+
157
+ let sentLineHook: ((client: Client, line: string) => void) | undefined;
158
+
159
+ /**
160
+ * Observe every command line the client sends, as encoded. A seam for the
161
+ * package's own tests; not exported from the package.
162
+ *
163
+ * @internal
164
+ */
165
+ export function onSentLine(hook: ((client: Client, line: string) => void) | undefined): void {
166
+ sentLineHook = hook;
167
+ }
168
+
169
+ /** @internal The internals of `client`. */
170
+ export function clientInternals(client: Client): ClientInternals {
171
+ return internalsOf(client);
172
+ }
173
+
174
+ /** How long a command waits for its answer unless told otherwise. */
175
+ const DEFAULT_COMMAND_TIMEOUT_MS = 10_000;
176
+
177
+ /**
178
+ * How long `disconnect()` waits for the server to acknowledge its goodbye
179
+ * unless told otherwise: the acknowledgement is a courtesy, and a connection
180
+ * that has already died would otherwise hold it for a full command timeout.
181
+ */
182
+ const DISCONNECT_TIMEOUT_MS = 1_000;
183
+
184
+ /** How long each reconnection attempt may take. */
185
+ const RECONNECT_ATTEMPT_TIMEOUT_MS = 30_000;
186
+
187
+ /** What the trace hooks need to know about one attempt, from its first milestone on. */
188
+ interface AttemptTrace {
189
+ readonly attempt: number;
190
+ readonly reconnect: boolean;
191
+ /** When the address was about to be resolved. */
192
+ readonly startedAt: number;
193
+ /** When the socket was about to be opened. */
194
+ connectStartedAt: number;
195
+ phase: ConnectPhase;
196
+ /** The `host:port` being dialled; empty until the address is resolved. */
197
+ target: string;
198
+ sessionStarted: boolean;
199
+ welcomeDone: boolean;
200
+ /** The channel rows the welcome sequence has delivered so far. */
201
+ channels: number;
202
+ }
203
+
204
+ /** A session that began with `sessionStart`, until its `sessionEnd`. */
205
+ interface TracedSession {
206
+ readonly clientID: ClientID;
207
+ readonly startedAt: number;
208
+ readonly attempt: number;
209
+ readonly reconnect: boolean;
210
+ }
211
+
212
+ /** The `initserver` parameters a trace never sees, because they could carry a secret. */
213
+ const SECRET_INITSERVER_PARAMS: ReadonlySet<string> = new Set([
214
+ "client_server_password",
215
+ "client_default_channel_password",
216
+ "client_default_token",
217
+ "client_key_offset",
218
+ ]);
219
+
220
+ /**
221
+ * One connection attempt, settled once by the handshake or its failure.
222
+ *
223
+ * The settling is also what makes the trace's promise true: `sessionStart`
224
+ * is fired by whoever settles it as connected and `attemptFailed` by `reject`
225
+ * and `rejectAfter`, all behind the one `settled` flag, so an attempt gets
226
+ * exactly one of them.
227
+ */
228
+ interface ConnectAttempt {
229
+ readonly promise: Promise<void>;
230
+ /**
231
+ * Aborted when the attempt fails, is abandoned, or is interrupted by
232
+ * disconnect(), so the address lookup and the socket being opened for it
233
+ * stop too instead of finishing a connection nobody wants.
234
+ */
235
+ readonly signal: AbortSignal;
236
+ settled: boolean;
237
+ /** The trace state, once the attempt has started. */
238
+ trace: AttemptTrace | undefined;
239
+ /** Called once, if the attempt settles as failed. */
240
+ onFail: ((error: unknown) => void) | undefined;
241
+ resolve(): void;
242
+ reject(error: unknown): void;
243
+ /**
244
+ * Settle the attempt as failed now, which stops its lookup and socket, but
245
+ * reject its promise only once `until` settles: disconnect() holds it until
246
+ * `disconnected` has been delivered, so a caller that awaits disconnect()
247
+ * before the connect() it interrupted still hears that reject in time.
248
+ */
249
+ rejectAfter(error: unknown, until: Promise<unknown>): void;
250
+ }
251
+
252
+ function newConnectAttempt(): ConnectAttempt {
253
+ let resolve!: () => void;
254
+ let reject!: (error: unknown) => void;
255
+ const promise = new Promise<void>((res, rej) => {
256
+ resolve = res;
257
+ reject = rej;
258
+ });
259
+ // The failure is reported to whoever awaits connect(); an attempt nobody
260
+ // awaits any more must not surface as an unhandled rejection.
261
+ promise.catch(() => {});
262
+ const controller = new AbortController();
263
+ const attempt: ConnectAttempt = {
264
+ promise,
265
+ signal: controller.signal,
266
+ settled: false,
267
+ trace: undefined,
268
+ onFail: undefined,
269
+ resolve() {
270
+ if (attempt.settled) return;
271
+ attempt.settled = true;
272
+ resolve();
273
+ },
274
+ reject(error) {
275
+ if (attempt.settled) return;
276
+ attempt.settled = true;
277
+ attempt.onFail?.(error);
278
+ controller.abort(error);
279
+ reject(error);
280
+ },
281
+ rejectAfter(error, until) {
282
+ if (attempt.settled) return;
283
+ attempt.settled = true;
284
+ attempt.onFail?.(error);
285
+ controller.abort(error);
286
+ void until.finally(() => reject(error));
287
+ },
288
+ };
289
+ return attempt;
290
+ }
291
+
292
+ /**
293
+ * Voice deliveries are dropped while more than this many deliveries of any
294
+ * kind are waiting: audio is fifty packets a second per speaker, and a
295
+ * listener that cannot keep up would otherwise queue it without bound.
296
+ */
297
+ const MAX_PENDING_DELIVERIES = 256;
298
+
299
+ /** How often dropped voice is reported, at most. */
300
+ const VOICE_DROP_WARN_INTERVAL_MS = 10_000;
301
+
302
+ /** The only commands handled before crypto init completes. */
303
+ const PRE_INIT_COMMANDS: ReadonlySet<string> = new Set(["clientinitiv", "initivexpand2", "error"]);
304
+
305
+ interface Subscription {
306
+ readonly listener: (payload: unknown) => void;
307
+ removed: boolean;
308
+ }
309
+
310
+ /**
311
+ * A TeamSpeak client over the voice protocol.
312
+ *
313
+ * Listeners run one at a time, in the order their events arrived, after the
314
+ * packet that carried them has been handled, so a listener may call the client
315
+ * and await an answer.
316
+ */
317
+ export class Client implements CommandExecutor, AsyncDisposable {
318
+ static {
319
+ internalsOf = (client) => client.#internals;
320
+ }
321
+
322
+ #crypt: Crypt;
323
+ #handler: PacketHandler;
324
+ #logger: Logger;
325
+ #nickname: string;
326
+ #clid = 0;
327
+ /**
328
+ * What the server reported about itself in initserver, including the UID
329
+ * hash it uses: TS3 hashes the public key with SHA-1 and TS6 with SHA-256.
330
+ */
331
+ #capabilities: ServerCapabilities = unknownServerCapabilities();
332
+ #internals: ClientInternals;
333
+
334
+ #identity: Identity;
335
+ #addr: string;
336
+ #resolver: AddrResolver;
337
+ #clientInitOptions: ClientInitOptions;
338
+ #socketFactory: SocketFactory | undefined;
339
+ #fileTransferSocketFactory: FileTransferSocketFactory | undefined;
340
+ /** A copy of the caller's trace, so changing theirs later changes nothing. */
341
+ #trace: ClientTrace | undefined;
342
+ /** The session in progress, for its `sessionEnd`; cleared when that has been reported. */
343
+ #session: TracedSession | undefined;
344
+ /** Undefined when the client does not reconnect. */
345
+ #reconnectOptions: ReconnectOptions | undefined;
346
+ /**
347
+ * Set while a reconnect attempt is in flight, so overlapping failures do not
348
+ * start competing loops.
349
+ */
350
+ #reconnecting = false;
351
+ /** The reconnect loop's latest attempt; 0 while it has made none. */
352
+ #loopAttempt = 0;
353
+ /** The last answer of `shouldRetry`, so that one failure asks it once. */
354
+ #retryAnswer:
355
+ | {
356
+ readonly err: Error;
357
+ readonly attempt: number;
358
+ readonly retry: boolean;
359
+ readonly threw: boolean;
360
+ }
361
+ | undefined;
362
+ /**
363
+ * Why the last established session dropped: a reconnect loop whose own
364
+ * attempt connected and then dropped before the loop resumed retries for it.
365
+ */
366
+ #lastDrop: Error | undefined;
367
+ /** Set by an explicit disconnect(), which must never be undone by a retry. */
368
+ #stopped = false;
369
+ /**
370
+ * The goodbye of a disconnect() still in progress, which a connect() waits
371
+ * for: tearing the old session down after a new one has started would end
372
+ * the new one instead.
373
+ */
374
+ #leaving: Promise<void> | undefined;
375
+ /** Ends a disconnect()'s wait for its goodbye to be answered, while it waits. */
376
+ #goodbyeAnswered: (() => void) | undefined;
377
+ /** How many times disconnect() was called, so a waiting connect() sees one. */
378
+ #disconnects = 0;
379
+ /**
380
+ * Settles once the last queued `disconnected` has been delivered. A
381
+ * connect() waits for it, so the end of one session is never heard during
382
+ * the next: not by a listener added for the new session, and not by an
383
+ * events() iterator started for it.
384
+ */
385
+ #disconnectedDelivered: Promise<void> | undefined;
386
+ /** Cuts short the reconnect loop's wait, on disconnect(). */
387
+ #stopReconnecting: AbortController | undefined;
388
+ #status: ClientStatus = ClientStatus.Disconnected;
389
+ #throttle = new CommandThrottle();
390
+ #cmdTrack = new CommandTracker(() => this.#clid);
391
+ #clients = new Map<number, ClientEnterEvent>();
392
+ #attempt: ConnectAttempt = newConnectAttempt();
393
+
394
+ #listeners = new Map<keyof EventMap, Subscription[]>();
395
+ /** Deliveries waiting for their turn; see #emit. */
396
+ #queue: Array<() => void> = [];
397
+ #draining = false;
398
+ #voiceDropped = 0;
399
+ #voiceDropWarnedAt = -Infinity;
400
+
401
+ #eventMiddlewares: readonly EventMiddleware[];
402
+ #send: CommandExecutor["send"];
403
+ #eventChain: (event: ServerEvent) => void;
404
+
405
+ constructor(identity: Identity, addr: string, nickname: string, options: ClientOptions = {}) {
406
+ this.#identity = identity;
407
+ this.#addr = addr;
408
+ this.#nickname = nickname;
409
+ this.#logger = options.logger ?? noopLogger;
410
+ this.#resolver = options.resolver ?? new Resolver({ nicknameLookup: options.nicknameLookup });
411
+ this.#clientInitOptions = normalizeClientInitOptions(options);
412
+ this.#socketFactory = options.socketFactory;
413
+ this.#fileTransferSocketFactory = options.fileTransferSocketFactory;
414
+ this.#reconnectOptions = options.reconnect;
415
+ this.#trace = options.trace === undefined ? undefined : { ...options.trace };
416
+
417
+ this.#crypt = new Crypt(identity);
418
+ this.#handler = this.#newHandler();
419
+
420
+ // oxlint-disable-next-line no-this-alias -- accessors cannot be arrow functions
421
+ const self = this;
422
+ this.#internals = {
423
+ get crypt() {
424
+ return self.#crypt;
425
+ },
426
+ get handler() {
427
+ return self.#handler;
428
+ },
429
+ get logger() {
430
+ return self.#logger;
431
+ },
432
+ get initOptions() {
433
+ return self.#clientInitOptions;
434
+ },
435
+ get nickname() {
436
+ return self.#nickname;
437
+ },
438
+ set nickname(value) {
439
+ self.#nickname = value;
440
+ },
441
+ get clid() {
442
+ return self.#clid;
443
+ },
444
+ set clid(value) {
445
+ self.#clid = value;
446
+ },
447
+ get capabilities() {
448
+ return self.#capabilities;
449
+ },
450
+ set capabilities(value) {
451
+ self.#capabilities = value;
452
+ },
453
+ markConnected: (initServer) => this.#markConnected(initServer),
454
+ markHandshakeDone: (serverPublicKey) => this.#markHandshakeDone(serverPublicKey),
455
+ execNoWait: (command) => this.#execNoWait(command, undefined, true),
456
+ handlePacket: (packet) => this.#handlePacket(packet),
457
+ };
458
+
459
+ // Built once: the chains are read on every command and event, and
460
+ // changing them while those run would make the behaviour depend on timing.
461
+ const cmdMiddlewares: readonly CommandMiddleware[] = options.commandMiddleware ?? [];
462
+ this.#eventMiddlewares = options.eventMiddleware ?? [];
463
+ this.#send = buildCommandChain(cmdMiddlewares, (request, commandOptions = {}) =>
464
+ this.#exec(encodeRequest(request, prepareClientPassword), commandOptions, false),
465
+ );
466
+ this.#eventChain = buildEventChain([...this.#eventMiddlewares], (event) =>
467
+ this.#deliver(event.name, event.payload),
468
+ );
469
+ }
470
+
471
+ /** Where the client is in its connection's life. */
472
+ get status(): ClientStatus {
473
+ return this.#status;
474
+ }
475
+
476
+ // ---- Connection -----------------------------------------------------------
477
+
478
+ /**
479
+ * Connect to the server. Resolves once the handshake completes.
480
+ *
481
+ * An address that cannot be one — no host, a port outside 1–65535 — rejects
482
+ * with an InvalidAddressError at once, before anything starts. A host name
483
+ * that does not resolve fails the attempt with a TeamspeakError whose
484
+ * `cause` is the lookup's error.
485
+ *
486
+ * A failed attempt rejects with its cause, such as the server's error for a
487
+ * rejected password. Aborting `signal` abandons the attempt and rejects with
488
+ * the signal's reason. The signal bounds only the connecting: once this
489
+ * resolves, the connection lasts until `disconnect()` or a drop.
490
+ * `connect()` does not retry; the `reconnect` option only retries a
491
+ * connection that drops after it was established.
492
+ *
493
+ * Called while a `disconnect()` is still saying goodbye, or while an earlier
494
+ * session's `disconnected` is still waiting to be delivered, this waits for
495
+ * that first, so the old session is closed, and its `disconnected`
496
+ * delivered, before the new one starts: no listener or `events()` iterator
497
+ * of the new session hears the old one end. A `disconnect()` called during
498
+ * that wait wins: this then rejects with a NotConnectedError.
499
+ *
500
+ * `connected` is delivered after this resolves, so a listener added right
501
+ * after `await client.connect()` still hears it.
502
+ */
503
+ async connect(options: { readonly signal?: AbortSignal | undefined } = {}): Promise<void> {
504
+ return this.#connect(options, 1, false);
505
+ }
506
+
507
+ async #connect(
508
+ options: { readonly signal?: AbortSignal | undefined },
509
+ attemptNumber: number,
510
+ reconnect: boolean,
511
+ ): Promise<void> {
512
+ const { signal } = options;
513
+ signal?.throwIfAborted();
514
+ const disconnects = this.#disconnects;
515
+ if (this.#leaving !== undefined) await abortable(this.#leaving, signal);
516
+ while (this.#disconnectedDelivered !== undefined) {
517
+ await abortable(this.#disconnectedDelivered, signal);
518
+ }
519
+ if (this.#disconnects !== disconnects) throw new NotConnectedError();
520
+ if (this.#status !== ClientStatus.Disconnected) throw new AlreadyConnectedError();
521
+ // Checked before anything changes: an address that can never work leaves
522
+ // the client as it was, with no attempt to announce the end of.
523
+ parseConnectAddress(this.#addr);
524
+ this.#stopped = false;
525
+
526
+ this.#resetForConnect();
527
+ this.#status = ClientStatus.Connecting;
528
+ const attempt = this.#attempt;
529
+ const trace: AttemptTrace = {
530
+ attempt: attemptNumber,
531
+ reconnect,
532
+ startedAt: performance.now(),
533
+ connectStartedAt: 0,
534
+ phase: ConnectPhase.Open,
535
+ target: "",
536
+ sessionStarted: false,
537
+ welcomeDone: false,
538
+ channels: 0,
539
+ };
540
+ attempt.trace = trace;
541
+ attempt.onFail = (error) =>
542
+ this.#callHook(this.#trace?.attemptFailed, () => ({
543
+ attempt: trace.attempt,
544
+ reconnect: trace.reconnect,
545
+ phase: trace.phase,
546
+ error,
547
+ target: trace.target,
548
+ durationMs: performance.now() - trace.startedAt,
549
+ }));
550
+
551
+ // The handshake may complete just as the signal fires, in which case
552
+ // #failConnection leaves the session alone and the caller gets the
553
+ // connection it made rather than one it would believe had failed.
554
+ const onAbort = (): void => this.#failConnection(abortReason(signal!));
555
+ signal?.addEventListener("abort", onAbort, { once: true });
556
+ try {
557
+ try {
558
+ this.#callHook(this.#trace?.resolveStart, () => ({
559
+ attempt: trace.attempt,
560
+ reconnect: trace.reconnect,
561
+ addr: this.#addr,
562
+ }));
563
+ const resolveStarted = performance.now();
564
+ const resolution = await this.#resolveAddr(attempt.signal);
565
+ const targetAddr = resolution.target;
566
+ trace.target = targetAddr;
567
+ if (!attempt.settled) {
568
+ this.#callHook(this.#trace?.resolveDone, () => ({
569
+ attempt: trace.attempt,
570
+ reconnect: trace.reconnect,
571
+ addr: this.#addr,
572
+ target: targetAddr,
573
+ source: resolution.source,
574
+ candidates: resolution.candidates,
575
+ error: resolution.error,
576
+ durationMs: performance.now() - resolveStarted,
577
+ }));
578
+ }
579
+ if (!attempt.settled) {
580
+ this.#logger.info("connecting to server", { address: targetAddr });
581
+ trace.connectStartedAt = performance.now();
582
+ this.#callHook(this.#trace?.connectStart, () => ({
583
+ attempt: trace.attempt,
584
+ reconnect: trace.reconnect,
585
+ target: targetAddr,
586
+ }));
587
+ }
588
+ if (!attempt.settled) {
589
+ await this.#handler.connect(targetAddr, attempt.signal);
590
+ // The socket is open and the first packet is out: a failure from
591
+ // here to the shared secret is the handshake's.
592
+ if (trace.phase === ConnectPhase.Open) trace.phase = ConnectPhase.Handshake;
593
+ }
594
+ } catch (error) {
595
+ // Without this the client stays Connecting and every later connect()
596
+ // fails with AlreadyConnectedError.
597
+ this.#failConnection(error);
598
+ }
599
+ await attempt.promise;
600
+ } finally {
601
+ signal?.removeEventListener("abort", onAbort);
602
+ }
603
+ }
604
+
605
+ /**
606
+ * Leave the server and close the connection.
607
+ *
608
+ * Says goodbye first, waiting for the server's acknowledgement for a second
609
+ * at most, or less if `signal` aborts sooner. The connection is closed
610
+ * either way. A `connect()` still waiting for its handshake rejects with a
611
+ * NotConnectedError, and so do the commands still waiting for an answer.
612
+ * Resolves once `disconnected` has been delivered to the listeners, so one
613
+ * added after `await client.disconnect()` does not hear it. Does nothing on
614
+ * a client that is not connected; called again while an earlier call is
615
+ * still saying goodbye, it waits for that one.
616
+ */
617
+ async disconnect(options: { readonly signal?: AbortSignal | undefined } = {}): Promise<void> {
618
+ // Recorded before anything else: a dropped socket during the goodbye below
619
+ // must not be mistaken for an outage worth retrying.
620
+ this.#stopped = true;
621
+ this.#disconnects++;
622
+ this.#stopReconnecting?.abort();
623
+
624
+ if (this.#leaving !== undefined) return this.#leaving;
625
+ // Already ended, by a drop or a failed attempt: its `disconnected` may
626
+ // still be on its way.
627
+ if (this.#status === ClientStatus.Disconnected) return this.#disconnectedDelivered;
628
+
629
+ const wasConnected = this.#status === ClientStatus.Connected;
630
+ this.#status = ClientStatus.Disconnected;
631
+ let left!: () => void;
632
+ this.#attempt.rejectAfter(new NotConnectedError(), new Promise<void>((r) => (left = r)));
633
+
634
+ const leaving = this.#leave(wasConnected, options.signal).finally(left);
635
+ this.#leaving = leaving;
636
+ try {
637
+ await leaving;
638
+ } finally {
639
+ this.#leaving = undefined;
640
+ }
641
+ }
642
+
643
+ async #leave(wasConnected: boolean, signal: AbortSignal | undefined): Promise<void> {
644
+ this.#logger.info("disconnecting from server");
645
+
646
+ if (wasConnected) {
647
+ this.#callHook(this.#trace?.disconnectStart, () => ({}));
648
+ const goodbyeStarted = performance.now();
649
+ // The server answers clientdisconnect with a notifyclientleftview about
650
+ // this client, and no error line; either one ends the wait. A goodbye
651
+ // that is not answered in time is a courtesy lost: the connection
652
+ // closes regardless.
653
+ const left = new Promise<boolean>((resolve) => {
654
+ this.#goodbyeAnswered = () => resolve(true);
655
+ });
656
+ // On the internal path: the status already says Disconnected.
657
+ const answered = this.#exec(
658
+ "clientdisconnect reasonmsg=Shutdown",
659
+ { signal, timeoutMs: DISCONNECT_TIMEOUT_MS },
660
+ true,
661
+ ).then(
662
+ () => true,
663
+ () => false,
664
+ );
665
+ const acknowledged = await Promise.race([answered, left]);
666
+ this.#goodbyeAnswered = undefined;
667
+ this.#callHook(this.#trace?.disconnectDone, () => ({
668
+ acknowledged,
669
+ durationMs: performance.now() - goodbyeStarted,
670
+ }));
671
+ }
672
+
673
+ this.#handler.close();
674
+ this.#cmdTrack.reset(new NotConnectedError());
675
+ this.#endSession(undefined);
676
+ // Announced here; #handleConnectionClosed stays quiet once the status is
677
+ // already Disconnected, so listeners hear about it once.
678
+ await this.#announceDisconnected(undefined, false);
679
+ }
680
+
681
+ /** `await using client = …` disconnects when the scope ends. */
682
+ [Symbol.asyncDispose](): Promise<void> {
683
+ return this.disconnect();
684
+ }
685
+
686
+ // ---- Commands ------------------------------------------------------------
687
+
688
+ /**
689
+ * Send a raw command line and return the rows that answer it: the escape
690
+ * hatch for a command the typed functions do not cover. The line is sent as
691
+ * given, so its values must already be escaped and any channel password
692
+ * already hashed. `CommandName` lists the command names.
693
+ *
694
+ * Rejects with a NotConnectedError unless the client is connected: while it
695
+ * is still connecting, the session's keys may not exist yet.
696
+ */
697
+ // oxlint-disable-next-line typescript/array-type -- the public API report spells this `[]`; respelling it changes the report
698
+ exec(command: string, options: CommandOptions = {}): Promise<Record<string, string>[]> {
699
+ return this.#exec(command, options, false);
700
+ }
701
+
702
+ /**
703
+ * Send a raw command line without waiting for an answer, for the few
704
+ * commands the server answers with nothing at all. `CommandName` lists
705
+ * the command names.
706
+ *
707
+ * Commands are paced by a flood throttle; aborting `signal` while this waits
708
+ * for its turn rejects with the signal's reason and sends nothing. Rejects
709
+ * with a NotConnectedError unless the client is connected.
710
+ */
711
+ execNoWait(
712
+ command: string,
713
+ options: { readonly signal?: AbortSignal | undefined } = {},
714
+ ): Promise<void> {
715
+ return this.#execNoWait(command, options.signal, false);
716
+ }
717
+
718
+ /**
719
+ * Whether a command may go out now. The handshake's own commands (`internal`)
720
+ * need only an open socket; everything else needs a connected session, so
721
+ * nothing a caller sends can go out under the public dummy key, or after
722
+ * disconnect() has begun saying goodbye.
723
+ */
724
+ #canSend(internal: boolean): boolean {
725
+ return this.#handler.isOpen && (internal || this.#status === ClientStatus.Connected);
726
+ }
727
+
728
+ async #execNoWait(
729
+ command: string,
730
+ signal: AbortSignal | undefined,
731
+ internal: boolean,
732
+ ): Promise<void> {
733
+ signal?.throwIfAborted();
734
+ if (!this.#canSend(internal)) throw new NotConnectedError();
735
+ await this.#throttle.wait(signal);
736
+ if (!this.#canSend(internal)) throw new NotConnectedError();
737
+ this.#sendLine(command);
738
+ }
739
+
740
+ /**
741
+ * Send a typed command; this is the CommandExecutor the typed commands run on.
742
+ *
743
+ * The request passes through the `commandMiddleware` first. Channel
744
+ * passwords are then hashed, because that is this protocol's rule: the voice
745
+ * protocol expects `base64(sha1(password))`, where ServerQuery takes the
746
+ * password itself.
747
+ */
748
+ // oxlint-disable-next-line typescript/array-type -- the public API report spells this `[]`; respelling it changes the report
749
+ send(request: CommandRequest, options: CommandOptions = {}): Promise<Record<string, string>[]> {
750
+ return this.#send(request, options);
751
+ }
752
+
753
+ #sendLine(line: string): void {
754
+ const hook = sentLineHook;
755
+ if (hook) hook(this, line);
756
+ this.#handler.sendPacket(PacketType.Command, Buffer.from(line), 0);
757
+ }
758
+
759
+ #exec(
760
+ command: string,
761
+ options: CommandOptions,
762
+ internal: boolean,
763
+ ): Promise<Array<Record<string, string>>> {
764
+ if (!commandChannel.hasSubscribers) return this.#execUntraced(command, options, internal);
765
+ const trace: CommandTrace = { command: parseCommand(command)?.name ?? "", client: this };
766
+ return commandChannel.tracePromise(() => this.#execUntraced(command, options, internal), trace);
767
+ }
768
+
769
+ async #execUntraced(
770
+ command: string,
771
+ options: CommandOptions,
772
+ internal: boolean,
773
+ ): Promise<Array<Record<string, string>>> {
774
+ const { signal, timeoutMs = DEFAULT_COMMAND_TIMEOUT_MS } = options;
775
+ signal?.throwIfAborted();
776
+ // A command sent on no socket used to vanish and surface 10 seconds later
777
+ // as a timeout, which reads like a slow server rather than a usage error.
778
+ if (!this.#canSend(internal)) throw new NotConnectedError();
779
+
780
+ // Which notifications answer this command, and — for answers that arrive
781
+ // after the `error` — the request field they echo back.
782
+ const parsed = parseCommand(command);
783
+ const spec = responseSpec(parsed?.name ?? "");
784
+ const key = spec?.correlated?.key;
785
+ const correlation = key === undefined ? undefined : parsed?.params[key];
786
+
787
+ const [rc, answered] = this.#cmdTrack.register(spec, correlation);
788
+ let timer: ReturnType<typeof setTimeout> | undefined;
789
+ let onAbort: (() => void) | undefined;
790
+ // Started before the throttle: the timeout bounds the whole command, its
791
+ // wait for a turn included, and so does the signal.
792
+ const givenUp = new Promise<never>((_, reject) => {
793
+ timer = setTimeout(() => reject(new CommandTimeoutError(parsed?.name ?? "")), timeoutMs);
794
+ onAbort = () => reject(abortReason(signal!));
795
+ signal?.addEventListener("abort", onAbort, { once: true });
796
+ });
797
+ givenUp.catch(() => {});
798
+ const throttleAbort = new AbortController();
799
+ try {
800
+ const withRc = appendReturnCode(command, rc);
801
+ await Promise.race([this.#throttle.wait(throttleAbort.signal), givenUp]);
802
+ if (!this.#canSend(internal)) throw new NotConnectedError();
803
+ this.#sendLine(withRc);
804
+
805
+ const result = await Promise.race([answered, givenUp]);
806
+ if (result.err) throw result.err;
807
+ return result.data;
808
+ } finally {
809
+ // A command given up while it waited for its turn gives the turn back.
810
+ throttleAbort.abort();
811
+ // Cleared, not left to fire: a pending timer keeps the process alive for
812
+ // the full timeout after the last command has long been answered.
813
+ clearTimeout(timer);
814
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
815
+ this.#cmdTrack.unregister(rc);
816
+ }
817
+ }
818
+
819
+ // ---- Events --------------------------------------------------------------
820
+
821
+ /**
822
+ * Listen for an event. Returns a function that removes the listener.
823
+ *
824
+ * The event is named by an {@link EventName} constant or by its string, and
825
+ * the listener's payload type follows from it:
826
+ *
827
+ * ```ts
828
+ * client.on(EventName.TextMessage, (message) => console.log(message.message));
829
+ * ```
830
+ *
831
+ * A listener that throws does not stop the others: the rest of the event's
832
+ * listeners, and the events after it, are still delivered, and the exception
833
+ * is rethrown on its own, from a microtask, so it surfaces as an
834
+ * `uncaughtException` just as an EventEmitter listener's would. An async
835
+ * listener's rejection is not caught, and surfaces as an unhandled
836
+ * rejection.
837
+ */
838
+ on<K extends keyof EventMap>(event: K, listener: Listener<EventMap, K>): Unsubscribe {
839
+ const subscription: Subscription = {
840
+ listener: listener as (payload: unknown) => void,
841
+ removed: false,
842
+ };
843
+ // A new array rather than an edit in place: a delivery may be iterating
844
+ // over the old one.
845
+ this.#listeners.set(event, [...(this.#listeners.get(event) ?? []), subscription]);
846
+
847
+ const unsubscribe = (): void => {
848
+ if (subscription.removed) return;
849
+ subscription.removed = true;
850
+ const list = this.#listeners.get(event) ?? [];
851
+ this.#listeners.set(
852
+ event,
853
+ list.filter((s) => s !== subscription),
854
+ );
855
+ };
856
+ return Object.assign(unsubscribe, { [Symbol.dispose]: unsubscribe });
857
+ }
858
+
859
+ /** Listen for the next occurrence of an event only. */
860
+ once<K extends keyof EventMap>(event: K, listener: Listener<EventMap, K>): Unsubscribe {
861
+ const unsubscribe = this.on(event, ((payload: EventMap[K]) => {
862
+ unsubscribe();
863
+ listener(payload);
864
+ }) as Listener<EventMap, K>);
865
+ return unsubscribe;
866
+ }
867
+
868
+ /**
869
+ * An event as an async iterator, for `for await`:
870
+ *
871
+ * ```ts
872
+ * for await (const message of client.events("textMessage", { signal })) { … }
873
+ * ```
874
+ *
875
+ * Events that arrive while the loop body runs are buffered, so none is
876
+ * missed. The buffer is unbounded: an iterator that is not consumed as fast
877
+ * as events arrive holds every one of them in memory until it is read, so
878
+ * stop iterating (or abort `signal`) when you stop reading. Voice is the
879
+ * exception: at most 256 `voiceData` frames are buffered, and the rest are
880
+ * dropped, as for a listener that falls behind.
881
+ *
882
+ * Iteration ends when the loop exits early (`break`, `return`, a throw), and
883
+ * — for every event but `disconnected` — when the client disconnects. When
884
+ * `signal` aborts, listening stops at once, whatever is buffered is
885
+ * discarded, and the pending and every later `next()` reject with the
886
+ * signal's reason, as `events.on` in Node does.
887
+ *
888
+ * `next()` may be called again before an earlier call has settled; the calls
889
+ * are answered in order.
890
+ */
891
+ events<K extends keyof EventMap>(
892
+ event: K,
893
+ options: { readonly signal?: AbortSignal | undefined } = {},
894
+ ): AsyncIterableIterator<EventMap[K]> {
895
+ const { signal } = options;
896
+ const buffered: Array<EventMap[K]> = [];
897
+ // The next() calls waiting for an event, oldest first.
898
+ const waiting: Array<{
899
+ resolve: (result: IteratorResult<EventMap[K]>) => void;
900
+ reject: (reason: unknown) => void;
901
+ }> = [];
902
+ let ended = false;
903
+ let aborted = false;
904
+
905
+ const finishWaiting = (): void => {
906
+ for (const waiter of waiting.splice(0)) {
907
+ waiter.resolve({ value: undefined, done: true });
908
+ }
909
+ };
910
+
911
+ const stopListening = this.on(event, ((payload: EventMap[K]) => {
912
+ if (ended) return;
913
+ const waiter = waiting.shift();
914
+ if (waiter) {
915
+ waiter.resolve({ value: payload, done: false });
916
+ return;
917
+ }
918
+ if (event === "voiceData" && buffered.length >= MAX_PENDING_DELIVERIES) {
919
+ this.#dropVoice();
920
+ return;
921
+ }
922
+ buffered.push(payload);
923
+ }) as Listener<EventMap, K>);
924
+ // Ends after what is already buffered, which arrived before the disconnect.
925
+ const stopOnDisconnect =
926
+ event === "disconnected"
927
+ ? undefined
928
+ : this.on("disconnected", () => {
929
+ cleanup();
930
+ finishWaiting();
931
+ });
932
+ const cleanup = (): void => {
933
+ ended = true;
934
+ stopListening();
935
+ stopOnDisconnect?.();
936
+ signal?.removeEventListener("abort", abort);
937
+ };
938
+ const abort = (): void => {
939
+ aborted = true;
940
+ buffered.length = 0;
941
+ cleanup();
942
+ const reason = abortReason(signal!);
943
+ for (const waiter of waiting.splice(0)) waiter.reject(reason);
944
+ };
945
+ if (signal?.aborted) abort();
946
+ else signal?.addEventListener("abort", abort, { once: true });
947
+
948
+ const iterator: AsyncIterableIterator<EventMap[K]> = {
949
+ next(): Promise<IteratorResult<EventMap[K]>> {
950
+ if (aborted) return Promise.reject(abortReason(signal!));
951
+ if (buffered.length > 0) return Promise.resolve({ value: buffered.shift()!, done: false });
952
+ if (ended) {
953
+ cleanup();
954
+ return Promise.resolve({ value: undefined, done: true });
955
+ }
956
+ return new Promise((resolve, reject) => waiting.push({ resolve, reject }));
957
+ },
958
+ return(): Promise<IteratorResult<EventMap[K]>> {
959
+ buffered.length = 0;
960
+ cleanup();
961
+ finishWaiting();
962
+ return Promise.resolve({ value: undefined, done: true });
963
+ },
964
+ [Symbol.asyncIterator]() {
965
+ return iterator;
966
+ },
967
+ };
968
+ return iterator;
969
+ }
970
+
971
+ // ---- API shorthand -------------------------------------------------------
972
+
973
+ /** This client's id on the server, assigned in the handshake; 0 before it. */
974
+ get clientID(): ClientID {
975
+ return asClientID(this.#clid);
976
+ }
977
+
978
+ /**
979
+ * What the connected server is: version, generation, and the uid hash it
980
+ * uses. Read from `initserver`; before connecting the family is `unknown`
981
+ * and the uid hash SHA-1.
982
+ */
983
+ get serverCapabilities(): ServerCapabilities {
984
+ return this.#capabilities;
985
+ }
986
+
987
+ /**
988
+ * Our own `client_unique_identifier`, hashed with the algorithm the connected
989
+ * server uses.
990
+ *
991
+ * TS3 uses SHA-1 and TS6 SHA-256, so this reads the algorithm learned during
992
+ * initserver rather than assuming one. Comparing a hard-coded SHA-1 UID to a
993
+ * TS6 server silently never matches.
994
+ */
995
+ get uid(): UID {
996
+ return this.#identity.uid(this.#capabilities.uidAlgorithm);
997
+ }
998
+
999
+ /** The channel this client is in, as it last learned; 0 before connecting. */
1000
+ get channelID(): ChannelID {
1001
+ return this.#clients.get(this.#clid)?.channelID ?? asChannelID(0n);
1002
+ }
1003
+
1004
+ /**
1005
+ * Send Opus voice directly to specific clients, bypassing channel routing.
1006
+ * Throws a NotConnectedError unless the client is connected, and a
1007
+ * RangeError for no target, more than 32, or an id that is not a client id.
1008
+ */
1009
+ sendWhisper(data: Uint8Array, targets: WhisperTargets, codec: Codec): void {
1010
+ if (!this.#canSend(false)) throw new NotConnectedError();
1011
+ this.#handler.sendWhisperPacket(data, [...(targets.clients ?? [])], codec);
1012
+ }
1013
+
1014
+ /**
1015
+ * Send one encoded audio frame to the channel this client is in. Throws a
1016
+ * NotConnectedError unless the client is connected.
1017
+ */
1018
+ sendVoice(data: Uint8Array, codec: Codec, options?: VoiceOptions): void {
1019
+ // Reserved: VoiceOptions has no fields to read yet.
1020
+ void options;
1021
+ if (!this.#canSend(false)) throw new NotConnectedError();
1022
+ this.#handler.sendVoicePacket(data, codec);
1023
+ }
1024
+
1025
+ // ---- File Transfer -------------------------------------------------------
1026
+
1027
+ /**
1028
+ * Upload `data` over a negotiated transfer, through the client's
1029
+ * `fileTransferSocketFactory` if it has one.
1030
+ */
1031
+ uploadFileData(
1032
+ host: string,
1033
+ info: FileUploadInfo,
1034
+ data: Readable,
1035
+ options: Pick<FileTransferOptions, "signal" | "trace"> = {},
1036
+ ): Promise<void> {
1037
+ return uploadFileData(host, info, data, {
1038
+ ...options,
1039
+ socketFactory: this.#fileTransferSocketFactory,
1040
+ });
1041
+ }
1042
+
1043
+ /**
1044
+ * Download a negotiated transfer into `dest`, through the client's
1045
+ * `fileTransferSocketFactory` if it has one.
1046
+ */
1047
+ downloadFileData(
1048
+ host: string,
1049
+ info: FileDownloadInfo,
1050
+ dest: Writable,
1051
+ options: Pick<FileTransferOptions, "signal" | "trace"> = {},
1052
+ ): Promise<void> {
1053
+ return downloadFileData(host, info, dest, {
1054
+ ...options,
1055
+ socketFactory: this.#fileTransferSocketFactory,
1056
+ });
1057
+ }
1058
+
1059
+ // ---- Internal (package-visible) ------------------------------------------
1060
+
1061
+ #markConnected(initServer: Readonly<Record<string, string>> = {}): void {
1062
+ // Only the attempt in progress can complete: never one that disconnect()
1063
+ // or a failure has already ended.
1064
+ if (this.#status !== ClientStatus.Connecting || this.#attempt.settled) return;
1065
+ this.#status = ClientStatus.Connected;
1066
+ // Settled before the hook runs, so that nothing it does can turn this
1067
+ // attempt into a failed one; connect() resumes only after the hook returns.
1068
+ this.#attempt.resolve();
1069
+ const trace = this.#attempt.trace;
1070
+ if (trace !== undefined) {
1071
+ trace.sessionStarted = true;
1072
+ this.#session = {
1073
+ clientID: asClientID(this.#clid),
1074
+ startedAt: performance.now(),
1075
+ attempt: trace.attempt,
1076
+ reconnect: trace.reconnect,
1077
+ };
1078
+ this.#callHook(this.#trace?.sessionStart, () => {
1079
+ const safe: Record<string, string> = {};
1080
+ for (const [key, value] of Object.entries(initServer)) {
1081
+ if (!SECRET_INITSERVER_PARAMS.has(key)) safe[key] = value;
1082
+ }
1083
+ const talkPower = Number.parseInt(initServer["client_talk_power"] ?? "", 10);
1084
+ return {
1085
+ attempt: trace.attempt,
1086
+ reconnect: trace.reconnect,
1087
+ clientID: asClientID(this.#clid),
1088
+ nickname: initServer["acn"] ?? this.#nickname,
1089
+ talkPower: Number.isNaN(talkPower) ? 0 : talkPower,
1090
+ initServer: Object.freeze(safe),
1091
+ capabilities: this.#capabilities,
1092
+ durationMs: performance.now() - trace.connectStartedAt,
1093
+ };
1094
+ });
1095
+ }
1096
+ this.#emit("connected", { reconnected: trace?.reconnect ?? false });
1097
+ }
1098
+
1099
+ /** The socket is open: the attempt's handshake begins. */
1100
+ #markConnectDone(socket: DatagramSocket): void {
1101
+ const trace = this.#attempt.trace;
1102
+ if (trace === undefined || this.#attempt.settled || trace.phase !== ConnectPhase.Open) return;
1103
+ trace.phase = ConnectPhase.Handshake;
1104
+ this.#callHook(this.#trace?.connectDone, () => {
1105
+ let localAddr = "";
1106
+ try {
1107
+ const local = socket.address?.();
1108
+ if (local !== undefined) localAddr = joinHostPort(local.address, String(local.port));
1109
+ } catch {
1110
+ // A socket that cannot say where it is bound has no local address to report.
1111
+ }
1112
+ return {
1113
+ attempt: trace.attempt,
1114
+ reconnect: trace.reconnect,
1115
+ target: trace.target,
1116
+ localAddr,
1117
+ durationMs: performance.now() - trace.connectStartedAt,
1118
+ };
1119
+ });
1120
+ }
1121
+
1122
+ #markHandshakeDone(serverPublicKey = ""): void {
1123
+ const trace = this.#attempt.trace;
1124
+ if (trace === undefined || this.#attempt.settled || trace.phase !== ConnectPhase.Handshake) {
1125
+ return;
1126
+ }
1127
+ trace.phase = ConnectPhase.Join;
1128
+ this.#callHook(this.#trace?.handshakeDone, () => {
1129
+ const puzzle = puzzleOf(this.#crypt);
1130
+ return {
1131
+ attempt: trace.attempt,
1132
+ reconnect: trace.reconnect,
1133
+ durationMs: performance.now() - trace.connectStartedAt,
1134
+ puzzleLevel: puzzle.level,
1135
+ puzzleDurationMs: puzzle.durationMs,
1136
+ // The handler is this attempt's own, so its count starts at the socket.
1137
+ resends: this.#handler.resends,
1138
+ serverPublicKey,
1139
+ };
1140
+ });
1141
+ }
1142
+
1143
+ #markWelcomeDone(): void {
1144
+ const trace = this.#attempt.trace;
1145
+ if (trace === undefined || !trace.sessionStarted || trace.welcomeDone) return;
1146
+ if (this.#status !== ClientStatus.Connected) return;
1147
+ trace.welcomeDone = true;
1148
+ this.#callHook(this.#trace?.welcomeDone, () => ({
1149
+ attempt: trace.attempt,
1150
+ reconnect: trace.reconnect,
1151
+ channelID: this.channelID,
1152
+ channels: trace.channels,
1153
+ clients: this.#clients.size,
1154
+ durationMs: performance.now() - trace.connectStartedAt,
1155
+ }));
1156
+ }
1157
+
1158
+ /** Report the end of the session in progress, once. */
1159
+ #endSession(error: unknown): void {
1160
+ const session = this.#session;
1161
+ if (session === undefined) return;
1162
+ this.#session = undefined;
1163
+ this.#callHook(this.#trace?.sessionEnd, () => ({
1164
+ clientID: session.clientID,
1165
+ error,
1166
+ durationMs: performance.now() - session.startedAt,
1167
+ attempt: session.attempt,
1168
+ reconnect: session.reconnect,
1169
+ }));
1170
+ }
1171
+
1172
+ /**
1173
+ * Call a trace hook, if there is one, and never let it touch the
1174
+ * connection: see callHook. The info is built only when there is a hook.
1175
+ */
1176
+ #callHook<I>(hook: ((info: I) => unknown) | undefined, info: () => I): void {
1177
+ callHook(hook, this.#trace, info);
1178
+ }
1179
+
1180
+ // ---- Private -------------------------------------------------------------
1181
+
1182
+ #newHandler(): PacketHandler {
1183
+ const handler = new PacketHandler(this.#crypt, this.#logger, this.#socketFactory);
1184
+ // Each callback checks that its handler is still the current one: a
1185
+ // packet or close reported late by one a later connect() already replaced
1186
+ // must not reach, or tear down, the new connection.
1187
+ handler.onPacket = (p) => {
1188
+ if (handler === this.#handler) this.#handlePacket(p);
1189
+ };
1190
+ handler.onClosed = (err) => {
1191
+ if (handler === this.#handler) this.#handleConnectionClosed(err);
1192
+ };
1193
+ handler.onOpen = (socket) => {
1194
+ if (handler === this.#handler) this.#markConnectDone(socket);
1195
+ };
1196
+ handler.onReceiveError = (error) => {
1197
+ if (handler === this.#handler) this.#handleReceiveError(error);
1198
+ };
1199
+ return handler;
1200
+ }
1201
+
1202
+ #resetForConnect(): void {
1203
+ this.#handler.close();
1204
+ this.#crypt = new Crypt(this.#identity);
1205
+ this.#handler = this.#newHandler();
1206
+ this.#attempt = newConnectAttempt();
1207
+ this.#cmdTrack.reset(new NotConnectedError());
1208
+ this.#clients.clear();
1209
+ this.#clid = 0;
1210
+ this.#capabilities = unknownServerCapabilities();
1211
+ }
1212
+
1213
+ async #resolveAddr(signal: AbortSignal): Promise<{
1214
+ target: string;
1215
+ source: string;
1216
+ candidates: readonly ResolvedAddr[];
1217
+ error: unknown;
1218
+ }> {
1219
+ // Parsed, not tested for a colon: an IPv6 literal has colons and no port.
1220
+ const { host, port } = splitHostPort(this.#addr);
1221
+ const fallback = joinHostPort(host, port);
1222
+ // Every resolver, a custom one too, gets the same budget: past it the
1223
+ // address is used as given. A timer the tests can control, not
1224
+ // AbortSignal.timeout().
1225
+ const budget = new AbortController();
1226
+ const timer = setTimeout(
1227
+ () => budget.abort(new TeamspeakError("address resolution took too long")),
1228
+ RESOLVE_BUDGET_MS,
1229
+ );
1230
+ const lookup = AbortSignal.any([signal, budget.signal]);
1231
+ try {
1232
+ // Raced against the signal: a resolver that ignores it must still not
1233
+ // hold up an attempt that has been given up.
1234
+ const resolved = await abortable(
1235
+ this.#resolver.resolve(this.#addr, { signal: lookup }),
1236
+ lookup,
1237
+ );
1238
+ const first = resolved[0];
1239
+ return {
1240
+ target: first?.addr ?? fallback,
1241
+ source: first?.source ?? "",
1242
+ candidates: resolved,
1243
+ error: undefined,
1244
+ };
1245
+ } catch (error) {
1246
+ signal.throwIfAborted();
1247
+ const reason = budget.signal.aborted ? budget.signal.reason : error;
1248
+ this.#logger.warn("address resolution failed, falling back to direct", {
1249
+ error: String(reason),
1250
+ });
1251
+ return { target: fallback, source: "", candidates: [], error: reason };
1252
+ } finally {
1253
+ clearTimeout(timer);
1254
+ }
1255
+ }
1256
+
1257
+ /**
1258
+ * A datagram from the server could not be handled. During the handshake that
1259
+ * is the connection failing, reported as a HandshakeError with the cause;
1260
+ * once connected, one bad packet is not worth the session, so it is dropped.
1261
+ */
1262
+ #handleReceiveError(error: unknown): void {
1263
+ if (this.#status !== ClientStatus.Connected) {
1264
+ this.#failConnection(
1265
+ error instanceof HandshakeError
1266
+ ? error
1267
+ : new HandshakeError("the handshake failed on a malformed packet", { cause: error }),
1268
+ );
1269
+ return;
1270
+ }
1271
+ this.#logger.debug("dropped a malformed packet", { error: String(error) });
1272
+ }
1273
+
1274
+ #handlePacket(p: Packet): void {
1275
+ const pType = p.typeFlagged & 0x0f;
1276
+ if (pType === 8 /* Init1 */) {
1277
+ if (this.#crypt.cryptoInitComplete) return;
1278
+ const response = processInit1(this.#crypt, p.data);
1279
+ if (response) {
1280
+ this.#handler.sendPacket(PacketType.Init1, response, 0);
1281
+ }
1282
+ return;
1283
+ }
1284
+
1285
+ if ((pType === 0 /* Voice */ || pType === 1) /* VoiceWhisper */ && p.data.length > 5) {
1286
+ this.#handleVoicePacket(p.data);
1287
+ return;
1288
+ }
1289
+
1290
+ if ((pType === 2 /* Command */ || pType === 3) /* CommandLow */ && p.data.length > 0) {
1291
+ this.#handleCommandLines(Buffer.from(p.data).toString("utf8"));
1292
+ }
1293
+ }
1294
+
1295
+ /**
1296
+ * Parse an incoming S2C voice packet.
1297
+ * Format: [VId: u16] [CId: u16] [Codec: u8] [Data: var]
1298
+ */
1299
+ #handleVoicePacket(payload: Uint8Array): void {
1300
+ // Audio arrives fifty times a second per speaker; build no event nobody
1301
+ // will see.
1302
+ if (!this.#listeners.get("voiceData")?.length && this.#eventMiddlewares.length === 0) return;
1303
+ if (this.#queue.length > MAX_PENDING_DELIVERIES) {
1304
+ this.#dropVoice();
1305
+ return;
1306
+ }
1307
+
1308
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
1309
+ const clientId = view.getUint16(2, false);
1310
+ if (clientId === this.#clid) return;
1311
+
1312
+ // Copied: the packet's buffer is reused once this returns, and a listener
1313
+ // runs later.
1314
+ const data = payload.slice(5);
1315
+ this.#emitServerEvent({
1316
+ name: "voiceData",
1317
+ payload: { clientID: asClientID(clientId), codec: payload[4]!, data },
1318
+ });
1319
+ }
1320
+
1321
+ #handleCommandLines(s: string): void {
1322
+ if (!s) return;
1323
+ const lines = s.split("\0").join("\n").split("\n");
1324
+ for (const line of lines) {
1325
+ const trimmed = line.replace(/\r$/, "");
1326
+ if (!trimmed) continue;
1327
+ for (const row of splitCommandRows(trimmed)) {
1328
+ this.#handleCommandStr(row);
1329
+ }
1330
+ }
1331
+ }
1332
+
1333
+ #handleCommandStr(s: string): void {
1334
+ const cmd = parseCommand(s);
1335
+ if (!cmd) return;
1336
+ // Before crypto init a packet needs only the public dummy key, so anyone
1337
+ // on the path could have sent it: nothing but the handshake's own steps,
1338
+ // and an error that may end the attempt, is taken then. A notification
1339
+ // would be a forged event, a row a forged answer.
1340
+ if (!this.#crypt.cryptoInitComplete && !PRE_INIT_COMMANDS.has(cmd.name)) {
1341
+ this.#logger.debug("dropped a command that arrived before crypto init", {
1342
+ command: cmd.name,
1343
+ });
1344
+ return;
1345
+ }
1346
+ if (incomingChannel.hasSubscribers)
1347
+ incomingChannel.publish({ command: cmd.name, client: this });
1348
+
1349
+ // No name means a response row: the server sends data without echoing the
1350
+ // command, so the row belongs to whichever command is awaiting a result.
1351
+ if (cmd.name === "") {
1352
+ if (Object.keys(cmd.params).length > 0) this.#cmdTrack.buffer(cmd.params);
1353
+ return;
1354
+ }
1355
+
1356
+ // `channellistfinished` ends the server's welcome sequence. It carries no
1357
+ // data of its own, so it is the only reliable marker: the guard used to
1358
+ // trip on our own notifycliententerview, which the server sends *in the
1359
+ // middle* of the sequence — the channellist rows after it were then
1360
+ // buffered as if they were the response to the caller's first command,
1361
+ // which is how a channellist could come back with duplicate and empty rows.
1362
+ if (cmd.name === "channellistfinished") {
1363
+ this.#cmdTrack.signalWelcomeComplete();
1364
+ this.#markWelcomeDone();
1365
+ return;
1366
+ }
1367
+
1368
+ if (cmd.name === "channellist") {
1369
+ const trace = this.#attempt.trace;
1370
+ if (trace !== undefined && !trace.welcomeDone) trace.channels++;
1371
+ }
1372
+
1373
+ // The server answers our goodbye by announcing that we left, not with an
1374
+ // error line; that announcement is what disconnect() waits for.
1375
+ if (
1376
+ cmd.name === "notifyclientleftview" &&
1377
+ this.#goodbyeAnswered !== undefined &&
1378
+ cmd.params["clid"] === String(this.#clid)
1379
+ ) {
1380
+ this.#goodbyeAnswered();
1381
+ }
1382
+
1383
+ if (cmd.name.startsWith("notify")) {
1384
+ // Some commands are answered by a notification instead of data rows;
1385
+ // it still goes on to be dispatched as an event, since the same
1386
+ // notification also arrives unprompted.
1387
+ if (this.#cmdTrack.expects(cmd.name)) {
1388
+ this.#cmdTrack.buffer(cmd.params, cmd.name);
1389
+ this.#cmdTrack.offerCorrelated(cmd.name, cmd.params);
1390
+ }
1391
+ const result = handleNotification(cmd, this.#clid, this.#clients);
1392
+ this.#processNotificationResult(result);
1393
+ if (this.#listeners.get("notification")?.length || this.#eventMiddlewares.length > 0) {
1394
+ this.#emitServerEvent({
1395
+ name: "notification",
1396
+ payload: { name: cmd.name, params: { ...cmd.params } },
1397
+ });
1398
+ }
1399
+ return;
1400
+ }
1401
+
1402
+ switch (cmd.name) {
1403
+ // The handshake's steps happen once: repeated after crypto init, they
1404
+ // could only re-key or re-announce a session that is already set up.
1405
+ case "clientinitiv":
1406
+ if (!this.#crypt.cryptoInitComplete) handleHandshakeInitIV(this.#internals, cmd.params);
1407
+ break;
1408
+ case "initivexpand2":
1409
+ if (!this.#crypt.cryptoInitComplete) handleHandshakeExpand2(this.#internals, cmd.params);
1410
+ break;
1411
+ case "initserver":
1412
+ // Only on a session with its keys: before crypto init a packet needs
1413
+ // nothing but the public dummy key, and an initserver taken then would
1414
+ // report a connection whose next command — clientinit with its password
1415
+ // hashes among them — goes out under that dummy key.
1416
+ if (this.#status === ClientStatus.Connecting && this.#crypt.cryptoInitComplete) {
1417
+ handleInitServer(this.#internals, cmd.params);
1418
+ }
1419
+ break;
1420
+ case "error":
1421
+ this.#handleError(cmd.params);
1422
+ break;
1423
+ default:
1424
+ // A named command the SDK does not model. Held under its own name, so
1425
+ // it answers a command only if that command declared it — not merely by
1426
+ // arriving while one is in flight.
1427
+ this.#cmdTrack.buffer(cmd.params, cmd.name);
1428
+ break;
1429
+ }
1430
+ }
1431
+
1432
+ #handleError(params: Record<string, string>): void {
1433
+ const { err, rc } = parseServerError(params);
1434
+ if (rc !== null) {
1435
+ this.#cmdTrack.resolve(rc, err);
1436
+ } else {
1437
+ // No return_code: server is acknowledging an unsolicited command
1438
+ // (welcome-sequence channellist, no-RC commands like clientupdate, etc.).
1439
+ // Discard any rows buffered since the last resolved command.
1440
+ this.#cmdTrack.discardBuffer();
1441
+ }
1442
+
1443
+ // A server error before the welcome sequence finished is the connection
1444
+ // failure itself — a rejected password, or an invalid clientinit parameter.
1445
+ // Report it as the cause instead of leaving the caller with a bare timeout.
1446
+ if (err && this.#status !== ClientStatus.Connected) {
1447
+ this.#failConnection(err);
1448
+ return;
1449
+ }
1450
+
1451
+ // Only a connected session gets here, so only after crypto init: an error
1452
+ // under the public dummy key can fail an attempt, never stop the client.
1453
+ if (err?.code === ErrorCode.ConnectFailedBanned) {
1454
+ this.#logger.warn("banned by the server, closing the connection");
1455
+ setImmediate(() => {
1456
+ this.disconnect().catch(() => {});
1457
+ });
1458
+ }
1459
+ }
1460
+
1461
+ #processNotificationResult(result: NotificationResult): void {
1462
+ switch (result.kind) {
1463
+ case "clientEnter": {
1464
+ const info = result.info;
1465
+ // Identify self by the clid initserver already assigned rather than by
1466
+ // nickname: any other client whose nickname happens to be "<our
1467
+ // nick><digits>" — which is how the server renames a client whose
1468
+ // nickname was taken — would otherwise be mistaken for us, poisoning
1469
+ // every outgoing packet header with a foreign clientID until the server
1470
+ // drops the connection for command-resend timeout.
1471
+ //
1472
+ // This no longer marks the end of the welcome sequence: the server
1473
+ // sends more welcome data after it, and `channellistfinished` is the
1474
+ // real terminator.
1475
+ if (info.id === this.#clid) {
1476
+ // Carries the rename the server applied if our nickname was taken.
1477
+ this.#nickname = info.nickname;
1478
+ } else if (this.#clid === 0 && isAutoNicknameMatch(this.#nickname, info.nickname)) {
1479
+ // initserver carried no aclid, so the welcome enter is the only way
1480
+ // to learn our clid. Gated on clid still being unknown so a later
1481
+ // lookalike can never hijack an established session.
1482
+ this.#clid = info.id;
1483
+ this.#handler.setClientID(info.id);
1484
+ this.#nickname = info.nickname;
1485
+ }
1486
+ this.#emitServerEvent({ name: "clientEnter", payload: info });
1487
+ break;
1488
+ }
1489
+ case "clientLeave": {
1490
+ const event = result.event;
1491
+ this.#emitServerEvent({ name: "clientLeave", payload: event });
1492
+ if (!result.isSelf) break;
1493
+ if (event.reason === Reason.KickServer || event.reason === Reason.KickServerBan) {
1494
+ this.#emit("kicked", kickedEvent(event));
1495
+ }
1496
+ this.#removedByServer(
1497
+ new RemovedError(event.reason, event.reasonMessage, event.invokerName),
1498
+ );
1499
+ break;
1500
+ }
1501
+ case "clientMoved":
1502
+ this.#emitServerEvent({ name: "clientMoved", payload: result.event });
1503
+ // A channel kick moves the client to the default channel; it arrives
1504
+ // as a move, not as leaving view, which is where it used to be looked
1505
+ // for.
1506
+ if (result.event.clientID === this.#clid && result.event.reason === Reason.KickChannel) {
1507
+ this.#emit("kicked", kickedEvent(result.event));
1508
+ }
1509
+ break;
1510
+ case "textMessage":
1511
+ this.#emitServerEvent({ name: "textMessage", payload: result.message });
1512
+ break;
1513
+ case "poked":
1514
+ this.#emitServerEvent({ name: "poked", payload: result.event });
1515
+ break;
1516
+ case "unknown":
1517
+ break;
1518
+ }
1519
+ }
1520
+
1521
+ /**
1522
+ * End a session the server has ended. The server stops answering a client it
1523
+ * has removed, so waiting for the transport to notice reported the end a
1524
+ * minute late, without its cause, and with the client claiming to be
1525
+ * connected meanwhile.
1526
+ */
1527
+ #removedByServer(cause: Error): void {
1528
+ this.#handleConnectionClosed(cause);
1529
+ this.#handler.close();
1530
+ }
1531
+
1532
+ /**
1533
+ * Count a dropped voice delivery, and report the drops now and then: at most
1534
+ * once every ten seconds, with how many were dropped since the last report.
1535
+ */
1536
+ #dropVoice(): void {
1537
+ this.#voiceDropped++;
1538
+ const now = performance.now();
1539
+ if (now - this.#voiceDropWarnedAt < VOICE_DROP_WARN_INTERVAL_MS) return;
1540
+ this.#voiceDropWarnedAt = now;
1541
+ // The count since the last warning, so each one says how bad it is now.
1542
+ this.#logger.warn("voice dropped: listeners are not keeping up", {
1543
+ dropped: this.#voiceDropped,
1544
+ });
1545
+ this.#voiceDropped = 0;
1546
+ }
1547
+
1548
+ /** Queue a server event, through the event middleware. */
1549
+ #emitServerEvent(event: ServerEvent): void {
1550
+ this.#enqueue(() => this.#eventChain(event));
1551
+ }
1552
+
1553
+ /**
1554
+ * Queue `disconnected`; the promise settles once it has been delivered, and
1555
+ * a connect() waits for it until then.
1556
+ */
1557
+ #announceDisconnected(cause: Error | undefined, willReconnect: boolean): Promise<void> {
1558
+ const delivered = new Promise<void>((resolve) =>
1559
+ this.#enqueue(() => {
1560
+ try {
1561
+ this.#deliver("disconnected", { error: cause, willReconnect });
1562
+ } finally {
1563
+ resolve();
1564
+ }
1565
+ }),
1566
+ );
1567
+ this.#disconnectedDelivered = delivered;
1568
+ void delivered.then(() => {
1569
+ if (this.#disconnectedDelivered === delivered) this.#disconnectedDelivered = undefined;
1570
+ });
1571
+ return delivered;
1572
+ }
1573
+
1574
+ /** Queue a lifecycle event, which middleware does not see. */
1575
+ #emit<K extends Exclude<keyof EventMap, ServerEventName>>(event: K, payload: EventMap[K]): void {
1576
+ this.#enqueue(() => this.#deliver(event, payload));
1577
+ }
1578
+
1579
+ #deliver<K extends keyof EventMap>(event: K, payload: EventMap[K]): void {
1580
+ for (const subscription of this.#listeners.get(event) ?? []) {
1581
+ // Checked at delivery: a listener removed while its event was queued
1582
+ // does not get it.
1583
+ if (subscription.removed) continue;
1584
+ try {
1585
+ subscription.listener(payload);
1586
+ } catch (error) {
1587
+ // Rethrown on its own, as an uncaught exception, so it surfaces as one
1588
+ // from an EventEmitter listener would, and the listeners after it
1589
+ // still get the event.
1590
+ queueMicrotask(() => {
1591
+ throw error;
1592
+ });
1593
+ }
1594
+ }
1595
+ }
1596
+
1597
+ /**
1598
+ * Run deliveries one at a time, in order, once the packet being handled is
1599
+ * done with. A listener that throws does so as an uncaught exception, as it
1600
+ * would from an EventEmitter, and the listeners and deliveries behind it
1601
+ * still run.
1602
+ */
1603
+ #enqueue(delivery: () => void): void {
1604
+ this.#queue.push(delivery);
1605
+ if (this.#draining) return;
1606
+ this.#draining = true;
1607
+ setImmediate(this.#drain);
1608
+ }
1609
+
1610
+ #drain = (): void => {
1611
+ try {
1612
+ while (this.#queue.length > 0) this.#queue.shift()!();
1613
+ } finally {
1614
+ if (this.#queue.length > 0) setImmediate(this.#drain);
1615
+ else this.#draining = false;
1616
+ }
1617
+ };
1618
+
1619
+ #handleConnectionClosed(err: Error | null): void {
1620
+ if (this.#status === ClientStatus.Disconnected) return;
1621
+ // Nothing in flight can be answered any more; failing it now, with the
1622
+ // reason, beats every caller timing out one by one.
1623
+ this.#cmdTrack.reset(new NotConnectedError(err ? { cause: err } : undefined));
1624
+ if (this.#status !== ClientStatus.Connected) {
1625
+ // The socket closed before the handshake finished, so this is a failed
1626
+ // connection attempt rather than a disconnect of a live session.
1627
+ this.#failConnection(
1628
+ err ?? new TeamspeakError("connection closed before the TeamSpeak handshake completed"),
1629
+ );
1630
+ return;
1631
+ }
1632
+ this.#status = ClientStatus.Disconnected;
1633
+ // Never undefined for a drop: undefined means disconnect() only.
1634
+ const cause = err ?? new TeamspeakError("connection closed");
1635
+ this.#lastDrop = cause;
1636
+ this.#endSession(cause);
1637
+
1638
+ // Announced first, then retried: a caller watching `disconnected` should
1639
+ // hear about the drop even when a reconnect is already on its way, because
1640
+ // a silent recovery hides an outage.
1641
+ void this.#announceDisconnected(cause, this.#willReconnect(cause, this.#loopAttempt + 1));
1642
+ this.#scheduleReconnect(cause).catch((error: unknown) => {
1643
+ this.#logger.error("reconnecting failed", { error: String(error) });
1644
+ });
1645
+ }
1646
+
1647
+ /**
1648
+ * Whether the reconnect loop will make attempt number `attempt` after `err`.
1649
+ * `disconnected` reports it, and the loop acts on the same answer: the
1650
+ * caller's `shouldRetry` is asked once per failure, not once to announce it
1651
+ * and again to act on it.
1652
+ */
1653
+ #willReconnect(err: Error, attempt: number): boolean {
1654
+ const options = this.#reconnectOptions;
1655
+ if (options === undefined || this.#stopped) return false;
1656
+ const { maxAttempts } = resolveBackoffPolicy(options);
1657
+ if (maxAttempts !== 0 && attempt > maxAttempts) return false;
1658
+ const asked = this.#retryAnswer;
1659
+ if (asked?.err === err && asked.attempt === attempt) return asked.retry;
1660
+ let retry: boolean;
1661
+ let threw = false;
1662
+ try {
1663
+ retry = (options.shouldRetry ?? defaultShouldRetry)(err, attempt);
1664
+ } catch (error) {
1665
+ this.#logger.error("shouldRetry threw; not reconnecting", { error: String(error) });
1666
+ retry = false;
1667
+ threw = true;
1668
+ }
1669
+ this.#retryAnswer = { err, attempt, retry, threw };
1670
+ return retry;
1671
+ }
1672
+
1673
+ /**
1674
+ * Retry a dropped connection according to the reconnect policy.
1675
+ *
1676
+ * Never runs after an explicit disconnect, and never more than one at a time:
1677
+ * two failures in quick succession would otherwise start competing loops, and
1678
+ * a loop shorter than the server's antiflood window bans the IP rather than
1679
+ * reconnecting it. A drop while the loop runs is the loop's to retry: it
1680
+ * ends only once its attempt is still connected when it resumes.
1681
+ */
1682
+ async #scheduleReconnect(err: Error): Promise<void> {
1683
+ const options = this.#reconnectOptions;
1684
+ if (options === undefined || this.#stopped || this.#reconnecting) return;
1685
+
1686
+ const policy = resolveBackoffPolicy(options);
1687
+ this.#reconnecting = true;
1688
+
1689
+ const stop = new AbortController();
1690
+ this.#stopReconnecting = stop;
1691
+ // The attempts the loop has made, and why it stopped, for `reconnectStopped`.
1692
+ let made = 0;
1693
+ let stoppedBy: { readonly cause: unknown } | undefined;
1694
+ try {
1695
+ for (let attempt = 1; policy.maxAttempts === 0 || attempt <= policy.maxAttempts; attempt++) {
1696
+ if (this.#stopped) {
1697
+ stoppedBy = { cause: undefined };
1698
+ return;
1699
+ }
1700
+ if (!this.#willReconnect(err, attempt)) {
1701
+ if (!this.#retryAnswer?.threw) {
1702
+ this.#logger.info("not retrying", { attempt, reason: err.message });
1703
+ }
1704
+ stoppedBy = { cause: err };
1705
+ return;
1706
+ }
1707
+
1708
+ const delay = backoffDelay(policy, attempt);
1709
+ this.#logger.info("reconnecting", { attempt, delayMs: delay });
1710
+ this.#callHook(this.#trace?.reconnectScheduled, () => ({
1711
+ attempt,
1712
+ delayMs: delay,
1713
+ cause: err,
1714
+ }));
1715
+ // A timer that keeps the process alive: an application that does
1716
+ // nothing but stay connected would otherwise exit during the wait.
1717
+ await sleep(delay, stop.signal);
1718
+ if (this.#stopped) {
1719
+ stoppedBy = { cause: undefined };
1720
+ return;
1721
+ }
1722
+ // Connected, or connecting, by hand during the wait: nothing is left to
1723
+ // retry, and an attempt now would only fail with AlreadyConnectedError.
1724
+ if (this.#status !== ClientStatus.Disconnected) {
1725
+ this.#logger.info("reconnect loop ended: connected by other means", { attempt });
1726
+ return;
1727
+ }
1728
+
1729
+ try {
1730
+ made++;
1731
+ this.#loopAttempt = attempt;
1732
+ await this.#connect(
1733
+ { signal: AbortSignal.timeout(RECONNECT_ATTEMPT_TIMEOUT_MS) },
1734
+ attempt,
1735
+ true,
1736
+ );
1737
+ // Read afresh: the status may have changed while connect() resolved.
1738
+ if (this.status === ClientStatus.Connected) {
1739
+ this.#logger.info("reconnected", { attempt });
1740
+ return;
1741
+ }
1742
+ // The new session dropped before this loop resumed — initserver and
1743
+ // the server's goodbye in one datagram, say. That drop found this
1744
+ // loop running and left the retrying to it.
1745
+ err = this.#lastDrop ?? new TeamspeakError("connection closed");
1746
+ } catch (retryErr) {
1747
+ if (retryErr instanceof AlreadyConnectedError) return;
1748
+ err =
1749
+ retryErr instanceof Error
1750
+ ? retryErr
1751
+ : new TeamspeakError(String(retryErr), { cause: retryErr });
1752
+ }
1753
+ }
1754
+ this.#logger.warn("reconnect attempts exhausted", { attempts: policy.maxAttempts });
1755
+ stoppedBy = { cause: err };
1756
+ } finally {
1757
+ if (stoppedBy !== undefined) {
1758
+ const { cause } = stoppedBy;
1759
+ this.#callHook(this.#trace?.reconnectStopped, () => ({ attempts: made, cause }));
1760
+ }
1761
+ this.#reconnecting = false;
1762
+ this.#loopAttempt = 0;
1763
+ if (this.#stopReconnecting === stop) this.#stopReconnecting = undefined;
1764
+ }
1765
+ }
1766
+
1767
+ /**
1768
+ * A connection attempt has failed for good: settle it with the cause, and
1769
+ * tear the connection down. Does nothing once the handshake has completed,
1770
+ * so it cannot end a live session.
1771
+ *
1772
+ * Without this, a handshake the server rejects (a wrong password, say, which
1773
+ * the server answers with an error instead of closing the socket) surfaces
1774
+ * only as the caller's own timeout, and the client stays in `Connecting`
1775
+ * forever without ever emitting `disconnected`.
1776
+ */
1777
+ #failConnection(error: unknown): void {
1778
+ if (this.#status === ClientStatus.Connected) return;
1779
+ this.#attempt.reject(error);
1780
+
1781
+ if (this.#status === ClientStatus.Disconnected) return;
1782
+ this.#status = ClientStatus.Disconnected;
1783
+ this.#handler.close();
1784
+ const cause =
1785
+ error instanceof Error ? error : new TeamspeakError(String(error), { cause: error });
1786
+ // Only an attempt of the reconnect loop can be followed by another; a
1787
+ // connect() that fails is the caller's to retry.
1788
+ void this.#announceDisconnected(
1789
+ cause,
1790
+ this.#reconnecting && this.#willReconnect(cause, this.#loopAttempt + 1),
1791
+ );
1792
+ }
1793
+ }
1794
+
1795
+ function kickedEvent(event: {
1796
+ readonly reason: number;
1797
+ readonly reasonMessage: string;
1798
+ readonly invokerName: string;
1799
+ readonly invokerUID: UID;
1800
+ readonly invokerID: ClientID;
1801
+ }): KickedEvent {
1802
+ return {
1803
+ reason: event.reason,
1804
+ reasonMessage: event.reasonMessage,
1805
+ invokerName: event.invokerName,
1806
+ invokerUID: event.invokerUID,
1807
+ invokerID: event.invokerID,
1808
+ };
1809
+ }