lordceaser-baileys 2.0.0 → 2.0.2

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 (439) hide show
  1. package/WAProto/index.js +136901 -78899
  2. package/WASignalGroup/GroupProtocol.js +1697 -0
  3. package/WASignalGroup/ciphertext_message.js +16 -0
  4. package/WASignalGroup/group_cipher.js +120 -0
  5. package/WASignalGroup/group_session_builder.js +46 -0
  6. package/WASignalGroup/index.js +5 -0
  7. package/WASignalGroup/keyhelper.js +21 -0
  8. package/WASignalGroup/protobufs.js +3 -0
  9. package/WASignalGroup/queue_job.js +69 -0
  10. package/WASignalGroup/sender_chain_key.js +50 -0
  11. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  12. package/WASignalGroup/sender_key_message.js +92 -0
  13. package/WASignalGroup/sender_key_name.js +70 -0
  14. package/WASignalGroup/sender_key_record.js +56 -0
  15. package/WASignalGroup/sender_key_state.js +129 -0
  16. package/{lib/Signal/Group/sender-message-key.js → WASignalGroup/sender_message_key.js} +16 -3
  17. package/index.js +17 -0
  18. package/lib/Defaults/baileys-version.json +3 -0
  19. package/lib/Defaults/index.d.ts +15 -37
  20. package/lib/Defaults/index.js +60 -81
  21. package/lib/Signal/libsignal.d.ts +3 -5
  22. package/lib/Signal/libsignal.js +80 -359
  23. package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +5 -4
  24. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  25. package/lib/Socket/Client/index.d.ts +3 -3
  26. package/lib/Socket/Client/index.js +19 -3
  27. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  28. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  29. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +2 -3
  30. package/lib/Socket/Client/web-socket-client.js +62 -0
  31. package/lib/Socket/business.d.ts +100 -147
  32. package/lib/Socket/business.js +43 -162
  33. package/lib/Socket/chats.d.ts +41 -85
  34. package/lib/Socket/chats.js +321 -569
  35. package/lib/Socket/groups.d.ts +57 -103
  36. package/lib/Socket/groups.js +84 -116
  37. package/lib/Socket/index.d.ts +106 -194
  38. package/lib/Socket/index.js +9 -11
  39. package/lib/Socket/messages-recv.d.ts +89 -134
  40. package/lib/Socket/messages-recv.js +475 -1275
  41. package/lib/Socket/messages-send.d.ts +97 -141
  42. package/lib/Socket/messages-send.js +633 -691
  43. package/lib/Socket/newsletter.d.ts +74 -112
  44. package/lib/Socket/newsletter.js +202 -147
  45. package/lib/Socket/registration.d.ts +264 -0
  46. package/lib/Socket/registration.js +166 -0
  47. package/lib/Socket/socket.d.ts +19 -34
  48. package/lib/Socket/socket.js +219 -547
  49. package/lib/Socket/usync.d.ts +37 -0
  50. package/lib/Socket/usync.js +70 -0
  51. package/lib/Store/index.d.ts +3 -0
  52. package/lib/Store/index.js +10 -0
  53. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  54. package/lib/Store/make-cache-manager-store.js +83 -0
  55. package/lib/Store/make-in-memory-store.d.ts +118 -0
  56. package/lib/Store/make-in-memory-store.js +431 -0
  57. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  58. package/lib/Store/make-ordered-dictionary.js +81 -0
  59. package/lib/Store/object-repository.d.ts +10 -0
  60. package/lib/Store/object-repository.js +27 -0
  61. package/lib/Types/Auth.d.ts +11 -19
  62. package/lib/Types/Auth.js +2 -2
  63. package/lib/Types/Call.d.ts +1 -3
  64. package/lib/Types/Call.js +2 -2
  65. package/lib/Types/Chat.d.ts +8 -25
  66. package/lib/Types/Chat.js +4 -8
  67. package/lib/Types/Contact.d.ts +1 -8
  68. package/lib/Types/Contact.js +2 -2
  69. package/lib/Types/Events.d.ts +17 -101
  70. package/lib/Types/Events.js +2 -2
  71. package/lib/Types/GroupMetadata.d.ts +3 -18
  72. package/lib/Types/GroupMetadata.js +2 -2
  73. package/lib/Types/Label.d.ts +0 -1
  74. package/lib/Types/Label.js +5 -3
  75. package/lib/Types/LabelAssociation.d.ts +0 -1
  76. package/lib/Types/LabelAssociation.js +5 -3
  77. package/lib/Types/Message.d.ts +204 -91
  78. package/lib/Types/Message.js +9 -11
  79. package/lib/Types/Newsletter.d.ts +92 -0
  80. package/lib/Types/Newsletter.js +32 -0
  81. package/lib/Types/Product.d.ts +1 -2
  82. package/lib/Types/Product.js +2 -2
  83. package/lib/Types/Signal.d.ts +2 -32
  84. package/lib/Types/Signal.js +2 -2
  85. package/lib/Types/Socket.d.ts +24 -44
  86. package/lib/Types/Socket.js +2 -3
  87. package/lib/Types/State.d.ts +2 -72
  88. package/lib/Types/State.js +2 -56
  89. package/lib/Types/USync.d.ts +2 -3
  90. package/lib/Types/USync.js +2 -2
  91. package/lib/Types/index.d.ts +16 -16
  92. package/lib/Types/index.js +31 -15
  93. package/lib/Utils/auth-utils.d.ts +6 -12
  94. package/lib/Utils/auth-utils.js +143 -239
  95. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  96. package/lib/Utils/baileys-event-stream.js +63 -0
  97. package/lib/Utils/business.d.ts +3 -4
  98. package/lib/Utils/business.js +69 -66
  99. package/lib/Utils/c4-compat.js +0 -8
  100. package/lib/Utils/chat-utils.d.ts +17 -47
  101. package/lib/Utils/chat-utils.js +237 -364
  102. package/lib/Utils/crypto.d.ts +21 -18
  103. package/lib/Utils/crypto.js +125 -44
  104. package/lib/Utils/decode-wa-message.d.ts +8 -38
  105. package/lib/Utils/decode-wa-message.js +90 -173
  106. package/lib/Utils/event-buffer.d.ts +8 -9
  107. package/lib/Utils/event-buffer.js +71 -176
  108. package/lib/Utils/generics.d.ts +22 -26
  109. package/lib/Utils/generics.js +175 -166
  110. package/lib/Utils/history.d.ts +11 -16
  111. package/lib/Utils/history.js +53 -93
  112. package/lib/Utils/index.d.ts +17 -22
  113. package/lib/Utils/index.js +34 -22
  114. package/lib/Utils/link-preview.d.ts +5 -5
  115. package/lib/Utils/link-preview.js +24 -16
  116. package/lib/Utils/logger.d.ts +1 -11
  117. package/lib/Utils/logger.js +7 -3
  118. package/lib/Utils/lt-hash.d.ts +12 -8
  119. package/lib/Utils/lt-hash.js +46 -3
  120. package/lib/Utils/make-mutex.d.ts +0 -2
  121. package/lib/Utils/make-mutex.js +34 -24
  122. package/lib/Utils/messages-media.d.ts +45 -65
  123. package/lib/Utils/messages-media.js +358 -425
  124. package/lib/Utils/messages.d.ts +18 -32
  125. package/lib/Utils/messages.js +720 -392
  126. package/lib/Utils/noise-handler.d.ts +13 -13
  127. package/lib/Utils/noise-handler.js +108 -149
  128. package/lib/Utils/process-message.d.ts +11 -30
  129. package/lib/Utils/process-message.js +166 -423
  130. package/lib/Utils/signal.d.ts +6 -20
  131. package/lib/Utils/signal.js +65 -107
  132. package/lib/Utils/use-multi-file-auth-state.d.ts +1 -2
  133. package/lib/Utils/use-multi-file-auth-state.js +103 -57
  134. package/lib/Utils/use-single-file-auth-state.d.ts +12 -0
  135. package/lib/Utils/use-single-file-auth-state.js +76 -0
  136. package/lib/Utils/validate-connection.d.ts +6 -6
  137. package/lib/Utils/validate-connection.js +114 -119
  138. package/lib/WABinary/constants.d.ts +4 -5
  139. package/lib/WABinary/constants.js +20 -1281
  140. package/lib/WABinary/decode.d.ts +3 -4
  141. package/lib/WABinary/decode.js +53 -51
  142. package/lib/WABinary/encode.d.ts +1 -2
  143. package/lib/WABinary/encode.js +44 -12
  144. package/lib/WABinary/generic-utils.d.ts +6 -7
  145. package/lib/WABinary/generic-utils.js +43 -46
  146. package/lib/WABinary/index.d.ts +5 -6
  147. package/lib/WABinary/index.js +21 -6
  148. package/lib/WABinary/jid-utils.d.ts +7 -24
  149. package/lib/WABinary/jid-utils.js +40 -74
  150. package/lib/WABinary/types.d.ts +1 -2
  151. package/lib/WABinary/types.js +2 -2
  152. package/lib/WAM/BinaryInfo.d.ts +1 -2
  153. package/lib/WAM/BinaryInfo.js +5 -2
  154. package/lib/WAM/constants.d.ts +3 -5
  155. package/lib/WAM/constants.js +11958 -19461
  156. package/lib/WAM/encode.d.ts +2 -3
  157. package/lib/WAM/encode.js +22 -17
  158. package/lib/WAM/index.d.ts +3 -4
  159. package/lib/WAM/index.js +19 -4
  160. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +3 -4
  161. package/lib/WAUSync/Protocols/USyncContactProtocol.js +13 -33
  162. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -3
  163. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +14 -11
  164. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -3
  165. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +12 -9
  166. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -3
  167. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +13 -9
  168. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +3 -4
  169. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +22 -20
  170. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +3 -5
  171. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +8 -13
  172. package/lib/WAUSync/Protocols/index.d.ts +4 -6
  173. package/lib/WAUSync/Protocols/index.js +20 -6
  174. package/lib/WAUSync/USyncQuery.d.ts +4 -6
  175. package/lib/WAUSync/USyncQuery.js +35 -44
  176. package/lib/WAUSync/USyncUser.d.ts +4 -11
  177. package/lib/WAUSync/USyncUser.js +5 -10
  178. package/lib/WAUSync/index.d.ts +3 -4
  179. package/lib/WAUSync/index.js +19 -4
  180. package/lib/index.js +31 -13
  181. package/package.json +19 -10
  182. package/WAProto/GenerateStatics.sh +0 -3
  183. package/WAProto/WAProto.proto +0 -5479
  184. package/WAProto/fix-imports.js +0 -85
  185. package/WAProto/index.d.ts +0 -14017
  186. package/lib/Defaults/index.d.ts.map +0 -1
  187. package/lib/Defaults/index.js.map +0 -1
  188. package/lib/Signal/Group/ciphertext-message.d.ts +0 -10
  189. package/lib/Signal/Group/ciphertext-message.d.ts.map +0 -1
  190. package/lib/Signal/Group/ciphertext-message.js +0 -12
  191. package/lib/Signal/Group/ciphertext-message.js.map +0 -1
  192. package/lib/Signal/Group/group-session-builder.d.ts +0 -15
  193. package/lib/Signal/Group/group-session-builder.d.ts.map +0 -1
  194. package/lib/Signal/Group/group-session-builder.js +0 -30
  195. package/lib/Signal/Group/group-session-builder.js.map +0 -1
  196. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  197. package/lib/Signal/Group/group_cipher.d.ts.map +0 -1
  198. package/lib/Signal/Group/group_cipher.js +0 -82
  199. package/lib/Signal/Group/group_cipher.js.map +0 -1
  200. package/lib/Signal/Group/index.d.ts +0 -12
  201. package/lib/Signal/Group/index.d.ts.map +0 -1
  202. package/lib/Signal/Group/index.js +0 -12
  203. package/lib/Signal/Group/index.js.map +0 -1
  204. package/lib/Signal/Group/keyhelper.d.ts +0 -11
  205. package/lib/Signal/Group/keyhelper.d.ts.map +0 -1
  206. package/lib/Signal/Group/keyhelper.js +0 -18
  207. package/lib/Signal/Group/keyhelper.js.map +0 -1
  208. package/lib/Signal/Group/sender-chain-key.d.ts +0 -14
  209. package/lib/Signal/Group/sender-chain-key.d.ts.map +0 -1
  210. package/lib/Signal/Group/sender-chain-key.js +0 -26
  211. package/lib/Signal/Group/sender-chain-key.js.map +0 -1
  212. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -17
  213. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +0 -1
  214. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  215. package/lib/Signal/Group/sender-key-distribution-message.js.map +0 -1
  216. package/lib/Signal/Group/sender-key-message.d.ts +0 -19
  217. package/lib/Signal/Group/sender-key-message.d.ts.map +0 -1
  218. package/lib/Signal/Group/sender-key-message.js +0 -66
  219. package/lib/Signal/Group/sender-key-message.js.map +0 -1
  220. package/lib/Signal/Group/sender-key-name.d.ts +0 -18
  221. package/lib/Signal/Group/sender-key-name.d.ts.map +0 -1
  222. package/lib/Signal/Group/sender-key-name.js +0 -48
  223. package/lib/Signal/Group/sender-key-name.js.map +0 -1
  224. package/lib/Signal/Group/sender-key-record.d.ts +0 -31
  225. package/lib/Signal/Group/sender-key-record.d.ts.map +0 -1
  226. package/lib/Signal/Group/sender-key-record.js +0 -41
  227. package/lib/Signal/Group/sender-key-record.js.map +0 -1
  228. package/lib/Signal/Group/sender-key-state.d.ts +0 -39
  229. package/lib/Signal/Group/sender-key-state.d.ts.map +0 -1
  230. package/lib/Signal/Group/sender-key-state.js +0 -84
  231. package/lib/Signal/Group/sender-key-state.js.map +0 -1
  232. package/lib/Signal/Group/sender-message-key.d.ts +0 -12
  233. package/lib/Signal/Group/sender-message-key.d.ts.map +0 -1
  234. package/lib/Signal/Group/sender-message-key.js.map +0 -1
  235. package/lib/Signal/libsignal.d.ts.map +0 -1
  236. package/lib/Signal/libsignal.js.map +0 -1
  237. package/lib/Signal/lid-mapping.d.ts +0 -23
  238. package/lib/Signal/lid-mapping.d.ts.map +0 -1
  239. package/lib/Signal/lid-mapping.js +0 -277
  240. package/lib/Signal/lid-mapping.js.map +0 -1
  241. package/lib/Socket/Client/index.d.ts.map +0 -1
  242. package/lib/Socket/Client/index.js.map +0 -1
  243. package/lib/Socket/Client/types.d.ts.map +0 -1
  244. package/lib/Socket/Client/types.js +0 -11
  245. package/lib/Socket/Client/types.js.map +0 -1
  246. package/lib/Socket/Client/websocket.d.ts.map +0 -1
  247. package/lib/Socket/Client/websocket.js +0 -54
  248. package/lib/Socket/Client/websocket.js.map +0 -1
  249. package/lib/Socket/business.d.ts.map +0 -1
  250. package/lib/Socket/business.js.map +0 -1
  251. package/lib/Socket/chats.d.ts.map +0 -1
  252. package/lib/Socket/chats.js.map +0 -1
  253. package/lib/Socket/communities.d.ts +0 -273
  254. package/lib/Socket/communities.d.ts.map +0 -1
  255. package/lib/Socket/communities.js +0 -431
  256. package/lib/Socket/communities.js.map +0 -1
  257. package/lib/Socket/groups.d.ts.map +0 -1
  258. package/lib/Socket/groups.js.map +0 -1
  259. package/lib/Socket/index.d.ts.map +0 -1
  260. package/lib/Socket/index.js.map +0 -1
  261. package/lib/Socket/messages-recv.d.ts.map +0 -1
  262. package/lib/Socket/messages-recv.js.map +0 -1
  263. package/lib/Socket/messages-send.d.ts.map +0 -1
  264. package/lib/Socket/messages-send.js.map +0 -1
  265. package/lib/Socket/mex.d.ts +0 -3
  266. package/lib/Socket/mex.d.ts.map +0 -1
  267. package/lib/Socket/mex.js +0 -42
  268. package/lib/Socket/mex.js.map +0 -1
  269. package/lib/Socket/newsletter.d.ts.map +0 -1
  270. package/lib/Socket/newsletter.js.map +0 -1
  271. package/lib/Socket/socket.d.ts.map +0 -1
  272. package/lib/Socket/socket.js.map +0 -1
  273. package/lib/Types/Auth.d.ts.map +0 -1
  274. package/lib/Types/Auth.js.map +0 -1
  275. package/lib/Types/Bussines.d.ts +0 -25
  276. package/lib/Types/Bussines.d.ts.map +0 -1
  277. package/lib/Types/Bussines.js +0 -2
  278. package/lib/Types/Bussines.js.map +0 -1
  279. package/lib/Types/Call.d.ts.map +0 -1
  280. package/lib/Types/Call.js.map +0 -1
  281. package/lib/Types/Chat.d.ts.map +0 -1
  282. package/lib/Types/Chat.js.map +0 -1
  283. package/lib/Types/Contact.d.ts.map +0 -1
  284. package/lib/Types/Contact.js.map +0 -1
  285. package/lib/Types/Events.d.ts.map +0 -1
  286. package/lib/Types/Events.js.map +0 -1
  287. package/lib/Types/GroupMetadata.d.ts.map +0 -1
  288. package/lib/Types/GroupMetadata.js.map +0 -1
  289. package/lib/Types/Label.d.ts.map +0 -1
  290. package/lib/Types/Label.js.map +0 -1
  291. package/lib/Types/LabelAssociation.d.ts.map +0 -1
  292. package/lib/Types/LabelAssociation.js.map +0 -1
  293. package/lib/Types/Message.d.ts.map +0 -1
  294. package/lib/Types/Message.js.map +0 -1
  295. package/lib/Types/Mex.d.ts +0 -141
  296. package/lib/Types/Mex.d.ts.map +0 -1
  297. package/lib/Types/Mex.js +0 -37
  298. package/lib/Types/Mex.js.map +0 -1
  299. package/lib/Types/Product.d.ts.map +0 -1
  300. package/lib/Types/Product.js.map +0 -1
  301. package/lib/Types/Signal.d.ts.map +0 -1
  302. package/lib/Types/Signal.js.map +0 -1
  303. package/lib/Types/Socket.d.ts.map +0 -1
  304. package/lib/Types/Socket.js.map +0 -1
  305. package/lib/Types/State.d.ts.map +0 -1
  306. package/lib/Types/State.js.map +0 -1
  307. package/lib/Types/USync.d.ts.map +0 -1
  308. package/lib/Types/USync.js.map +0 -1
  309. package/lib/Types/index.d.ts.map +0 -1
  310. package/lib/Types/index.js.map +0 -1
  311. package/lib/Utils/auth-utils.d.ts.map +0 -1
  312. package/lib/Utils/auth-utils.js.map +0 -1
  313. package/lib/Utils/browser-utils.d.ts +0 -4
  314. package/lib/Utils/browser-utils.d.ts.map +0 -1
  315. package/lib/Utils/browser-utils.js +0 -29
  316. package/lib/Utils/browser-utils.js.map +0 -1
  317. package/lib/Utils/business.d.ts.map +0 -1
  318. package/lib/Utils/business.js.map +0 -1
  319. package/lib/Utils/chat-utils.d.ts.map +0 -1
  320. package/lib/Utils/chat-utils.js.map +0 -1
  321. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  322. package/lib/Utils/companion-reg-client-utils.d.ts.map +0 -1
  323. package/lib/Utils/companion-reg-client-utils.js +0 -35
  324. package/lib/Utils/companion-reg-client-utils.js.map +0 -1
  325. package/lib/Utils/crypto.d.ts.map +0 -1
  326. package/lib/Utils/crypto.js.map +0 -1
  327. package/lib/Utils/decode-wa-message.d.ts.map +0 -1
  328. package/lib/Utils/decode-wa-message.js.map +0 -1
  329. package/lib/Utils/event-buffer.d.ts.map +0 -1
  330. package/lib/Utils/event-buffer.js.map +0 -1
  331. package/lib/Utils/generics.d.ts.map +0 -1
  332. package/lib/Utils/generics.js.map +0 -1
  333. package/lib/Utils/history.d.ts.map +0 -1
  334. package/lib/Utils/history.js.map +0 -1
  335. package/lib/Utils/identity-change-handler.d.ts +0 -44
  336. package/lib/Utils/identity-change-handler.d.ts.map +0 -1
  337. package/lib/Utils/identity-change-handler.js +0 -50
  338. package/lib/Utils/identity-change-handler.js.map +0 -1
  339. package/lib/Utils/index.d.ts.map +0 -1
  340. package/lib/Utils/index.js.map +0 -1
  341. package/lib/Utils/link-preview.d.ts.map +0 -1
  342. package/lib/Utils/link-preview.js.map +0 -1
  343. package/lib/Utils/logger.d.ts.map +0 -1
  344. package/lib/Utils/logger.js.map +0 -1
  345. package/lib/Utils/lt-hash.d.ts.map +0 -1
  346. package/lib/Utils/lt-hash.js.map +0 -1
  347. package/lib/Utils/make-mutex.d.ts.map +0 -1
  348. package/lib/Utils/make-mutex.js.map +0 -1
  349. package/lib/Utils/message-retry-manager.d.ts +0 -115
  350. package/lib/Utils/message-retry-manager.d.ts.map +0 -1
  351. package/lib/Utils/message-retry-manager.js +0 -265
  352. package/lib/Utils/message-retry-manager.js.map +0 -1
  353. package/lib/Utils/messages-media.d.ts.map +0 -1
  354. package/lib/Utils/messages-media.js.map +0 -1
  355. package/lib/Utils/messages.d.ts.map +0 -1
  356. package/lib/Utils/messages.js.map +0 -1
  357. package/lib/Utils/noise-handler.d.ts.map +0 -1
  358. package/lib/Utils/noise-handler.js.map +0 -1
  359. package/lib/Utils/offline-node-processor.d.ts +0 -17
  360. package/lib/Utils/offline-node-processor.d.ts.map +0 -1
  361. package/lib/Utils/offline-node-processor.js +0 -40
  362. package/lib/Utils/offline-node-processor.js.map +0 -1
  363. package/lib/Utils/pre-key-manager.d.ts +0 -28
  364. package/lib/Utils/pre-key-manager.d.ts.map +0 -1
  365. package/lib/Utils/pre-key-manager.js +0 -106
  366. package/lib/Utils/pre-key-manager.js.map +0 -1
  367. package/lib/Utils/process-message.d.ts.map +0 -1
  368. package/lib/Utils/process-message.js.map +0 -1
  369. package/lib/Utils/reporting-utils.d.ts +0 -11
  370. package/lib/Utils/reporting-utils.d.ts.map +0 -1
  371. package/lib/Utils/reporting-utils.js +0 -258
  372. package/lib/Utils/reporting-utils.js.map +0 -1
  373. package/lib/Utils/signal.d.ts.map +0 -1
  374. package/lib/Utils/signal.js.map +0 -1
  375. package/lib/Utils/stanza-ack.d.ts +0 -11
  376. package/lib/Utils/stanza-ack.d.ts.map +0 -1
  377. package/lib/Utils/stanza-ack.js +0 -38
  378. package/lib/Utils/stanza-ack.js.map +0 -1
  379. package/lib/Utils/sync-action-utils.d.ts +0 -19
  380. package/lib/Utils/sync-action-utils.d.ts.map +0 -1
  381. package/lib/Utils/sync-action-utils.js +0 -49
  382. package/lib/Utils/sync-action-utils.js.map +0 -1
  383. package/lib/Utils/tc-token-utils.d.ts +0 -37
  384. package/lib/Utils/tc-token-utils.d.ts.map +0 -1
  385. package/lib/Utils/tc-token-utils.js +0 -164
  386. package/lib/Utils/tc-token-utils.js.map +0 -1
  387. package/lib/Utils/use-multi-file-auth-state.d.ts.map +0 -1
  388. package/lib/Utils/use-multi-file-auth-state.js.map +0 -1
  389. package/lib/Utils/validate-connection.d.ts.map +0 -1
  390. package/lib/Utils/validate-connection.js.map +0 -1
  391. package/lib/WABinary/constants.d.ts.map +0 -1
  392. package/lib/WABinary/constants.js.map +0 -1
  393. package/lib/WABinary/decode.d.ts.map +0 -1
  394. package/lib/WABinary/decode.js.map +0 -1
  395. package/lib/WABinary/encode.d.ts.map +0 -1
  396. package/lib/WABinary/encode.js.map +0 -1
  397. package/lib/WABinary/generic-utils.d.ts.map +0 -1
  398. package/lib/WABinary/generic-utils.js.map +0 -1
  399. package/lib/WABinary/index.d.ts.map +0 -1
  400. package/lib/WABinary/index.js.map +0 -1
  401. package/lib/WABinary/jid-utils.d.ts.map +0 -1
  402. package/lib/WABinary/jid-utils.js.map +0 -1
  403. package/lib/WABinary/types.d.ts.map +0 -1
  404. package/lib/WABinary/types.js.map +0 -1
  405. package/lib/WAM/BinaryInfo.d.ts.map +0 -1
  406. package/lib/WAM/BinaryInfo.js.map +0 -1
  407. package/lib/WAM/constants.d.ts.map +0 -1
  408. package/lib/WAM/constants.js.map +0 -1
  409. package/lib/WAM/encode.d.ts.map +0 -1
  410. package/lib/WAM/encode.js.map +0 -1
  411. package/lib/WAM/index.d.ts.map +0 -1
  412. package/lib/WAM/index.js.map +0 -1
  413. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +0 -1
  414. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +0 -1
  415. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +0 -1
  416. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +0 -1
  417. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +0 -1
  418. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +0 -1
  419. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +0 -1
  420. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +0 -1
  421. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  422. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +0 -1
  423. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  424. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +0 -1
  425. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +0 -1
  426. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +0 -1
  427. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +0 -1
  428. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +0 -1
  429. package/lib/WAUSync/Protocols/index.d.ts.map +0 -1
  430. package/lib/WAUSync/Protocols/index.js.map +0 -1
  431. package/lib/WAUSync/USyncQuery.d.ts.map +0 -1
  432. package/lib/WAUSync/USyncQuery.js.map +0 -1
  433. package/lib/WAUSync/USyncUser.d.ts.map +0 -1
  434. package/lib/WAUSync/USyncUser.js.map +0 -1
  435. package/lib/WAUSync/index.d.ts.map +0 -1
  436. package/lib/WAUSync/index.js.map +0 -1
  437. package/lib/index.d.ts +0 -12
  438. package/lib/index.d.ts.map +0 -1
  439. package/lib/index.js.map +0 -1
