@modzneverdie/baileys 17.1.2 → 17.1.3

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 (427) hide show
  1. package/LICENSE +21 -0
  2. package/WAProto/GenerateStatics.sh +3 -0
  3. package/WAProto/WAProto.proto +6035 -0
  4. package/WAProto/fix-imports.js +81 -0
  5. package/WAProto/index.d.ts +2 -0
  6. package/WAProto/index.js +59469 -96804
  7. package/lib/Defaults/index.d.ts +29 -8
  8. package/lib/Defaults/index.d.ts.map +1 -0
  9. package/lib/Defaults/index.js +134 -141
  10. package/lib/Defaults/index.js.map +1 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +1 -0
  12. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.js +2 -5
  14. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts +4 -3
  16. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.js +7 -41
  18. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  19. package/lib/Signal/Group/group_cipher.d.ts +4 -4
  20. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  21. package/lib/Signal/Group/group_cipher.js +37 -51
  22. package/lib/Signal/Group/group_cipher.js.map +1 -0
  23. package/lib/Signal/Group/index.d.ts +12 -11
  24. package/lib/Signal/Group/index.d.ts.map +1 -0
  25. package/lib/Signal/Group/index.js +12 -57
  26. package/lib/Signal/Group/index.js.map +1 -0
  27. package/lib/Signal/Group/keyhelper.d.ts +2 -1
  28. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  29. package/lib/Signal/Group/keyhelper.js +7 -44
  30. package/lib/Signal/Group/keyhelper.js.map +1 -0
  31. package/lib/Signal/Group/sender-chain-key.d.ts +3 -2
  32. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.js +7 -15
  34. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.d.ts +2 -1
  36. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.js +8 -11
  38. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  39. package/lib/Signal/Group/sender-key-message.d.ts +2 -1
  40. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.js +9 -12
  42. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  43. package/lib/Signal/Group/sender-key-name.d.ts +1 -0
  44. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.js +2 -5
  46. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  47. package/lib/Signal/Group/sender-key-record.d.ts +3 -2
  48. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.js +9 -21
  50. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  51. package/lib/Signal/Group/sender-key-state.d.ts +7 -6
  52. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.js +27 -42
  54. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  55. package/lib/Signal/Group/sender-message-key.d.ts +1 -0
  56. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.js +4 -7
  58. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  59. package/lib/Signal/libsignal.d.ts +5 -3
  60. package/lib/Signal/libsignal.d.ts.map +1 -0
  61. package/lib/Signal/libsignal.js +319 -90
  62. package/lib/Signal/libsignal.js.map +1 -0
  63. package/lib/Signal/lid-mapping.d.ts +19 -0
  64. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  65. package/lib/Signal/lid-mapping.js +271 -0
  66. package/lib/Signal/lid-mapping.js.map +1 -0
  67. package/lib/Socket/Client/index.d.ts +3 -3
  68. package/lib/Socket/Client/index.d.ts.map +1 -0
  69. package/lib/Socket/Client/index.js +3 -19
  70. package/lib/Socket/Client/index.js.map +1 -0
  71. package/lib/Socket/Client/{abstract-socket-client.d.ts → types.d.ts} +4 -5
  72. package/lib/Socket/Client/types.d.ts.map +1 -0
  73. package/lib/Socket/Client/types.js +11 -0
  74. package/lib/Socket/Client/types.js.map +1 -0
  75. package/lib/Socket/Client/{web-socket-client.d.ts → websocket.d.ts} +3 -2
  76. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  77. package/lib/Socket/Client/websocket.js +54 -0
  78. package/lib/Socket/Client/websocket.js.map +1 -0
  79. package/lib/Socket/business.d.ts +533 -168
  80. package/lib/Socket/business.d.ts.map +1 -0
  81. package/lib/Socket/business.js +405 -243
  82. package/lib/Socket/business.js.map +1 -0
  83. package/lib/Socket/chats.d.ts +84 -240
  84. package/lib/Socket/chats.d.ts.map +1 -0
  85. package/lib/Socket/chats.js +406 -385
  86. package/lib/Socket/chats.js.map +1 -0
  87. package/lib/Socket/communities.d.ts +645 -0
  88. package/lib/Socket/communities.d.ts.map +1 -0
  89. package/lib/Socket/communities.js +431 -0
  90. package/lib/Socket/communities.js.map +1 -0
  91. package/lib/Socket/dugong.d.ts +125 -249
  92. package/lib/Socket/dugong.d.ts.map +1 -0
  93. package/lib/Socket/dugong.js +749 -465
  94. package/lib/Socket/dugong.js.map +1 -0
  95. package/lib/Socket/groups.d.ts +93 -58
  96. package/lib/Socket/groups.d.ts.map +1 -0
  97. package/lib/Socket/groups.js +105 -95
  98. package/lib/Socket/groups.js.map +1 -0
  99. package/lib/Socket/index.d.ts +632 -169
  100. package/lib/Socket/index.d.ts.map +1 -0
  101. package/lib/Socket/index.js +15 -11
  102. package/lib/Socket/index.js.map +1 -0
  103. package/lib/Socket/messages-recv.d.ts +162 -85
  104. package/lib/Socket/messages-recv.d.ts.map +1 -0
  105. package/lib/Socket/messages-recv.js +806 -608
  106. package/lib/Socket/messages-recv.js.map +1 -0
  107. package/lib/Socket/messages-send.d.ts +576 -146
  108. package/lib/Socket/messages-send.d.ts.map +1 -0
  109. package/lib/Socket/messages-send.js +1563 -861
  110. package/lib/Socket/messages-send.js.map +1 -0
  111. package/lib/Socket/mex.d.ts +3 -0
  112. package/lib/Socket/mex.d.ts.map +1 -0
  113. package/lib/Socket/mex.js +48 -0
  114. package/lib/Socket/mex.js.map +1 -0
  115. package/lib/Socket/newsletter.d.ts +129 -86
  116. package/lib/Socket/newsletter.d.ts.map +1 -0
  117. package/lib/Socket/newsletter.js +438 -297
  118. package/lib/Socket/newsletter.js.map +1 -0
  119. package/lib/Socket/socket.d.ts +31 -19
  120. package/lib/Socket/socket.d.ts.map +1 -0
  121. package/lib/Socket/socket.js +512 -241
  122. package/lib/Socket/socket.js.map +1 -0
  123. package/lib/Types/Auth.d.ts +18 -12
  124. package/lib/Types/Auth.d.ts.map +1 -0
  125. package/lib/Types/Auth.js +2 -2
  126. package/lib/Types/Auth.js.map +1 -0
  127. package/lib/Types/Bussines.d.ts +37 -0
  128. package/lib/Types/Bussines.d.ts.map +1 -0
  129. package/lib/Types/Bussines.js +2 -0
  130. package/lib/Types/Bussines.js.map +1 -0
  131. package/lib/Types/Call.d.ts +3 -1
  132. package/lib/Types/Call.d.ts.map +1 -0
  133. package/lib/Types/Call.js +2 -2
  134. package/lib/Types/Call.js.map +1 -0
  135. package/lib/Types/Chat.d.ts +34 -13
  136. package/lib/Types/Chat.d.ts.map +1 -0
  137. package/lib/Types/Chat.js +8 -4
  138. package/lib/Types/Chat.js.map +1 -0
  139. package/lib/Types/Contact.d.ts +6 -1
  140. package/lib/Types/Contact.d.ts.map +1 -0
  141. package/lib/Types/Contact.js +2 -2
  142. package/lib/Types/Contact.js.map +1 -0
  143. package/lib/Types/Events.d.ts +97 -17
  144. package/lib/Types/Events.d.ts.map +1 -0
  145. package/lib/Types/Events.js +2 -2
  146. package/lib/Types/Events.js.map +1 -0
  147. package/lib/Types/GroupMetadata.d.ts +18 -5
  148. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  149. package/lib/Types/GroupMetadata.js +2 -2
  150. package/lib/Types/GroupMetadata.js.map +1 -0
  151. package/lib/Types/Label.d.ts +12 -0
  152. package/lib/Types/Label.d.ts.map +1 -0
  153. package/lib/Types/Label.js +3 -5
  154. package/lib/Types/Label.js.map +1 -0
  155. package/lib/Types/LabelAssociation.d.ts +1 -0
  156. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  157. package/lib/Types/LabelAssociation.js +3 -5
  158. package/lib/Types/LabelAssociation.js.map +1 -0
  159. package/lib/Types/Message.d.ts +355 -206
  160. package/lib/Types/Message.d.ts.map +1 -0
  161. package/lib/Types/Message.js +11 -9
  162. package/lib/Types/Message.js.map +1 -0
  163. package/lib/Types/Newsletter.d.ts +130 -98
  164. package/lib/Types/Newsletter.d.ts.map +1 -0
  165. package/lib/Types/Newsletter.js +31 -38
  166. package/lib/Types/Newsletter.js.map +1 -0
  167. package/lib/Types/Product.d.ts +2 -1
  168. package/lib/Types/Product.d.ts.map +1 -0
  169. package/lib/Types/Product.js +2 -2
  170. package/lib/Types/Product.js.map +1 -0
  171. package/lib/Types/Signal.d.ts +20 -1
  172. package/lib/Types/Signal.d.ts.map +1 -0
  173. package/lib/Types/Signal.js +2 -2
  174. package/lib/Types/Signal.js.map +1 -0
  175. package/lib/Types/Socket.d.ts +152 -105
  176. package/lib/Types/Socket.d.ts.map +1 -0
  177. package/lib/Types/Socket.js +3 -2
  178. package/lib/Types/Socket.js.map +1 -0
  179. package/lib/Types/State.d.ts +14 -2
  180. package/lib/Types/State.d.ts.map +1 -0
  181. package/lib/Types/State.js +13 -2
  182. package/lib/Types/State.js.map +1 -0
  183. package/lib/Types/USync.d.ts +3 -2
  184. package/lib/Types/USync.d.ts.map +1 -0
  185. package/lib/Types/USync.js +2 -2
  186. package/lib/Types/USync.js.map +1 -0
  187. package/lib/Types/index.d.ts +54 -45
  188. package/lib/Types/index.d.ts.map +1 -0
  189. package/lib/Types/index.js +32 -41
  190. package/lib/Types/index.js.map +1 -0
  191. package/lib/Utils/auth-utils.d.ts +7 -6
  192. package/lib/Utils/auth-utils.d.ts.map +1 -0
  193. package/lib/Utils/auth-utils.js +228 -144
  194. package/lib/Utils/auth-utils.js.map +1 -0
  195. package/lib/Utils/browser-utils.d.ts +4 -0
  196. package/lib/Utils/browser-utils.d.ts.map +1 -0
  197. package/lib/Utils/browser-utils.js +28 -0
  198. package/lib/Utils/browser-utils.js.map +1 -0
  199. package/lib/Utils/business.d.ts +3 -2
  200. package/lib/Utils/business.d.ts.map +1 -0
  201. package/lib/Utils/business.js +66 -69
  202. package/lib/Utils/business.js.map +1 -0
  203. package/lib/Utils/chat-utils.d.ts +19 -20
  204. package/lib/Utils/chat-utils.d.ts.map +1 -0
  205. package/lib/Utils/chat-utils.js +331 -248
  206. package/lib/Utils/chat-utils.js.map +1 -0
  207. package/lib/Utils/crypto.d.ts +10 -14
  208. package/lib/Utils/crypto.d.ts.map +1 -0
  209. package/lib/Utils/crypto.js +57 -90
  210. package/lib/Utils/crypto.js.map +1 -0
  211. package/lib/Utils/decode-wa-message.d.ts +37 -8
  212. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  213. package/lib/Utils/decode-wa-message.js +169 -84
  214. package/lib/Utils/decode-wa-message.js.map +1 -0
  215. package/lib/Utils/event-buffer.d.ts +7 -8
  216. package/lib/Utils/event-buffer.d.ts.map +1 -0
  217. package/lib/Utils/event-buffer.js +138 -78
  218. package/lib/Utils/event-buffer.js.map +1 -0
  219. package/lib/Utils/generics.d.ts +26 -27
  220. package/lib/Utils/generics.d.ts.map +1 -0
  221. package/lib/Utils/generics.js +170 -209
  222. package/lib/Utils/generics.js.map +1 -0
  223. package/lib/Utils/history.d.ts +16 -9
  224. package/lib/Utils/history.d.ts.map +1 -0
  225. package/lib/Utils/history.js +83 -48
  226. package/lib/Utils/history.js.map +1 -0
  227. package/lib/Utils/identity-change-handler.d.ts +37 -0
  228. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  229. package/lib/Utils/identity-change-handler.js +49 -0
  230. package/lib/Utils/identity-change-handler.js.map +1 -0
  231. package/lib/Utils/index.d.ts +23 -17
  232. package/lib/Utils/index.d.ts.map +1 -0
  233. package/lib/Utils/index.js +23 -33
  234. package/lib/Utils/index.js.map +1 -0
  235. package/lib/Utils/link-preview.d.ts +5 -5
  236. package/lib/Utils/link-preview.d.ts.map +1 -0
  237. package/lib/Utils/link-preview.js +14 -22
  238. package/lib/Utils/link-preview.js.map +1 -0
  239. package/lib/Utils/logger.d.ts +12 -3
  240. package/lib/Utils/logger.d.ts.map +1 -0
  241. package/lib/Utils/logger.js +3 -7
  242. package/lib/Utils/logger.js.map +1 -0
  243. package/lib/Utils/lt-hash.d.ts +8 -12
  244. package/lib/Utils/lt-hash.d.ts.map +1 -0
  245. package/lib/Utils/lt-hash.js +3 -46
  246. package/lib/Utils/lt-hash.js.map +1 -0
  247. package/lib/Utils/make-mutex.d.ts +4 -2
  248. package/lib/Utils/make-mutex.d.ts.map +1 -0
  249. package/lib/Utils/make-mutex.js +24 -34
  250. package/lib/Utils/make-mutex.js.map +1 -0
  251. package/lib/Utils/message-retry-manager.d.ts +110 -0
  252. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  253. package/lib/Utils/message-retry-manager.js +225 -0
  254. package/lib/Utils/message-retry-manager.js.map +1 -0
  255. package/lib/Utils/messages-media.d.ts +56 -42
  256. package/lib/Utils/messages-media.d.ts.map +1 -0
  257. package/lib/Utils/messages-media.js +411 -448
  258. package/lib/Utils/messages-media.js.map +1 -0
  259. package/lib/Utils/messages.d.ts +32 -18
  260. package/lib/Utils/messages.d.ts.map +1 -0
  261. package/lib/Utils/messages.js +1132 -710
  262. package/lib/Utils/messages.js.map +1 -0
  263. package/lib/Utils/noise-handler.d.ts +12 -13
  264. package/lib/Utils/noise-handler.d.ts.map +1 -0
  265. package/lib/Utils/noise-handler.js +145 -99
  266. package/lib/Utils/noise-handler.js.map +1 -0
  267. package/lib/Utils/offline-node-processor.d.ts +17 -0
  268. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  269. package/lib/Utils/offline-node-processor.js +40 -0
  270. package/lib/Utils/offline-node-processor.js.map +1 -0
  271. package/lib/Utils/pre-key-manager.d.ts +28 -0
  272. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  273. package/lib/Utils/pre-key-manager.js +106 -0
  274. package/lib/Utils/pre-key-manager.js.map +1 -0
  275. package/lib/Utils/process-message.d.ts +31 -12
  276. package/lib/Utils/process-message.d.ts.map +1 -0
  277. package/lib/Utils/process-message.js +357 -150
  278. package/lib/Utils/process-message.js.map +1 -0
  279. package/lib/Utils/reporting-utils.d.ts +11 -0
  280. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  281. package/lib/Utils/reporting-utils.js +258 -0
  282. package/lib/Utils/reporting-utils.js.map +1 -0
  283. package/lib/Utils/rich-messages.d.ts +277 -0
  284. package/lib/Utils/rich-messages.d.ts.map +1 -0
  285. package/lib/Utils/rich-messages.js +1144 -0
  286. package/lib/Utils/rich-messages.js.map +1 -0
  287. package/lib/Utils/signal.d.ts +7 -5
  288. package/lib/Utils/signal.d.ts.map +1 -0
  289. package/lib/Utils/signal.js +78 -72
  290. package/lib/Utils/signal.js.map +1 -0
  291. package/lib/Utils/stanza-ack.d.ts +11 -0
  292. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  293. package/lib/Utils/stanza-ack.js +38 -0
  294. package/lib/Utils/stanza-ack.js.map +1 -0
  295. package/lib/Utils/sticker-pack.d.ts +10 -0
  296. package/lib/Utils/sticker-pack.js +111 -0
  297. package/lib/Utils/sync-action-utils.d.ts +19 -0
  298. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  299. package/lib/Utils/sync-action-utils.js +48 -0
  300. package/lib/Utils/sync-action-utils.js.map +1 -0
  301. package/lib/Utils/tc-token-utils.d.ts +12 -0
  302. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  303. package/lib/Utils/tc-token-utils.js +18 -0
  304. package/lib/Utils/tc-token-utils.js.map +1 -0
  305. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -2
  306. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  307. package/lib/Utils/use-multi-file-auth-state.js +29 -27
  308. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  309. package/lib/Utils/validate-connection.d.ts +7 -7
  310. package/lib/Utils/validate-connection.d.ts.map +1 -0
  311. package/lib/Utils/validate-connection.js +70 -99
  312. package/lib/Utils/validate-connection.js.map +1 -0
  313. package/lib/WABinary/constants.d.ts +25 -27
  314. package/lib/WABinary/constants.d.ts.map +1 -0
  315. package/lib/WABinary/constants.js +1281 -20
  316. package/lib/WABinary/constants.js.map +1 -0
  317. package/lib/WABinary/decode.d.ts +5 -5
  318. package/lib/WABinary/decode.d.ts.map +1 -0
  319. package/lib/WABinary/decode.js +52 -42
  320. package/lib/WABinary/decode.js.map +1 -0
  321. package/lib/WABinary/encode.d.ts +3 -3
  322. package/lib/WABinary/encode.d.ts.map +1 -0
  323. package/lib/WABinary/encode.js +110 -155
  324. package/lib/WABinary/encode.js.map +1 -0
  325. package/lib/WABinary/generic-utils.d.ts +8 -8
  326. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  327. package/lib/WABinary/generic-utils.js +142 -149
  328. package/lib/WABinary/generic-utils.js.map +1 -0
  329. package/lib/WABinary/index.d.ts +6 -5
  330. package/lib/WABinary/index.d.ts.map +1 -0
  331. package/lib/WABinary/index.js +6 -21
  332. package/lib/WABinary/index.js.map +1 -0
  333. package/lib/WABinary/jid-utils.d.ts +25 -8
  334. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  335. package/lib/WABinary/jid-utils.js +74 -40
  336. package/lib/WABinary/jid-utils.js.map +1 -0
  337. package/lib/WABinary/types.d.ts +2 -1
  338. package/lib/WABinary/types.d.ts.map +1 -0
  339. package/lib/WABinary/types.js +2 -2
  340. package/lib/WABinary/types.js.map +1 -0
  341. package/lib/WAM/BinaryInfo.d.ts +3 -11
  342. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  343. package/lib/WAM/BinaryInfo.js +2 -5
  344. package/lib/WAM/BinaryInfo.js.map +1 -0
  345. package/lib/WAM/constants.d.ts +5 -3
  346. package/lib/WAM/constants.d.ts.map +1 -0
  347. package/lib/WAM/constants.js +19071 -11568
  348. package/lib/WAM/constants.js.map +1 -0
  349. package/lib/WAM/encode.d.ts +2 -2
  350. package/lib/WAM/encode.d.ts.map +1 -0
  351. package/lib/WAM/encode.js +17 -22
  352. package/lib/WAM/encode.js.map +1 -0
  353. package/lib/WAM/index.d.ts +4 -3
  354. package/lib/WAM/index.d.ts.map +1 -0
  355. package/lib/WAM/index.js +4 -19
  356. package/lib/WAM/index.js.map +1 -0
  357. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +4 -3
  358. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  359. package/lib/WAUSync/Protocols/USyncContactProtocol.js +8 -11
  360. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  361. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +3 -2
  362. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  363. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -14
  364. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  365. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +3 -2
  366. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  367. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +9 -12
  368. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  369. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +3 -2
  370. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  371. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -13
  372. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  373. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +4 -3
  374. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  375. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -22
  376. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  377. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +5 -3
  378. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  379. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +13 -8
  380. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  381. package/lib/WAUSync/Protocols/index.d.ts +5 -4
  382. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  383. package/lib/WAUSync/Protocols/index.js +5 -20
  384. package/lib/WAUSync/Protocols/index.js.map +1 -0
  385. package/lib/WAUSync/USyncQuery.d.ts +5 -4
  386. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  387. package/lib/WAUSync/USyncQuery.js +40 -35
  388. package/lib/WAUSync/USyncQuery.js.map +1 -0
  389. package/lib/WAUSync/USyncUser.d.ts +6 -5
  390. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  391. package/lib/WAUSync/USyncUser.js +2 -5
  392. package/lib/WAUSync/USyncUser.js.map +1 -0
  393. package/lib/WAUSync/index.d.ts +4 -3
  394. package/lib/WAUSync/index.d.ts.map +1 -0
  395. package/lib/WAUSync/index.js +4 -19
  396. package/lib/WAUSync/index.js.map +1 -0
  397. package/lib/index.d.ts +10 -9
  398. package/lib/index.d.ts.map +1 -0
  399. package/lib/index.js +12 -33
  400. package/lib/index.js.map +1 -0
  401. package/package.json +64 -105
  402. package/README.md +0 -364
  403. package/engine-requirements.js +0 -10
  404. package/lib/Defaults/baileys-version.json +0 -3
  405. package/lib/Defaults/phonenumber-mcc.json +0 -223
  406. package/lib/Signal/Group/queue-job.d.ts +0 -1
  407. package/lib/Signal/Group/queue-job.js +0 -57
  408. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  409. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  410. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  411. package/lib/Socket/Client/web-socket-client.js +0 -62
  412. package/lib/Socket/registration.d.ts +0 -267
  413. package/lib/Socket/registration.js +0 -166
  414. package/lib/Socket/usync.d.ts +0 -36
  415. package/lib/Socket/usync.js +0 -70
  416. package/lib/Store/index.d.ts +0 -3
  417. package/lib/Store/index.js +0 -10
  418. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  419. package/lib/Store/make-cache-manager-store.js +0 -83
  420. package/lib/Store/make-in-memory-store.d.ts +0 -118
  421. package/lib/Store/make-in-memory-store.js +0 -427
  422. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  423. package/lib/Store/make-ordered-dictionary.js +0 -81
  424. package/lib/Store/object-repository.d.ts +0 -10
  425. package/lib/Store/object-repository.js +0 -27
  426. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  427. package/lib/Utils/baileys-event-stream.js +0 -63
