@honeybbq/teamspeak 0.0.1 → 1.0.0-beta.10

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