@@ -1,69 +1,73 @@
1
- import { Boom } from '@hapi/boom';
2
- import { randomBytes } from 'crypto';
3
- import { URL } from 'url';
4
- import { promisify } from 'util';
5
- import { proto } from '../../WAProto/index.js';
6
- import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, INITIAL_PREKEY_COUNT, MIN_PREKEY_COUNT, NOISE_WA_HEADER, PROCESSABLE_HISTORY_TYPES, TimeMs, UPLOAD_TIMEOUT } from '../Defaults/index.js';
7
- import { QueryIds, ReachoutTimelockEnforcementType } from '../Types/index.js';
8
- import { DisconnectReason, XWAPaths } from '../Types/index.js';
9
- import { addTransactionCapability, aesEncryptCTR, bindWaitForConnectionUpdate, buildPairingQRData, bytesToCrockford, configureSuccessfulPairing, Curve, derivePairingCodeKey, generateLoginNode, generateMdTagPrefix, generateRegistrationNode, getCodeFromWSError, getCompanionPlatformId, getErrorCodeFromStreamError, getNextPreKeysNode, makeEventBuffer, makeNoiseHandler, promiseTimeout, signedKeyPair, xmppSignedPreKey } from '../Utils/index.js';
10
- import { assertNodeErrorFree, binaryNodeToString, encodeBinaryNode, getAllBinaryNodeChildren, getBinaryNodeChild, getBinaryNodeChildren, isLidUser, jidDecode, jidEncode, S_WHATSAPP_NET } from '../WABinary/index.js';
11
- import { BinaryInfo } from '../WAM/BinaryInfo.js';
12
- import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
- import { WebSocketClient } from './Client/index.js';
14
- import { executeWMexQuery } from './mex.js';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeSocket = void 0;
4
+ const boom_1 = require("@hapi/boom");
5
+ const crypto_1 = require("crypto");
6
+ const url_1 = require("url");
7
+ const util_1 = require("util");
8
+ const WAProto_1 = require("../../WAProto");
9
+ const Defaults_1 = require("../Defaults");
10
+ const Types_1 = require("../Types");
11
+ const Utils_1 = require("../Utils");
12
+ const WABinary_1 = require("../WABinary");
13
+ const Client_1 = require("./Client");
15
14
  /**
16
15
  * Connects to WA servers and performs:
17
16
  * - simple queries (no retry mechanism, wait for connection establishment)
18
17
  * - listen to messages and emit events
19
18
  * - query phone connection
20
19
  */