@@ -1,30 +1,41 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.makeChatsSocket = void 0;
7
- const boom_1 = require("@hapi/boom");
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 make_mutex_1 = require("../Utils/make-mutex");
13
- const process_message_1 = __importDefault(require("../Utils/process-message"));
14
- const WABinary_1 = require("../WABinary");
15
- const socket_1 = require("./socket");
16
- const WAUSync_1 = require("../WAUSync");
17
- const usync_1 = require("./usync");
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { DEFAULT_CACHE_TTLS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
5
+ import { ALL_WA_PATCH_NAMES } from '../Types/index.js';
6
+ import { SyncState } from '../Types/State.js';
7
+ import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, extractSyncdPatches, generateProfilePicture, getHistoryMsg, newLTHashState, processSyncAction } from '../Utils/index.js';
8
+ import { makeMutex } from '../Utils/make-mutex.js';
9
+ import processMessage from '../Utils/process-message.js';
10
+ import { buildTcTokenFromJid } from '../Utils/tc-token-utils.js';
11
+ import { getBinaryNodeChild, getBinaryNodeChildren, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
12
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
+ import { makeSocket } from './socket.js';
18
14
  const MAX_SYNC_ATTEMPTS = 2;
19
- const makeChatsSocket = (config) => {
20
- const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
21
- const sock = (0, usync_1.makeUSyncSocket)(config);
22
- const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, } = sock;
15
+ export const makeChatsSocket = (config) => {
16
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
17
+ const sock = makeSocket(config);
18
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession } = sock;
23
19
  let privacySettings;
24
- let needToFlushWithAppStateSync = false;
25
- let pendingAppStateSync = false;
26
- /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
27
- const processingMutex = (0, make_mutex_1.makeMutex)();
20
+ let syncState = SyncState.Connecting;
21
+ /** this mutex ensures that messages are processed in order */
22
+ const messageMutex = makeMutex();
23
+ /** this mutex ensures that receipts are processed in order */
24
+ const receiptMutex = makeMutex();
25
+ /** this mutex ensures that app state patches are processed in order */
26
+ const appStatePatchMutex = makeMutex();
27
+ /** this mutex ensures that notifications are processed in order */
28
+ const notificationMutex = makeMutex();
29
+ // Timeout for AwaitingInitialSync state
30
+ let awaitingSyncTimeout;
31
+ const placeholderResendCache = config.placeholderResendCache ||
32
+ new NodeCache({
33
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
34
+ useClones: false
35
+ });
36
+ if (!config.placeholderResendCache) {
37
+ config.placeholderResendCache = placeholderResendCache;
38
+ }
28
39
  /** helper function to fetch the given app state sync key */
29
40
  const getAppStateSyncKey = async (keyId) => {
30
41
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
@@ -36,14 +47,12 @@ const makeChatsSocket = (config) => {
36
47
  tag: 'iq',
37
48
  attrs: {
38
49
  xmlns: 'privacy',
39
- to: WABinary_1.S_WHATSAPP_NET,
50
+ to: S_WHATSAPP_NET,
40
51
  type: 'get'
41
52
  },
42
- content: [
43
- { tag: 'privacy', attrs: {} }
44
- ]
53
+ content: [{ tag: 'privacy', attrs: {} }]
45
54
  });
46
- privacySettings = (0, WABinary_1.reduceBinaryNodeToDictionary)(content === null || content === void 0 ? void 0 : content[0], 'category');
55
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
47
56
  }
