bitget-api 2.3.6 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (421) hide show
  1. package/README.md +272 -18
  2. package/{lib → dist/cjs}/broker-client.d.ts +3 -2
  3. package/{lib → dist/cjs}/broker-client.js +4 -4
  4. package/dist/cjs/broker-client.js.map +1 -0
  5. package/{lib → dist/cjs}/constants/enum.d.ts +3 -0
  6. package/{lib → dist/cjs}/constants/enum.js +3 -0
  7. package/dist/cjs/constants/enum.js.map +1 -0
  8. package/{lib → dist/cjs}/futures-client.d.ts +5 -2
  9. package/{lib → dist/cjs}/futures-client.js +18 -9
  10. package/dist/cjs/futures-client.js.map +1 -0
  11. package/dist/cjs/index.d.ts +50 -0
  12. package/dist/cjs/index.js +67 -0
  13. package/dist/cjs/index.js.map +1 -0
  14. package/dist/cjs/package.json +3 -0
  15. package/{lib → dist/cjs}/rest-client-v2.d.ts +17 -2
  16. package/{lib → dist/cjs}/rest-client-v2.js +62 -74
  17. package/dist/cjs/rest-client-v2.js.map +1 -0
  18. package/dist/cjs/rest-client-v3.d.ts +440 -0
  19. package/dist/cjs/rest-client-v3.js +573 -0
  20. package/dist/cjs/rest-client-v3.js.map +1 -0
  21. package/{lib → dist/cjs}/spot-client.d.ts +5 -2
  22. package/{lib → dist/cjs}/spot-client.js +21 -23
  23. package/dist/cjs/spot-client.js.map +1 -0
  24. package/{lib → dist/cjs}/types/request/shared.d.ts +4 -4
  25. package/dist/cjs/types/request/shared.js.map +1 -0
  26. package/{lib → dist/cjs}/types/request/v1/brokerV1.d.ts +1 -1
  27. package/dist/cjs/types/request/v1/brokerV1.js.map +1 -0
  28. package/{lib → dist/cjs}/types/request/v1/futuresV1.d.ts +10 -10
  29. package/dist/cjs/types/request/v1/futuresV1.js.map +1 -0
  30. package/{lib → dist/cjs}/types/request/v1/spotV1.d.ts +4 -4
  31. package/dist/cjs/types/request/v1/spotV1.js.map +1 -0
  32. package/{lib → dist/cjs}/types/request/v2/broker.d.ts +3 -3
  33. package/dist/cjs/types/request/v2/broker.js.map +1 -0
  34. package/{lib → dist/cjs}/types/request/v2/common.d.ts +1 -1
  35. package/dist/cjs/types/request/v2/common.js.map +1 -0
  36. package/{lib → dist/cjs}/types/request/v2/copytrading.d.ts +5 -5
  37. package/dist/cjs/types/request/v2/copytrading.js.map +1 -0
  38. package/dist/cjs/types/request/v2/earn.js.map +1 -0
  39. package/{lib → dist/cjs}/types/request/v2/futures.d.ts +9 -9
  40. package/dist/cjs/types/request/v2/futures.js.map +1 -0
  41. package/{lib → dist/cjs}/types/request/v2/margin.d.ts +5 -5
  42. package/dist/cjs/types/request/v2/margin.js.map +1 -0
  43. package/{lib → dist/cjs}/types/request/v2/spot.d.ts +12 -12
  44. package/dist/cjs/types/request/v2/spot.js.map +1 -0
  45. package/dist/cjs/types/request/v3/account.d.ts +162 -0
  46. package/dist/cjs/types/request/v3/account.js +4 -0
  47. package/dist/cjs/types/request/v3/account.js.map +1 -0
  48. package/dist/cjs/types/request/v3/loan.d.ts +31 -0
  49. package/dist/cjs/types/request/v3/loan.js +3 -0
  50. package/dist/cjs/types/request/v3/loan.js.map +1 -0
  51. package/dist/cjs/types/request/v3/public.d.ts +65 -0
  52. package/dist/cjs/types/request/v3/public.js +3 -0
  53. package/dist/cjs/types/request/v3/public.js.map +1 -0
  54. package/dist/cjs/types/request/v3/strategy.d.ts +46 -0
  55. package/dist/cjs/types/request/v3/strategy.js +3 -0
  56. package/dist/cjs/types/request/v3/strategy.js.map +1 -0
  57. package/dist/cjs/types/request/v3/trade.d.ts +112 -0
  58. package/dist/cjs/types/request/v3/trade.js +3 -0
  59. package/dist/cjs/types/request/v3/trade.js.map +1 -0
  60. package/{lib → dist/cjs}/types/response/v1/futures.d.ts +1 -1
  61. package/dist/cjs/types/response/v1/futures.js.map +1 -0
  62. package/dist/cjs/types/response/v1/shared.js.map +1 -0
  63. package/dist/cjs/types/response/v1/spot.js.map +1 -0
  64. package/dist/cjs/types/response/v2/broker.js.map +1 -0
  65. package/dist/cjs/types/response/v2/common.js.map +1 -0
  66. package/dist/cjs/types/response/v2/copy-trading.js.map +1 -0
  67. package/dist/cjs/types/response/v2/earn.js.map +1 -0
  68. package/{lib → dist/cjs}/types/response/v2/futures.d.ts +1 -1
  69. package/dist/cjs/types/response/v2/futures.js.map +1 -0
  70. package/dist/cjs/types/response/v2/margin.js.map +1 -0
  71. package/{lib → dist/cjs}/types/response/v2/spot.d.ts +1 -1
  72. package/dist/cjs/types/response/v2/spot.js.map +1 -0
  73. package/dist/cjs/types/response/v3/account.d.ts +197 -0
  74. package/dist/cjs/types/response/v3/account.js +3 -0
  75. package/dist/cjs/types/response/v3/account.js.map +1 -0
  76. package/dist/cjs/types/response/v3/loan.d.ts +85 -0
  77. package/dist/cjs/types/response/v3/loan.js +3 -0
  78. package/dist/cjs/types/response/v3/loan.js.map +1 -0
  79. package/dist/cjs/types/response/v3/public.d.ts +142 -0
  80. package/dist/cjs/types/response/v3/public.js +3 -0
  81. package/dist/cjs/types/response/v3/public.js.map +1 -0
  82. package/dist/cjs/types/response/v3/strategy.d.ts +26 -0
  83. package/dist/cjs/types/response/v3/strategy.js +3 -0
  84. package/dist/cjs/types/response/v3/strategy.js.map +1 -0
  85. package/dist/cjs/types/response/v3/trade.d.ts +193 -0
  86. package/dist/cjs/types/response/v3/trade.js +3 -0
  87. package/dist/cjs/types/response/v3/trade.js.map +1 -0
  88. package/dist/cjs/types/shared.d.ts +8 -0
  89. package/{lib → dist/cjs}/types/shared.js.map +1 -1
  90. package/dist/cjs/types/websockets/ws-api-request.d.ts +20 -0
  91. package/dist/cjs/types/websockets/ws-api-request.js +3 -0
  92. package/dist/cjs/types/websockets/ws-api-request.js.map +1 -0
  93. package/dist/cjs/types/websockets/ws-api-response.d.ts +6 -0
  94. package/dist/cjs/types/websockets/ws-api-response.js +3 -0
  95. package/dist/cjs/types/websockets/ws-api-response.js.map +1 -0
  96. package/dist/cjs/types/websockets/ws-api.d.ts +91 -0
  97. package/dist/cjs/types/websockets/ws-api.js +11 -0
  98. package/dist/cjs/types/websockets/ws-api.js.map +1 -0
  99. package/{lib/types/websockets/events.d.ts → dist/cjs/types/websockets/ws-events.d.ts} +6 -0
  100. package/dist/cjs/types/websockets/ws-events.js +11 -0
  101. package/dist/cjs/types/websockets/ws-events.js.map +1 -0
  102. package/dist/cjs/types/websockets/ws-general.d.ts +112 -0
  103. package/dist/cjs/types/websockets/ws-general.js +3 -0
  104. package/dist/cjs/types/websockets/ws-general.js.map +1 -0
  105. package/{lib → dist/cjs}/util/BaseRestClient.d.ts +3 -2
  106. package/dist/cjs/util/BaseRestClient.js +274 -0
  107. package/dist/cjs/util/BaseRestClient.js.map +1 -0
  108. package/dist/cjs/util/BaseWSClient.d.ts +197 -0
  109. package/dist/cjs/util/BaseWSClient.js +759 -0
  110. package/dist/cjs/util/BaseWSClient.js.map +1 -0
  111. package/dist/cjs/util/WsStore.d.ts +74 -0
  112. package/dist/cjs/util/WsStore.js +287 -0
  113. package/dist/cjs/util/WsStore.js.map +1 -0
  114. package/{lib → dist/cjs}/util/WsStore.types.d.ts +27 -1
  115. package/{lib → dist/cjs}/util/WsStore.types.js +3 -2
  116. package/dist/cjs/util/WsStore.types.js.map +1 -0
  117. package/dist/cjs/util/logger.d.ts +8 -0
  118. package/{lib → dist/cjs}/util/logger.js +2 -10
  119. package/dist/cjs/util/logger.js.map +1 -0
  120. package/{lib → dist/cjs}/util/requestUtils.d.ts +18 -1
  121. package/{lib → dist/cjs}/util/requestUtils.js +6 -5
  122. package/dist/cjs/util/requestUtils.js.map +1 -0
  123. package/{lib → dist/cjs}/util/type-guards.d.ts +4 -1
  124. package/{lib → dist/cjs}/util/type-guards.js +20 -10
  125. package/dist/cjs/util/type-guards.js.map +1 -0
  126. package/dist/cjs/util/webCryptoAPI.d.ts +14 -0
  127. package/dist/cjs/util/webCryptoAPI.js +80 -0
  128. package/dist/cjs/util/webCryptoAPI.js.map +1 -0
  129. package/dist/cjs/util/websocket-util.d.ts +88 -0
  130. package/dist/cjs/util/websocket-util.js +241 -0
  131. package/dist/cjs/util/websocket-util.js.map +1 -0
  132. package/dist/cjs/websocket-api-client.d.ts +89 -0
  133. package/dist/cjs/websocket-api-client.js +122 -0
  134. package/dist/cjs/websocket-api-client.js.map +1 -0
  135. package/{lib/websocket-client.d.ts → dist/cjs/websocket-client-legacy-v1.d.ts} +6 -6
  136. package/{lib/websocket-client.js → dist/cjs/websocket-client-legacy-v1.js} +211 -156
  137. package/dist/cjs/websocket-client-legacy-v1.js.map +1 -0
  138. package/dist/cjs/websocket-client-v2.d.ts +79 -0
  139. package/dist/cjs/websocket-client-v2.js +339 -0
  140. package/dist/cjs/websocket-client-v2.js.map +1 -0
  141. package/dist/cjs/websocket-client-v3.d.ts +84 -0
  142. package/dist/cjs/websocket-client-v3.js +408 -0
  143. package/dist/cjs/websocket-client-v3.js.map +1 -0
  144. package/dist/mjs/broker-client.d.ts +127 -0
  145. package/dist/mjs/broker-client.js +158 -0
  146. package/dist/mjs/broker-client.js.map +1 -0
  147. package/dist/mjs/constants/enum.d.ts +31 -0
  148. package/dist/mjs/constants/enum.js +32 -0
  149. package/dist/mjs/constants/enum.js.map +1 -0
  150. package/dist/mjs/futures-client.d.ts +184 -0
  151. package/dist/mjs/futures-client.js +473 -0
  152. package/dist/mjs/futures-client.js.map +1 -0
  153. package/dist/mjs/index.d.ts +50 -0
  154. package/dist/mjs/index.js +51 -0
  155. package/dist/mjs/index.js.map +1 -0
  156. package/dist/mjs/package.json +3 -0
  157. package/dist/mjs/rest-client-v2.d.ts +1098 -0
  158. package/dist/mjs/rest-client-v2.js +1092 -0
  159. package/dist/mjs/rest-client-v2.js.map +1 -0
  160. package/dist/mjs/rest-client-v3.d.ts +440 -0
  161. package/dist/mjs/rest-client-v3.js +566 -0
  162. package/dist/mjs/rest-client-v3.js.map +1 -0
  163. package/dist/mjs/spot-client.d.ts +154 -0
  164. package/dist/mjs/spot-client.js +273 -0
  165. package/dist/mjs/spot-client.js.map +1 -0
  166. package/dist/mjs/types/request/shared.d.ts +23 -0
  167. package/dist/mjs/types/request/shared.js +2 -0
  168. package/dist/mjs/types/request/shared.js.map +1 -0
  169. package/dist/mjs/types/request/v1/brokerV1.d.ts +23 -0
  170. package/dist/mjs/types/request/v1/brokerV1.js +2 -0
  171. package/dist/mjs/types/request/v1/brokerV1.js.map +1 -0
  172. package/dist/mjs/types/request/v1/futuresV1.d.ts +168 -0
  173. package/dist/mjs/types/request/v1/futuresV1.js +2 -0
  174. package/dist/mjs/types/request/v1/futuresV1.js.map +1 -0
  175. package/dist/mjs/types/request/v1/spotV1.d.ts +105 -0
  176. package/dist/mjs/types/request/v1/spotV1.js +2 -0
  177. package/dist/mjs/types/request/v1/spotV1.js.map +1 -0
  178. package/dist/mjs/types/request/v2/broker.d.ts +69 -0
  179. package/dist/mjs/types/request/v2/broker.js +7 -0
  180. package/dist/mjs/types/request/v2/broker.js.map +1 -0
  181. package/dist/mjs/types/request/v2/common.d.ts +163 -0
  182. package/dist/mjs/types/request/v2/common.js +2 -0
  183. package/dist/mjs/types/request/v2/common.js.map +1 -0
  184. package/dist/mjs/types/request/v2/copytrading.d.ts +196 -0
  185. package/dist/mjs/types/request/v2/copytrading.js +9 -0
  186. package/dist/mjs/types/request/v2/copytrading.js.map +1 -0
  187. package/dist/mjs/types/request/v2/earn.d.ts +121 -0
  188. package/dist/mjs/types/request/v2/earn.js +9 -0
  189. package/dist/mjs/types/request/v2/earn.js.map +1 -0
  190. package/dist/mjs/types/request/v2/futures.d.ts +363 -0
  191. package/dist/mjs/types/request/v2/futures.js +2 -0
  192. package/dist/mjs/types/request/v2/futures.js.map +1 -0
  193. package/dist/mjs/types/request/v2/margin.d.ts +121 -0
  194. package/dist/mjs/types/request/v2/margin.js +7 -0
  195. package/dist/mjs/types/request/v2/margin.js.map +1 -0
  196. package/dist/mjs/types/request/v2/spot.d.ts +265 -0
  197. package/dist/mjs/types/request/v2/spot.js +2 -0
  198. package/dist/mjs/types/request/v2/spot.js.map +1 -0
  199. package/dist/mjs/types/request/v3/account.d.ts +162 -0
  200. package/dist/mjs/types/request/v3/account.js +3 -0
  201. package/dist/mjs/types/request/v3/account.js.map +1 -0
  202. package/dist/mjs/types/request/v3/loan.d.ts +31 -0
  203. package/dist/mjs/types/request/v3/loan.js +2 -0
  204. package/dist/mjs/types/request/v3/loan.js.map +1 -0
  205. package/dist/mjs/types/request/v3/public.d.ts +65 -0
  206. package/dist/mjs/types/request/v3/public.js +2 -0
  207. package/dist/mjs/types/request/v3/public.js.map +1 -0
  208. package/dist/mjs/types/request/v3/strategy.d.ts +46 -0
  209. package/dist/mjs/types/request/v3/strategy.js +2 -0
  210. package/dist/mjs/types/request/v3/strategy.js.map +1 -0
  211. package/dist/mjs/types/request/v3/trade.d.ts +112 -0
  212. package/dist/mjs/types/request/v3/trade.js +2 -0
  213. package/dist/mjs/types/request/v3/trade.js.map +1 -0
  214. package/dist/mjs/types/response/v1/futures.d.ts +72 -0
  215. package/dist/mjs/types/response/v1/futures.js +2 -0
  216. package/dist/mjs/types/response/v1/futures.js.map +1 -0
  217. package/dist/mjs/types/response/v1/shared.d.ts +15 -0
  218. package/dist/mjs/types/response/v1/shared.js +2 -0
  219. package/dist/mjs/types/response/v1/shared.js.map +1 -0
  220. package/dist/mjs/types/response/v1/spot.d.ts +65 -0
  221. package/dist/mjs/types/response/v1/spot.js +2 -0
  222. package/dist/mjs/types/response/v1/spot.js.map +1 -0
  223. package/dist/mjs/types/response/v2/broker.d.ts +135 -0
  224. package/dist/mjs/types/response/v2/broker.js +7 -0
  225. package/dist/mjs/types/response/v2/broker.js.map +1 -0
  226. package/dist/mjs/types/response/v2/common.d.ts +384 -0
  227. package/dist/mjs/types/response/v2/common.js +7 -0
  228. package/dist/mjs/types/response/v2/common.js.map +1 -0
  229. package/dist/mjs/types/response/v2/copy-trading.d.ts +385 -0
  230. package/dist/mjs/types/response/v2/copy-trading.js +9 -0
  231. package/dist/mjs/types/response/v2/copy-trading.js.map +1 -0
  232. package/dist/mjs/types/response/v2/earn.d.ts +294 -0
  233. package/dist/mjs/types/response/v2/earn.js +9 -0
  234. package/dist/mjs/types/response/v2/earn.js.map +1 -0
  235. package/dist/mjs/types/response/v2/futures.d.ts +546 -0
  236. package/dist/mjs/types/response/v2/futures.js +7 -0
  237. package/dist/mjs/types/response/v2/futures.js.map +1 -0
  238. package/dist/mjs/types/response/v2/margin.d.ts +277 -0
  239. package/dist/mjs/types/response/v2/margin.js +7 -0
  240. package/dist/mjs/types/response/v2/margin.js.map +1 -0
  241. package/dist/mjs/types/response/v2/spot.d.ts +385 -0
  242. package/dist/mjs/types/response/v2/spot.js +7 -0
  243. package/dist/mjs/types/response/v2/spot.js.map +1 -0
  244. package/dist/mjs/types/response/v3/account.d.ts +197 -0
  245. package/dist/mjs/types/response/v3/account.js +2 -0
  246. package/dist/mjs/types/response/v3/account.js.map +1 -0
  247. package/dist/mjs/types/response/v3/loan.d.ts +85 -0
  248. package/dist/mjs/types/response/v3/loan.js +2 -0
  249. package/dist/mjs/types/response/v3/loan.js.map +1 -0
  250. package/dist/mjs/types/response/v3/public.d.ts +142 -0
  251. package/dist/mjs/types/response/v3/public.js +2 -0
  252. package/dist/mjs/types/response/v3/public.js.map +1 -0
  253. package/dist/mjs/types/response/v3/strategy.d.ts +26 -0
  254. package/dist/mjs/types/response/v3/strategy.js +2 -0
  255. package/dist/mjs/types/response/v3/strategy.js.map +1 -0
  256. package/dist/mjs/types/response/v3/trade.d.ts +193 -0
  257. package/dist/mjs/types/response/v3/trade.js +2 -0
  258. package/dist/mjs/types/response/v3/trade.js.map +1 -0
  259. package/dist/mjs/types/shared.d.ts +8 -0
  260. package/dist/mjs/types/shared.js +2 -0
  261. package/{lib/types/request → dist/mjs/types}/shared.js.map +1 -1
  262. package/dist/mjs/types/websockets/ws-api-request.d.ts +20 -0
  263. package/dist/mjs/types/websockets/ws-api-request.js +2 -0
  264. package/dist/mjs/types/websockets/ws-api-request.js.map +1 -0
  265. package/dist/mjs/types/websockets/ws-api-response.d.ts +6 -0
  266. package/dist/mjs/types/websockets/ws-api-response.js +2 -0
  267. package/dist/mjs/types/websockets/ws-api-response.js.map +1 -0
  268. package/dist/mjs/types/websockets/ws-api.d.ts +91 -0
  269. package/dist/mjs/types/websockets/ws-api.js +8 -0
  270. package/dist/mjs/types/websockets/ws-api.js.map +1 -0
  271. package/dist/mjs/types/websockets/ws-events.d.ts +81 -0
  272. package/dist/mjs/types/websockets/ws-events.js +8 -0
  273. package/dist/mjs/types/websockets/ws-events.js.map +1 -0
  274. package/dist/mjs/types/websockets/ws-general.d.ts +112 -0
  275. package/dist/mjs/types/websockets/ws-general.js +2 -0
  276. package/dist/mjs/types/websockets/ws-general.js.map +1 -0
  277. package/dist/mjs/util/BaseRestClient.d.ts +40 -0
  278. package/dist/mjs/util/BaseRestClient.js +268 -0
  279. package/dist/mjs/util/BaseRestClient.js.map +1 -0
  280. package/dist/mjs/util/BaseWSClient.d.ts +197 -0
  281. package/dist/mjs/util/BaseWSClient.js +752 -0
  282. package/dist/mjs/util/BaseWSClient.js.map +1 -0
  283. package/dist/mjs/util/WsStore.d.ts +74 -0
  284. package/dist/mjs/util/WsStore.js +282 -0
  285. package/dist/mjs/util/WsStore.js.map +1 -0
  286. package/dist/mjs/util/WsStore.types.d.ts +52 -0
  287. package/dist/mjs/util/WsStore.types.js +11 -0
  288. package/dist/mjs/util/WsStore.types.js.map +1 -0
  289. package/dist/mjs/util/logger.d.ts +8 -0
  290. package/dist/mjs/util/logger.js +14 -0
  291. package/dist/mjs/util/logger.js.map +1 -0
  292. package/dist/mjs/util/requestUtils.d.ts +61 -0
  293. package/dist/mjs/util/requestUtils.js +50 -0
  294. package/dist/mjs/util/requestUtils.js.map +1 -0
  295. package/dist/mjs/util/type-guards.d.ts +16 -0
  296. package/dist/mjs/util/type-guards.js +62 -0
  297. package/dist/mjs/util/type-guards.js.map +1 -0
  298. package/dist/mjs/util/webCryptoAPI.d.ts +14 -0
  299. package/dist/mjs/util/webCryptoAPI.js +76 -0
  300. package/dist/mjs/util/webCryptoAPI.js.map +1 -0
  301. package/dist/mjs/util/websocket-util.d.ts +88 -0
  302. package/dist/mjs/util/websocket-util.js +227 -0
  303. package/dist/mjs/util/websocket-util.js.map +1 -0
  304. package/dist/mjs/websocket-api-client.d.ts +89 -0
  305. package/dist/mjs/websocket-api-client.js +118 -0
  306. package/dist/mjs/websocket-api-client.js.map +1 -0
  307. package/{lib/util/BaseWSClient.d.ts → dist/mjs/websocket-client-legacy-v1.d.ts} +44 -27
  308. package/dist/mjs/websocket-client-legacy-v1.js +502 -0
  309. package/dist/mjs/websocket-client-legacy-v1.js.map +1 -0
  310. package/dist/mjs/websocket-client-v2.d.ts +79 -0
  311. package/dist/mjs/websocket-client-v2.js +335 -0
  312. package/dist/mjs/websocket-client-v2.js.map +1 -0
  313. package/dist/mjs/websocket-client-v3.d.ts +84 -0
  314. package/dist/mjs/websocket-client-v3.js +404 -0
  315. package/dist/mjs/websocket-client-v3.js.map +1 -0
  316. package/package.json +33 -15
  317. package/index.js +0 -1
  318. package/lib/broker-client.js.map +0 -1
  319. package/lib/constants/enum.js.map +0 -1
  320. package/lib/futures-client.js.map +0 -1
  321. package/lib/index.d.ts +0 -10
  322. package/lib/index.js +0 -27
  323. package/lib/index.js.map +0 -1
  324. package/lib/rest-client-v2.js.map +0 -1
  325. package/lib/spot-client.js.map +0 -1
  326. package/lib/types/index.d.ts +0 -4
  327. package/lib/types/index.js +0 -21
  328. package/lib/types/index.js.map +0 -1
  329. package/lib/types/request/index.d.ts +0 -11
  330. package/lib/types/request/index.js +0 -28
  331. package/lib/types/request/index.js.map +0 -1
  332. package/lib/types/request/v1/brokerV1.js.map +0 -1
  333. package/lib/types/request/v1/futuresV1.js.map +0 -1
  334. package/lib/types/request/v1/spotV1.js.map +0 -1
  335. package/lib/types/request/v2/broker.js.map +0 -1
  336. package/lib/types/request/v2/common.js.map +0 -1
  337. package/lib/types/request/v2/copytrading.js.map +0 -1
  338. package/lib/types/request/v2/earn.js.map +0 -1
  339. package/lib/types/request/v2/futures.js.map +0 -1
  340. package/lib/types/request/v2/margin.js.map +0 -1
  341. package/lib/types/request/v2/spot.js.map +0 -1
  342. package/lib/types/response/index.d.ts +0 -10
  343. package/lib/types/response/index.js +0 -27
  344. package/lib/types/response/index.js.map +0 -1
  345. package/lib/types/response/v1/futures.js.map +0 -1
  346. package/lib/types/response/v1/shared.js.map +0 -1
  347. package/lib/types/response/v1/spot.js.map +0 -1
  348. package/lib/types/response/v2/broker.js.map +0 -1
  349. package/lib/types/response/v2/common.js.map +0 -1
  350. package/lib/types/response/v2/copy-trading.js.map +0 -1
  351. package/lib/types/response/v2/earn.js.map +0 -1
  352. package/lib/types/response/v2/futures.js.map +0 -1
  353. package/lib/types/response/v2/margin.js.map +0 -1
  354. package/lib/types/response/v2/spot.js.map +0 -1
  355. package/lib/types/shared.d.ts +0 -8
  356. package/lib/types/websockets/client.d.ts +0 -76
  357. package/lib/types/websockets/client.js +0 -3
  358. package/lib/types/websockets/client.js.map +0 -1
  359. package/lib/types/websockets/events.js +0 -3
  360. package/lib/types/websockets/events.js.map +0 -1
  361. package/lib/types/websockets/index.d.ts +0 -2
  362. package/lib/types/websockets/index.js +0 -19
  363. package/lib/types/websockets/index.js.map +0 -1
  364. package/lib/util/BaseRestClient.js +0 -221
  365. package/lib/util/BaseRestClient.js.map +0 -1
  366. package/lib/util/BaseWSClient.js +0 -395
  367. package/lib/util/BaseWSClient.js.map +0 -1
  368. package/lib/util/WsStore.d.ts +0 -26
  369. package/lib/util/WsStore.js +0 -126
  370. package/lib/util/WsStore.js.map +0 -1
  371. package/lib/util/WsStore.types.js.map +0 -1
  372. package/lib/util/browser-support.d.ts +0 -1
  373. package/lib/util/browser-support.js +0 -45
  374. package/lib/util/browser-support.js.map +0 -1
  375. package/lib/util/index.d.ts +0 -6
  376. package/lib/util/index.js +0 -23
  377. package/lib/util/index.js.map +0 -1
  378. package/lib/util/logger.d.ts +0 -9
  379. package/lib/util/logger.js.map +0 -1
  380. package/lib/util/node-support.d.ts +0 -2
  381. package/lib/util/node-support.js +0 -34
  382. package/lib/util/node-support.js.map +0 -1
  383. package/lib/util/requestUtils.js.map +0 -1
  384. package/lib/util/type-guards.js.map +0 -1
  385. package/lib/util/websocket-util.d.ts +0 -47
  386. package/lib/util/websocket-util.js +0 -154
  387. package/lib/util/websocket-util.js.map +0 -1
  388. package/lib/websocket-client-v2.d.ts +0 -33
  389. package/lib/websocket-client-v2.js +0 -104
  390. package/lib/websocket-client-v2.js.map +0 -1
  391. package/lib/websocket-client.js.map +0 -1
  392. /package/{lib → dist/cjs}/types/request/shared.js +0 -0
  393. /package/{lib → dist/cjs}/types/request/v1/brokerV1.js +0 -0
  394. /package/{lib → dist/cjs}/types/request/v1/futuresV1.js +0 -0
  395. /package/{lib → dist/cjs}/types/request/v1/spotV1.js +0 -0
  396. /package/{lib → dist/cjs}/types/request/v2/broker.js +0 -0
  397. /package/{lib → dist/cjs}/types/request/v2/common.js +0 -0
  398. /package/{lib → dist/cjs}/types/request/v2/copytrading.js +0 -0
  399. /package/{lib → dist/cjs}/types/request/v2/earn.d.ts +0 -0
  400. /package/{lib → dist/cjs}/types/request/v2/earn.js +0 -0
  401. /package/{lib → dist/cjs}/types/request/v2/futures.js +0 -0
  402. /package/{lib → dist/cjs}/types/request/v2/margin.js +0 -0
  403. /package/{lib → dist/cjs}/types/request/v2/spot.js +0 -0
  404. /package/{lib → dist/cjs}/types/response/v1/futures.js +0 -0
  405. /package/{lib → dist/cjs}/types/response/v1/shared.d.ts +0 -0
  406. /package/{lib → dist/cjs}/types/response/v1/shared.js +0 -0
  407. /package/{lib → dist/cjs}/types/response/v1/spot.d.ts +0 -0
  408. /package/{lib → dist/cjs}/types/response/v1/spot.js +0 -0
  409. /package/{lib → dist/cjs}/types/response/v2/broker.d.ts +0 -0
  410. /package/{lib → dist/cjs}/types/response/v2/broker.js +0 -0
  411. /package/{lib → dist/cjs}/types/response/v2/common.d.ts +0 -0
  412. /package/{lib → dist/cjs}/types/response/v2/common.js +0 -0
  413. /package/{lib → dist/cjs}/types/response/v2/copy-trading.d.ts +0 -0
  414. /package/{lib → dist/cjs}/types/response/v2/copy-trading.js +0 -0
  415. /package/{lib → dist/cjs}/types/response/v2/earn.d.ts +0 -0
  416. /package/{lib → dist/cjs}/types/response/v2/earn.js +0 -0
  417. /package/{lib → dist/cjs}/types/response/v2/futures.js +0 -0
  418. /package/{lib → dist/cjs}/types/response/v2/margin.d.ts +0 -0
  419. /package/{lib → dist/cjs}/types/response/v2/margin.js +0 -0
  420. /package/{lib → dist/cjs}/types/response/v2/spot.js +0 -0
  421. /package/{lib → dist/cjs}/types/shared.js +0 -0