21
- export const makeSocket = (config) => {
22
- const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository } = config;
23
- const publicWAMBuffer = new BinaryInfo();
24
- let serverTimeOffsetMs = 0;
25
- const uqTagId = generateMdTagPrefix();
26
- const generateMessageTag = () => `${uqTagId}${epoch++}`;
27
- if (printQRInTerminal) {
28
- logger.warn({}, '⚠️ The printQRInTerminal option has been deprecated. You will no longer receive QR codes in the terminal automatically. Please listen to the connection.update event yourself and handle the QR your way. You can remove this message by removing this opttion. This message will be removed in a future version.');
20
+ const makeSocket = (config) => {
21
+ var _a, _b;
22
+ const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
23
+ let url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
24
+ config.mobile = config.mobile || url.protocol === 'tcp:';
25
+ if (config.mobile && url.protocol !== 'tcp:') {
26
+ url = new url_1.URL(`tcp://${Defaults_1.MOBILE_ENDPOINT}:${Defaults_1.MOBILE_PORT}`);
29
27
  }
30
- if (browser[1].toLocaleLowerCase().includes('android')) {
31
- logger.warn('⚠️ Using the Android browser is experimental and may lead to unexpected behavior. Use at your own risk.');
32
- }
33
- const syncDisabled = PROCESSABLE_HISTORY_TYPES.map(syncType => config.shouldSyncHistoryMessage({ syncType })).filter(x => x === false)
34
- .length === PROCESSABLE_HISTORY_TYPES.length;
35
- if (syncDisabled) {
36
- logger.warn('⚠️ DANGER: DISABLING ALL SYNC BY shouldSyncHistoryMsg PREVENTS BAILEYS FROM ACCESSING INITIAL LID MAPPINGS, LEADING TO INSTABILIY AND SESSION ERRORS');
28
+ if (!config.mobile && url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
29
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
37
30
  }
38
- const url = typeof waWebSocketUrl === 'string' ? new URL(waWebSocketUrl) : waWebSocketUrl;
39
31
  if (config.mobile || url.protocol === 'tcp:') {
40
- throw new Boom('Mobile API is not supported anymore', { statusCode: DisconnectReason.loggedOut });
32
+ throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut });
41
33
  }
42
- if (url.protocol === 'wss' && authState?.creds?.routingInfo) {
34
+ if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
43
35
  url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
44
36
  }
37
+ const ws = config.socket ? config.socket : config.mobile ? new Client_1.MobileSocketClient(url, config) : new Client_1.WebSocketClient(url, config);
38
+ ws.connect();
39
+ const ev = (0, Utils_1.makeEventBuffer)(logger);
45
40
  /** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */
46
- const ephemeralKeyPair = Curve.generateKeyPair();
41
+ const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
47
42
  /** WA noise protocol wrapper */
48
- const noise = makeNoiseHandler({
43
+ const noise = (0, Utils_1.makeNoiseHandler)({
49
44
  keyPair: ephemeralKeyPair,
50
- NOISE_HEADER: NOISE_WA_HEADER,
45
+ NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
46
+ mobile: config.mobile,
51
47
  logger,
52
- routingInfo: authState?.creds?.routingInfo
48
+ routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
53
49
  });
54
- const ws = new WebSocketClient(url, config);
55
- ws.connect();
56
- const sendPromise = promisify(ws.send);
50
+ const { creds } = authState;
51
+ // add transaction capability
52
+ const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
53
+ const signalRepository = makeSignalRepository({ creds, keys });
54
+ let lastDateRecv;
55
+ let epoch = 1;
56
+ let keepAliveReq;
57
+ let qrTimer;
58
+ let closed = false;
59
+ const uqTagId = (0, Utils_1.generateMdTagPrefix)();
60
+ const generateMessageTag = () => `${uqTagId}${epoch++}`;
61
+ const sendPromise = (0, util_1.promisify)(ws.send);
57
62
  /** send a raw buffer */
58
63
  const sendRawMessage = async (data) => {
59
64
  if (!ws.isOpen) {
60
- throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
65
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
61
66
  }
62
67
  const bytes = noise.encodeFrame(data);
63
- await promiseTimeout(connectTimeoutMs, async (resolve, reject) => {
68
+ return await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
64
69
  try {
65
- await sendPromise.call(ws, bytes);
66
- resolve();
70
+ resolve(await sendPromise.call(ws, bytes));
67
71
  }
68
72
  catch (error) {
69
73
  reject(error);
@@ -73,11 +77,41 @@ export const makeSocket = (config) => {
73
77
  /** send a binary node */
74
78
  const sendNode = (frame) => {
75
79
  if (logger.level === 'trace') {
76
- logger.trace({ xml: binaryNodeToString(frame), msg: 'xml send' });
80
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
77
81
  }
78
- const buff = encodeBinaryNode(frame);
82
+ const buff = (0, WABinary_1.encodeBinaryNode)(frame);
79
83
  return sendRawMessage(buff);
80
84
  };
85
+ /** log & process any unexpected errors */
86
+ const onUnexpectedError = (err, msg) => {
87
+ logger.error({ err }, `unexpected error in '${msg}'`);
88
+ };
89
+ /** await the next incoming message */
90
+ const awaitNextMessage = async (sendMsg) => {
91
+ if (!ws.isOpen) {
92
+ throw new boom_1.Boom('Connection Closed', {
93
+ statusCode: Types_1.DisconnectReason.connectionClosed
94
+ });
95
+ }
96
+ let onOpen;
97
+ let onClose;
98
+ const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
99
+ onOpen = resolve;
100
+ onClose = mapWebSocketError(reject);
101
+ ws.on('frame', onOpen);
102
+ ws.on('close', onClose);
103
+ ws.on('error', onClose);
104
+ })
105
+ .finally(() => {
106
+ ws.off('frame', onOpen);
107
+ ws.off('close', onClose);
108
+ ws.off('error', onClose);
109
+ });
110
+ if (sendMsg) {
111
+ sendRawMessage(sendMsg).catch(onClose);
112
+ }
113
+ return result;
114
+ };
81
115
  /**
82
116
  * Wait for a message with a certain tag to be received
83
117
  * @param msgId the message tag to await
@@ -87,38 +121,20 @@ export const makeSocket = (config) => {
87
121
  let onRecv;
88
122
  let onErr;
89
123
  try {
90
- const result = await promiseTimeout(timeoutMs, (resolve, reject) => {
91
- onRecv = data => {
92
- resolve(data);
93
- };
124
+ return await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
125
+ onRecv = resolve;
94
126
  onErr = err => {
95
- reject(err ||
96
- new Boom('Connection Closed', {
97
- statusCode: DisconnectReason.connectionClosed
98
- }));
127
+ reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
99
128
  };
100
129
  ws.on(`TAG:${msgId}`, onRecv);
101
- ws.on('close', onErr);
102
- ws.on('error', onErr);
103
- return () => reject(new Boom('Query Cancelled'));
130
+ ws.on('close', onErr); // if the socket closes, you'll never receive the message
131
+ ws.off('error', onErr);
104
132
  });
105
- return result;
106
- }
107
- catch (error) {
108
- // Catch timeout and return undefined instead of throwing
109
- if (error instanceof Boom && error.output?.statusCode === DisconnectReason.timedOut) {
110
- logger?.warn?.({ msgId }, 'timed out waiting for message');
111
- return undefined;
112
- }
113
- throw error;
114
133
  }
115
134
  finally {
116
- if (onRecv)
117
- ws.off(`TAG:${msgId}`, onRecv);
118
- if (onErr) {
119
- ws.off('close', onErr);
120
- ws.off('error', onErr);
121
- }
135
+ ws.off(`TAG:${msgId}`, onRecv);
136
+ ws.off('close', onErr); // if the socket closes, you'll never receive the message
137
+ ws.off('error', onErr);
122
138
  }
123
139
  };
124
140
  /** send a query, and wait for its response. auto-generates message ID if not provided */
@@ -127,180 +143,11 @@ export const makeSocket = (config) => {
127
143
  node.attrs.id = generateMessageTag();
128
144
  }
129
145
  const msgId = node.attrs.id;
130
- const result = await promiseTimeout(timeoutMs, async (resolve, reject) => {
131
- const result = waitForMessage(msgId, timeoutMs).catch(reject);
132
- sendNode(node)
133
- .then(async () => resolve(await result))
134
- .catch(reject);
135
- });
136
- if (result && 'tag' in result) {
137
- assertNodeErrorFree(result);
138
- }
139
- return result;
140
- };
141
- // Validate current key-bundle on server; on failure, trigger pre-key upload and rethrow
142
- const digestKeyBundle = async () => {
143
- const res = await query({
144
- tag: 'iq',
145
- attrs: { to: S_WHATSAPP_NET, type: 'get', xmlns: 'encrypt' },
146
- content: [{ tag: 'digest', attrs: {} }]
147
- });
148
- const digestNode = getBinaryNodeChild(res, 'digest');
149
- if (!digestNode) {
150
- await uploadPreKeys();
151
- throw new Error('encrypt/get digest returned no digest node');
152
- }
153
- };
154
- // Rotate our signed pre-key on server; on failure, run digest as fallback and rethrow
155
- const rotateSignedPreKey = async () => {
156
- const newId = (creds.signedPreKey.keyId || 0) + 1;
157
- const skey = await signedKeyPair(creds.signedIdentityKey, newId);
158
- await query({
159
- tag: 'iq',
160
- attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'encrypt' },
161
- content: [
162
- {
163
- tag: 'rotate',
164
- attrs: {},
165
- content: [xmppSignedPreKey(skey)]
166
- }
167
- ]
168
- });
169
- // Persist new signed pre-key in creds
170
- ev.emit('creds.update', { signedPreKey: skey });
171
- };
172
- const executeUSyncQuery = async (usyncQuery) => {
173
- if (usyncQuery.protocols.length === 0) {
174
- throw new Boom('USyncQuery must have at least one protocol');
175
- }
176
- // todo: validate users, throw WARNING on no valid users
177
- // variable below has only validated users
178
- const validUsers = usyncQuery.users;
179
- const userNodes = validUsers.map(user => {
180
- return {
181
- tag: 'user',
182
- attrs: {
183
- jid: !user.phone ? user.id : undefined
184
- },
185
- content: usyncQuery.protocols.map(a => a.getUserElement(user)).filter(a => a !== null)
186
- };
187
- });
188
- const listNode = {
189
- tag: 'list',
190
- attrs: {},
191
- content: userNodes
192
- };
193
- const queryNode = {
194
- tag: 'query',
195
- attrs: {},
196
- content: usyncQuery.protocols.map(a => a.getQueryElement())
197
- };
198
- const iq = {
199
- tag: 'iq',
200
- attrs: {
201
- to: S_WHATSAPP_NET,
202
- type: 'get',
203
- xmlns: 'usync'
204
- },
205
- content: [
206
- {
207
- tag: 'usync',
208
- attrs: {
209
- context: usyncQuery.context,
210
- mode: usyncQuery.mode,
211
- sid: generateMessageTag(),
212
- last: 'true',
213
- index: '0'
214
- },
215
- content: [queryNode, listNode]
216
- }
217
- ]
218
- };
219
- const result = await query(iq);
220
- return usyncQuery.parseUSyncQueryResult(result);
221
- };
222
- const onWhatsApp = async (...phoneNumber) => {
223
- let usyncQuery = new USyncQuery();
224
- let contactEnabled = false;
225
- for (const jid of phoneNumber) {
226
- if (isLidUser(jid)) {
227
- logger?.warn('LIDs are not supported with onWhatsApp');
228
- continue;
229
- }
230
- else {
231
- if (!contactEnabled) {
232
- contactEnabled = true;
233
- usyncQuery = usyncQuery.withContactProtocol();
234
- }
235
- const phone = `+${jid.replace('+', '').split('@')[0]?.split(':')[0]}`;
236
- usyncQuery.withUser(new USyncUser().withPhone(phone));
237
- }
238
- }
239
- if (usyncQuery.users.length === 0) {
240
- return []; // return early without forcing an empty query
241
- }
242
- const results = await executeUSyncQuery(usyncQuery);
243
- if (results) {
244
- return results.list.filter(a => !!a.contact).map(({ contact, id }) => ({ jid: id, exists: contact }));
245
- }
246
- };
247
- const pnFromLIDUSync = async (jids) => {
248
- const usyncQuery = new USyncQuery().withLIDProtocol().withContext('background');
249
- for (const jid of jids) {
250
- if (isLidUser(jid)) {
251
- logger?.warn('LID user found in LID fetch call');
252
- continue;
253
- }
254
- else {
255
- usyncQuery.withUser(new USyncUser().withId(jid));
256
- }
257
- }
258
- if (usyncQuery.users.length === 0) {
259
- return []; // return early without forcing an empty query
260
- }
261
- const results = await executeUSyncQuery(usyncQuery);
262
- if (results) {
263
- return results.list.filter(a => !!a.lid).map(({ lid, id }) => ({ pn: id, lid: lid }));
264
- }
265
- return [];
266
- };
267
- const ev = makeEventBuffer(logger);
268
- const { creds } = authState;
269
- // add transaction capability
270
- const keys = addTransactionCapability(authState.keys, logger, transactionOpts);
271
- const signalRepository = makeSignalRepository({ creds, keys }, logger, pnFromLIDUSync);
272
- let lastDateRecv;
273
- let epoch = 1;
274
- let keepAliveReq;
275
- let qrTimer;
276
- let closed = false;
277
- const socketEndHandlers = [];
278
- /** log & process any unexpected errors */
279
- const onUnexpectedError = (err, msg) => {
280
- logger.error({ err }, `unexpected error in '${msg}'`);
281
- };
282
- /** await the next incoming message */
283
- const awaitNextMessage = async (sendMsg) => {
284
- if (!ws.isOpen) {
285
- throw new Boom('Connection Closed', {
286
- statusCode: DisconnectReason.connectionClosed
287
- });
288
- }
289
- let onOpen;
290
- let onClose;
291
- const result = promiseTimeout(connectTimeoutMs, (resolve, reject) => {
292
- onOpen = resolve;
293
- onClose = mapWebSocketError(reject);
294
- ws.on('frame', onOpen);
295
- ws.on('close', onClose);
296
- ws.on('error', onClose);
297
- }).finally(() => {
298
- ws.off('frame', onOpen);
299
- ws.off('close', onClose);
300
- ws.off('error', onClose);
301
- });
302
- if (sendMsg) {
303
- sendRawMessage(sendMsg).catch(onClose);
146
+ const wait = waitForMessage(msgId, timeoutMs);
147
+ await sendNode(node);
148
+ const result = await wait;
149
+ if ('tag' in result) {
150
+ (0, WABinary_1.assertNodeErrorFree)(result);
304
151
  }
305
152
  return result;
306
153
  };
@@ -309,28 +156,31 @@ export const makeSocket = (config) => {
309
156
  let helloMsg = {
310
157
  clientHello: { ephemeral: ephemeralKeyPair.public }
311
158
  };
312
- helloMsg = proto.HandshakeMessage.fromObject(helloMsg);
159
+ helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg);
313
160
  logger.info({ browser, helloMsg }, 'connected to WA');
314
- const init = proto.HandshakeMessage.encode(helloMsg).finish();
161
+ const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish();
315
162
  const result = await awaitNextMessage(init);
316
- const handshake = proto.HandshakeMessage.decode(result);
163
+ const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
317
164
  logger.trace({ handshake }, 'handshake recv from WA');
318
- const keyEnc = noise.processHandshake(handshake, creds.noiseKey);
165
+ const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
319
166
  let node;
320
- if (!creds.me) {
321
- node = generateRegistrationNode(creds, config);
167
+ if (config.mobile) {
168
+ node = (0, Utils_1.generateMobileNode)(config);
169
+ }
170
+ else if (!creds.me) {
171
+ node = (0, Utils_1.generateRegistrationNode)(creds, config);
322
172
  logger.info({ node }, 'not logged in, attempting registration...');
323
173
  }
324
174
  else {
325
- node = generateLoginNode(creds.me.id, config);
175
+ node = (0, Utils_1.generateLoginNode)(creds.me.id, config);
326
176
  logger.info({ node }, 'logging in...');
327
177
  }
328
- const payloadEnc = noise.encrypt(proto.ClientPayload.encode(node).finish());
329
- await sendRawMessage(proto.HandshakeMessage.encode({
178
+ const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish());
179
+ await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
330
180
  clientFinish: {
331
181
  static: keyEnc,
332
- payload: payloadEnc
333
- }
182
+ payload: payloadEnc,
183
+ },
334
184
  }).finish());
335
185
  await noise.finishInit();
336
186
  startKeepAliveRequest();
@@ -342,104 +192,35 @@ export const makeSocket = (config) => {
342
192
  id: generateMessageTag(),
343
193
  xmlns: 'encrypt',
344
194
  type: 'get',
345
- to: S_WHATSAPP_NET
195
+ to: WABinary_1.S_WHATSAPP_NET
346
196
  },
347
- content: [{ tag: 'count', attrs: {} }]
197
+ content: [
198
+ { tag: 'count', attrs: {} }
199
+ ]
348
200
  });
349
- const countChild = getBinaryNodeChild(result, 'count');
201
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
350
202
  return +countChild.attrs.value;
351
203
  };
352
- // WAWeb has no time throttle here; the server drives uploads via PreKeyLow notifications.
353
- let uploadPreKeysPromise = null;
354
204
  /** generates and uploads a set of pre-keys to the server */
355
- const uploadPreKeys = async (count = MIN_PREKEY_COUNT) => {
356
- if (uploadPreKeysPromise) {
357
- logger.debug('Pre-key upload already in progress, waiting for completion');
358
- await uploadPreKeysPromise;
359
- return;
360
- }
361
- const uploadLogic = async (retryCount) => {
362
- logger.info({ count, retryCount }, 'uploading pre-keys');
363
- // Generate and save pre-keys atomically (prevents ID collisions on retry)
364
- const node = await keys.transaction(async () => {
365
- logger.debug({ requestedCount: count }, 'generating pre-keys with requested count');
366
- const { update, node } = await getNextPreKeysNode({ creds, keys }, count);
367
- // Update credentials immediately to prevent duplicate IDs on retry
368
- ev.emit('creds.update', update);
369
- return node;
370
- }, creds?.me?.id || 'upload-pre-keys');
371
- // Upload to server (outside transaction, can fail without affecting local keys)
372
- try {
373
- await query(node);
374
- logger.info({ count }, 'uploaded pre-keys successfully');
375
- }
376
- catch (uploadError) {
377
- logger.error({ uploadError: uploadError.toString(), count }, 'Failed to upload pre-keys to server');
378
- // Recurse into uploadLogic; calling uploadPreKeys would await its own in-flight promise.
379
- if (retryCount < 3) {
380
- const backoffDelay = Math.min(1000 * Math.pow(2, retryCount), 10000);
381
- logger.info(`Retrying pre-key upload in ${backoffDelay}ms`);
382
- await new Promise(resolve => setTimeout(resolve, backoffDelay));
383
- return uploadLogic(retryCount + 1);
384
- }
385
- throw uploadError;
386
- }
387
- };
388
- // Add timeout protection
389
- uploadPreKeysPromise = Promise.race([
390
- uploadLogic(0),
391
- new Promise((_, reject) => setTimeout(() => reject(new Boom('Pre-key upload timeout', { statusCode: 408 })), UPLOAD_TIMEOUT))
392
- ]);
393
- try {
394
- await uploadPreKeysPromise;
395
- }
396
- finally {
397
- uploadPreKeysPromise = null;
398
- }
399
- };
400
- const verifyCurrentPreKeyExists = async () => {
401
- const currentPreKeyId = creds.nextPreKeyId - 1;
402
- if (currentPreKeyId <= 0) {
403
- return { exists: false, currentPreKeyId: 0 };
404
- }
405
- const preKeys = await keys.get('pre-key', [currentPreKeyId.toString()]);
406
- const exists = !!preKeys[currentPreKeyId.toString()];
407
- return { exists, currentPreKeyId };
205
+ const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
206
+ await keys.transaction(async () => {
207
+ logger.info({ count }, 'uploading pre-keys');
208
+ const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count);
209
+ await query(node);
210
+ ev.emit('creds.update', update);
211
+ logger.info({ count }, 'uploaded pre-keys');
212
+ });
408
213
  };