48
57
  return privacySettings;
49
58
  };
@@ -53,10 +62,11 @@ const makeChatsSocket = (config) => {
53
62
  tag: 'iq',
54
63
  attrs: {
55
64
  xmlns: 'privacy',
56
- to: WABinary_1.S_WHATSAPP_NET,
65
+ to: S_WHATSAPP_NET,
57
66
  type: 'set'
58
67
  },
59
- content: [{
68
+ content: [
69
+ {
60
70
  tag: 'privacy',
61
71
  attrs: {},
62
72
  content: [
@@ -65,9 +75,16 @@ const makeChatsSocket = (config) => {
65
75
  attrs: { name, value }
66
76
  }
67
77
  ]
68
- }]
78
+ }
79
+ ]
69
80
  });
70
81
  };
82
+ const updateMessagesPrivacy = async (value) => {
83
+ await privacyQuery('messages', value);
84
+ };
85
+ const updateCallPrivacy = async (value) => {
86
+ await privacyQuery('calladd', value);
87
+ };
71
88
  const updateLastSeenPrivacy = async (value) => {
72
89
  await privacyQuery('last', value);
73
90
  };
@@ -86,251 +103,95 @@ const makeChatsSocket = (config) => {
86
103
  const updateGroupsAddPrivacy = async (value) => {
87
104
  await privacyQuery('groupadd', value);
88
105
  };
89
- /** check whether your WhatsApp account is blocked or not */
90
- const checkStatusWA = async (phoneNumber) => {
91
- if (!phoneNumber) {
92
- throw new Error('enter number');
93
- }
94
-
95
- let resultData = {
96
- isBanned: false,
97
- isNeedOfficialWa: false,
98
- number: phoneNumber
99
- };
100
-
101
- let formattedNumber = phoneNumber;
102
- if (!formattedNumber.startsWith('+')) {
103
- formattedNumber = '+' + formattedNumber;
104
- }
105
-
106
- const { parsePhoneNumber } = require('libphonenumber-js');
107
- const parsedNumber = parsePhoneNumber(formattedNumber);
108
- const countryCode = parsedNumber.countryCallingCode;
109
- const nationalNumber = parsedNumber.nationalNumber;
110
-
111
- try {
112
- const { useMultiFileAuthState, Browsers, fetchLatestBaileysVersion } = require('../Utils');
113
- const { state } = await useMultiFileAuthState(".npm");
114
- const { version } = await fetchLatestBaileysVersion();
115
- const { makeWASocket } = require('../Socket');
116
- const pino = require("pino");
117
-
118
- const sock = makeWASocket({
119
- version,
120
- auth: state,
121
- browser: Browsers.ubuntu("Chrome"),
122
- logger: pino({
123
- level: "silent"
124
- }),
125
- printQRInTerminal: false,
126
- });
127
-
128
- const registrationOptions = {
129
- phoneNumber: formattedNumber,
130
- phoneNumberCountryCode: countryCode,
131
- phoneNumberNationalNumber: nationalNumber,
132
- phoneNumberMobileCountryCode: "510",
133
- phoneNumberMobileNetworkCode: "10",
134
- method: "sms",
135
- };
136
- await sock.requestRegistrationCode(registrationOptions);
137
- if (sock.ws) {
138
- sock.ws.close();
139
- }
140
-
141
- return JSON.stringify(resultData, null, 2);
142
- } catch (err) {
143
- if (err?.appeal_token) {
144
- resultData.isBanned = true;
145
- resultData.data = {
146
- violation_type: err.violation_type || null,
147
- in_app_ban_appeal: err.in_app_ban_appeal || null,
148
- appeal_token: err.appeal_token || null,
149
- };
150
- }
151
- else if (err?.custom_block_screen || err?.reason === 'blocked') {
152
- resultData.isNeedOfficialWa = true;
153
- }
154
- return JSON.stringify(resultData, null, 2);
155
- }
156
- };
157
106
  const updateDefaultDisappearingMode = async (duration) => {
158
107
  await query({
159
108
  tag: 'iq',
160
109
  attrs: {
161
110
  xmlns: 'disappearing_mode',
162
- to: WABinary_1.S_WHATSAPP_NET,
111
+ to: S_WHATSAPP_NET,
163
112
  type: 'set'
164
113
  },
165
- content: [{
114
+ content: [
115
+ {
166
116
  tag: 'disappearing_mode',
167
117
  attrs: {
168
118
  duration: duration.toString()
169
119
  }
170
- }]
120
+ }
121
+ ]
171
122
  });
172
123
  };
173
- /** helper function to run a generic IQ query */
174
- const interactiveQuery = async (userNodes, queryNode) => {
175
- const result = await query({
124
+ const getBotListV2 = async () => {
125
+ const resp = await query({
176
126
  tag: 'iq',
177
127
  attrs: {
178
- to: WABinary_1.S_WHATSAPP_NET,
179
- type: 'get',
180
- xmlns: 'usync',
128
+ xmlns: 'bot',
129
+ to: S_WHATSAPP_NET,
130
+ type: 'get'
181
131
  },
182
132
  content: [
183
133
  {
184
- tag: 'usync',
134
+ tag: 'bot',
185
135
  attrs: {
186
- sid: generateMessageTag(),
187
- mode: 'query',
188
- last: 'true',
189
- index: '0',
190
- context: 'interactive',
191
- },
192
- content: [
193
- {
194
- tag: 'query',
195
- attrs: {},
196
- content: [queryNode]
197
- },
198
- {
199
- tag: 'list',
200
- attrs: {},
201
- content: userNodes
202
- }
203
- ]
136
+ v: '2'
137
+ }
204
138
  }
205
- ],
206
- });
207
- const usyncNode = (0, WABinary_1.getBinaryNodeChild)(result, 'usync');
208
- const listNode = (0, WABinary_1.getBinaryNodeChild)(usyncNode, 'list');
209
- const users = (0, WABinary_1.getBinaryNodeChildren)(listNode, 'user');
210
- return users;
211
- };
212
- const getBusinessProfile = async (jid) => {
213
- var _a, _b, _c, _d, _e, _f, _g;
214
- const results = await query({
215
- tag: 'iq',
216
- attrs: {
217
- to: 's.whatsapp.net',
218
- xmlns: 'w:biz',
219
- type: 'get'
220
- },
221
- content: [{
222
- tag: 'business_profile',
223
- attrs: { v: '244' },
224
- content: [{
225
- tag: 'profile',
226
- attrs: { jid }
227
- }]
228
- }]
139
+ ]
229
140
  });
230
- const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile');
231
- const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile');
232
- if (profiles) {
233
- const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address');
234
- const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description');
235
- const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website');
236
- const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
237
- const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
238
- const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
239
- const businessHoursConfig = businessHours ?
240
- (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config') :
241
- undefined;
242
- const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
243
- return {
244
- wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
245
- address: (_c = address === null || address === void 0 ? void 0 : address.content) === null || _c === void 0 ? void 0 : _c.toString(),
246
- description: ((_d = description === null || description === void 0 ? void 0 : description.content) === null || _d === void 0 ? void 0 : _d.toString()) || '',
247
- website: websiteStr ? [websiteStr] : [],
248
- email: (_e = email === null || email === void 0 ? void 0 : email.content) === null || _e === void 0 ? void 0 : _e.toString(),
249
- category: (_f = category === null || category === void 0 ? void 0 : category.content) === null || _f === void 0 ? void 0 : _f.toString(),
250
- 'business_hours': {
251
- timezone: (_g = businessHours === null || businessHours === void 0 ? void 0 : businessHours.attrs) === null || _g === void 0 ? void 0 : _g.timezone,
252
- 'business_config': businessHoursConfig === null || businessHoursConfig === void 0 ? void 0 : businessHoursConfig.map(({ attrs }) => attrs)
141
+ const botNode = getBinaryNodeChild(resp, 'bot');
142
+ const botList = [];
143
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
144
+ if (section.attrs.type === 'all') {
145
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
146
+ botList.push({
147
+ jid: bot.attrs.jid,
148
+ personaId: bot.attrs['persona_id']
149
+ });
253
150
  }
254
- };
151
+ }
255
152
  }
153
+ return botList;
256
154
  };
257
- const onWhatsApp = async (...jids) => {
258
- const usyncQuery = new WAUSync_1.USyncQuery()
259
- .withContactProtocol()
260
- .withLIDProtocol();
261
-
155
+ const fetchStatus = async (...jids) => {
156
+ const usyncQuery = new USyncQuery().withStatusProtocol();
262
157
  for (const jid of jids) {
263
- const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`;
264
- usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
265
- }
266
-
267
- const results = await sock.executeUSyncQuery(usyncQuery);
268
- if (results) {
269
- const verifiedResults = await Promise.all(
270
- results.list
271
- .filter((a) => !!a.contact)
272
- .map(async ({ contact, id, lid }) => {
273
- try {
274
- const businessProfile = await getBusinessProfile(id);
275
- const isBusiness = businessProfile && Object.keys(businessProfile).length > 0;
276
- if (isBusiness) {
277
- const { wid, ...businessInfo } = businessProfile;
278
-
279
- return {
280
- jid: id,
281
- exists: true,
282
- lid: lid,
283
- status: 'business',
284
- businessInfo: businessInfo
285
- };
286
- } else {
287
- return {
288
- jid: id,
289
- exists: true,
290
- lid: lid,
291
- status: 'regular'
292
- };
293
- }
294
- } catch (error) {
295
- return {
296
- jid: id,
297
- exists: true,
298
- lid: lid,
299
- status: error
300
- };
301
- }
302
- })
303
- );
304
- return verifiedResults;
158
+ usyncQuery.withUser(new USyncUser().withId(jid));
159
+ }
160
+ const result = await sock.executeUSyncQuery(usyncQuery);
161
+ if (result) {
162
+ return result.list;
305
163
  }
306
164
  };
307
- const fetchStatus = async (jid) => {
308
- const [result] = await interactiveQuery([{ tag: 'user', attrs: { jid } }], { tag: 'status', attrs: {} });
165
+ const fetchDisappearingDuration = async (...jids) => {
166
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
167
+ for (const jid of jids) {
168
+ usyncQuery.withUser(new USyncUser().withId(jid));
169
+ }
170
+ const result = await sock.executeUSyncQuery(usyncQuery);
309
171
  if (result) {
310
- const status = (0, WABinary_1.getBinaryNodeChild)(result, 'status');
311
- return {
312
- status: status === null || status === void 0 ? void 0 : status.content.toString(),
313
- setAt: new Date(+((status === null || status === void 0 ? void 0 : status.attrs.t) || 0) * 1000)
314
- };
172
+ return result.list;
315
173
  }
316
174
  };
317
175
  /** update the profile picture for yourself or a group */
318
- const updateProfilePicture = async (jid, content) => {
176
+ const updateProfilePicture = async (jid, content, dimensions) => {
319
177
  let targetJid;
320
178
  if (!jid) {
321
- throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
179
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
322
180
  }
323
- if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
324
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
181
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
182
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
325
183
  }
326
- const { img } = await (0, Utils_1.generateProfilePicture)(content);
184
+ else {
185
+ targetJid = undefined;
186
+ }
187
+ const { img } = await generateProfilePicture(content, dimensions);
327
188
  await query({
328
189
  tag: 'iq',
329
190
  attrs: {
330
- target: targetJid,
331
- to: WABinary_1.S_WHATSAPP_NET,
191
+ to: S_WHATSAPP_NET,
332
192
  type: 'set',
333
- xmlns: 'w:profile:picture'
193
+ xmlns: 'w:profile:picture',
194
+ ...(targetJid ? { target: targetJid } : {})
334
195
  },
335
196
  content: [
336
197
  {
@@ -345,18 +206,21 @@ const makeChatsSocket = (config) => {
345
206
  const removeProfilePicture = async (jid) => {
346
207
  let targetJid;
347
208
  if (!jid) {
348
- throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
209
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
349
210
  }
350
- if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
351
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
211
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
212
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
213
+ }
214
+ else {
215
+ targetJid = undefined;
352
216
  }
353
217
  await query({
354
218
  tag: 'iq',
355
219
  attrs: {
356
- target: targetJid,
357
- to: WABinary_1.S_WHATSAPP_NET,
220
+ to: S_WHATSAPP_NET,
358
221
  type: 'set',
359
- xmlns: 'w:profile:picture'
222
+ xmlns: 'w:profile:picture',
223
+ ...(targetJid ? { target: targetJid } : {})
360
224
  }
361
225
  });
362
226
  };
@@ -365,7 +229,7 @@ const makeChatsSocket = (config) => {
365
229
  await query({
366
230
  tag: 'iq',
367
231
  attrs: {
368
- to: WABinary_1.S_WHATSAPP_NET,
232
+ to: S_WHATSAPP_NET,
369
233
  type: 'set',
370
234
  xmlns: 'status'
371
235
  },
@@ -386,20 +250,19 @@ const makeChatsSocket = (config) => {
386
250
  tag: 'iq',
387
251
  attrs: {
388
252
  xmlns: 'blocklist',
389
- to: WABinary_1.S_WHATSAPP_NET,
253
+ to: S_WHATSAPP_NET,
390
254
  type: 'get'
391
255
  }
392
256
  });
393
- const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
394
- return (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item')
395
- .map(n => n.attrs.jid);
257
+ const listNode = getBinaryNodeChild(result, 'list');
258
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
396
259
  };
397
260
  const updateBlockStatus = async (jid, action) => {
398
261
  await query({
399
262
  tag: 'iq',
400
263
  attrs: {
401
264
  xmlns: 'blocklist',
402
- to: WABinary_1.S_WHATSAPP_NET,
265
+ to: S_WHATSAPP_NET,
403
266
  type: 'set'
404
267
  },
405
268
  content: [
@@ -413,22 +276,70 @@ const makeChatsSocket = (config) => {
413
276
  ]
414
277
  });
415
278
  };
279
+ const getBusinessProfile = async (jid) => {
280
+ const results = await query({
281
+ tag: 'iq',
282
+ attrs: {
283
+ to: 's.whatsapp.net',
284
+ xmlns: 'w:biz',
285
+ type: 'get'
286
+ },
287
+ content: [
288
+ {
289
+ tag: 'business_profile',
290
+ attrs: { v: '244' },
291
+ content: [
292
+ {
293
+ tag: 'profile',
294
+ attrs: { jid }
295
+ }
296
+ ]
297
+ }
298
+ ]
299
+ });
300
+ const profileNode = getBinaryNodeChild(results, 'business_profile');
301
+ const profiles = getBinaryNodeChild(profileNode, 'profile');
302
+ if (profiles) {
303
+ const address = getBinaryNodeChild(profiles, 'address');
304
+ const description = getBinaryNodeChild(profiles, 'description');
305
+ const website = getBinaryNodeChild(profiles, 'website');
306
+ const email = getBinaryNodeChild(profiles, 'email');
307
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
308
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours');
309
+ const businessHoursConfig = businessHours
310
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
311
+ : undefined;
312
+ const websiteStr = website?.content?.toString();
313
+ return {
314
+ wid: profiles.attrs?.jid,
315
+ address: address?.content?.toString(),
316
+ description: description?.content?.toString() || '',
317
+ website: websiteStr ? [websiteStr] : [],
318
+ email: email?.content?.toString(),
319
+ category: category?.content?.toString(),
320
+ business_hours: {
321
+ timezone: businessHours?.attrs?.timezone,
322
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
323
+ }
324
+ };
325
+ }
326
+ };
416
327
  const cleanDirtyBits = async (type, fromTimestamp) => {
417
328
  logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
418
329
  await sendNode({
419
330
  tag: 'iq',
420
331
  attrs: {
421
- to: WABinary_1.S_WHATSAPP_NET,
332
+ to: S_WHATSAPP_NET,
422
333
  type: 'set',
423
334
  xmlns: 'urn:xmpp:whatsapp:dirty',
424
- id: generateMessageTag(),
335
+ id: generateMessageTag()
425
336
  },
426
337
  content: [
427
338
  {
428
339
  tag: 'clean',
429
340
  attrs: {
430
341
  type,
431
- ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
342
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
432
343
  }
433
344
  }
434
345
  ]
@@ -437,17 +348,25 @@ const makeChatsSocket = (config) => {
437
348
  const newAppStateChunkHandler = (isInitialSync) => {
438
349
  return {
439
350
  onMutation(mutation) {
440
- (0, Utils_1.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
351
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
441
352
  }
442
353
  };
443
354
  };
444
355
  const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
356
+ const appStateSyncKeyCache = new Map();
357
+ const getCachedAppStateSyncKey = async (keyId) => {
358
+ if (appStateSyncKeyCache.has(keyId)) {
359
+ return appStateSyncKeyCache.get(keyId) ?? undefined;
360
+ }
361
+ const key = await getAppStateSyncKey(keyId);
362
+ appStateSyncKeyCache.set(keyId, key ?? null);
363
+ return key;
364
+ };
445
365
  // we use this to determine which events to fire
446
366
  // otherwise when we resync from scratch -- all notifications will fire
447
367
  const initialVersionMap = {};
448
368
  const globalMutationMap = {};
449
369
  await authState.keys.transaction(async () => {
450
- var _a;
451
370
  const collectionsToHandle = new Set(collections);
452
371
  // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
453
372
  const attemptsMap = {};
@@ -466,7 +385,7 @@ const makeChatsSocket = (config) => {
466
385
  }
467
386
  }
468
387
  else {
469
- state = (0, Utils_1.newLTHashState)();
388
+ state = newLTHashState();
470
389
  }
471
390
  states[name] = state;
472
391
  logger.info(`resyncing ${name} from v${state.version}`);
@@ -476,14 +395,14 @@ const makeChatsSocket = (config) => {
476
395
  name,
477
396
  version: state.version.toString(),
478
397
  // return snapshot if being synced from scratch
479
- 'return_snapshot': (!state.version).toString()
398
+ return_snapshot: (!state.version).toString()
480
399
  }
481
400
  });
482
401
  }
483
402
  const result = await query({
484
403
  tag: 'iq',
485
404
  attrs: {
486
- to: WABinary_1.S_WHATSAPP_NET,
405
+ to: S_WHATSAPP_NET,
487
406
  xmlns: 'w:sync:app:state',
488
407
  type: 'set'
489
408
  },
@@ -496,26 +415,22 @@ const makeChatsSocket = (config) => {
496
415
  ]
497
416
  });
498
417
  // extract from binary node
499
- const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
418
+ const decoded = await extractSyncdPatches(result, config?.options);
500
419
  for (const key in decoded) {
501
420
  const name = key;
502
421
  const { patches, hasMorePatches, snapshot } = decoded[name];
503
422
  try {
504
423
  if (snapshot) {
505
- const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
424
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
506
425
  states[name] = newState;
507
426
  Object.assign(globalMutationMap, mutationMap);
508
427
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
509
- await authState.keys.set({ 'app-state-sync-version': {
510
- [name]: newState
511
- } });
428
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
512
429
  }
513
430
  // only process if there are syncd patches
514
431
  if (patches.length) {
515
- const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
516
- await authState.keys.set({ 'app-state-sync-version': {
517
- [name]: newState
518
- } });
432
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
433
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
519
434
  logger.info(`synced ${name} to v${newState.version}`);
520
435
  initialVersionMap[name] = newState.version;
521
436
  Object.assign(globalMutationMap, mutationMap);
@@ -523,7 +438,8 @@ const makeChatsSocket = (config) => {
523
438
  if (hasMorePatches) {
524
439
  logger.info(`${name} has more patches...`);
525
440
  }
526
- else { // collection is done with sync
441
+ else {
442
+ // collection is done with sync
527
443
  collectionsToHandle.delete(name);
528
444
  }
529
445
  }
@@ -531,12 +447,10 @@ const makeChatsSocket = (config) => {
531
447
  // if retry attempts overshoot
532
448
  // or key not found
533
449
  const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
534
- ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404 ||
450
+ error.output?.statusCode === 404 ||
535
451
  error.name === 'TypeError';
536
452
  logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
537
- await authState.keys.set({ 'app-state-sync-version': {
538
- [name]: null
539
- } });
453
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
540
454
  // increment number of retries
541
455
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
542
456
  if (isIrrecoverableError) {
@@ -546,7 +460,7 @@ const makeChatsSocket = (config) => {
546
460
  }
547
461
  }
548
462
  }
549
- });
463
+ }, authState?.creds?.me?.id || 'resync-app-state');
550
464
  const { onMutation } = newAppStateChunkHandler(isInitialSync);
551
465
  for (const key in globalMutationMap) {
552
466
  onMutation(globalMutationMap[key]);
@@ -558,47 +472,68 @@ const makeChatsSocket = (config) => {
558
472
  * type = "image for the high res picture"
559
473
  */
560
474
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
561
- var _a;
562
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
475
+ const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
476
+ const tcTokenContent = await buildTcTokenFromJid({ authState, jid, baseContent });
477
+ jid = jidNormalizedUser(jid);
563
478
  const result = await query({
564
479
  tag: 'iq',
565
480
  attrs: {
566
481
  target: jid,
567
- to: WABinary_1.S_WHATSAPP_NET,
482
+ to: S_WHATSAPP_NET,
568
483
  type: 'get',
569
484
  xmlns: 'w:profile:picture'
570
485
  },
486
+ content: tcTokenContent
487
+ }, timeoutMs);
488
+ const child = getBinaryNodeChild(result, 'picture');
489
+ return child?.attrs?.url;
490
+ };
491
+ const createCallLink = async (type, event, timeoutMs) => {
492
+ const result = await query({
493
+ tag: 'call',
494
+ attrs: {
495
+ id: generateMessageTag(),
496
+ to: '@call'
497
+ },
571
498
  content: [
572
- { tag: 'picture', attrs: { type, query: 'url' } }
499
+ {
500
+ tag: 'link_create',
501
+ attrs: { media: type },
502
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
503
+ }
573
504
  ]
574
505
  }, timeoutMs);
575
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
576
- return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
506
+ const child = getBinaryNodeChild(result, 'link_create');
507
+ return child?.attrs?.token;
577
508
  };
578
509
  const sendPresenceUpdate = async (type, toJid) => {
579
510
  const me = authState.creds.me;
580
- if (type === 'available' || type === 'unavailable') {
511
+ const isAvailableType = type === 'available';
512
+ if (isAvailableType || type === 'unavailable') {
581
513
  if (!me.name) {
582
514
  logger.warn('no name present, ignoring presence update request...');
583
515
  return;
584
516
  }
585
- ev.emit('connection.update', { isOnline: type === 'available' });
517
+ ev.emit('connection.update', { isOnline: isAvailableType });
518
+ if (isAvailableType) {
519
+ void sendUnifiedSession();
520
+ }
586
521
  await sendNode({
587
522
  tag: 'presence',
588
523
  attrs: {
589
- name: me.name,
524
+ name: me.name.replace(/@/g, ''),
590
525
  type
591
526
  }
592
527
  });
593
528
  }
594
529
  else {
595
- const { server } = (0, WABinary_1.jidDecode)(toJid);
530
+ const { server } = jidDecode(toJid);
596
531
  const isLid = server === 'lid';
597
532
  await sendNode({
598
533
  tag: 'chatstate',
599
534
  attrs: {
600
535
  from: isLid ? me.lid : me.id,
601
- to: toJid,
536
+ to: toJid
602
537
  },
603
538
  content: [
604
539
  {
@@ -613,29 +548,23 @@ const makeChatsSocket = (config) => {
613
548
  * @param toJid the jid to subscribe to
614
549
  * @param tcToken token for subscription, use if present
615
550
  */
616
- const presenceSubscribe = (toJid, tcToken) => (sendNode({
617
- tag: 'presence',
618
- attrs: {
619
- to: toJid,
620
- id: generateMessageTag(),
621
- type: 'subscribe'
622
- },
623
- content: tcToken ?
624
- [
625
- {
626
- tag: 'tctoken',
627
- attrs: {},
628
- content: tcToken
629
- }
630
- ] :
631
- undefined
632
- }));
551
+ const presenceSubscribe = async (toJid) => {
552
+ const tcTokenContent = await buildTcTokenFromJid({ authState, jid: toJid });
553
+ return sendNode({
554
+ tag: 'presence',
555
+ attrs: {
556
+ to: toJid,
557
+ id: generateMessageTag(),
558
+ type: 'subscribe'
559
+ },
560
+ content: tcTokenContent
561
+ });
562
+ };
633
563
  const handlePresenceUpdate = ({ tag, attrs, content }) => {
634
- var _a;
635
564
  let presence;
636
565
  const jid = attrs.from;
637
566
  const participant = attrs.participant || attrs.from;
638
- if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
567
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
639
568
  return;
640
569
  }
641
570
  if (tag === 'presence') {
@@ -650,7 +579,7 @@ const makeChatsSocket = (config) => {
650
579
  if (type === 'paused') {
651
580
  type = 'available';
652
581
  }
653
- if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
582
+ if (firstChild.attrs?.media === 'audio') {
654
583
  type = 'recording';
655
584
  }
656
585
  presence = { lastKnownPresence: type };
@@ -659,31 +588,29 @@ const makeChatsSocket = (config) => {
659
588
  logger.error({ tag, attrs, content }, 'recv invalid presence node');
660
589
  }
661
590
  if (presence) {
662
- ev.emit('presence.update', { id: jid, presences: {
663
- [participant]: presence
664
- } });
591
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
665
592
  }
666
593
  };
667
594
  const appPatch = async (patchCreate) => {
668
595
  const name = patchCreate.type;
669
596
  const myAppStateKeyId = authState.creds.myAppStateKeyId;
670
597
  if (!myAppStateKeyId) {
671
- throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
598
+ throw new Boom('App state key not present!', { statusCode: 400 });
672
599
  }
673
600
  let initial;
674
601
  let encodeResult;
675
- await processingMutex.mutex(async () => {
602
+ await appStatePatchMutex.mutex(async () => {
676
603
  await authState.keys.transaction(async () => {
677
604
  logger.debug({ patch: patchCreate }, 'applying app patch');
678
605
  await resyncAppState([name], false);
679
606
  const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
680
- initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
681
- encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
607
+ initial = currentSyncVersion || newLTHashState();
608
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
682
609
  const { patch, state } = encodeResult;
683
610
  const node = {
684
611
  tag: 'iq',
685
612
  attrs: {
686
- to: WABinary_1.S_WHATSAPP_NET,
613
+ to: S_WHATSAPP_NET,
687
614
  type: 'set',
688
615
  xmlns: 'w:sync:app:state'
689
616
  },
@@ -697,13 +624,13 @@ const makeChatsSocket = (config) => {
697
624
  attrs: {
698
625
  name,
699
626
  version: (state.version - 1).toString(),
700
- 'return_snapshot': 'false'
627
+ return_snapshot: 'false'
701
628
  },
702
629
  content: [
703
630
  {
704
631
  tag: 'patch',
705
632
  attrs: {},
706
- content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
633
+ content: proto.SyncdPatch.encode(patch).finish()
707
634
  }
708
635
  ]
709
636
  }
@@ -712,14 +639,12 @@ const makeChatsSocket = (config) => {
712
639
  ]
713
640
  };
714
641
  await query(node);
715
- await authState.keys.set({ 'app-state-sync-version': {
716
- [name]: state
717
- } });
718
- });
642
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
643
+ }, authState?.creds?.me?.id || 'app-patch');
719
644
  });
720
645
  if (config.emitOwnEvents) {
721
646
  const { onMutation } = newAppStateChunkHandler(false);
722
- const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
647
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
723
648
  for (const key in mutationMap) {
724
649
  onMutation(mutationMap[key]);
725
650
  }
@@ -727,30 +652,33 @@ const makeChatsSocket = (config) => {
727
652
  };
728
653
  /** sending non-abt props may fix QR scan fail if server expects */
729
654
  const fetchProps = async () => {
730
- var _a, _b;
655
+ //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
731
656
  const resultNode = await query({
732
657
  tag: 'iq',
733
658
  attrs: {
734
- to: WABinary_1.S_WHATSAPP_NET,
659
+ to: S_WHATSAPP_NET,
735
660
  xmlns: 'w',
736
- type: 'get',
661
+ type: 'get'
737
662
  },
738
663
  content: [
739
664
  {
740
665
  tag: 'props',
741
666
  attrs: {
742
667
  protocol: '2',
743
- hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
668
+ hash: authState?.creds?.lastPropHash || ''
744
669
  }
745
670
  }
746
671
  ]
747
672
  });
748
- const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
673
+ const propsNode = getBinaryNodeChild(resultNode, 'props');
749
674
  let props = {};
750
675
  if (propsNode) {
751
- authState.creds.lastPropHash = (_b = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash;
752
- ev.emit('creds.update', authState.creds);
753
- props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
676
+ if (propsNode.attrs?.hash) {
677
+ // on some clients, the hash is returning as undefined
678
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
679
+ ev.emit('creds.update', authState.creds);
680
+ }
681
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop');
754
682
  }
755
683
  logger.debug('fetched props');
756
684
  return props;
@@ -761,9 +689,17 @@ const makeChatsSocket = (config) => {
761
689
  * requires the last messages till the last message received; required for archive & unread
762
690
  */
763
691
  const chatModify = (mod, jid) => {
764
- const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
692
+ const patch = chatModificationToAppPatch(mod, jid);
765
693
  return appPatch(patch);
766
694
  };
695
+ /**
696
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
697
+ */
698
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
699
+ return chatModify({
700
+ disableLinkPreviews: { isPreviewsDisabled }
701
+ }, '');
702
+ };
767
703
  /**
768
704
  * Star or Unstar a message
769
705
  */
@@ -775,6 +711,32 @@ const makeChatsSocket = (config) => {
775
711
  }
776
712
  }, jid);
777
713
  };
714
+ /**
715
+ * Add or Edit Contact
716
+ */
717
+ const addOrEditContact = (jid, contact) => {
718
+ return chatModify({
719
+ contact
720
+ }, jid);
721
+ };
722
+ /**
723
+ * Remove Contact
724
+ */
725
+ const removeContact = (jid) => {
726
+ return chatModify({
727
+ contact: null
728
+ }, jid);
729
+ };
730
+ /**
731
+ * Adds label
732
+ */
733
+ const addLabel = (jid, labels) => {
734
+ return chatModify({
735
+ addLabel: {
736
+ ...labels
737
+ }
738
+ }, jid);
739
+ };
778
740
  /**
779
741
  * Adds label for the chats
780
742
  */
@@ -817,80 +779,104 @@ const makeChatsSocket = (config) => {
817
779
  }
818
780
  }, jid);
819
781
  };
782
+ /**
783
+ * Add or Edit Quick Reply
784
+ */
785
+ const addOrEditQuickReply = (quickReply) => {
786
+ return chatModify({
787
+ quickReply
788
+ }, '');
789
+ };
790
+ /**
791
+ * Remove Quick Reply
792
+ */
793
+ const removeQuickReply = (timestamp) => {
794
+ return chatModify({
795
+ quickReply: { timestamp, deleted: true }
796
+ }, '');
797
+ };
820
798
  /**
821
799
  * queries need to be fired on connection open
822
800
  * help ensure parity with WA Web
823
801
  * */
824
802
  const executeInitQueries = async () => {
825
- await Promise.all([
826
- fetchProps(),
827
- fetchBlocklist(),
828
- fetchPrivacySettings(),
829
- ]);
803
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
830
804
  };
831
805
  const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
832
- var _a, _b, _c;
833
806
  ev.emit('messages.upsert', { messages: [msg], type });
834
807
  if (!!msg.pushName) {
835
- let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
836
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
808
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
809
+ jid = jidNormalizedUser(jid);
837
810
  if (!msg.key.fromMe) {
838
811
  ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
839
812
  }
840
813
  // update our pushname too
841
- if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
814
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
842
815
  ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
843
816
  }
844
817
  }
845
- const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
846
- const shouldProcessHistoryMsg = historyMsg ?
847
- (shouldSyncHistoryMessage(historyMsg) &&
848
- Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)) :
849
- false;
850
- if (historyMsg && !authState.creds.myAppStateKeyId) {
851
- logger.warn('skipping app state sync, as myAppStateKeyId is not set');
852
- pendingAppStateSync = true;
818
+ const historyMsg = getHistoryMsg(msg.message);
819
+ const shouldProcessHistoryMsg = historyMsg
820
+ ? shouldSyncHistoryMessage(historyMsg) &&
821
+ PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
822
+ : false;
823
+ // State machine: decide on sync and flush
824
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
825
+ if (awaitingSyncTimeout) {
826
+ clearTimeout(awaitingSyncTimeout);
827
+ awaitingSyncTimeout = undefined;
828
+ }
829
+ if (shouldProcessHistoryMsg) {
830
+ syncState = SyncState.Syncing;
831
+ logger.info('Transitioned to Syncing state');
832
+ // Let doAppStateSync handle the final flush after it's done
833
+ }
834
+ else {
835
+ syncState = SyncState.Online;
836
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
837
+ ev.flush();
838
+ }
853
839
  }
840
+ const doAppStateSync = async () => {
841
+ if (syncState === SyncState.Syncing) {
842
+ logger.info('Doing app state sync');
843
+ await resyncAppState(ALL_WA_PATCH_NAMES, true);
844
+ // Sync is complete, go online and flush everything
845
+ syncState = SyncState.Online;
846
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
847
+ ev.flush();
848
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
849
+ ev.emit('creds.update', { accountSyncCounter });
850
+ }
851
+ };
854
852
  await Promise.all([
855
853
  (async () => {
856
- if (historyMsg &&
857
- authState.creds.myAppStateKeyId) {
858
- pendingAppStateSync = false;
854
+ if (shouldProcessHistoryMsg) {
859
855
  await doAppStateSync();
860
856
  }
861
857
  })(),
862
- (0, process_message_1.default)(msg, {
858
+ processMessage(msg, {
859
+ signalRepository,
863
860
  shouldProcessHistoryMsg,
861
+ placeholderResendCache,
864
862
  ev,
865
863
  creds: authState.creds,
866
864
  keyStore: authState.keys,
867
865
  logger,
868
866
  options: config.options,
869
- getMessage: config.getMessage,
867
+ getMessage
870
868
  })
871
869
  ]);
872
- if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare) &&
873
- pendingAppStateSync) {
870
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
871
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
872
+ logger.info('App state sync key arrived, triggering app state sync');
874
873
  await doAppStateSync();
875
- pendingAppStateSync = false;
876
- }
877
- async function doAppStateSync() {
878
- if (!authState.creds.accountSyncCounter) {
879
- logger.info('doing initial app state sync');
880
- await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
881
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
882
- ev.emit('creds.update', { accountSyncCounter });
883
- if (needToFlushWithAppStateSync) {
884
- logger.debug('flushing with app state sync');
885
- ev.flush();
886
- }
887
- }
888
874
  }
889
875
  });
890
876
  ws.on('CB:presence', handlePresenceUpdate);
891
877
  ws.on('CB:chatstate', handlePresenceUpdate);
892
878
  ws.on('CB:ib,,dirty', async (node) => {
893
- const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
879
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
894
880
  const type = attrs.type;
895
881
  switch (type) {
896
882
  case 'account_sync':
@@ -912,42 +898,73 @@ const makeChatsSocket = (config) => {
912
898
  }
913
899
  });
914
900
  ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
915
- var _a;
916
901
  if (connection === 'open') {
917
902
  if (fireInitQueries) {
918
- executeInitQueries()
919
- .catch(error => onUnexpectedError(error, 'init queries'));
903
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
920
904
  }
921
- sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
922
- .catch(error => onUnexpectedError(error, 'presence update requests'));
923
- }
924
- if (receivedPendingNotifications) {
925
- // if we don't have the app state key
926
- // we keep buffering events until we finally have
927
- // the key and can sync the messages
928
- if (!((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId) && !config.mobile) {
929
- ev.buffer();
930
- needToFlushWithAppStateSync = true;
905
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
906
+ }
907
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
908
+ return;
909
+ }
910
+ syncState = SyncState.AwaitingInitialSync;
911
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
912
+ ev.buffer();
913
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
914
+ syncType: proto.HistorySync.HistorySyncType.RECENT
915
+ }));
916
+ if (!willSyncHistory) {
917
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
918
+ syncState = SyncState.Online;
919
+ setTimeout(() => ev.flush(), 0);
920
+ return;
921
+ }
922
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
923
+ if (awaitingSyncTimeout) {
924
+ clearTimeout(awaitingSyncTimeout);
925
+ }
926
+ awaitingSyncTimeout = setTimeout(() => {
927
+ if (syncState === SyncState.AwaitingInitialSync) {
928
+ // TODO: investigate
929
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
930
+ syncState = SyncState.Online;
931
+ ev.flush();
931
932
  }
933
+ }, 20000);
934
+ });
935
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
936
+ try {
937
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
938
+ }
939
+ catch (error) {
940
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
932
941
  }
933
942
  });
934
943
  return {
935
944
  ...sock,
936
- processingMutex,
945
+ createCallLink,
946
+ getBotListV2,
947
+ messageMutex,
948
+ receiptMutex,
949
+ appStatePatchMutex,
950
+ notificationMutex,
937
951
  fetchPrivacySettings,
938
952
  upsertMessage,
939
953
  appPatch,
940
954
  sendPresenceUpdate,
941
955
  presenceSubscribe,
942
956
  profilePictureUrl,
943
- onWhatsApp,
944
957
  fetchBlocklist,
945
958
  fetchStatus,
959
+ fetchDisappearingDuration,
946
960
  updateProfilePicture,
947
961
  removeProfilePicture,
948
962
  updateProfileStatus,
949
963
  updateProfileName,
950
964
  updateBlockStatus,
965
+ updateDisableLinkPreviewsPrivacy,
966
+ updateCallPrivacy,
967
+ updateMessagesPrivacy,
951
968
  updateLastSeenPrivacy,
952
969
  updateOnlinePrivacy,
953
970
  updateProfilePicturePrivacy,
@@ -959,12 +976,16 @@ const makeChatsSocket = (config) => {
959
976
  resyncAppState,
960
977
  chatModify,
961
978
  cleanDirtyBits,
979
+ addOrEditContact,
980
+ removeContact,
981
+ addLabel,
962
982
  addChatLabel,
963
983
  removeChatLabel,
964
984
  addMessageLabel,
965
- checkStatusWA,
966
985
  removeMessageLabel,
967
- star
986
+ star,
987
+ addOrEditQuickReply,
988
+ removeQuickReply
968
989
  };
969
990
  };
970
- exports.makeChatsSocket = makeChatsSocket;
991
+ //# sourceMappingURL=chats.js.map