@@ -0,0 +1,759 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BaseWebsocketClient = void 0;
7
+ /* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */
8
+ const events_1 = __importDefault(require("events"));
9
+ const isomorphic_ws_1 = __importDefault(require("isomorphic-ws"));
10
+ const ws_events_js_1 = require("../types/websockets/ws-events.js");
11
+ const logger_js_1 = require("./logger.js");
12
+ const websocket_util_js_1 = require("./websocket-util.js");
13
+ const WsStore_js_1 = __importDefault(require("./WsStore.js"));
14
+ const WsStore_types_js_1 = require("./WsStore.types.js");
15
+ /**
16
+ * Appends wsKey and isWSAPIResponse to all events.
17
+ * Some events are arrays, this handles that nested scenario too.
18
+ */
19
+ function getFinalEmittable(emittable, wsKey, isWSAPIResponse) {
20
+ if (Array.isArray(emittable)) {
21
+ return emittable.map((subEvent) => getFinalEmittable(subEvent, wsKey, isWSAPIResponse));
22
+ }
23
+ if (Array.isArray(emittable.event)) {
24
+ // Some topics just emit an array.
25
+ // This is consistent with how it was before the WS API upgrade:
26
+ return emittable.event.map((subEvent) => getFinalEmittable(subEvent, wsKey, isWSAPIResponse));
27
+ // const { event, ...others } = emittable;
28
+ // return {
29
+ // ...others,
30
+ // event: event.map((subEvent) =>
31
+ // getFinalEmittable(subEvent, wsKey, isWSAPIResponse),
32
+ // ),
33
+ // };
34
+ }
35
+ if (emittable.event) {
36
+ return {
37
+ ...emittable.event,
38
+ wsKey: wsKey,
39
+ isWSAPIResponse: !!isWSAPIResponse,
40
+ };
41
+ }
42
+ return {
43
+ ...emittable,
44
+ wsKey: wsKey,
45
+ isWSAPIResponse: !!isWSAPIResponse,
46
+ };
47
+ }
48
+ class BaseWebsocketClient extends events_1.default {
49
+ /**
50
+ * State store to track a list of topics (topic requests) we are expected to be subscribed to if reconnected
51
+ */
52
+ wsStore;
53
+ logger;
54
+ options;
55
+ wsApiRequestId = 0;
56
+ timeOffsetMs = 0;
57
+ /**
58
+ * { [wsKey]: { [requestId]: request } }
59
+ */
60
+ midflightRequestCache = {};
61
+ constructor(options, logger) {
62
+ super();
63
+ this.logger = logger || logger_js_1.DefaultLogger;
64
+ this.wsStore = new WsStore_js_1.default(this.logger);
65
+ this.options = {
66
+ demoTrading: false,
67
+ pongTimeout: 1000,
68
+ pingInterval: 10000,
69
+ reconnectTimeout: 500,
70
+ recvWindow: 0,
71
+ // Automatically send an authentication op/request after a connection opens, for private connections.
72
+ authPrivateConnectionsOnConnect: true,
73
+ // Individual requests do not require a signature, so this is disabled.
74
+ authPrivateRequests: false,
75
+ ...options,
76
+ };
77
+ }
78
+ isPrivateWsKey(wsKey) {
79
+ return this.getPrivateWSKeys().includes(wsKey);
80
+ }
81
+ /** Returns auto-incrementing request ID, used to track promise references for async requests */
82
+ getNewRequestId() {
83
+ return ++this.wsApiRequestId;
84
+ }
85
+ getTimeOffsetMs() {
86
+ return this.timeOffsetMs;
87
+ }
88
+ setTimeOffsetMs(newOffset) {
89
+ this.timeOffsetMs = newOffset;
90
+ }
91
+ /**
92
+ * Don't call directly! Use subscribe() instead!
93
+ *
94
+ * Subscribe to one or more topics on a WS connection (identified by WS Key).
95
+ *
96
+ * - Topics are automatically cached
97
+ * - Connections are automatically opened, if not yet connected
98
+ * - Authentication is automatically handled
99
+ * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key).
100
+ *
101
+ * @param wsRequests array of topics to subscribe to
102
+ * @param wsKey ws key referring to the ws connection these topics should be subscribed on
103
+ */
104
+ async subscribeTopicsForWsKey(wsTopicRequests, wsKey) {
105
+ const normalisedTopicRequests = (0, websocket_util_js_1.getNormalisedTopicRequests)(wsTopicRequests);
106
+ // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically
107
+ for (const topic of normalisedTopicRequests) {
108
+ this.wsStore.addTopic(wsKey, topic);
109
+ }
110
+ const isConnected = this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTED);
111
+ const isConnectionInProgress = this.wsStore.isConnectionAttemptInProgress(wsKey);
112
+ // start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect
113
+ if (!isConnected && !isConnectionInProgress) {
114
+ return this.connect(wsKey);
115
+ }
116
+ // Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore.
117
+ if (!isConnected) {
118
+ /**
119
+ * Are we in the process of connection? Nothing to send yet.
120
+ */
121
+ this.logger.trace('WS not connected - requests queued for retry once connected.', {
122
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
123
+ wsKey,
124
+ wsTopicRequests,
125
+ });
126
+ return isConnectionInProgress;
127
+ }
128
+ // We're connected. Check if auth is needed and if already authenticated
129
+ const isPrivateConnection = this.isPrivateWsKey(wsKey);
130
+ const isAuthenticated = this.wsStore.get(wsKey)?.isAuthenticated;
131
+ if (isPrivateConnection && !isAuthenticated) {
132
+ /**
133
+ * If not authenticated yet and auth is required, don't request topics yet.
134
+ *
135
+ * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success.
136
+ */
137
+ return false;
138
+ }
139
+ // Finally, request subscription to topics if the connection is healthy and ready
140
+ return this.requestSubscribeTopics(wsKey, normalisedTopicRequests);
141
+ }
142
+ async unsubscribeTopicsForWsKey(wsTopicRequests, wsKey) {
143
+ const normalisedTopicRequests = (0, websocket_util_js_1.getNormalisedTopicRequests)(wsTopicRequests);
144
+ // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically
145
+ for (const topic of normalisedTopicRequests) {
146
+ this.wsStore.deleteTopic(wsKey, topic);
147
+ }
148
+ const isConnected = this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTED);
149
+ // If not connected, don't need to do anything.
150
+ // Removing the topic from the store is enough to stop it from being resubscribed to on reconnect.
151
+ if (!isConnected) {
152
+ return;
153
+ }
154
+ // We're connected. Check if auth is needed and if already authenticated
155
+ const isPrivateConnection = this.isPrivateWsKey(wsKey);
156
+ const isAuthenticated = this.wsStore.get(wsKey)?.isAuthenticated;
157
+ if (isPrivateConnection && !isAuthenticated) {
158
+ /**
159
+ * If not authenticated yet and auth is required, don't need to do anything.
160
+ * We don't subscribe to topics until auth is complete anyway.
161
+ */
162
+ return;
163
+ }
164
+ // Finally, request subscription to topics if the connection is healthy and ready
165
+ return this.requestUnsubscribeTopics(wsKey, normalisedTopicRequests);
166
+ }
167
+ /**
168
+ * Splits topic requests into two groups, public & private topic requests
169
+ */
170
+ sortTopicRequestsIntoPublicPrivate(wsTopicRequests, wsKey) {
171
+ const publicTopicRequests = [];
172
+ const privateTopicRequests = [];
173
+ for (const topic of wsTopicRequests) {
174
+ if (this.isPrivateTopicRequest(topic, wsKey)) {
175
+ privateTopicRequests.push(topic);
176
+ }
177
+ else {
178
+ publicTopicRequests.push(topic);
179
+ }
180
+ }
181
+ return {
182
+ publicReqs: publicTopicRequests,
183
+ privateReqs: privateTopicRequests,
184
+ };
185
+ }
186
+ /** Get the WsStore that tracks websockets & topics */
187
+ getWsStore() {
188
+ return this.wsStore;
189
+ }
190
+ close(wsKey, force) {
191
+ this.logger.info('Closing connection', { ...websocket_util_js_1.WS_LOGGER_CATEGORY, wsKey });
192
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CLOSING);
193
+ this.clearTimers(wsKey);
194
+ const ws = this.getWs(wsKey);
195
+ ws?.close();
196
+ if (force) {
197
+ (0, websocket_util_js_1.safeTerminateWs)(ws);
198
+ }
199
+ }
200
+ closeAll(force) {
201
+ const keys = this.wsStore.getKeys();
202
+ this.logger.info(`Closing all ws connections: ${keys}`);
203
+ keys.forEach((key) => {
204
+ this.close(key, force);
205
+ });
206
+ }
207
+ isConnected(wsKey) {
208
+ return this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTED);
209
+ }
210
+ /**
211
+ * Request connection to a specific websocket, instead of waiting for automatic connection.
212
+ */
213
+ async connect(wsKey, customUrl, throwOnError) {
214
+ try {
215
+ if (this.wsStore.isWsOpen(wsKey)) {
216
+ this.logger.error('Refused to connect to ws with existing active connection', { ...websocket_util_js_1.WS_LOGGER_CATEGORY, wsKey });
217
+ return { wsKey, ws: this.wsStore.getWs(wsKey) };
218
+ }
219
+ if (this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTING)) {
220
+ this.logger.error('Refused to connect to ws, connection attempt already active', { ...websocket_util_js_1.WS_LOGGER_CATEGORY, wsKey });
221
+ return this.wsStore.getConnectionInProgressPromise(wsKey)?.promise;
222
+ }
223
+ if (!this.wsStore.getConnectionState(wsKey) ||
224
+ this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.INITIAL)) {
225
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTING);
226
+ }
227
+ if (!this.wsStore.getConnectionInProgressPromise(wsKey)) {
228
+ this.wsStore.createConnectionInProgressPromise(wsKey, false);
229
+ }
230
+ const url = customUrl || (await this.getWsUrl(wsKey));
231
+ const ws = this.connectToWsUrl(url, wsKey);
232
+ this.wsStore.setWs(wsKey, ws);
233
+ }
234
+ catch (err) {
235
+ this.parseWsError('Connection failed', err, wsKey);
236
+ this.reconnectWithDelay(wsKey, this.options.reconnectTimeout);
237
+ if (throwOnError) {
238
+ throw err;
239
+ }
240
+ }
241
+ return this.wsStore.getConnectionInProgressPromise(wsKey)?.promise;
242
+ }
243
+ connectToWsUrl(url, wsKey) {
244
+ this.logger.trace(`Opening WS connection to URL: ${url}`, {
245
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
246
+ wsKey,
247
+ });
248
+ const { protocols = [], ...wsOptions } = this.options.wsOptions || {};
249
+ const ws = new isomorphic_ws_1.default(url, protocols, wsOptions);
250
+ ws.onopen = (event) => this.onWsOpen(event, wsKey, url, ws);
251
+ ws.onmessage = (event) => this.onWsMessage(event, wsKey, ws);
252
+ ws.onerror = (event) => this.parseWsError('Websocket onWsError', event, wsKey);
253
+ ws.onclose = (event) => this.onWsClose(event, wsKey);
254
+ // Native ws ping/pong frames are not in use for bitget
255
+ // if (typeof ws.on === 'function') {
256
+ // ws.on('ping', (event) => this.onWsPing(event, wsKey, ws, 'event'));
257
+ // ws.on('pong', (event) => this.onWsPong(event, wsKey, 'event'));
258
+ // }
259
+ // // Not sure these work in the browser, the traditional event listeners are required for ping/pong frames in node
260
+ // ws.onping = (event) => this.onWsPing(event, wsKey, ws, 'function');
261
+ // ws.onpong = (event) => this.onWsPong(event, wsKey, 'function');
262
+ ws.wsKey = wsKey;
263
+ return ws;
264
+ }
265
+ parseWsError(context, error, wsKey) {
266
+ if (!error.message) {
267
+ this.logger.error(`${context} due to unexpected error: `, error);
268
+ this.emit('response', { ...error, wsKey });
269
+ this.emit('exception', { ...error, wsKey });
270
+ return;
271
+ }
272
+ switch (error.message) {
273
+ case 'Unexpected server response: 401':
274
+ this.logger.error(`${context} due to 401 authorization failure.`, {
275
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
276
+ wsKey,
277
+ });
278
+ break;
279
+ default:
280
+ this.logger.error(`${context} due to unexpected response error: "${error?.msg || error?.message || error}"`, { ...websocket_util_js_1.WS_LOGGER_CATEGORY, wsKey, error });
281
+ break;
282
+ }
283
+ this.emit('response', { ...error, wsKey });
284
+ this.emit('exception', { ...error, wsKey });
285
+ }
286
+ /** Get a signature, build the auth request and send it */
287
+ async sendAuthRequest(wsKey) {
288
+ try {
289
+ this.logger.trace('Sending auth request...', {
290
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
291
+ wsKey,
292
+ });
293
+ await this.assertIsConnected(wsKey);
294
+ if (!this.wsStore.getAuthenticationInProgressPromise(wsKey)) {
295
+ this.wsStore.createAuthenticationInProgressPromise(wsKey, false);
296
+ }
297
+ const request = await this.getWsAuthRequestEvent(wsKey);
298
+ // console.log('ws auth req', request);
299
+ this.tryWsSend(wsKey, JSON.stringify(request));
300
+ return this.wsStore.getAuthenticationInProgressPromise(wsKey)?.promise;
301
+ }
302
+ catch (e) {
303
+ this.logger.trace(e, { ...websocket_util_js_1.WS_LOGGER_CATEGORY, wsKey });
304
+ }
305
+ }
306
+ reconnectWithDelay(wsKey, connectionDelayMs) {
307
+ this.clearTimers(wsKey);
308
+ if (this.wsStore.getConnectionState(wsKey) !==
309
+ WsStore_types_js_1.WsConnectionStateEnum.CONNECTING) {
310
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.RECONNECTING);
311
+ }
312
+ this.wsStore.get(wsKey, true).activeReconnectTimer = setTimeout(() => {
313
+ this.logger.info('Reconnecting to websocket', {
314
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
315
+ wsKey,
316
+ });
317
+ this.connect(wsKey);
318
+ }, connectionDelayMs);
319
+ }
320
+ ping(wsKey) {
321
+ if (this.wsStore.get(wsKey, true).activePongTimer) {
322
+ return;
323
+ }
324
+ this.clearPongTimer(wsKey);
325
+ this.logger.trace('Sending ping', { ...websocket_util_js_1.WS_LOGGER_CATEGORY, wsKey });
326
+ this.tryWsSend(wsKey, 'ping');
327
+ this.wsStore.get(wsKey, true).activePongTimer = setTimeout(() => {
328
+ this.logger.info('Pong timeout - closing socket to reconnect', {
329
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
330
+ wsKey,
331
+ });
332
+ (0, websocket_util_js_1.safeTerminateWs)(this.getWs(wsKey), true);
333
+ delete this.wsStore.get(wsKey, true).activePongTimer;
334
+ }, this.options.pongTimeout);
335
+ }
336
+ clearTimers(wsKey) {
337
+ this.clearPingTimer(wsKey);
338
+ this.clearPongTimer(wsKey);
339
+ const wsState = this.wsStore.get(wsKey);
340
+ if (wsState?.activeReconnectTimer) {
341
+ clearTimeout(wsState.activeReconnectTimer);
342
+ }
343
+ }
344
+ // Send a ping at intervals
345
+ clearPingTimer(wsKey) {
346
+ const wsState = this.wsStore.get(wsKey);
347
+ if (wsState?.activePingTimer) {
348
+ clearInterval(wsState.activePingTimer);
349
+ wsState.activePingTimer = undefined;
350
+ }
351
+ }
352
+ // Expect a pong within a time limit
353
+ clearPongTimer(wsKey) {
354
+ const wsState = this.wsStore.get(wsKey);
355
+ if (wsState?.activePongTimer) {
356
+ clearTimeout(wsState.activePongTimer);
357
+ wsState.activePongTimer = undefined;
358
+ }
359
+ }
360
+ /**
361
+ * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics
362
+ *
363
+ * If events are an object, these should be stringified (`return JSON.stringify(event);`)
364
+ * Each event returned by this will be sent one at a time
365
+ *
366
+ * Events are automatically split into smaller batches, by this method, if needed.
367
+ */
368
+ async getWsOperationEventsForTopics(topics, wsKey, operation) {
369
+ if (!topics.length) {
370
+ return [];
371
+ }
372
+ // Events that are ready to send (usually stringified JSON)
373
+ const requestEvents = [];
374
+ const maxTopicsPerEvent = this.getMaxTopicsPerSubscribeEvent(wsKey);
375
+ if (maxTopicsPerEvent &&
376
+ maxTopicsPerEvent !== null &&
377
+ topics.length > maxTopicsPerEvent) {
378
+ for (let i = 0; i < topics.length; i += maxTopicsPerEvent) {
379
+ const batch = topics.slice(i, i + maxTopicsPerEvent);
380
+ const subscribeRequestEvents = await this.getWsRequestEvents(operation, batch, wsKey);
381
+ requestEvents.push(...subscribeRequestEvents);
382
+ }
383
+ return requestEvents;
384
+ }
385
+ const subscribeRequestEvents = await this.getWsRequestEvents(operation, topics, wsKey);
386
+ return subscribeRequestEvents;
387
+ }
388
+ /**
389
+ * @private Use the `subscribe(topics)` method to subscribe to topics. Send WS message to subscribe to topics.
390
+ */
391
+ async requestSubscribeTopics(wsKey, wsTopicRequests) {
392
+ if (!wsTopicRequests.length) {
393
+ return;
394
+ }
395
+ // Automatically splits requests into smaller batches, if needed
396
+ const subscribeWsMessages = await this.getWsOperationEventsForTopics(wsTopicRequests, wsKey, 'subscribe');
397
+ this.logger.trace(`Subscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`);
398
+ // console.log(`batches: `, JSON.stringify(subscribeWsMessages, null, 2));
399
+ for (const midflightRequest of subscribeWsMessages) {
400
+ const wsMessage = midflightRequest.requestEvent;
401
+ if (!this.midflightRequestCache[wsKey]) {
402
+ this.midflightRequestCache[wsKey] = {};
403
+ }
404
+ // Cache the request for this call, so we can enrich the response with request info
405
+ // this.midflightRequestCache[wsKey][midflightRequest.requestKey] =
406
+ // midflightRequest.requestEvent;
407
+ this.logger.trace(
408
+ // `Sending batch via message: "${JSON.stringify(wsMessage)}", cached with key "${midflightRequest.requestKey}"`,
409
+ `Sending batch via message: "${JSON.stringify(wsMessage)}"`);
410
+ try {
411
+ this.tryWsSend(wsKey, JSON.stringify(wsMessage), true);
412
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
413
+ }
414
+ catch (e) {
415
+ delete this.midflightRequestCache[wsKey][midflightRequest.requestKey];
416
+ }
417
+ }
418
+ }
419
+ /**
420
+ * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics.
421
+ */
422
+ async requestUnsubscribeTopics(wsKey, wsTopicRequests) {
423
+ if (!wsTopicRequests.length) {
424
+ return;
425
+ }
426
+ const subscribeWsMessages = await this.getWsOperationEventsForTopics(wsTopicRequests, wsKey, 'unsubscribe');
427
+ this.logger.trace(`Unsubscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches. Events: "${JSON.stringify(wsTopicRequests)}"`);
428
+ for (const midflightRequest of subscribeWsMessages) {
429
+ const wsMessage = midflightRequest.requestEvent;
430
+ if (!this.midflightRequestCache[wsKey]) {
431
+ this.midflightRequestCache[wsKey] = {};
432
+ }
433
+ // Cache the request for this call, so we can enrich the response with request info
434
+ // this.midflightRequestCache[wsKey][midflightRequest.requestKey] =
435
+ // midflightRequest.requestEvent;
436
+ this.logger.trace(`Sending batch via message: "${wsMessage}"`);
437
+ try {
438
+ this.tryWsSend(wsKey, JSON.stringify(wsMessage));
439
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
440
+ }
441
+ catch (e) {
442
+ delete this.midflightRequestCache[wsKey][midflightRequest.requestKey];
443
+ }
444
+ }
445
+ this.logger.trace(`Finished unsubscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`);
446
+ // const wsMessage = JSON.stringify({
447
+ // op: 'unsubscribe',
448
+ // args: wsTopicRequests,
449
+ // });
450
+ }
451
+ getCachedMidFlightRequest(wsKey, requestKey) {
452
+ if (!this.midflightRequestCache[wsKey]) {
453
+ this.midflightRequestCache[wsKey] = {};
454
+ }
455
+ return this.midflightRequestCache[wsKey][requestKey];
456
+ }
457
+ // Not in use for Bitget. If desired, call from resolveEmittableEvents() for WS API responses.
458
+ // See binance SDK for reference
459
+ removeCachedMidFlightRequest(wsKey, requestKey) {
460
+ if (this.getCachedMidFlightRequest(wsKey, requestKey)) {
461
+ delete this.midflightRequestCache[wsKey][requestKey];
462
+ }
463
+ }
464
+ tryWsSend(wsKey, wsMessage, throwExceptions) {
465
+ try {
466
+ this.logger.trace('Sending upstream ws message: ', {
467
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
468
+ wsMessage,
469
+ wsKey,
470
+ });
471
+ if (!wsKey) {
472
+ throw new Error('Cannot send message due to no known websocket for this wsKey');
473
+ }
474
+ const ws = this.getWs(wsKey);
475
+ if (!ws) {
476
+ throw new Error(`${wsKey} socket not connected yet, call "connectAll()" first then try again when the "open" event arrives`);
477
+ }
478
+ ws.send(wsMessage);
479
+ }
480
+ catch (e) {
481
+ this.logger.error('Failed to send WS message', {
482
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
483
+ wsMessage,
484
+ wsKey,
485
+ exception: e,
486
+ });
487
+ if (throwExceptions) {
488
+ throw e;
489
+ }
490
+ }
491
+ }
492
+ async onWsOpen(event, wsKey, url, ws) {
493
+ const isFreshConnectionAttempt = this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTING);
494
+ const isReconnectionAttempt = this.wsStore.isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.RECONNECTING);
495
+ if (isFreshConnectionAttempt) {
496
+ this.logger.info('Websocket connected', {
497
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
498
+ wsKey,
499
+ });
500
+ this.emit('open', { wsKey, event, wsUrl: url, ws });
501
+ }
502
+ else if (isReconnectionAttempt) {
503
+ this.logger.info('Websocket reconnected', {
504
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
505
+ wsKey,
506
+ });
507
+ this.emit('reconnected', { wsKey, event, wsUrl: url, ws });
508
+ }
509
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTED);
510
+ this.logger.trace('Enabled ping timer', { ...websocket_util_js_1.WS_LOGGER_CATEGORY, wsKey });
511
+ this.wsStore.get(wsKey, true).activePingTimer = setInterval(() => this.ping(wsKey), this.options.pingInterval);
512
+ // Resolve & cleanup deferred "connection attempt in progress" promise
513
+ try {
514
+ const connectionInProgressPromise = this.wsStore.getConnectionInProgressPromise(wsKey);
515
+ if (connectionInProgressPromise?.resolve) {
516
+ connectionInProgressPromise.resolve({
517
+ wsKey,
518
+ ws,
519
+ });
520
+ }
521
+ }
522
+ catch (e) {
523
+ this.logger.error('Exception trying to resolve "connectionInProgress" promise', e);
524
+ }
525
+ // Remove before continuing, in case there's more requests queued
526
+ this.wsStore.removeConnectingInProgressPromise(wsKey);
527
+ // Some websockets require an auth packet to be sent after opening the connection
528
+ if (this.isAuthOnConnectWsKey(wsKey) &&
529
+ this.options.authPrivateConnectionsOnConnect) {
530
+ await this.assertIsAuthenticated(wsKey);
531
+ }
532
+ // Reconnect to topics known before it connected
533
+ const { privateReqs, publicReqs } = this.sortTopicRequestsIntoPublicPrivate([...this.wsStore.getTopics(wsKey)], wsKey);
534
+ // Request sub to public topics, if any
535
+ this.requestSubscribeTopics(wsKey, publicReqs);
536
+ // Request sub to private topics, if auth on connect isn't needed
537
+ // Else, this is automatic after authentication is successfully confirmed
538
+ if (!this.options.authPrivateConnectionsOnConnect) {
539
+ this.requestSubscribeTopics(wsKey, privateReqs);
540
+ }
541
+ }
542
+ /**
543
+ * Handle subscription to private topics _after_ authentication successfully completes asynchronously.
544
+ *
545
+ * Only used for exchanges that require auth before sending private topic subscription requests
546
+ */
547
+ onWsAuthenticated(wsKey, event) {
548
+ const wsState = this.wsStore.get(wsKey, true);
549
+ wsState.isAuthenticated = true;
550
+ // Resolve & cleanup deferred "auth attempt in progress" promise
551
+ try {
552
+ const inProgressPromise = this.wsStore.getAuthenticationInProgressPromise(wsKey);
553
+ if (inProgressPromise?.resolve) {
554
+ inProgressPromise.resolve({
555
+ wsKey,
556
+ event,
557
+ ws: wsState.ws,
558
+ });
559
+ }
560
+ }
561
+ catch (e) {
562
+ this.logger.error('Exception trying to resolve "authenticationInProgress" promise', e);
563
+ }
564
+ // Remove before continuing, in case there's more requests queued
565
+ this.wsStore.removeAuthenticationInProgressPromise(wsKey);
566
+ if (this.options.authPrivateConnectionsOnConnect) {
567
+ const topics = [...this.wsStore.getTopics(wsKey)];
568
+ const privateTopics = topics.filter((topic) => this.isPrivateTopicRequest(topic, wsKey));
569
+ if (privateTopics.length) {
570
+ this.subscribeTopicsForWsKey(privateTopics, wsKey);
571
+ }
572
+ }
573
+ }
574
+ /**
575
+ * Raw incoming event handler. Parsing happens in integration layer via resolveEmittableEvents().
576
+ */
577
+ onWsMessage(event, wsKey, ws) {
578
+ try {
579
+ // console.log('onMessageRaw: ', (event as any).data);
580
+ // any message can clear the pong timer - wouldn't get a message if the ws wasn't working
581
+ this.clearPongTimer(wsKey);
582
+ if (this.isWsPong(event)) {
583
+ this.logger.trace('Received pong', {
584
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
585
+ wsKey,
586
+ event: event?.data,
587
+ });
588
+ return;
589
+ }
590
+ if (this.isWsPing(event)) {
591
+ this.logger.trace('Received ping', {
592
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
593
+ wsKey,
594
+ event,
595
+ });
596
+ this.sendPongEvent(wsKey, ws);
597
+ return;
598
+ }
599
+ if ((0, ws_events_js_1.isMessageEvent)(event)) {
600
+ const data = event.data;
601
+ const dataType = event.type;
602
+ const emittableEvents = this.resolveEmittableEvents(wsKey, event);
603
+ if (!emittableEvents.length) {
604
+ // console.log(`raw event: `, { data, dataType, emittableEvents });
605
+ this.logger.error('Unhandled/unrecognised ws event message - returned no emittable data', {
606
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
607
+ message: data || 'no message',
608
+ dataType,
609
+ event,
610
+ wsKey,
611
+ });
612
+ return this.emit('update', { ...event, wsKey });
613
+ }
614
+ for (const emittable of emittableEvents) {
615
+ if (this.isWsPong(emittable)) {
616
+ this.logger.trace('Received pong2', {
617
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
618
+ wsKey,
619
+ data,
620
+ });
621
+ continue;
622
+ }
623
+ // this.logger.trace(
624
+ // 'getFinalEmittable()->pre(): ',
625
+ // JSON.stringify(emittable),
626
+ // );
627
+ const emittableFinalEvent = getFinalEmittable(emittable, wsKey, emittable.isWSAPIResponse);
628
+ // this.logger.trace(
629
+ // 'getFinalEmittable()->post(): ',
630
+ // JSON.stringify(emittable),
631
+ // );
632
+ if (emittable.eventType === 'authenticated') {
633
+ this.logger.trace('Successfully authenticated', {
634
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
635
+ wsKey,
636
+ emittable,
637
+ });
638
+ this.emit(emittable.eventType, emittableFinalEvent);
639
+ this.onWsAuthenticated(wsKey, emittable.event);
640
+ continue;
641
+ }
642
+ // Other event types are automatically emitted here
643
+ // this.logger.trace(
644
+ // `onWsMessage().emit(${emittable.eventType})`,
645
+ // emittableFinalEvent,
646
+ // );
647
+ try {
648
+ this.emit(emittable.eventType, emittableFinalEvent);
649
+ }
650
+ catch (e) {
651
+ this.logger.error(`Exception in onWsMessage().emit(${emittable.eventType}) handler:`, e);
652
+ }
653
+ // this.logger.trace(
654
+ // `onWsMessage().emit(${emittable.eventType}).done()`,
655
+ // emittableFinalEvent,
656
+ // );
657
+ }
658
+ return;
659
+ }
660
+ this.logger.error('Unhandled/unrecognised ws event message - unexpected message format', {
661
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
662
+ message: event || 'no message',
663
+ event,
664
+ wsKey,
665
+ });
666
+ }
667
+ catch (e) {
668
+ this.logger.error('Failed to parse ws event message', {
669
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
670
+ error: e,
671
+ event,
672
+ wsKey,
673
+ });
674
+ }
675
+ }
676
+ onWsClose(event, wsKey) {
677
+ this.logger.info('Websocket connection closed', {
678
+ ...websocket_util_js_1.WS_LOGGER_CATEGORY,
679
+ wsKey,
680
+ });
681
+ const wsState = this.wsStore.get(wsKey, true);
682
+ wsState.isAuthenticated = false;
683
+ if (this.wsStore.getConnectionState(wsKey) !== WsStore_types_js_1.WsConnectionStateEnum.CLOSING) {
684
+ // unintentional close, attempt recovery
685
+ this.logger.trace(`onWsClose(${wsKey}): rejecting all deferred promises...`);
686
+ // clean up any pending promises for this connection
687
+ this.getWsStore().rejectAllDeferredPromises(wsKey, 'connection lost, reconnecting');
688
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.INITIAL);
689
+ this.reconnectWithDelay(wsKey, this.options.reconnectTimeout);
690
+ this.emit('reconnect', { wsKey, event });
691
+ }
692
+ else {
693
+ // intentional close - clean up
694
+ // clean up any pending promises for this connection
695
+ this.logger.trace(`onWsClose(${wsKey}): rejecting all deferred promises...`);
696
+ this.getWsStore().rejectAllDeferredPromises(wsKey, 'disconnected');
697
+ this.setWsState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.INITIAL);
698
+ // This was an intentional close, delete all state for this connection, as if it never existed:
699
+ this.wsStore.delete(wsKey);
700
+ this.emit('close', { wsKey, event });
701
+ }
702
+ }
703
+ getWs(wsKey) {
704
+ return this.wsStore.getWs(wsKey);
705
+ }
706
+ setWsState(wsKey, state) {
707
+ this.wsStore.setConnectionState(wsKey, state);
708
+ }
709
+ /**
710
+ * Promise-driven method to assert that a ws has successfully connected (will await until connection is open)
711
+ */
712
+ async assertIsConnected(wsKey) {
713
+ const isConnected = this.getWsStore().isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTED);
714
+ if (isConnected) {
715
+ return true;
716
+ }
717
+ const inProgressPromise = this.getWsStore().getConnectionInProgressPromise(wsKey);
718
+ // Already in progress? Await shared promise and retry
719
+ if (inProgressPromise) {
720
+ this.logger.trace('assertIsConnected(): awaiting...');
721
+ await inProgressPromise.promise;
722
+ this.logger.trace('assertIsConnected(): awaiting...connected!');
723
+ return inProgressPromise.promise;
724
+ }
725
+ // Start connection, it should automatically store/return a promise.
726
+ this.logger.trace('assertIsConnected(): connecting...');
727
+ await this.connect(wsKey);
728
+ this.logger.trace('assertIsConnected(): connecting...newly connected!');
729
+ }
730
+ /**
731
+ * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed)
732
+ */
733
+ async assertIsAuthenticated(wsKey) {
734
+ const isConnected = this.getWsStore().isConnectionState(wsKey, WsStore_types_js_1.WsConnectionStateEnum.CONNECTED);
735
+ if (!isConnected) {
736
+ this.logger.trace('assertIsAuthenticated(): connecting...');
737
+ await this.assertIsConnected(wsKey);
738
+ }
739
+ const inProgressPromise = this.getWsStore().getAuthenticationInProgressPromise(wsKey);
740
+ // Already in progress? Await shared promise and retry
741
+ if (inProgressPromise) {
742
+ this.logger.trace('assertIsAuthenticated(): awaiting...');
743
+ await inProgressPromise.promise;
744
+ this.logger.trace('assertIsAuthenticated(): authenticated!');
745
+ return;
746
+ }
747
+ const isAuthenticated = this.wsStore.get(wsKey)?.isAuthenticated;
748
+ if (isAuthenticated) {
749
+ // this.logger.trace('assertIsAuthenticated(): ok');
750
+ return;
751
+ }
752
+ // Start authentication, it should automatically store/return a promise.
753
+ this.logger.trace('assertIsAuthenticated(): authenticating...');
754
+ await this.sendAuthRequest(wsKey);
755
+ this.logger.trace('assertIsAuthenticated(): newly authenticated!');
756
+ }
757
+ }
758
+ exports.BaseWebsocketClient = BaseWebsocketClient;
759
+ //# sourceMappingURL=BaseWSClient.js.map