409
214
  const uploadPreKeysToServerIfRequired = async () => {
410
- try {
411
- let count = 0;
412
- const preKeyCount = await getAvailablePreKeysOnServer();
413
- if (preKeyCount === 0)
414
- count = INITIAL_PREKEY_COUNT;
415
- else
416
- count = MIN_PREKEY_COUNT;
417
- const { exists: currentPreKeyExists, currentPreKeyId } = await verifyCurrentPreKeyExists();
418
- logger.info(`${preKeyCount} pre-keys found on server`);
419
- logger.info(`Current prekey ID: ${currentPreKeyId}, exists in storage: ${currentPreKeyExists}`);
420
- const lowServerCount = preKeyCount <= count;
421
- const missingCurrentPreKey = !currentPreKeyExists && currentPreKeyId > 0;
422
- const shouldUpload = lowServerCount || missingCurrentPreKey;
423
- if (shouldUpload) {
424
- const reasons = [];
425
- if (lowServerCount)
426
- reasons.push(`server count low (${preKeyCount})`);
427
- if (missingCurrentPreKey)
428
- reasons.push(`current prekey ${currentPreKeyId} missing from storage`);
429
- logger.info(`Uploading PreKeys due to: ${reasons.join(', ')}`);
430
- await uploadPreKeys(count);
431
- }
432
- else {
433
- logger.info(`PreKey validation passed - Server: ${preKeyCount}, Current prekey ${currentPreKeyId} exists`);
434
- }
435
- }
436
- catch (error) {
437
- logger.error({ error }, 'Failed to check/upload pre-keys during initialization');
438
- // Don't throw - allow connection to continue even if pre-key check fails
215
+ const preKeyCount = await getAvailablePreKeysOnServer();
216
+ logger.info(`${preKeyCount} pre-keys found on server`);
217
+ if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
218
+ await uploadPreKeys();
439
219
  }
440
220
  };
