zalo-toolkit 1.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 (393) hide show
  1. package/dist/Errors/ZaloApiError.d.ts +4 -0
  2. package/dist/Errors/ZaloApiError.js +7 -0
  3. package/dist/Errors/ZaloApiLoginQRAborted.d.ts +4 -0
  4. package/dist/Errors/ZaloApiLoginQRAborted.js +7 -0
  5. package/dist/Errors/ZaloApiLoginQRDeclined.d.ts +4 -0
  6. package/dist/Errors/ZaloApiLoginQRDeclined.js +7 -0
  7. package/dist/Errors/ZaloApiMissingImageMetadataGetter.d.ts +4 -0
  8. package/dist/Errors/ZaloApiMissingImageMetadataGetter.js +7 -0
  9. package/dist/Errors/index.d.ts +4 -0
  10. package/dist/Errors/index.js +4 -0
  11. package/dist/apis/acceptFriendRequest.d.ts +2 -0
  12. package/dist/apis/acceptFriendRequest.js +28 -0
  13. package/dist/apis/addGroupBlockedMember.d.ts +2 -0
  14. package/dist/apis/addGroupBlockedMember.js +28 -0
  15. package/dist/apis/addGroupDeputy.d.ts +2 -0
  16. package/dist/apis/addGroupDeputy.js +31 -0
  17. package/dist/apis/addPollOptions.d.ts +14 -0
  18. package/dist/apis/addPollOptions.js +26 -0
  19. package/dist/apis/addQuickMessage.d.ts +11 -0
  20. package/dist/apis/addQuickMessage.js +60 -0
  21. package/dist/apis/addReaction.d.ts +19 -0
  22. package/dist/apis/addReaction.js +292 -0
  23. package/dist/apis/addUnreadMark.d.ts +8 -0
  24. package/dist/apis/addUnreadMark.js +52 -0
  25. package/dist/apis/addUserToGroup.d.ts +5 -0
  26. package/dist/apis/addUserToGroup.js +34 -0
  27. package/dist/apis/blockUser.d.ts +2 -0
  28. package/dist/apis/blockUser.js +28 -0
  29. package/dist/apis/blockViewFeed.d.ts +2 -0
  30. package/dist/apis/blockViewFeed.js +30 -0
  31. package/dist/apis/changeAccountAvatar.d.ts +2 -0
  32. package/dist/apis/changeAccountAvatar.js +51 -0
  33. package/dist/apis/changeFriendAlias.d.ts +2 -0
  34. package/dist/apis/changeFriendAlias.js +27 -0
  35. package/dist/apis/changeGroupAvatar.d.ts +2 -0
  36. package/dist/apis/changeGroupAvatar.js +42 -0
  37. package/dist/apis/changeGroupName.d.ts +4 -0
  38. package/dist/apis/changeGroupName.js +32 -0
  39. package/dist/apis/changeGroupOwner.d.ts +4 -0
  40. package/dist/apis/changeGroupOwner.js +31 -0
  41. package/dist/apis/createAutoReply.d.ts +14 -0
  42. package/dist/apis/createAutoReply.js +37 -0
  43. package/dist/apis/createCatalog.d.ts +7 -0
  44. package/dist/apis/createCatalog.js +29 -0
  45. package/dist/apis/createGroup.d.ts +22 -0
  46. package/dist/apis/createGroup.js +43 -0
  47. package/dist/apis/createNote.d.ts +7 -0
  48. package/dist/apis/createNote.js +47 -0
  49. package/dist/apis/createPoll.d.ts +55 -0
  50. package/dist/apis/createPoll.js +40 -0
  51. package/dist/apis/createProductCatalog.d.ts +23 -0
  52. package/dist/apis/createProductCatalog.js +50 -0
  53. package/dist/apis/createReminder.d.ts +12 -0
  54. package/dist/apis/createReminder.js +63 -0
  55. package/dist/apis/custom.d.ts +9 -0
  56. package/dist/apis/custom.js +15 -0
  57. package/dist/apis/deleteAutoReply.d.ts +5 -0
  58. package/dist/apis/deleteAutoReply.js +29 -0
  59. package/dist/apis/deleteAvatar.d.ts +9 -0
  60. package/dist/apis/deleteAvatar.js +27 -0
  61. package/dist/apis/deleteCatalog.d.ts +2 -0
  62. package/dist/apis/deleteCatalog.js +28 -0
  63. package/dist/apis/deleteChat.d.ts +19 -0
  64. package/dist/apis/deleteChat.js +50 -0
  65. package/dist/apis/deleteGroupInviteBox.d.ts +9 -0
  66. package/dist/apis/deleteGroupInviteBox.js +27 -0
  67. package/dist/apis/deleteMessage.d.ts +14 -0
  68. package/dist/apis/deleteMessage.js +52 -0
  69. package/dist/apis/deleteProductCatalog.d.ts +10 -0
  70. package/dist/apis/deleteProductCatalog.js +31 -0
  71. package/dist/apis/disableGroupLink.d.ts +2 -0
  72. package/dist/apis/disableGroupLink.js +24 -0
  73. package/dist/apis/disperseGroup.d.ts +2 -0
  74. package/dist/apis/disperseGroup.js +28 -0
  75. package/dist/apis/editNote.d.ts +17 -0
  76. package/dist/apis/editNote.js +46 -0
  77. package/dist/apis/editReminder.d.ts +13 -0
  78. package/dist/apis/editReminder.js +61 -0
  79. package/dist/apis/enableGroupLink.d.ts +6 -0
  80. package/dist/apis/enableGroupLink.js +25 -0
  81. package/dist/apis/fetchAccountInfo.d.ts +3 -0
  82. package/dist/apis/fetchAccountInfo.js +10 -0
  83. package/dist/apis/findUser.d.ts +15 -0
  84. package/dist/apis/findUser.js +40 -0
  85. package/dist/apis/forwardAttachment.d.ts +16 -0
  86. package/dist/apis/forwardAttachment.js +80 -0
  87. package/dist/apis/forwardMessage.d.ts +33 -0
  88. package/dist/apis/forwardMessage.js +119 -0
  89. package/dist/apis/getAliasList.d.ts +8 -0
  90. package/dist/apis/getAliasList.js +28 -0
  91. package/dist/apis/getAllFriends.d.ts +3 -0
  92. package/dist/apis/getAllFriends.js +32 -0
  93. package/dist/apis/getAllGroups.d.ts +7 -0
  94. package/dist/apis/getAllGroups.js +10 -0
  95. package/dist/apis/getArchivedChatList.d.ts +5 -0
  96. package/dist/apis/getArchivedChatList.js +23 -0
  97. package/dist/apis/getAutoDeleteChat.d.ts +9 -0
  98. package/dist/apis/getAutoDeleteChat.js +21 -0
  99. package/dist/apis/getAutoReplyList.d.ts +6 -0
  100. package/dist/apis/getAutoReplyList.js +24 -0
  101. package/dist/apis/getAvatarList.d.ts +12 -0
  102. package/dist/apis/getAvatarList.js +28 -0
  103. package/dist/apis/getBizAccount.d.ts +24 -0
  104. package/dist/apis/getBizAccount.js +27 -0
  105. package/dist/apis/getCatalogList.d.ts +18 -0
  106. package/dist/apis/getCatalogList.js +32 -0
  107. package/dist/apis/getContext.d.ts +1 -0
  108. package/dist/apis/getContext.js +4 -0
  109. package/dist/apis/getCookie.d.ts +1 -0
  110. package/dist/apis/getCookie.js +9 -0
  111. package/dist/apis/getFriendBoardList.d.ts +5 -0
  112. package/dist/apis/getFriendBoardList.js +26 -0
  113. package/dist/apis/getFriendOnlines.d.ts +10 -0
  114. package/dist/apis/getFriendOnlines.js +35 -0
  115. package/dist/apis/getFriendRecommendations.d.ts +42 -0
  116. package/dist/apis/getFriendRecommendations.js +27 -0
  117. package/dist/apis/getFriendRequestStatus.d.ts +8 -0
  118. package/dist/apis/getFriendRequestStatus.js +25 -0
  119. package/dist/apis/getGroupBlockedMember.d.ts +23 -0
  120. package/dist/apis/getGroupBlockedMember.js +29 -0
  121. package/dist/apis/getGroupInfo.d.ts +16 -0
  122. package/dist/apis/getGroupInfo.js +32 -0
  123. package/dist/apis/getGroupInviteBoxInfo.d.ts +32 -0
  124. package/dist/apis/getGroupInviteBoxInfo.js +38 -0
  125. package/dist/apis/getGroupInviteBoxList.d.ts +38 -0
  126. package/dist/apis/getGroupInviteBoxList.js +31 -0
  127. package/dist/apis/getGroupLinkDetail.d.ts +9 -0
  128. package/dist/apis/getGroupLinkDetail.js +25 -0
  129. package/dist/apis/getGroupLinkInfo.d.ts +34 -0
  130. package/dist/apis/getGroupLinkInfo.js +28 -0
  131. package/dist/apis/getGroupMembersInfo.d.ts +17 -0
  132. package/dist/apis/getGroupMembersInfo.js +24 -0
  133. package/dist/apis/getHiddenConversations.d.ts +11 -0
  134. package/dist/apis/getHiddenConversations.js +23 -0
  135. package/dist/apis/getLabels.d.ts +7 -0
  136. package/dist/apis/getLabels.js +28 -0
  137. package/dist/apis/getLastMessage.d.ts +9 -0
  138. package/dist/apis/getLastMessage.js +20 -0
  139. package/dist/apis/getListBoard.d.ts +21 -0
  140. package/dist/apis/getListBoard.js +45 -0
  141. package/dist/apis/getListReminder.d.ts +28 -0
  142. package/dist/apis/getListReminder.js +47 -0
  143. package/dist/apis/getMute.d.ts +13 -0
  144. package/dist/apis/getMute.js +22 -0
  145. package/dist/apis/getOwnId.d.ts +1 -0
  146. package/dist/apis/getOwnId.js +4 -0
  147. package/dist/apis/getPendingGroupMembers.d.ts +11 -0
  148. package/dist/apis/getPendingGroupMembers.js +27 -0
  149. package/dist/apis/getPinConversations.d.ts +5 -0
  150. package/dist/apis/getPinConversations.js +22 -0
  151. package/dist/apis/getPollDetail.d.ts +3 -0
  152. package/dist/apis/getPollDetail.js +30 -0
  153. package/dist/apis/getProductCatalogList.d.ts +20 -0
  154. package/dist/apis/getProductCatalogList.js +33 -0
  155. package/dist/apis/getQR.d.ts +4 -0
  156. package/dist/apis/getQR.js +29 -0
  157. package/dist/apis/getQuickMessageList.d.ts +7 -0
  158. package/dist/apis/getQuickMessageList.js +24 -0
  159. package/dist/apis/getRecommendFriends.d.ts +40 -0
  160. package/dist/apis/getRecommendFriends.js +20 -0
  161. package/dist/apis/getRelatedFriendGroup.d.ts +6 -0
  162. package/dist/apis/getRelatedFriendGroup.js +30 -0
  163. package/dist/apis/getReminder.d.ts +3 -0
  164. package/dist/apis/getReminder.js +25 -0
  165. package/dist/apis/getReminderResponses.d.ts +5 -0
  166. package/dist/apis/getReminderResponses.js +24 -0
  167. package/dist/apis/getSentFriendRequest.d.ts +18 -0
  168. package/dist/apis/getSentFriendRequest.js +24 -0
  169. package/dist/apis/getSettings.d.ts +3 -0
  170. package/dist/apis/getSettings.js +20 -0
  171. package/dist/apis/getStickers.d.ts +1 -0
  172. package/dist/apis/getStickers.js +40 -0
  173. package/dist/apis/getStickersDetail.d.ts +24 -0
  174. package/dist/apis/getStickersDetail.js +40 -0
  175. package/dist/apis/getUnreadMark.d.ts +14 -0
  176. package/dist/apis/getUnreadMark.js +30 -0
  177. package/dist/apis/getUserInfo.d.ts +8 -0
  178. package/dist/apis/getUserInfo.js +42 -0
  179. package/dist/apis/inviteUserToGroups.d.ts +10 -0
  180. package/dist/apis/inviteUserToGroups.js +30 -0
  181. package/dist/apis/joinGroupInviteBox.d.ts +2 -0
  182. package/dist/apis/joinGroupInviteBox.js +25 -0
  183. package/dist/apis/joinGroupLink.d.ts +2 -0
  184. package/dist/apis/joinGroupLink.js +27 -0
  185. package/dist/apis/keepAlive.d.ts +4 -0
  186. package/dist/apis/keepAlive.js +22 -0
  187. package/dist/apis/lastOnline.d.ts +7 -0
  188. package/dist/apis/lastOnline.js +26 -0
  189. package/dist/apis/leaveGroup.d.ts +4 -0
  190. package/dist/apis/leaveGroup.js +33 -0
  191. package/dist/apis/listen.d.ts +141 -0
  192. package/dist/apis/listen.js +822 -0
  193. package/dist/apis/lockPoll.d.ts +2 -0
  194. package/dist/apis/lockPoll.js +28 -0
  195. package/dist/apis/login.d.ts +3 -0
  196. package/dist/apis/login.js +96 -0
  197. package/dist/apis/loginQR.d.ts +42 -0
  198. package/dist/apis/loginQR.js +274 -0
  199. package/dist/apis/parseLink.d.ts +21 -0
  200. package/dist/apis/parseLink.js +27 -0
  201. package/dist/apis/rejectFriendRequest.d.ts +2 -0
  202. package/dist/apis/rejectFriendRequest.js +27 -0
  203. package/dist/apis/removeFriend.d.ts +2 -0
  204. package/dist/apis/removeFriend.js +28 -0
  205. package/dist/apis/removeFriendAlias.d.ts +2 -0
  206. package/dist/apis/removeFriendAlias.js +24 -0
  207. package/dist/apis/removeGroupBlockedMember.d.ts +2 -0
  208. package/dist/apis/removeGroupBlockedMember.js +28 -0
  209. package/dist/apis/removeGroupDeputy.d.ts +2 -0
  210. package/dist/apis/removeGroupDeputy.js +30 -0
  211. package/dist/apis/removeQuickMessage.d.ts +5 -0
  212. package/dist/apis/removeQuickMessage.js +27 -0
  213. package/dist/apis/removeReminder.d.ts +3 -0
  214. package/dist/apis/removeReminder.js +40 -0
  215. package/dist/apis/removeUnreadMark.d.ts +8 -0
  216. package/dist/apis/removeUnreadMark.js +50 -0
  217. package/dist/apis/removeUserFromGroup.d.ts +4 -0
  218. package/dist/apis/removeUserFromGroup.js +34 -0
  219. package/dist/apis/resetHiddenConversPin.d.ts +2 -0
  220. package/dist/apis/resetHiddenConversPin.js +20 -0
  221. package/dist/apis/reuseAvatar.d.ts +2 -0
  222. package/dist/apis/reuseAvatar.js +26 -0
  223. package/dist/apis/reviewPendingMemberRequest.d.ts +14 -0
  224. package/dist/apis/reviewPendingMemberRequest.js +38 -0
  225. package/dist/apis/sendBankCard.d.ts +9 -0
  226. package/dist/apis/sendBankCard.js +37 -0
  227. package/dist/apis/sendCard.d.ts +10 -0
  228. package/dist/apis/sendCard.js +59 -0
  229. package/dist/apis/sendDeliveredEvent.d.ts +16 -0
  230. package/dist/apis/sendDeliveredEvent.js +55 -0
  231. package/dist/apis/sendFriendRequest.d.ts +2 -0
  232. package/dist/apis/sendFriendRequest.js +39 -0
  233. package/dist/apis/sendLink.d.ts +10 -0
  234. package/dist/apis/sendLink.js +57 -0
  235. package/dist/apis/sendMessage.d.ts +100 -0
  236. package/dist/apis/sendMessage.js +437 -0
  237. package/dist/apis/sendReport.d.ts +17 -0
  238. package/dist/apis/sendReport.js +53 -0
  239. package/dist/apis/sendSeenEvent.d.ts +16 -0
  240. package/dist/apis/sendSeenEvent.js +63 -0
  241. package/dist/apis/sendSticker.d.ts +10 -0
  242. package/dist/apis/sendSticker.js +56 -0
  243. package/dist/apis/sendTypingEvent.d.ts +5 -0
  244. package/dist/apis/sendTypingEvent.js +33 -0
  245. package/dist/apis/sendVideo.d.ts +35 -0
  246. package/dist/apis/sendVideo.js +118 -0
  247. package/dist/apis/sendVoice.d.ts +12 -0
  248. package/dist/apis/sendVoice.js +73 -0
  249. package/dist/apis/setArchivedConversations.d.ts +10 -0
  250. package/dist/apis/setArchivedConversations.js +34 -0
  251. package/dist/apis/setHiddenConversations.d.ts +3 -0
  252. package/dist/apis/setHiddenConversations.js +39 -0
  253. package/dist/apis/setMute.d.ts +20 -0
  254. package/dist/apis/setMute.js +67 -0
  255. package/dist/apis/setPinnedConversations.d.ts +3 -0
  256. package/dist/apis/setPinnedConversations.js +34 -0
  257. package/dist/apis/sharePoll.d.ts +2 -0
  258. package/dist/apis/sharePoll.js +28 -0
  259. package/dist/apis/unblockUser.d.ts +2 -0
  260. package/dist/apis/unblockUser.js +28 -0
  261. package/dist/apis/undo.d.ts +9 -0
  262. package/dist/apis/undo.js +42 -0
  263. package/dist/apis/undoFriendRequest.d.ts +2 -0
  264. package/dist/apis/undoFriendRequest.js +27 -0
  265. package/dist/apis/updateActiveStatus.d.ts +4 -0
  266. package/dist/apis/updateActiveStatus.js +27 -0
  267. package/dist/apis/updateAutoDeleteChat.d.ts +9 -0
  268. package/dist/apis/updateAutoDeleteChat.js +40 -0
  269. package/dist/apis/updateAutoReply.d.ts +15 -0
  270. package/dist/apis/updateAutoReply.js +38 -0
  271. package/dist/apis/updateCatalog.d.ts +11 -0
  272. package/dist/apis/updateCatalog.js +30 -0
  273. package/dist/apis/updateGroupSettings.d.ts +40 -0
  274. package/dist/apis/updateGroupSettings.js +43 -0
  275. package/dist/apis/updateHiddenConversPin.d.ts +2 -0
  276. package/dist/apis/updateHiddenConversPin.js +30 -0
  277. package/dist/apis/updateLabels.d.ts +15 -0
  278. package/dist/apis/updateLabels.js +34 -0
  279. package/dist/apis/updateLang.d.ts +6 -0
  280. package/dist/apis/updateLang.js +30 -0
  281. package/dist/apis/updateProductCatalog.d.ts +25 -0
  282. package/dist/apis/updateProductCatalog.js +51 -0
  283. package/dist/apis/updateProfile.d.ts +20 -0
  284. package/dist/apis/updateProfile.js +43 -0
  285. package/dist/apis/updateQuickMessage.d.ts +11 -0
  286. package/dist/apis/updateQuickMessage.js +61 -0
  287. package/dist/apis/updateSettings.d.ts +16 -0
  288. package/dist/apis/updateSettings.js +90 -0
  289. package/dist/apis/uploadAttachment.d.ts +51 -0
  290. package/dist/apis/uploadAttachment.js +195 -0
  291. package/dist/apis/uploadProductPhoto.d.ts +13 -0
  292. package/dist/apis/uploadProductPhoto.js +45 -0
  293. package/dist/apis/votePoll.d.ts +5 -0
  294. package/dist/apis/votePoll.js +29 -0
  295. package/dist/apis.d.ts +293 -0
  296. package/dist/apis.js +287 -0
  297. package/dist/cjs/Errors/ZaloApiError.cjs +11 -0
  298. package/dist/cjs/Errors/ZaloApiLoginQRAborted.cjs +12 -0
  299. package/dist/cjs/Errors/ZaloApiLoginQRDeclined.cjs +12 -0
  300. package/dist/cjs/Errors/ZaloApiMissingImageMetadataGetter.cjs +12 -0
  301. package/dist/cjs/apis/login.cjs +102 -0
  302. package/dist/cjs/apis/loginQR.cjs +282 -0
  303. package/dist/cjs/apis/reviewPendingMemberRequest.cjs +21 -0
  304. package/dist/cjs/apis/sendMessage.cjs +44 -0
  305. package/dist/cjs/apis/sendReport.cjs +28 -0
  306. package/dist/cjs/apis/setMute.cjs +33 -0
  307. package/dist/cjs/apis/updateAutoDeleteChat.cjs +28 -0
  308. package/dist/cjs/apis/updateLang.cjs +19 -0
  309. package/dist/cjs/apis/updateSettings.cjs +29 -0
  310. package/dist/cjs/context.cjs +19 -0
  311. package/dist/cjs/index.cjs +142 -0
  312. package/dist/cjs/models/AutoReply.cjs +9 -0
  313. package/dist/cjs/models/Board.cjs +8 -0
  314. package/dist/cjs/models/DeliveredMessage.cjs +23 -0
  315. package/dist/cjs/models/Enum.cjs +253 -0
  316. package/dist/cjs/models/FriendEvent.cjs +87 -0
  317. package/dist/cjs/models/Group.cjs +13 -0
  318. package/dist/cjs/models/GroupEvent.cjs +94 -0
  319. package/dist/cjs/models/Listen.cjs +134 -0
  320. package/dist/cjs/models/Message.cjs +40 -0
  321. package/dist/cjs/models/Reaction.cjs +74 -0
  322. package/dist/cjs/models/Reminder.cjs +9 -0
  323. package/dist/cjs/models/SeenMessage.cjs +23 -0
  324. package/dist/cjs/models/Typing.cjs +23 -0
  325. package/dist/cjs/models/Undo.cjs +16 -0
  326. package/dist/cjs/models/ZBusiness.cjs +39 -0
  327. package/dist/cjs/utils.cjs +320 -0
  328. package/dist/cjs/zalo.cjs +127 -0
  329. package/dist/context.d.ts +199 -0
  330. package/dist/context.js +27 -0
  331. package/dist/core/enums/common.d.ts +11 -0
  332. package/dist/core/enums/common.js +12 -0
  333. package/dist/core/interfaces/common.d.ts +7 -0
  334. package/dist/core/interfaces/common.js +1 -0
  335. package/dist/core/utils/deserializer.d.ts +4 -0
  336. package/dist/core/utils/deserializer.js +25 -0
  337. package/dist/core/utils/index.d.ts +2 -0
  338. package/dist/core/utils/index.js +28 -0
  339. package/dist/core/utils/serializer.d.ts +9 -0
  340. package/dist/core/utils/serializer.js +24 -0
  341. package/dist/index.d.ts +144 -0
  342. package/dist/index.js +12 -0
  343. package/dist/models/AutoReply.d.ts +20 -0
  344. package/dist/models/AutoReply.js +7 -0
  345. package/dist/models/Board.d.ts +60 -0
  346. package/dist/models/Board.js +6 -0
  347. package/dist/models/Catalog.d.ts +16 -0
  348. package/dist/models/Catalog.js +1 -0
  349. package/dist/models/DeliveredMessage.d.ts +27 -0
  350. package/dist/models/DeliveredMessage.js +17 -0
  351. package/dist/models/Enum.d.ts +247 -0
  352. package/dist/models/Enum.js +251 -0
  353. package/dist/models/FriendEvent.d.ts +107 -0
  354. package/dist/models/FriendEvent.js +83 -0
  355. package/dist/models/Group.d.ts +125 -0
  356. package/dist/models/Group.js +11 -0
  357. package/dist/models/GroupEvent.d.ts +178 -0
  358. package/dist/models/GroupEvent.js +90 -0
  359. package/dist/models/Label.d.ts +10 -0
  360. package/dist/models/Label.js +1 -0
  361. package/dist/models/Listen.d.ts +186 -0
  362. package/dist/models/Listen.js +194 -0
  363. package/dist/models/Message.d.ts +97 -0
  364. package/dist/models/Message.js +34 -0
  365. package/dist/models/Mute.d.ts +10 -0
  366. package/dist/models/Mute.js +1 -0
  367. package/dist/models/ProductCatalog.d.ts +17 -0
  368. package/dist/models/ProductCatalog.js +1 -0
  369. package/dist/models/QuickMessage.d.ts +25 -0
  370. package/dist/models/QuickMessage.js +1 -0
  371. package/dist/models/Reaction.d.ts +85 -0
  372. package/dist/models/Reaction.js +70 -0
  373. package/dist/models/Reminder.d.ts +51 -0
  374. package/dist/models/Reminder.js +7 -0
  375. package/dist/models/SeenMessage.d.ts +26 -0
  376. package/dist/models/SeenMessage.js +17 -0
  377. package/dist/models/Typing.d.ts +24 -0
  378. package/dist/models/Typing.js +17 -0
  379. package/dist/models/Undo.d.ts +34 -0
  380. package/dist/models/Undo.js +12 -0
  381. package/dist/models/User.d.ts +49 -0
  382. package/dist/models/User.js +1 -0
  383. package/dist/models/ZBusiness.d.ts +22 -0
  384. package/dist/models/ZBusiness.js +35 -0
  385. package/dist/models/index.d.ts +19 -0
  386. package/dist/models/index.js +19 -0
  387. package/dist/socket/config-socket.d.ts +38 -0
  388. package/dist/socket/config-socket.js +202 -0
  389. package/dist/utils.d.ts +190 -0
  390. package/dist/utils.js +749 -0
  391. package/dist/zalo.d.ts +64 -0
  392. package/dist/zalo.js +103 -0
  393. package/package.json +61 -0
@@ -0,0 +1,822 @@
1
+ import { EventEmitter } from 'stream';
2
+ import { GroupDeliveredMessage, UserDeliveredMessage } from '../models/DeliveredMessage.js';
3
+ import { initializeFriendEvent } from '../models/FriendEvent.js';
4
+ import { initializeGroupEvent } from '../models/GroupEvent.js';
5
+ import { CloseReason, ConnectionErrorCode, DEFAULT_RETRY_DELAYS, KeepAliveCommand, MessageCommand, NetworkErrorCode, SocketEvent } from '../models/Listen.js';
6
+ import { GroupMessage, UserMessage } from '../models/Message.js';
7
+ import { Reaction } from '../models/Reaction.js';
8
+ import { GroupSeenMessage, UserSeenMessage } from '../models/SeenMessage.js';
9
+ import { GroupTyping, UserTyping } from '../models/Typing.js';
10
+ import { Undo } from '../models/Undo.js';
11
+ import { decodeEventData, FibonacciRetry, getFriendEventType, getGroupEventType, logger, looksLikeJson, makeURL } from '../utils.js';
12
+ import { ConfigSocket } from '../socket/config-socket.js';
13
+ import { ZaloApiError } from '../Errors/ZaloApiError.js';
14
+ import WebSocket from 'ws';
15
+ import { last } from 'lodash';
16
+ export class Listener extends EventEmitter {
17
+ constructor(api) {
18
+ super();
19
+ this.api = api;
20
+ this.id = 0;
21
+ this.retries = {};
22
+ this.retriesRound2 = {};
23
+ this.rotateCount = 0;
24
+ this.listUrlSocket = [];
25
+ this.pingHttp = {};
26
+ this.fibonacciRetry = new FibonacciRetry();
27
+ this.configChanged = false;
28
+ this._onClose = (event) => {
29
+ console.log('Is closed now ', this.ctx.uid, event.code);
30
+ this.afterClose();
31
+ if (!event || event.code === null) {
32
+ this.handleError(ConnectionErrorCode.Unknown);
33
+ return;
34
+ }
35
+ if (event.code === CloseReason.AbnormalClosure) {
36
+ this.retry(NetworkErrorCode.CannotReachServerNum);
37
+ return;
38
+ }
39
+ if (event.code === CloseReason.NormalClosure) {
40
+ return;
41
+ }
42
+ if (event.code > 1000 && event.code <= 1015) {
43
+ this.retry(NetworkErrorCode.Internal);
44
+ return;
45
+ }
46
+ return this.handleError(event.code);
47
+ };
48
+ this.shouldCloseAndReconnect = (errorCode) => {
49
+ var _a, _b;
50
+ return !!((_b = (_a = this.settingSocket) === null || _a === void 0 ? void 0 : _a.close_and_retry_codes) === null || _b === void 0 ? void 0 : _b.includes(errorCode));
51
+ };
52
+ this.genNextReqId = () => {
53
+ return 'req_' + this.id++;
54
+ };
55
+ this.ctx = api.getContext();
56
+ if (!this.ctx.cookie)
57
+ throw new Error('Cookie is not available');
58
+ if (!this.ctx.userAgent)
59
+ throw new Error('User agent is not available');
60
+ this.listUrlSocket = api.wsUrls;
61
+ this.url = this.getSocketUrl(false, true);
62
+ this.cookie = this.ctx.cookie.getCookieStringSync('https://chat.zalo.me');
63
+ this.userAgent = this.ctx.userAgent;
64
+ this.selfListen = this.ctx.options.selfListen;
65
+ this.settingSocket = this.ctx.settings.features.socket;
66
+ this.onlineConfigs = this.ctx.settings.features.online_configs;
67
+ this.retries = this.ctx.settings.features.socket.retries;
68
+ this._configRetriesRound2();
69
+ this.ws = null;
70
+ this.onConnectedCallback = () => { };
71
+ this.onClosedCallback = () => { };
72
+ this.onErrorCallback = () => { };
73
+ this.onMessageCallback = () => { };
74
+ this.onGroupEventCallback = () => { };
75
+ this.onMuteCallback = () => { };
76
+ this.onReactionCallback = () => { };
77
+ this.onOldMessageCallback = () => { };
78
+ this.onUndoMessageCallback = () => { };
79
+ this.onUpdateQueueStatusCallback = () => { };
80
+ this.onLabelEventCallback = () => { };
81
+ this.onFriendEventCallback = () => { };
82
+ }
83
+ onConnected(cb) {
84
+ this.onConnectedCallback = cb;
85
+ }
86
+ onClosed(cb) {
87
+ this.onClosedCallback = cb;
88
+ }
89
+ onError(cb) {
90
+ this.onErrorCallback = cb;
91
+ }
92
+ onMessage(cb) {
93
+ this.onMessageCallback = cb;
94
+ }
95
+ onOldMessage(cb) {
96
+ this.onOldMessageCallback = cb;
97
+ }
98
+ onGroupEvent(cb) {
99
+ this.onGroupEventCallback = cb;
100
+ }
101
+ onMute(cb) {
102
+ this.onMuteCallback = cb;
103
+ }
104
+ onReaction(cb) {
105
+ this.onReactionCallback = cb;
106
+ }
107
+ onUndo(cb) {
108
+ this.onUndoMessageCallback = cb;
109
+ }
110
+ onUpdateQueueStatus(cb) {
111
+ this.onUpdateQueueStatusCallback = cb;
112
+ }
113
+ onLabelEvent(cb) {
114
+ this.onLabelEventCallback = cb;
115
+ }
116
+ onFriendEvent(cb) {
117
+ this.onFriendEventCallback = cb;
118
+ }
119
+ start() {
120
+ if (this.ws)
121
+ throw new ZaloApiError('Already started');
122
+ const ws = new WebSocket(this.url, {
123
+ headers: {
124
+ 'accept-encoding': 'gzip, deflate, br, zstd',
125
+ 'accept-language': 'en-US,en;q=0.9',
126
+ 'cache-control': 'no-cache',
127
+ connection: 'Upgrade',
128
+ host: new URL(this.url).host,
129
+ origin: 'https://chat.zalo.me',
130
+ prgama: 'no-cache',
131
+ 'sec-websocket-extensions': 'permessage-deflate; client_max_window_bits',
132
+ 'sec-websocket-version': '13',
133
+ upgrade: 'websocket',
134
+ 'user-agent': this.userAgent,
135
+ cookie: this.cookie,
136
+ },
137
+ });
138
+ this.ws = ws;
139
+ this.configSocket = new ConfigSocket(ws, this.ctx.settings.features, this.ctx, this);
140
+ ws.onopen = () => {
141
+ this.onConnectedCallback();
142
+ this.emit('connected');
143
+ };
144
+ ws.onclose = this._onClose;
145
+ ws.onerror = (event) => {
146
+ // console.log('event error: ', this.ctx.uid, event);
147
+ };
148
+ ws.onmessage = async (event) => {
149
+ var _a, _b, _c;
150
+ const { data } = event;
151
+ if (!(data instanceof Buffer))
152
+ return;
153
+ const encodedHeader = data.subarray(0, 4);
154
+ const [version, cmd, subCmd] = getHeader(encodedHeader);
155
+ try {
156
+ const dataToDecode = data.subarray(4);
157
+ const decodedData = new TextDecoder('utf-8').decode(dataToDecode);
158
+ if (decodedData.length == 0)
159
+ return;
160
+ const parsed = JSON.parse(decodedData);
161
+ if (cmd === MessageCommand.Ping) {
162
+ if (subCmd === KeepAliveCommand.KeepConnection || this.onlineConfigs.send_active_to_keep_live) {
163
+ if ((_a = this.settingSocket.debug) === null || _a === void 0 ? void 0 : _a.skip_ping) {
164
+ return;
165
+ }
166
+ this.pong(parsed);
167
+ }
168
+ if (parsed && !isNaN(parsed.status)) {
169
+ this.emit(SocketEvent.ON_PING_ACTIVE_KEEP_ALIVE, parsed);
170
+ }
171
+ }
172
+ if (version == 1 && cmd == 1 && subCmd == 1 && parsed.hasOwnProperty('key')) {
173
+ this.cipherKey = parsed.key;
174
+ this.emit('cipher_key', parsed.key);
175
+ this.clearPingTimer();
176
+ this.createPingTimerServer();
177
+ if (this.pingInterval)
178
+ clearInterval(this.pingInterval);
179
+ this.pingInterval = setInterval(() => {
180
+ this.ping();
181
+ }, 3 * 60 * 1000);
182
+ }
183
+ if (version == 1 && cmd == 501 && subCmd == 0) {
184
+ const parsedData = (await decodeEventData(parsed, this.cipherKey)).data;
185
+ const { msgs, queueStatus } = parsedData;
186
+ const listUndo = [];
187
+ const listMessages = [];
188
+ for (const msg of msgs) {
189
+ if (typeof msg.content == 'object' && msg.content.hasOwnProperty('deleteMsg')) {
190
+ const undoObject = new Undo(this.ctx.uid, msg, false);
191
+ if (undoObject.isSelf && !this.selfListen)
192
+ continue;
193
+ listUndo.push(undoObject);
194
+ this.emit('undo', undoObject);
195
+ }
196
+ else {
197
+ const messageObject = new UserMessage(this.ctx.uid, msg, queueStatus);
198
+ if (messageObject.isSelf && !this.selfListen)
199
+ continue;
200
+ listMessages.push(messageObject);
201
+ this.emit('message', messageObject);
202
+ }
203
+ }
204
+ const lastMsg = last(msgs);
205
+ const timestamp = lastMsg ? Number(lastMsg.ts) : Date.now();
206
+ this.onUndoMessageCallback(listUndo);
207
+ this.onMessageCallback(listMessages);
208
+ this.onUpdateQueueStatusCallback(queueStatus, timestamp);
209
+ }
210
+ if (version == 1 && cmd == 521 && subCmd == 0) {
211
+ const parsedData = (await decodeEventData(parsed, this.cipherKey)).data;
212
+ const { groupMsgs, queueStatus } = parsedData;
213
+ const listUndo = [];
214
+ const listMessages = [];
215
+ for (const msg of groupMsgs) {
216
+ if (typeof msg.content == 'object' && msg.content.hasOwnProperty('deleteMsg')) {
217
+ const undoObject = new Undo(this.ctx.uid, msg, true);
218
+ if (undoObject.isSelf && !this.selfListen)
219
+ continue;
220
+ listUndo.push(undoObject);
221
+ this.emit('undo', undoObject);
222
+ }
223
+ else {
224
+ const messageObject = new GroupMessage(this.ctx.uid, msg, queueStatus);
225
+ if (messageObject.isSelf && !this.selfListen)
226
+ continue;
227
+ listMessages.push(messageObject);
228
+ this.emit('message', messageObject);
229
+ }
230
+ }
231
+ const lastMsg = last(groupMsgs);
232
+ const timestamp = lastMsg ? Number(lastMsg.ts) : Date.now();
233
+ this.onUndoMessageCallback(listUndo);
234
+ this.onMessageCallback(listMessages);
235
+ this.onUpdateQueueStatusCallback(queueStatus, timestamp);
236
+ }
237
+ if ([510, 511, 610, 611, 603, 604].includes(cmd)) {
238
+ const parsedData = (await decodeEventData(parsed, this.cipherKey)).data;
239
+ this.configSocket.onGotOffline(cmd, subCmd, { data: parsedData });
240
+ }
241
+ if (version == 1 && [601, 603, 604].includes(cmd)) {
242
+ const parsedData = (await decodeEventData(parsed, this.cipherKey)).data;
243
+ const { controls, queueStatus } = parsedData;
244
+ const listGroupEvents = [];
245
+ const listMuteEvents = [];
246
+ const listFriendEvents = [];
247
+ let hasLabelEvent = false;
248
+ for (const control of controls) {
249
+ if (control.content.act_type == 'file_done') {
250
+ const data = {
251
+ fileUrl: control.content.data.url,
252
+ fileId: control.content.fileId,
253
+ };
254
+ const callbackId = `${this.ctx.uid}_${control.content.fileId}`;
255
+ (_c = (_b = this.api).uploadCompleted) === null || _c === void 0 ? void 0 : _c.call(_b, { callbackId, data });
256
+ this.emit('upload_attachment', data);
257
+ }
258
+ else if (control.content.act_type == 'group') {
259
+ // 31/08/2024
260
+ // for some reason, Zalo send both join and join_reject event when admin approve join requests
261
+ // Zalo itself doesn't seem to handle this properly either, so we gonna ignore the join_reject event
262
+ if (control.content.act == 'join_reject')
263
+ continue;
264
+ const groupEventData = typeof control.content.data == 'string' ? JSON.parse(control.content.data) : control.content.data;
265
+ const groupEvent = initializeGroupEvent(this.ctx.uid, groupEventData, getGroupEventType(control.content.act), control.content.act);
266
+ const { data } = groupEvent;
267
+ if (groupEvent.isSelf && !this.selfListen)
268
+ continue;
269
+ const timestamp = parseInt(data['time']) || Date.now();
270
+ this.onUpdateQueueStatusCallback(queueStatus, timestamp);
271
+ listGroupEvents.push(groupEvent);
272
+ this.emit('group_event', groupEvent);
273
+ }
274
+ else if (control.content.act_type == 'fr') {
275
+ // 28/02/2025
276
+ // Zalo send both req and req_v2 event when user send friend request
277
+ // Zalo itself doesn't seem to handle this properly either, so we gonna ignore the req event
278
+ if (control.content.act == 'req' || control.content.act == 'seen_fr_req')
279
+ continue;
280
+ const friendEventData = typeof control.content.data === 'string' && looksLikeJson(control.content.data) ? JSON.parse(control.content.data) : control.content.data;
281
+ // Handles the case when act is "pin_create" and params is a string
282
+ if (typeof friendEventData == 'object' && 'topic' in friendEventData && typeof friendEventData.topic == 'object' && 'params' in friendEventData.topic) {
283
+ friendEventData.topic.params = JSON.parse(`${friendEventData.topic.params}`);
284
+ }
285
+ const friendEvent = initializeFriendEvent(this.ctx.uid, friendEventData, getFriendEventType(control.content.act));
286
+ if (friendEvent.isSelf && !this.selfListen)
287
+ continue;
288
+ listFriendEvents.push(friendEvent);
289
+ }
290
+ else if (control.content.act_type == 'mute') {
291
+ const muteData = typeof control.content.data == 'string' && looksLikeJson(control.content.data) ? JSON.parse(control.content.data) : control.content.data;
292
+ const { systemTime } = muteData;
293
+ listMuteEvents.push({ data: muteData, act: control.content.act });
294
+ if (systemTime) {
295
+ this.onUpdateQueueStatusCallback(queueStatus, systemTime);
296
+ }
297
+ }
298
+ else if (control.content.act_type == 'label_convers') {
299
+ hasLabelEvent = true;
300
+ }
301
+ }
302
+ this.onGroupEventCallback(listGroupEvents);
303
+ this.onMuteCallback(listMuteEvents);
304
+ this.onFriendEventCallback(listFriendEvents);
305
+ if (hasLabelEvent) {
306
+ this.onLabelEventCallback();
307
+ }
308
+ }
309
+ if ([610, 611, 612].includes(cmd)) {
310
+ const parsedData = (await decodeEventData(parsed, this.cipherKey)).data;
311
+ const { reacts, reactGroups, queueStatus } = parsedData;
312
+ const listReactions = [];
313
+ for (const react of reacts) {
314
+ react.content = JSON.parse(react.content);
315
+ const reactionObject = new Reaction(this.ctx.uid, react, false);
316
+ if (reactionObject.isSelf && !this.selfListen)
317
+ continue;
318
+ listReactions.push(reactionObject);
319
+ this.emit('reaction', reactionObject);
320
+ }
321
+ for (const reactGroup of reactGroups) {
322
+ reactGroup.content = JSON.parse(reactGroup.content);
323
+ const reactionObject = new Reaction(this.ctx.uid, reactGroup, true);
324
+ if (reactionObject.isSelf && !this.selfListen)
325
+ continue;
326
+ listReactions.push(reactionObject);
327
+ this.emit('reaction', reactionObject);
328
+ }
329
+ const lastMsg = reacts.length > 0 ? last(reacts) : reactGroups.length > 0 ? last(reactGroups) : null;
330
+ const timestamp = lastMsg ? Number(lastMsg.ts) : Date.now();
331
+ this.onReactionCallback(listReactions);
332
+ this.onUpdateQueueStatusCallback(queueStatus, timestamp);
333
+ }
334
+ if (cmd == 510) {
335
+ const parsedData = (await decodeEventData(parsed, this.cipherKey)).data;
336
+ const { msgs, queueStatus } = parsedData;
337
+ const responseUndos = [];
338
+ const responseMsgs = [];
339
+ msgs.forEach((msg) => {
340
+ if (typeof msg.content == 'object' && msg.content.hasOwnProperty('deleteMsg')) {
341
+ const undoObject = new Undo(this.ctx.uid, msg, false);
342
+ responseUndos.push(undoObject);
343
+ }
344
+ else {
345
+ const messageObject = new UserMessage(this.ctx.uid, msg, queueStatus);
346
+ responseMsgs.push(messageObject);
347
+ }
348
+ });
349
+ const lastMsg = last(msgs);
350
+ const timestamp = lastMsg ? Number(lastMsg.ts) : Date.now();
351
+ this.onUpdateQueueStatusCallback(queueStatus, timestamp);
352
+ this.onOldMessageCallback(responseMsgs);
353
+ this.onUndoMessageCallback(responseUndos);
354
+ this.emit('old_messages', responseMsgs);
355
+ }
356
+ if (cmd == 511) {
357
+ const parsedData = (await decodeEventData(parsed, this.cipherKey)).data;
358
+ const { groupMsgs, queueStatus } = parsedData;
359
+ const responseUndos = [];
360
+ const responseMsgs = [];
361
+ for (const msg of groupMsgs) {
362
+ if (typeof msg.content == 'object' && msg.content.hasOwnProperty('deleteMsg')) {
363
+ const undoObject = new Undo(this.ctx.uid, msg, true);
364
+ responseUndos.push(undoObject);
365
+ }
366
+ else {
367
+ const messageObject = new GroupMessage(this.ctx.uid, msg, queueStatus);
368
+ responseMsgs.push(messageObject);
369
+ }
370
+ }
371
+ const lastMsg = last(groupMsgs);
372
+ const timestamp = lastMsg ? Number(lastMsg.ts) : Date.now();
373
+ this.onUpdateQueueStatusCallback(queueStatus, timestamp);
374
+ this.onOldMessageCallback(responseMsgs);
375
+ this.onUndoMessageCallback(responseUndos);
376
+ this.emit('old_messages', responseMsgs);
377
+ }
378
+ if (cmd == 518) {
379
+ const parsedData = (await decodeEventData(parsed, this.cipherKey)).data;
380
+ const { msgs, groupMsgs, queueStatus } = parsedData;
381
+ const parseMsgs = msgs.map((msg) => new UserMessage(this.ctx.uid, msg, queueStatus));
382
+ const parseGroupMsgs = groupMsgs.map((msg) => new GroupMessage(this.ctx.uid, msg, queueStatus));
383
+ const listMessage = [...parseMsgs, ...parseGroupMsgs];
384
+ const lastMsg = last(listMessage);
385
+ const timestamp = lastMsg ? Number(lastMsg.ts) : Date.now();
386
+ this.onUpdateQueueStatusCallback(queueStatus, timestamp);
387
+ this.onOldMessageCallback(listMessage);
388
+ this.emit('old_messages', listMessage);
389
+ }
390
+ if (cmd == 602 && subCmd == 0) {
391
+ const parsedData = (await decodeEventData(parsed, this.cipherKey)).data;
392
+ const { actions } = parsedData;
393
+ for (const action of actions) {
394
+ const data = JSON.parse(`{${action.data}}`);
395
+ if (action.act_type == 'typing') {
396
+ if (action.act == 'typing') {
397
+ const typingObject = new UserTyping(data);
398
+ this.emit('typing', typingObject);
399
+ }
400
+ else if (action.act == 'gtyping') {
401
+ // 26/02/2025
402
+ // For a group with only two people, Zalo doesn't send a typing event.
403
+ const typingObject = new GroupTyping(data);
404
+ this.emit('typing', typingObject);
405
+ }
406
+ }
407
+ }
408
+ }
409
+ if (cmd == 502 && subCmd == 0) {
410
+ const parsedData = (await decodeEventData(parsed, this.cipherKey)).data;
411
+ const { delivereds: deliveredMsgs, seens: seenMsgs } = parsedData;
412
+ if (Array.isArray(deliveredMsgs) && deliveredMsgs.length > 0) {
413
+ const deliveredObjects = deliveredMsgs.map((delivered) => new UserDeliveredMessage(delivered));
414
+ this.emit('delivered_messages', deliveredObjects);
415
+ }
416
+ if (Array.isArray(seenMsgs) && seenMsgs.length > 0) {
417
+ const seenObjects = seenMsgs.map((seen) => new UserSeenMessage(seen));
418
+ this.emit('seen_messages', seenObjects);
419
+ }
420
+ }
421
+ if (cmd == 522 && subCmd == 0) {
422
+ const parsedData = (await decodeEventData(parsed, this.cipherKey)).data;
423
+ const { delivereds: deliveredMsgs, groupSeens: groupSeenMsgs } = parsedData;
424
+ if (Array.isArray(deliveredMsgs) && deliveredMsgs.length > 0) {
425
+ let deliveredObjects = deliveredMsgs.map((delivered) => new GroupDeliveredMessage(this.ctx.uid, delivered));
426
+ if (!this.selfListen)
427
+ deliveredObjects = deliveredObjects.filter((delivered) => !delivered.isSelf);
428
+ this.emit('delivered_messages', deliveredObjects);
429
+ }
430
+ if (Array.isArray(groupSeenMsgs) && groupSeenMsgs.length > 0) {
431
+ let seenObjects = groupSeenMsgs.map((seen) => new GroupSeenMessage(this.ctx.uid, seen));
432
+ if (!this.selfListen)
433
+ seenObjects = seenObjects.filter((seen) => !seen.isSelf);
434
+ this.emit('seen_messages', seenObjects);
435
+ }
436
+ }
437
+ if (version == 1 && cmd == 3000 && subCmd == 0) {
438
+ console.log();
439
+ logger(this.ctx).error('Another connection is opened, closing this one');
440
+ console.log();
441
+ if (ws.readyState !== WebSocket.CLOSED)
442
+ ws.close(CloseReason.NotAuthenticated);
443
+ }
444
+ }
445
+ catch (error) {
446
+ this.onErrorCallback(error);
447
+ }
448
+ };
449
+ }
450
+ stop() {
451
+ if (this.ws) {
452
+ this.ws.close(CloseReason.NormalClosure);
453
+ this.reset();
454
+ }
455
+ }
456
+ getSocketUrl(shouldRotate = false, forceFirstEndpoint = false) {
457
+ if (!this.listUrlSocket.length)
458
+ return '';
459
+ let index = 0;
460
+ if (shouldRotate) {
461
+ index = (this.rotateCount + 1) % this.listUrlSocket.length;
462
+ }
463
+ if (forceFirstEndpoint) {
464
+ index = 0;
465
+ }
466
+ return makeURL(this.ctx, this.listUrlSocket[index], { t: Date.now() });
467
+ }
468
+ sendWs(payload, requireId = true) {
469
+ if (this.ws && this.getSocketState() === WebSocket.OPEN) {
470
+ if (requireId)
471
+ payload.data['req_id'] = `req_${this.id++}`;
472
+ const encodedData = new TextEncoder().encode(JSON.stringify(payload.data));
473
+ const dataLength = encodedData.length;
474
+ const data = new DataView(Buffer.alloc(4 + dataLength).buffer);
475
+ data.setUint8(0, payload.version);
476
+ data.setInt32(1, payload.cmd, true);
477
+ data.setInt8(3, payload.subCmd);
478
+ encodedData.forEach((e, i) => {
479
+ data.setUint8(4 + i, e);
480
+ });
481
+ this.ws.send(data);
482
+ }
483
+ }
484
+ shouldPingHttp() {
485
+ var _a;
486
+ const pingHttpLevel = ((_a = this.settingSocket) === null || _a === void 0 ? void 0 : _a.ping_http_level) || 0;
487
+ if (pingHttpLevel === 1) {
488
+ return Object.values(this.pingHttp).length === 0;
489
+ }
490
+ if (pingHttpLevel === 2) {
491
+ return !this.pingHttp[this.url];
492
+ }
493
+ return false;
494
+ }
495
+ ping(shouldTimeout = true) {
496
+ const currentTimestamp = Date.now();
497
+ const isPingAvailable = !this.pingTimer && this.getSocketState() === WebSocket.OPEN;
498
+ if (!isPingAvailable)
499
+ return;
500
+ this.sendWs({
501
+ version: 1,
502
+ cmd: MessageCommand.Ping,
503
+ subCmd: KeepAliveCommand.KeepConnection,
504
+ data: { eventId: currentTimestamp },
505
+ }, false);
506
+ if (shouldTimeout) {
507
+ this.pingTimer = setTimeout(() => {
508
+ if (!(!this.ws || this.getSocketState() === WebSocket.CLOSED)) {
509
+ this.handleError(ConnectionErrorCode.PingTimeout);
510
+ }
511
+ this.pingTimer = null;
512
+ }, 5000);
513
+ }
514
+ this.lastPing = currentTimestamp;
515
+ }
516
+ pingActive() {
517
+ this.sendWs({
518
+ version: 1,
519
+ cmd: MessageCommand.PingActive,
520
+ subCmd: KeepAliveCommand.KeepConnection,
521
+ data: { at: 2, reqId: 'cmd_4' },
522
+ });
523
+ }
524
+ pong(data) {
525
+ if (data.eventId === this.lastPing && this.pingTimer) {
526
+ this._resetCountRetry([ConnectionErrorCode.PingTimeout, ConnectionErrorCode.PingPong]);
527
+ clearTimeout(this.pingTimer);
528
+ this.pingTimer = null;
529
+ this.lastPong = Date.now();
530
+ }
531
+ }
532
+ handleError(errorCode) {
533
+ console.log('socket got error', errorCode, this.ctx.uid);
534
+ if (this.shouldCloseAndReconnect(errorCode)) {
535
+ this.retryAfterClose = errorCode;
536
+ this.close(CloseReason.NormalClosure);
537
+ return;
538
+ }
539
+ switch (errorCode) {
540
+ case CloseReason.NotFoundWorker:
541
+ this.retry(CloseReason.NotFoundWorker);
542
+ break;
543
+ case ConnectionErrorCode.InvalidConfig:
544
+ this.stopRetry(ConnectionErrorCode.InvalidConfig);
545
+ break;
546
+ case ConnectionErrorCode.EstablishTimeout:
547
+ this.retryAfterClose = ConnectionErrorCode.EstablishTimeout;
548
+ this.close(CloseReason.NormalClosure);
549
+ break;
550
+ case ConnectionErrorCode.PingTimeout:
551
+ const retryDelay = this._nextRetry(ConnectionErrorCode.PingPong);
552
+ if (retryDelay == null) {
553
+ this.retryAfterClose = ConnectionErrorCode.PingTimeout;
554
+ this.close(CloseReason.NormalClosure);
555
+ }
556
+ else {
557
+ setTimeout(() => {
558
+ this.ping();
559
+ }, retryDelay);
560
+ }
561
+ break;
562
+ default:
563
+ console.log('Unhandled error code', errorCode);
564
+ break;
565
+ }
566
+ }
567
+ getSocketState() {
568
+ return this.ws ? this.ws.readyState : -1;
569
+ }
570
+ reset() {
571
+ if (this.ws) {
572
+ this.ws.removeEventListener('error', (event) => { });
573
+ this.ws.removeEventListener('open', (event) => { });
574
+ this.ws.removeEventListener('message', (event) => { });
575
+ this.ws.removeEventListener('close', (event) => { });
576
+ this.ws.close();
577
+ this.ws = null;
578
+ }
579
+ this.cipherKey = undefined;
580
+ if (this.pingInterval)
581
+ clearInterval(this.pingInterval);
582
+ }
583
+ afterClose() {
584
+ this.reset();
585
+ if (this.retryAfterClose) {
586
+ this.retry(this.retryAfterClose);
587
+ this.retryAfterClose = undefined;
588
+ }
589
+ }
590
+ isEnableCloseTimeout() {
591
+ return this.settingSocket && (this.settingSocket.close_timeout || 0) > 0;
592
+ }
593
+ close(code = CloseReason.NormalClosure) {
594
+ var _a;
595
+ if (this.isEnableCloseTimeout()) {
596
+ return this.closeV2();
597
+ }
598
+ if (!this.ws) {
599
+ this.afterClose();
600
+ return;
601
+ }
602
+ const socketState = this.getSocketState();
603
+ if (socketState === WebSocket.OPEN || socketState === WebSocket.CONNECTING) {
604
+ (_a = this.ws) === null || _a === void 0 ? void 0 : _a.close(code);
605
+ }
606
+ else {
607
+ this.afterClose();
608
+ }
609
+ }
610
+ closeV2(code = CloseReason.NormalClosure) {
611
+ if (!this.ws) {
612
+ this.reset();
613
+ return this.afterClose();
614
+ }
615
+ if (this.getSocketState() === WebSocket.CLOSED) {
616
+ return this.afterClose();
617
+ }
618
+ if (!this.closeTimer) {
619
+ const socketRef = this.ws;
620
+ this.closeTimer = setTimeout(() => {
621
+ this.closeTimer = null;
622
+ this._onClose({ code: code, target: socketRef });
623
+ }, this.settingSocket.close_timeout);
624
+ }
625
+ this.ws.close(code);
626
+ }
627
+ shouldRetry() {
628
+ if (this.retryTimer) {
629
+ return false;
630
+ }
631
+ if (this.processingRetry) {
632
+ return false;
633
+ }
634
+ return true;
635
+ }
636
+ _nextRetry(errorCode) {
637
+ var _a;
638
+ if (errorCode == null) {
639
+ return DEFAULT_RETRY_DELAYS[DEFAULT_RETRY_DELAYS.length - 1];
640
+ }
641
+ const retryConfig = this.retries[errorCode];
642
+ if (retryConfig) {
643
+ let { times, count, max } = retryConfig;
644
+ if (max != null && count >= max) {
645
+ return null;
646
+ }
647
+ this.retries[errorCode].count = ((_a = this.retries[errorCode].count) !== null && _a !== void 0 ? _a : 0) + 1;
648
+ if (typeof times === 'number') {
649
+ return times;
650
+ }
651
+ if (!Array.isArray(times)) {
652
+ times = DEFAULT_RETRY_DELAYS;
653
+ }
654
+ return count < times.length ? times[count] : times[times.length - 1];
655
+ }
656
+ return DEFAULT_RETRY_DELAYS[DEFAULT_RETRY_DELAYS.length - 1];
657
+ }
658
+ shouldRotateEndPoint(errorCode) {
659
+ var _a;
660
+ const totalEndpoints = this.listUrlSocket.length;
661
+ const rotateErrorCodes = ((_a = this.settingSocket) === null || _a === void 0 ? void 0 : _a.rotate_error_codes) || [];
662
+ const shouldRotate = rotateErrorCodes.includes(errorCode) || rotateErrorCodes.includes(String(errorCode));
663
+ if (!shouldRotate) {
664
+ return false;
665
+ }
666
+ if (this.rotateCount < totalEndpoints - 1) {
667
+ this.rotateCount++;
668
+ return true;
669
+ }
670
+ return false;
671
+ }
672
+ rotateEndpoint() {
673
+ var _a, _b;
674
+ const newEndpoint = this.getSocketUrl(true);
675
+ this.url = newEndpoint;
676
+ const shouldResetEndpoint = (_a = this.settingSocket) === null || _a === void 0 ? void 0 : _a.reset_endpoint;
677
+ if (shouldResetEndpoint && !this.resetEndPointTime) {
678
+ this.resetEndPointTime = setTimeout(() => {
679
+ const originEndpoint = this.getSocketUrl(false, true);
680
+ this.url = originEndpoint;
681
+ this.handleError(NetworkErrorCode.SwapEndpointNum);
682
+ this.rotateCount = 0;
683
+ this.resetEndPointTime = null;
684
+ }, (_b = this.settingSocket) === null || _b === void 0 ? void 0 : _b.reset_endpoint);
685
+ }
686
+ }
687
+ _resetCountRetry(retryKeys) {
688
+ if (!retryKeys)
689
+ return;
690
+ retryKeys.forEach((key) => {
691
+ if (this.retries[key]) {
692
+ this.retries[key].count = 0;
693
+ }
694
+ if (this.retriesRound2[key]) {
695
+ this.retriesRound2[key].count = 0;
696
+ }
697
+ });
698
+ }
699
+ stopRetry(errorCode) {
700
+ var _a;
701
+ if ((_a = this.settingSocket) === null || _a === void 0 ? void 0 : _a.enable_fallback_lp) {
702
+ this.retries = {};
703
+ this.close();
704
+ }
705
+ }
706
+ retry(e) {
707
+ var _a;
708
+ if ((_a = this.settingSocket) === null || _a === void 0 ? void 0 : _a.disable_lp) {
709
+ this._retryV2(e);
710
+ return;
711
+ }
712
+ if (!this.shouldRetry())
713
+ return;
714
+ let retryDelay = this._nextRetry(e);
715
+ if (retryDelay == null && this.shouldRotateEndPoint(e)) {
716
+ this.rotateEndpoint();
717
+ this._resetCountRetry([e]);
718
+ retryDelay = this._nextRetry(e);
719
+ }
720
+ if (retryDelay == null) {
721
+ this.stopRetry(e);
722
+ return;
723
+ }
724
+ this.retryTimer = setTimeout(() => {
725
+ this.reset();
726
+ this.start();
727
+ this.retryTimer = null;
728
+ }, retryDelay);
729
+ }
730
+ getRetriesRound2Key(errorCode) {
731
+ let retryKey = errorCode;
732
+ if (!retryKey || !this.retriesRound2[retryKey]) {
733
+ retryKey = 'default';
734
+ }
735
+ return retryKey;
736
+ }
737
+ nextRetryRound2(errorCode) {
738
+ var _a, _b;
739
+ const t = this.getRetriesRound2Key(errorCode);
740
+ this.retriesRound2[t].count = ((_b = (_a = this.retriesRound2[t]) === null || _a === void 0 ? void 0 : _a.count) !== null && _b !== void 0 ? _b : 0) + 1;
741
+ const { multiple: a, count: n, max: s } = this.retriesRound2[t];
742
+ return this.fibonacciRetry.getNextRetry(n, a, s);
743
+ }
744
+ isRound2NotStartYet(errorCode) {
745
+ const retryRound2Key = this.getRetriesRound2Key(errorCode);
746
+ const retryInfo = this.retriesRound2[retryRound2Key];
747
+ return !retryInfo || retryInfo.count === 0;
748
+ }
749
+ _retryV2(errorCode) {
750
+ if (!this.shouldRetry())
751
+ return;
752
+ this.processingRetry = true;
753
+ let retryDelayMs = this._nextRetry(errorCode);
754
+ if (retryDelayMs == null && this.shouldRotateEndPoint(errorCode)) {
755
+ this.rotateEndpoint();
756
+ if (this.isRound2NotStartYet(errorCode)) {
757
+ this._resetCountRetry([errorCode]);
758
+ retryDelayMs = this._nextRetry(errorCode);
759
+ }
760
+ }
761
+ const scheduleRetryCallback = () => {
762
+ this.retryTimer = setTimeout(() => {
763
+ this.reset();
764
+ this.start();
765
+ this.retryTimer = null;
766
+ }, retryDelayMs || 0);
767
+ };
768
+ if (retryDelayMs == null) {
769
+ const shouldFallback = true;
770
+ if (shouldFallback) {
771
+ this.stopRetry(errorCode);
772
+ }
773
+ else {
774
+ retryDelayMs = this.nextRetryRound2(errorCode);
775
+ scheduleRetryCallback();
776
+ }
777
+ }
778
+ else {
779
+ scheduleRetryCallback();
780
+ }
781
+ this.processingRetry = false;
782
+ }
783
+ _configRetriesRound2() {
784
+ const retriesConfig = this.settingSocket.retries_round_2;
785
+ if (typeof retriesConfig !== 'object' || retriesConfig === null) {
786
+ return;
787
+ }
788
+ console.log('retriesConfig: ', this.ctx.uid, retriesConfig);
789
+ Object.entries(retriesConfig).forEach(([key, config]) => {
790
+ const { multiple, max } = config;
791
+ if (typeof multiple === 'number') {
792
+ this.retriesRound2[key] = {
793
+ multiple,
794
+ count: 0,
795
+ max,
796
+ };
797
+ }
798
+ });
799
+ }
800
+ createPingTimerServer() {
801
+ if (this.pingTimerToServer || !this.onlineConfigs.enable_active_deactive_v2)
802
+ return;
803
+ this.configChanged = false;
804
+ this.pingTimerToServer = setInterval(() => {
805
+ this.pingActive();
806
+ if (this.configChanged) {
807
+ this.clearPingTimer();
808
+ this.createPingTimerServer();
809
+ }
810
+ }, this.onlineConfigs.update_action_interval);
811
+ }
812
+ clearPingTimer() {
813
+ clearInterval(this.pingTimerToServer);
814
+ this.pingTimerToServer = null;
815
+ }
816
+ }
817
+ function getHeader(buffer) {
818
+ if (buffer.byteLength < 4) {
819
+ throw new Error('Invalid header');
820
+ }
821
+ return [buffer[0], buffer.readUInt16LE(1), buffer[3]];
822
+ }