441
- const onMessageReceived = async (data) => {
442
- await noise.decodeFrame(data, frame => {
221
+ const onMessageReceived = (data) => {
222
+ noise.decodeFrame(data, frame => {
223
+ var _a;
443
224
  // reset ping timeout
444
225
  lastDateRecv = new Date();
445
226
  let anyTriggered = false;
@@ -448,53 +229,45 @@ export const makeSocket = (config) => {
448
229
  if (!(frame instanceof Uint8Array)) {
449
230
  const msgId = frame.attrs.id;
450
231
  if (logger.level === 'trace') {
451
- logger.trace({ xml: binaryNodeToString(frame), msg: 'recv xml' });
232
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
452
233
  }
453
234
  /* Check if this is a response to a message we sent */
454
- anyTriggered = ws.emit(`${DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
235
+ anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
455
236
  /* Check if this is a response to a message we are expecting */
456
237
  const l0 = frame.tag;
457
238
  const l1 = frame.attrs || {};
458
- const l2 = Array.isArray(frame.content) ? frame.content[0]?.tag : '';
239
+ const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
459
240
  for (const key of Object.keys(l1)) {
460
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
461
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
462
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
241
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
242
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
243
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
463
244
  }
464
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
465
- anyTriggered = ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
245
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
246
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
466
247
  if (!anyTriggered && logger.level === 'debug') {
467
248
  logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
468
249
  }
469
250
  }
470
251
  });
471
252
  };
472
- const end = async (error) => {
253
+ const end = (error) => {
473
254
  if (closed) {
474
- logger.trace({ trace: error?.stack }, 'connection already closed');
255
+ logger.trace({ trace: error === null || error === void 0 ? void 0 : error.stack }, 'connection already closed');
475
256
  return;
476
257
  }
477
258
  closed = true;
478
- logger.info({ trace: error?.stack }, error ? 'connection errored' : 'connection closed');
259
+ logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack }, error ? 'connection errored' : 'connection closed');
479
260
  clearInterval(keepAliveReq);
480
261
  clearTimeout(qrTimer);
481
262
  ws.removeAllListeners('close');
263
+ ws.removeAllListeners('error');
482
264
  ws.removeAllListeners('open');
483
265
  ws.removeAllListeners('message');
484
- signalRepository.close?.();
485
266
  if (!ws.isClosed && !ws.isClosing) {
486
267
  try {
487
- await ws.close();
488
- }
489
- catch { }
490
- }
491
- for (const handler of socketEndHandlers) {
492
- try {
493
- await handler(error);
494
- }
495
- catch (err) {
496
- logger.error({ err }, 'error in socket end handler');
268
+ ws.close();
497
269
  }
270
+ catch (_a) { }
498
271
  }
499
272
  ev.emit('connection.update', {
500
273
  connection: 'close',
@@ -504,14 +277,13 @@ export const makeSocket = (config) => {
504
277
  }
505
278
  });
506
279
  ev.removeAllListeners('connection.update');
507
- ev.destroy();
508
280
  };
509
281
  const waitForSocketOpen = async () => {
510
282
  if (ws.isOpen) {
511
283
  return;
512
284
  }
513
285
  if (ws.isClosed || ws.isClosing) {
514
- throw new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed });
286
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
515
287
  }
516
288
  let onOpen;
517
289
  let onClose;
@@ -521,7 +293,8 @@ export const makeSocket = (config) => {
521
293
  ws.on('open', onOpen);
522
294
  ws.on('close', onClose);
523
295
  ws.on('error', onClose);
524
- }).finally(() => {
296
+ })
297
+ .finally(() => {
525
298
  ws.off('open', onOpen);
526
299
  ws.off('close', onClose);
527
300
  ws.off('error', onClose);
@@ -537,7 +310,7 @@ export const makeSocket = (config) => {
537
310
  it could be that the network is down
538
311
  */
539
312
  if (diff > keepAliveIntervalMs + 5000) {
540
- void end(new Boom('Connection was lost', { statusCode: DisconnectReason.connectionLost }));
313
+ end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
541
314
  }
542
315
  else if (ws.isOpen) {
543
316
  // if its all good, send a keep alive request
@@ -545,12 +318,13 @@ export const makeSocket = (config) => {
545
318
  tag: 'iq',
546
319
  attrs: {
547
320
  id: generateMessageTag(),
548
- to: S_WHATSAPP_NET,
321
+ to: WABinary_1.S_WHATSAPP_NET,
549
322
  type: 'get',
550
- xmlns: 'w:p'
323
+ xmlns: 'w:p',
551
324
  },
552
325
  content: [{ tag: 'ping', attrs: {} }]
553
- }).catch(err => {
326
+ })
327
+ .catch(err => {
554
328
  logger.error({ trace: err.stack }, 'error in sending keep alive');
555
329
  });
556
330
  }
@@ -559,23 +333,26 @@ export const makeSocket = (config) => {
559
333
  }
560
334
  }, keepAliveIntervalMs));
561
335
  /** i have no idea why this exists. pls enlighten me */
562
- const sendPassiveIq = (tag) => query({
336
+ const sendPassiveIq = (tag) => (query({
563
337
  tag: 'iq',
564
338
  attrs: {
565
- to: S_WHATSAPP_NET,
339
+ to: WABinary_1.S_WHATSAPP_NET,
566
340
  xmlns: 'passive',
567
- type: 'set'
341
+ type: 'set',
568
342
  },
569
- content: [{ tag, attrs: {} }]
570
- });
343
+ content: [
344
+ { tag, attrs: {} }
345
+ ]
346
+ }));
571
347
  /** logout & invalidate connection */
572
348
  const logout = async (msg) => {
573
- const jid = authState.creds.me?.id;
349
+ var _a;
350
+ const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
574
351
  if (jid) {
575
352
  await sendNode({
576
353
  tag: 'iq',
577
354
  attrs: {
578
- to: S_WHATSAPP_NET,
355
+ to: WABinary_1.S_WHATSAPP_NET,
579
356
  type: 'set',
580
357
  id: generateMessageTag(),
581
358
  xmlns: 'md'
@@ -591,23 +368,23 @@ export const makeSocket = (config) => {
591
368
  ]
592
369
  });
593
370
  }
594
- void end(new Boom(msg || 'Intentional Logout', { statusCode: DisconnectReason.loggedOut }));
371
+ end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
595
372
  };
596
- const requestPairingCode = async (phoneNumber, customPairingCode) => {
597
- const pairingCode = customPairingCode ?? bytesToCrockford(randomBytes(5));
598
- if (customPairingCode && customPairingCode?.length !== 8) {
599
- throw new Error('Custom pairing code must be exactly 8 chars');
373
+ const requestPairingCode = async (phoneNumber, pairKey = "ABCD1234") => {
374
+ if (pairKey) {
375
+ authState.creds.pairingCode = pairKey.toUpperCase()
376
+ } else {
377
+ authState.creds.pairingCode = (0, Utils_1.bytesToCrockford)((0, crypto_1.randomBytes)(5));
600
378
  }
601
- authState.creds.pairingCode = pairingCode;
602
379
  authState.creds.me = {
603
- id: jidEncode(phoneNumber, 's.whatsapp.net'),
380
+ id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
604
381
  name: '~'
605
382
  };
606
383
  ev.emit('creds.update', authState.creds);
607
- await sendNode({
384
+ const node = {
608
385
  tag: 'iq',
609
386
  attrs: {
610
- to: S_WHATSAPP_NET,
387
+ to: WABinary_1.S_WHATSAPP_NET,
611
388
  type: 'set',
612
389
  id: generateMessageTag(),
613
390
  xmlns: 'md'
@@ -634,7 +411,7 @@ export const makeSocket = (config) => {
634
411
  {
635
412
  tag: 'companion_platform_id',
636
413
  attrs: {},
637
- content: getCompanionPlatformId(browser)
414
+ content: (0, Utils_1.getPlatformId)(browser[1])
638
415
  },
639
416
  {
640
417
  tag: 'companion_platform_display',
@@ -649,28 +426,29 @@ export const makeSocket = (config) => {
649
426
  ]
650
427
  }
651
428
  ]
652
- });
429
+ };
430
+ await sendNode(node);
653
431
  return authState.creds.pairingCode;
654
432
  };
655
433
  async function generatePairingKey() {
656
- const salt = randomBytes(32);
657
- const randomIv = randomBytes(16);
658
- const key = await derivePairingCodeKey(authState.creds.pairingCode, salt);
659
- const ciphered = aesEncryptCTR(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
434
+ const salt = (0, crypto_1.randomBytes)(32);
435
+ const randomIv = (0, crypto_1.randomBytes)(16);
436
+ const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
437
+ const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
660
438
  return Buffer.concat([salt, randomIv, ciphered]);
661
439
  }
662
440
  const sendWAMBuffer = (wamBuffer) => {
663
441
  return query({
664
442
  tag: 'iq',
665
443
  attrs: {
666
- to: S_WHATSAPP_NET,
444
+ to: WABinary_1.S_WHATSAPP_NET,
667
445
  id: generateMessageTag(),
668
446
  xmlns: 'w:stats'
669
447
  },
670
448
  content: [
671
449
  {
672
450
  tag: 'add',
673
- attrs: { t: Math.round(Date.now() / 1000) + '' },
451
+ attrs: {},
674
452
  content: wamBuffer
675
453
  }
676
454
  ]
@@ -683,26 +461,26 @@ export const makeSocket = (config) => {
683
461
  }
684
462
  catch (err) {
685
463
  logger.error({ err }, 'error in validating connection');
686
- void end(err);
464
+ end(err);
687
465
  }
688
466
  });
689
467
  ws.on('error', mapWebSocketError(end));
690
- ws.on('close', () => void end(new Boom('Connection Terminated', { statusCode: DisconnectReason.connectionClosed })));
468
+ ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
691
469
  // the server terminated the connection
692
- ws.on('CB:xmlstreamend', () => void end(new Boom('Connection Terminated by Server', { statusCode: DisconnectReason.connectionClosed })));
470
+ ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })));
693
471
  // QR gen
694
472
  ws.on('CB:iq,type:set,pair-device', async (stanza) => {
695
473
  const iq = {
696
474
  tag: 'iq',
697
475
  attrs: {
698
- to: S_WHATSAPP_NET,
476
+ to: WABinary_1.S_WHATSAPP_NET,
699
477
  type: 'result',
700
- id: stanza.attrs.id
478
+ id: stanza.attrs.id,
701
479
  }
702
480
  };
703
481
  await sendNode(iq);
704
- const pairDeviceNode = getBinaryNodeChild(stanza, 'pair-device');
705
- const refNodes = getBinaryNodeChildren(pairDeviceNode, 'ref');
482
+ const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
483
+ const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
706
484
  const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
707
485
  const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
708
486
  const advB64 = creds.advSecretKey;
@@ -713,11 +491,11 @@ export const makeSocket = (config) => {
713
491
  }
714
492
  const refNode = refNodes.shift();
715
493
  if (!refNode) {
716
- void end(new Boom('QR refs attempts ended', { statusCode: DisconnectReason.timedOut }));
494
+ end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }));
717
495
  return;
718
496
  }
719
497
  const ref = refNode.content.toString('utf-8');
720
- const qr = buildPairingQRData(ref, noiseKeyB64, identityKeyB64, advB64, browser);
498
+ const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
721
499
  ev.emit('connection.update', { qr });
722
500
  qrTimer = setTimeout(genPairQR, qrMs);
723
501
  qrMs = qrTimeout || 20000; // shorter subsequent qrs
@@ -729,98 +507,65 @@ export const makeSocket = (config) => {
729
507
  ws.on('CB:iq,,pair-success', async (stanza) => {
730
508
  logger.debug('pair success recv');
731
509
  try {
732
- updateServerTimeOffset(stanza);
733
- const { reply, creds: updatedCreds } = configureSuccessfulPairing(stanza, creds);
510
+ const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
734
511
  logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
735
512
  ev.emit('creds.update', updatedCreds);
736
513
  ev.emit('connection.update', { isNewLogin: true, qr: undefined });
737
514
  await sendNode(reply);
738
- void sendUnifiedSession();
739
515
  }
740
516
  catch (error) {
741
517
  logger.info({ trace: error.stack }, 'error in pairing');
742
- void end(error);
518
+ end(error);
743
519
  }
744
520
  });
745
521
  // login complete
746
522
  ws.on('CB:success', async (node) => {
747
523
  try {
748
- updateServerTimeOffset(node);
749
524
  await uploadPreKeysToServerIfRequired();
750
525
  await sendPassiveIq('active');
751
- // After successful login, validate our key-bundle against server
752
- try {
753
- await digestKeyBundle();
754
- }
755
- catch (e) {
756
- logger.warn({ e }, 'failed to run digest after login');
757
- }
526
+ logger.info('opened connection to WA');
527
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
528
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
529
+ ev.emit('connection.update', { connection: 'open' });
758
530
  }
759
531
  catch (err) {
760
- logger.warn({ err }, 'failed to send initial passive iq');
761
- }
762
- logger.info('opened connection to WA');
763
- clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
764
- ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
765
- ev.emit('connection.update', { connection: 'open' });
766
- void sendUnifiedSession();
767
- if (node.attrs.lid && authState.creds.me?.id) {
768
- const myLID = node.attrs.lid;
769
- process.nextTick(async () => {
770
- try {
771
- const myPN = authState.creds.me.id;
772
- // Store our own LID-PN mapping
773
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: myLID, pn: myPN }]);
774
- // Create device list for our own user (needed for bulk migration)
775
- const { user, device } = jidDecode(myPN);
776
- await authState.keys.set({
777
- 'device-list': {
778
- [user]: [device?.toString() || '0']
779
- }
780
- });
781
- // migrate our own session
782
- await signalRepository.migrateSession(myPN, myLID);
783
- logger.info({ myPN, myLID }, 'Own LID session created successfully');
784
- }
785
- catch (error) {
786
- logger.error({ error, lid: myLID }, 'Failed to create own LID session');
787
- }
788
- });
532
+ logger.error({ err }, 'error opening connection');
533
+ end(err);
789
534
  }
790
535
  });
791
536
  ws.on('CB:stream:error', (node) => {
792
- const [reasonNode] = getAllBinaryNodeChildren(node);
793
- logger.error({ reasonNode, fullErrorNode: node }, 'stream errored out');
794
- const { reason, statusCode } = getErrorCodeFromStreamError(node);
795
- void end(new Boom(`Stream Errored (${reason})`, { statusCode, data: reasonNode || node }));
537
+ logger.error({ node }, 'stream errored out');
538
+ const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node);
539
+ end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
796
540
  });
797
541
  // stream fail, possible logout
798
542
  ws.on('CB:failure', (node) => {
799
543
  const reason = +(node.attrs.reason || 500);
800
- void end(new Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
544
+ end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
801
545
  });
802
546
  ws.on('CB:ib,,downgrade_webclient', () => {
803
- void end(new Boom('Multi-device beta not joined', { statusCode: DisconnectReason.multideviceMismatch }));
547
+ end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
804
548
  });
805
- ws.on('CB:ib,,offline_preview', async (node) => {
549
+ ws.on('CB:ib,,offline_preview', (node) => {
806
550
  logger.info('offline preview received', JSON.stringify(node));
807
- await sendNode({
551
+ sendNode({
808
552
  tag: 'ib',
809
553
  attrs: {},
810
554
  content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
811
555
  });
812
556
  });
813
557
  ws.on('CB:ib,,edge_routing', (node) => {
814
- const edgeRoutingNode = getBinaryNodeChild(node, 'edge_routing');
815
- const routingInfo = getBinaryNodeChild(edgeRoutingNode, 'routing_info');
816
- if (routingInfo?.content) {
817
- authState.creds.routingInfo = Buffer.from(routingInfo?.content);
558
+ const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
559
+ const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
560
+ if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
561
+ authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
818
562
  ev.emit('creds.update', authState.creds);
819
563
  }
820
564
  });
821
565
  let didStartBuffer = false;
822
566
  process.nextTick(() => {
823
- if (creds.me?.id) {
567
+ var _a;
568
+ if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
824
569
  // start buffering important events
825
570
  // if we're logged in
826
571
  ev.buffer();
@@ -830,8 +575,8 @@ export const makeSocket = (config) => {
830
575
  });
831
576
  // called when all offline notifs are handled
832
577
  ws.on('CB:ib,,offline', (node) => {
833
- const child = getBinaryNodeChild(node, 'offline');
834
- const offlineNotifs = +(child?.attrs.count || 0);
578
+ const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
579
+ const offlineNotifs = +((child === null || child === void 0 ? void 0 : child.attrs.count) || 0);
835
580
  logger.info(`handled ${offlineNotifs} offline messages/notifications`);
836
581
  if (didStartBuffer) {
837
582
  ev.flush();
@@ -841,87 +586,24 @@ export const makeSocket = (config) => {
841
586
  });
842
587
  // update credentials when required
843
588
  ev.on('creds.update', update => {
844
- const name = update.me?.name;
589
+ var _a, _b;
590
+ const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
845
591
  // if name has just been received
846
- if (creds.me?.name !== name) {
592
+ if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
847
593
  logger.debug({ name }, 'updated pushName');
848
594
  sendNode({
849
595
  tag: 'presence',
850
596
  attrs: { name: name }
851
- }).catch(err => {
597
+ })
598
+ .catch(err => {
852
599
  logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
853
600
  });
854
601
  }
855
602
  Object.assign(creds, update);
856
603
  });
857
- const updateServerTimeOffset = ({ attrs }) => {
858
- const tValue = attrs?.t;
859
- if (!tValue) {
860
- return;
861
- }
862
- const parsed = Number(tValue);
863
- if (Number.isNaN(parsed) || parsed <= 0) {
864
- return;
865
- }
866
- const localMs = Date.now();
867
- serverTimeOffsetMs = parsed * 1000 - localMs;
868
- logger.debug({ offset: serverTimeOffsetMs }, 'calculated server time offset');
869
- };
870
- const getUnifiedSessionId = () => {
871
- const offsetMs = 3 * TimeMs.Day;
872
- const now = Date.now() + serverTimeOffsetMs;
873
- const id = (now + offsetMs) % TimeMs.Week;
874
- return id.toString();
875
- };
876
- const sendUnifiedSession = async () => {
877
- if (!ws.isOpen) {
878
- return;
879
- }
880
- const node = {
881
- tag: 'ib',
882
- attrs: {},
883
- content: [
884
- {
885
- tag: 'unified_session',
886
- attrs: {
887
- id: getUnifiedSessionId()
888
- }
889
- }
890
- ]
891
- };
892
- try {
893
- await sendNode(node);
894
- }
895
- catch (error) {
896
- logger.debug({ error }, 'failed to send unified_session telemetry');
897
- }
898
- };
899
- const registerSocketEndHandler = (handler) => {
900
- socketEndHandlers.push(handler);
901
- };
902
- /**
903
- * Fetches your account's standing when it comes to restrictions.
904
- * @returns Returns the state of the restrictions.
905
- */
906
- const fetchAccountReachoutTimelock = async () => {
907
- const queryResult = await executeWMexQuery({}, QueryIds.REACHOUT_TIMELOCK, XWAPaths.xwa2_fetch_account_reachout_timelock, query, generateMessageTag);
908
- const result = {
909
- isActive: !!queryResult?.is_active,
910
- timeEnforcementEnds: queryResult?.time_enforcement_ends && queryResult?.time_enforcement_ends !== '0'
911
- ? new Date(parseInt(queryResult.time_enforcement_ends, 10) * 1000)
912
- : undefined,
913
- enforcementType: queryResult?.enforcement_type ?? ReachoutTimelockEnforcementType.DEFAULT
914
- };
915
- ev.emit('connection.update', { reachoutTimeLock: result });
916
- return result;
917
- };
918
- /**
919
- * Fetches your account's new chat limits.
920
- * @returns Returns the quota and the usage.
921
- */
922
- const fetchNewChatMessageCap = async () => {
923
- return executeWMexQuery({ input: { type: 'INDIVIDUAL_NEW_CHAT_MSG' } }, QueryIds.MESSAGE_CAPPING_INFO, XWAPaths.xwa2_message_capping_info, query, generateMessageTag);
924
- };
604
+ if (printQRInTerminal) {
605
+ (0, Utils_1.printQRIfNecessaryListener)(ev, logger);
606
+ }
925
607
  return {
926
608
  type: 'md',
927
609
  ws,
@@ -939,32 +621,22 @@ export const makeSocket = (config) => {
939
621
  sendNode,
940
622
  logout,
941
623
  end,
942
- registerSocketEndHandler,
943
624
  onUnexpectedError,
944
625
  uploadPreKeys,
945
626
  uploadPreKeysToServerIfRequired,
946
- digestKeyBundle,
947
- rotateSignedPreKey,
948
627
  requestPairingCode,
949
- updateServerTimeOffset,
950
- sendUnifiedSession,
951
- wamBuffer: publicWAMBuffer,
952
628
  /** Waits for the connection to WA to reach a state */
953
- waitForConnectionUpdate: bindWaitForConnectionUpdate(ev),
629
+ waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
954
630
  sendWAMBuffer,
955
- executeUSyncQuery,
956
- onWhatsApp,
957
- fetchAccountReachoutTimelock,
958
- fetchNewChatMessageCap
959
631
  };
960
632
  };
633
+ exports.makeSocket = makeSocket;
961
634
  /**
962
635
  * map the websocket error to the right type
963
636
  * so it can be retried by the caller
964
637
  * */
965
638
  function mapWebSocketError(handler) {
966
639
  return (error) => {
967
- handler(new Boom(`WebSocket Error (${error?.message})`, { statusCode: getCodeFromWSError(error), data: error }));
640
+ handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, { statusCode: (0, Utils_1.getCodeFromWSError)(error), data: error }));
968
641
  };
969
642
  }
970
- //# sourceMappingURL=socket.js.map