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,63 +1,37 @@
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, HISTORY_SYNC_PAUSED_TIMEOUT_MS, 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, ensureLTHashStateVersion, extractSyncdPatches, generateProfilePicture, getHistoryMsg, isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS, 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, isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
12
- import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
- import { makeSocket } from './socket.js';
14
- export const buildProfilePictureQueryContent = (type, tcTokenContent) => {
15
- const picture = { tag: 'picture', attrs: { type, query: 'url' } };
16
- if (tcTokenContent?.length) {
17
- picture.content = tcTokenContent;
18
- }
19
- return [picture];
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
20
4
  };
21
- export const makeChatsSocket = (config) => {
22
- const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
23
- const sock = makeSocket(config);
24
- const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
25
- const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeChatsSocket = void 0;
7
+ const node_cache_1 = __importDefault(require("node-cache"));
8
+ const boom_1 = require("@hapi/boom");
9
+ const WAProto_1 = require("../../WAProto");
10
+ const Defaults_1 = require("../Defaults");
11
+ const Types_1 = require("../Types");
12
+ const Utils_1 = require("../Utils");
13
+ const make_mutex_1 = require("../Utils/make-mutex");
14
+ const process_message_1 = __importDefault(require("../Utils/process-message"));
15
+ const WABinary_1 = require("../WABinary");
16
+ const WAUSync_1 = require("../WAUSync");
17
+ const usync_1 = require("./usync");
18
+ 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;
26
23
  let privacySettings;
27
- /** Server-assigned AB props for protocol behavior. */
28
- const serverProps = {
29
- /** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
30
- privacyTokenOn1to1: true,
31
- /** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
32
- profilePicPrivacyToken: true,
33
- /** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
34
- lidTrustedTokenIssueToLid: false
35
- };
36
- let syncState = SyncState.Connecting;
37
- /** this mutex ensures that messages are processed in order */
38
- const messageMutex = makeMutex();
39
- /** this mutex ensures that receipts are processed in order */
40
- const receiptMutex = makeMutex();
41
- /** this mutex ensures that app state patches are processed in order */
42
- const appStatePatchMutex = makeMutex();
43
- /** this mutex ensures that notifications are processed in order */
44
- const notificationMutex = makeMutex();
45
- // Timeout for AwaitingInitialSync state
46
- let awaitingSyncTimeout;
47
- // In-memory history sync completion tracking (resets on reconnection)
48
- const historySyncStatus = {
49
- initialBootstrapComplete: false,
50
- recentSyncComplete: false
51
- };
52
- let historySyncPausedTimeout;
53
- // Collections blocked on missing app state sync keys (mirrors WA Web's "Blocked" state).
54
- // When a key arrives via APP_STATE_SYNC_KEY_SHARE, these are re-synced.
55
- const blockedCollections = new Set();
56
- const placeholderResendCache = config.placeholderResendCache ||
57
- new NodeCache({
58
- stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
59
- useClones: false
60
- });
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)();
28
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
29
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
30
+ useClones: false
31
+ });
32
+ if (!config.placeholderResendCache) {
33
+ config.placeholderResendCache = placeholderResendCache;
34
+ }
61
35
  /** helper function to fetch the given app state sync key */
62
36
  const getAppStateSyncKey = async (keyId) => {
63
37
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
@@ -69,12 +43,14 @@ export const makeChatsSocket = (config) => {
69
43
  tag: 'iq',
70
44
  attrs: {
71
45
  xmlns: 'privacy',
72
- to: S_WHATSAPP_NET,
46
+ to: WABinary_1.S_WHATSAPP_NET,
73
47
  type: 'get'
74
48
  },
75
- content: [{ tag: 'privacy', attrs: {} }]
49
+ content: [
50
+ { tag: 'privacy', attrs: {} }
51
+ ]
76
52
  });
77
- privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
53
+ privacySettings = (0, WABinary_1.reduceBinaryNodeToDictionary)(content === null || content === void 0 ? void 0 : content[0], 'category');
78
54
  }
79
55
  return privacySettings;
80
56
  };
@@ -84,11 +60,10 @@ export const makeChatsSocket = (config) => {
84
60
  tag: 'iq',
85
61
  attrs: {
86
62
  xmlns: 'privacy',
87
- to: S_WHATSAPP_NET,
63
+ to: WABinary_1.S_WHATSAPP_NET,
88
64
  type: 'set'
89
65
  },
90
- content: [
91
- {
66
+ content: [{
92
67
  tag: 'privacy',
93
68
  attrs: {},
94
69
  content: [
@@ -97,8 +72,7 @@ export const makeChatsSocket = (config) => {
97
72
  attrs: { name, value }
98
73
  }
99
74
  ]
100
- }
101
- ]
75
+ }]
102
76
  });
103
77
  };
104
78
  const updateMessagesPrivacy = async (value) => {
@@ -130,17 +104,15 @@ export const makeChatsSocket = (config) => {
130
104
  tag: 'iq',
131
105
  attrs: {
132
106
  xmlns: 'disappearing_mode',
133
- to: S_WHATSAPP_NET,
107
+ to: WABinary_1.S_WHATSAPP_NET,
134
108
  type: 'set'
135
109
  },
136
- content: [
137
- {
110
+ content: [{
138
111
  tag: 'disappearing_mode',
139
112
  attrs: {
140
113
  duration: duration.toString()
141
114
  }
142
- }
143
- ]
115
+ }]
144
116
  });
145
117
  };
146
118
  const getBotListV2 = async () => {
@@ -148,23 +120,21 @@ export const makeChatsSocket = (config) => {
148
120
  tag: 'iq',
149
121
  attrs: {
150
122
  xmlns: 'bot',
151
- to: S_WHATSAPP_NET,
123
+ to: WABinary_1.S_WHATSAPP_NET,
152
124
  type: 'get'
153
125
  },
154
- content: [
155
- {
126
+ content: [{
156
127
  tag: 'bot',
157
128
  attrs: {
158
129
  v: '2'
159
130
  }
160
- }
161
- ]
131
+ }]
162
132
  });
163
- const botNode = getBinaryNodeChild(resp, 'bot');
133
+ const botNode = (0, WABinary_1.getBinaryNodeChild)(resp, 'bot');
164
134
  const botList = [];
165
- for (const section of getBinaryNodeChildren(botNode, 'section')) {
135
+ for (const section of (0, WABinary_1.getBinaryNodeChildren)(botNode, 'section')) {
166
136
  if (section.attrs.type === 'all') {
167
- for (const bot of getBinaryNodeChildren(section, 'bot')) {
137
+ for (const bot of (0, WABinary_1.getBinaryNodeChildren)(section, 'bot')) {
168
138
  botList.push({
169
139
  jid: bot.attrs.jid,
170
140
  personaId: bot.attrs['persona_id']
@@ -174,10 +144,78 @@ export const makeChatsSocket = (config) => {
174
144
  }
175
145
  return botList;
176
146
  };
147
+ /** helper function to run a generic IQ query */
148
+ const interactiveQuery = async (userNodes, queryNode) => {
149
+ const result = await query({
150
+ tag: 'iq',
151
+ attrs: {
152
+ to: WABinary_1.S_WHATSAPP_NET,
153
+ type: 'get',
154
+ xmlns: 'usync',
155
+ },
156
+ content: [
157
+ {
158
+ tag: 'usync',
159
+ attrs: {
160
+ sid: generateMessageTag(),
161
+ mode: 'query',
162
+ last: 'true',
163
+ index: '0',
164
+ context: 'interactive',
165
+ },
166
+ content: [
167
+ {
168
+ tag: 'query',
169
+ attrs: {},
170
+ content: [queryNode]
171
+ },
172
+ {
173
+ tag: 'list',
174
+ attrs: {},
175
+ content: userNodes
176
+ }
177
+ ]
178
+ }
179
+ ],
180
+ });
181
+ const usyncNode = (0, WABinary_1.getBinaryNodeChild)(result, 'usync');
182
+ const listNode = (0, WABinary_1.getBinaryNodeChild)(usyncNode, 'list');
183
+ const users = (0, WABinary_1.getBinaryNodeChildren)(listNode, 'user');
184
+ return users;
185
+ };
186
+ const fetchUserLid = async (jid) => {
187
+ const [result] = await interactiveQuery([
188
+ {
189
+ tag: 'user',
190
+ attrs: { jid }
191
+ }
192
+ ], {
193
+ tag: 'lid',
194
+ attrs: {}
195
+ });
196
+ if (result) {
197
+ const lid = (0, WABinary_1.getBinaryNodeChild)(result, 'lid');
198
+ return lid.attrs.val;
199
+ }
200
+ };
201
+ const onWhatsApp = async (...jids) => {
202
+ const usyncQuery = new WAUSync_1.USyncQuery()
203
+ .withContactProtocol()
204
+ .withLIDProtocol();
205
+ for (const jid of jids) {
206
+ const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`;
207
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
208
+ }
209
+ const results = await sock.executeUSyncQuery(usyncQuery);
210
+ if (results) {
211
+ return results.list.filter((a) => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }));
212
+ }
213
+ };
177
214
  const fetchStatus = async (...jids) => {
178
- const usyncQuery = new USyncQuery().withStatusProtocol();
215
+ const usyncQuery = new WAUSync_1.USyncQuery()
216
+ .withStatusProtocol();
179
217
  for (const jid of jids) {
180
- usyncQuery.withUser(new USyncUser().withId(jid));
218
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
181
219
  }
182
220
  const result = await sock.executeUSyncQuery(usyncQuery);
183
221
  if (result) {
@@ -185,9 +223,10 @@ export const makeChatsSocket = (config) => {
185
223
  }
186
224
  };
187
225
  const fetchDisappearingDuration = async (...jids) => {
188
- const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
226
+ const usyncQuery = new WAUSync_1.USyncQuery()
227
+ .withDisappearingModeProtocol();
189
228
  for (const jid of jids) {
190
- usyncQuery.withUser(new USyncUser().withId(jid));
229
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
191
230
  }
192
231
  const result = await sock.executeUSyncQuery(usyncQuery);
193
232
  if (result) {
@@ -195,25 +234,22 @@ export const makeChatsSocket = (config) => {
195
234
  }
196
235
  };
197
236
  /** update the profile picture for yourself or a group */
198
- const updateProfilePicture = async (jid, content, dimensions) => {
237
+ const updateProfilePicture = async (jid, content) => {
199
238
  let targetJid;
200
239
  if (!jid) {
201
- throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
202
- }
203
- if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
204
- targetJid = jidNormalizedUser(jid); // in case it is someone other than us
240
+ 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');
205
241
  }
206
- else {
207
- targetJid = undefined;
242
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
243
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
208
244
  }
209
- const { img } = await generateProfilePicture(content, dimensions);
245
+ const { img } = await (0, Utils_1.generateProfilePicture)(content);
210
246
  await query({
211
247
  tag: 'iq',
212
248
  attrs: {
213
- to: S_WHATSAPP_NET,
249
+ target: targetJid,
250
+ to: WABinary_1.S_WHATSAPP_NET,
214
251
  type: 'set',
215
- xmlns: 'w:profile:picture',
216
- ...(targetJid ? { target: targetJid } : {})
252
+ xmlns: 'w:profile:picture'
217
253
  },
218
254
  content: [
219
255
  {
@@ -228,21 +264,18 @@ export const makeChatsSocket = (config) => {
228
264
  const removeProfilePicture = async (jid) => {
229
265
  let targetJid;
230
266
  if (!jid) {
231
- throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
267
+ 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');
232
268
  }
233
- if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
234
- targetJid = jidNormalizedUser(jid); // in case it is someone other than us
235
- }
236
- else {
237
- targetJid = undefined;
269
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
270
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
238
271
  }
239
272
  await query({
240
273
  tag: 'iq',
241
274
  attrs: {
242
- to: S_WHATSAPP_NET,
275
+ target: targetJid,
276
+ to: WABinary_1.S_WHATSAPP_NET,
243
277
  type: 'set',
244
- xmlns: 'w:profile:picture',
245
- ...(targetJid ? { target: targetJid } : {})
278
+ xmlns: 'w:profile:picture'
246
279
  }
247
280
  });
248
281
  };
@@ -251,7 +284,7 @@ export const makeChatsSocket = (config) => {
251
284
  await query({
252
285
  tag: 'iq',
253
286
  attrs: {
254
- to: S_WHATSAPP_NET,
287
+ to: WABinary_1.S_WHATSAPP_NET,
255
288
  type: 'set',
256
289
  xmlns: 'status'
257
290
  },
@@ -272,66 +305,35 @@ export const makeChatsSocket = (config) => {
272
305
  tag: 'iq',
273
306
  attrs: {
274
307
  xmlns: 'blocklist',
275
- to: S_WHATSAPP_NET,
308
+ to: WABinary_1.S_WHATSAPP_NET,
276
309
  type: 'get'
277
310
  }
278
311
  });
279
- const listNode = getBinaryNodeChild(result, 'list');
280
- return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
312
+ const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
313
+ return (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item')
314
+ .map(n => n.attrs.jid);
281
315
  };
282
316
  const updateBlockStatus = async (jid, action) => {
283
- const normalizedJid = jidNormalizedUser(jid);
284
- let lid;
285
- let pn_jid;
286
- if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
287
- lid = normalizedJid;
288
- if (action === 'block') {
289
- const pn = await signalRepository.lidMapping.getPNForLID(normalizedJid);
290
- if (!pn) {
291
- throw new Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
292
- }
293
- pn_jid = jidNormalizedUser(pn);
294
- }
295
- }
296
- else if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
297
- const mapped = await signalRepository.lidMapping.getLIDForPN(normalizedJid);
298
- if (!mapped) {
299
- throw new Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
300
- }
301
- lid = mapped;
302
- if (action === 'block') {
303
- pn_jid = jidNormalizedUser(normalizedJid);
304
- }
305
- }
306
- else {
307
- throw new Boom(`Invalid jid: ${jid}`, { statusCode: 400 });
308
- }
309
- const itemAttrs = {
310
- action,
311
- jid: lid
312
- };
313
- if (action === 'block') {
314
- if (!pn_jid) {
315
- throw new Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 });
316
- }
317
- itemAttrs.pn_jid = pn_jid;
318
- }
319
317
  await query({
320
318
  tag: 'iq',
321
319
  attrs: {
322
320
  xmlns: 'blocklist',
323
- to: S_WHATSAPP_NET,
321
+ to: WABinary_1.S_WHATSAPP_NET,
324
322
  type: 'set'
325
323
  },
326
324
  content: [
327
325
  {
328
326
  tag: 'item',
329
- attrs: itemAttrs
327
+ attrs: {
328
+ action,
329
+ jid
330
+ }
330
331
  }
331
332
  ]
332
333
  });
333
334
  };
334
335
  const getBusinessProfile = async (jid) => {
336
+ var _a, _b, _c, _d, _e, _f, _g;
335
337
  const results = await query({
336
338
  tag: 'iq',
337
339
  attrs: {
@@ -339,42 +341,38 @@ export const makeChatsSocket = (config) => {
339
341
  xmlns: 'w:biz',
340
342
  type: 'get'
341
343
  },
342
- content: [
343
- {
344
+ content: [{
344
345
  tag: 'business_profile',
345
346
  attrs: { v: '244' },
346
- content: [
347
- {
347
+ content: [{
348
348
  tag: 'profile',
349
349
  attrs: { jid }
350
- }
351
- ]
352
- }
353
- ]
350
+ }]
351
+ }]
354
352
  });
355
- const profileNode = getBinaryNodeChild(results, 'business_profile');
356
- const profiles = getBinaryNodeChild(profileNode, 'profile');
353
+ const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile');
354
+ const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile');
357
355
  if (profiles) {
358
- const address = getBinaryNodeChild(profiles, 'address');
359
- const description = getBinaryNodeChild(profiles, 'description');
360
- const website = getBinaryNodeChild(profiles, 'website');
361
- const email = getBinaryNodeChild(profiles, 'email');
362
- const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
363
- const businessHours = getBinaryNodeChild(profiles, 'business_hours');
364
- const businessHoursConfig = businessHours
365
- ? getBinaryNodeChildren(businessHours, 'business_hours_config')
366
- : undefined;
367
- const websiteStr = website?.content?.toString();
356
+ const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address');
357
+ const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description');
358
+ const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website');
359
+ const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
360
+ const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
361
+ const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
362
+ const businessHoursConfig = businessHours ?
363
+ (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config') :
364
+ undefined;
365
+ const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
368
366
  return {
369
- wid: profiles.attrs?.jid,
370
- address: address?.content?.toString(),
371
- description: description?.content?.toString() || '',
367
+ wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
368
+ address: (_c = address === null || address === void 0 ? void 0 : address.content) === null || _c === void 0 ? void 0 : _c.toString(),
369
+ description: ((_d = description === null || description === void 0 ? void 0 : description.content) === null || _d === void 0 ? void 0 : _d.toString()) || '',
372
370
  website: websiteStr ? [websiteStr] : [],
373
- email: email?.content?.toString(),
374
- category: category?.content?.toString(),
375
- business_hours: {
376
- timezone: businessHours?.attrs?.timezone,
377
- business_config: businessHoursConfig?.map(({ attrs }) => attrs)
371
+ email: (_e = email === null || email === void 0 ? void 0 : email.content) === null || _e === void 0 ? void 0 : _e.toString(),
372
+ category: (_f = category === null || category === void 0 ? void 0 : category.content) === null || _f === void 0 ? void 0 : _f.toString(),
373
+ 'business_hours': {
374
+ timezone: (_g = businessHours === null || businessHours === void 0 ? void 0 : businessHours.attrs) === null || _g === void 0 ? void 0 : _g.timezone,
375
+ 'business_config': businessHoursConfig === null || businessHoursConfig === void 0 ? void 0 : businessHoursConfig.map(({ attrs }) => attrs)
378
376
  }
379
377
  };
380
378
  }
@@ -384,17 +382,17 @@ export const makeChatsSocket = (config) => {
384
382
  await sendNode({
385
383
  tag: 'iq',
386
384
  attrs: {
387
- to: S_WHATSAPP_NET,
385
+ to: WABinary_1.S_WHATSAPP_NET,
388
386
  type: 'set',
389
387
  xmlns: 'urn:xmpp:whatsapp:dirty',
390
- id: generateMessageTag()
388
+ id: generateMessageTag(),
391
389
  },
392
390
  content: [
393
391
  {
394
392
  tag: 'clean',
395
393
  attrs: {
396
394
  type,
397
- ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
395
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
398
396
  }
399
397
  }
400
398
  ]
@@ -403,31 +401,20 @@ export const makeChatsSocket = (config) => {
403
401
  const newAppStateChunkHandler = (isInitialSync) => {
404
402
  return {
405
403
  onMutation(mutation) {
406
- processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
404
+ (0, Utils_1.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
407
405
  }
408
406
  };
409
407
  };
410
408
  const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
411
- const appStateSyncKeyCache = new Map();
412
- const getCachedAppStateSyncKey = async (keyId) => {
413
- if (appStateSyncKeyCache.has(keyId)) {
414
- return appStateSyncKeyCache.get(keyId) ?? undefined;
415
- }
416
- const key = await getAppStateSyncKey(keyId);
417
- appStateSyncKeyCache.set(keyId, key ?? null);
418
- return key;
419
- };
420
409
  // we use this to determine which events to fire
421
410
  // otherwise when we resync from scratch -- all notifications will fire
422
411
  const initialVersionMap = {};
423
412
  const globalMutationMap = {};
424
413
  await authState.keys.transaction(async () => {
414
+ var _a;
425
415
  const collectionsToHandle = new Set(collections);
426
416
  // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
427
417
  const attemptsMap = {};
428
- // collections that failed and need a full snapshot on retry
429
- // mirrors WA Web's ErrorFatal -> force snapshot behavior
430
- const forceSnapshotCollections = new Set();
431
418
  // keep executing till all collections are done
432
419
  // sometimes a single patch request will not return all the patches (God knows why)
433
420
  // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
@@ -438,34 +425,29 @@ export const makeChatsSocket = (config) => {
438
425
  const result = await authState.keys.get('app-state-sync-version', [name]);
439
426
  let state = result[name];
440
427
  if (state) {
441
- state = ensureLTHashStateVersion(state);
442
428
  if (typeof initialVersionMap[name] === 'undefined') {
443
429
  initialVersionMap[name] = state.version;
444
430
  }
445
431
  }
446
432
  else {
447
- state = newLTHashState();
433
+ state = (0, Utils_1.newLTHashState)();
448
434
  }
449
435
  states[name] = state;
450
- const shouldForceSnapshot = forceSnapshotCollections.has(name);
451
- if (shouldForceSnapshot) {
452
- forceSnapshotCollections.delete(name);
453
- }
454
- logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`);
436
+ logger.info(`resyncing ${name} from v${state.version}`);
455
437
  nodes.push({
456
438
  tag: 'collection',
457
439
  attrs: {
458
440
  name,
459
441
  version: state.version.toString(),
460
- // return snapshot if syncing from scratch or forcing after a failed attempt
461
- return_snapshot: (shouldForceSnapshot || !state.version).toString()
442
+ // return snapshot if being synced from scratch
443
+ 'return_snapshot': (!state.version).toString()
462
444
  }
463
445
  });
464
446
  }
465
447
  const result = await query({
466
448
  tag: 'iq',
467
449
  attrs: {
468
- to: S_WHATSAPP_NET,
450
+ to: WABinary_1.S_WHATSAPP_NET,
469
451
  xmlns: 'w:sync:app:state',
470
452
  type: 'set'
471
453
  },
@@ -478,22 +460,26 @@ export const makeChatsSocket = (config) => {
478
460
  ]
479
461
  });
480
462
  // extract from binary node
481
- const decoded = await extractSyncdPatches(result, config?.options);
463
+ const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
482
464
  for (const key in decoded) {
483
465
  const name = key;
484
466
  const { patches, hasMorePatches, snapshot } = decoded[name];
485
467
  try {
486
468
  if (snapshot) {
487
- const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
469
+ const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
488
470
  states[name] = newState;
489
471
  Object.assign(globalMutationMap, mutationMap);
490
472
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
491
- await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
473
+ await authState.keys.set({ 'app-state-sync-version': {
474
+ [name]: newState
475
+ } });
492
476
  }
493
477
  // only process if there are syncd patches
494
478
  if (patches.length) {
495
- const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
496
- await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
479
+ const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
480
+ await authState.keys.set({ 'app-state-sync-version': {
481
+ [name]: newState
482
+ } });
497
483
  logger.info(`synced ${name} to v${newState.version}`);
498
484
  initialVersionMap[name] = newState.version;
499
485
  Object.assign(globalMutationMap, mutationMap);
@@ -501,47 +487,30 @@ export const makeChatsSocket = (config) => {
501
487
  if (hasMorePatches) {
502
488
  logger.info(`${name} has more patches...`);
503
489
  }
504
- else {
505
- // collection is done with sync
490
+ else { // collection is done with sync
506
491
  collectionsToHandle.delete(name);
507
492
  }
508
493
  }
509
494
  catch (error) {
495
+ // if retry attempts overshoot
496
+ // or key not found
497
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
498
+ ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404 ||
499
+ error.name === 'TypeError';
500
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
501
+ await authState.keys.set({ 'app-state-sync-version': {
502
+ [name]: null
503
+ } });
504
+ // increment number of retries
510
505
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
511
- const logData = {
512
- name,
513
- attempt: attemptsMap[name],
514
- version: states[name].version,
515
- statusCode: error.output?.statusCode,
516
- errorType: error.name,
517
- error: error.stack
518
- };
519
- if (isMissingKeyError(error) && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
520
- // WA Web treats missing keys as "Blocked" — park the collection
521
- // until the key arrives via APP_STATE_SYNC_KEY_SHARE.
522
- logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`);
523
- blockedCollections.add(name);
506
+ if (isIrrecoverableError) {
507
+ // stop retrying
524
508
  collectionsToHandle.delete(name);
525
509
  }
526
- else if (isMissingKeyError(error)) {
527
- // Retry with a snapshot which may use a different key.
528
- logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`);
529
- forceSnapshotCollections.add(name);
530
- }
531
- else if (isAppStateSyncIrrecoverable(error, attemptsMap[name])) {
532
- logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`);
533
- collectionsToHandle.delete(name);
534
- }
535
- else {
536
- logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`);
537
- // force a full snapshot on retry to recover from
538
- // corrupted local state (e.g. LTHash MAC mismatch)
539
- forceSnapshotCollections.add(name);
540
- }
541
510
  }
542
511
  }
543
512
  }
544
- }, authState?.creds?.me?.id || 'resync-app-state');
513
+ });
545
514
  const { onMutation } = newAppStateChunkHandler(isInitialSync);
546
515
  for (const key in globalMutationMap) {
547
516
  onMutation(globalMutationMap[key]);
@@ -551,83 +520,47 @@ export const makeChatsSocket = (config) => {
551
520
  * fetch the profile picture of a user/group
552
521
  * type = "preview" for a low res picture
553
522
  * type = "image for the high res picture"
554
- */
523
+ */;
555
524
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
556
- // WA Web only includes tctoken for user JIDs (not groups/newsletters)
557
- // and never for own profile pic (Chat model for self has no tcToken).
558
- // Including tctoken for own JID causes the server to never respond.
559
- const normalizedJid = jidNormalizedUser(jid);
560
- const isUserJid = isPnUser(normalizedJid) || isLidUser(normalizedJid);
561
- const me = authState.creds.me;
562
- const isSelf = me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)));
563
- let tcTokenContent;
564
- if (serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
565
- tcTokenContent = await buildTcTokenFromJid({
566
- authState,
567
- jid: normalizedJid,
568
- getLIDForPN
569
- });
570
- }
571
- jid = jidNormalizedUser(jid);
525
+ var _a;
526
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
572
527
  const result = await query({
573
528
  tag: 'iq',
574
529
  attrs: {
575
530
  target: jid,
576
- to: S_WHATSAPP_NET,
531
+ to: WABinary_1.S_WHATSAPP_NET,
577
532
  type: 'get',
578
533
  xmlns: 'w:profile:picture'
579
534
  },
580
- content: buildProfilePictureQueryContent(type, tcTokenContent)
581
- }, timeoutMs);
582
- const child = getBinaryNodeChild(result, 'picture');
583
- return child?.attrs?.url;
584
- };
585
- const createCallLink = async (type, event, timeoutMs) => {
586
- const result = await query({
587
- tag: 'call',
588
- attrs: {
589
- id: generateMessageTag(),
590
- to: '@call'
591
- },
592
535
  content: [
593
- {
594
- tag: 'link_create',
595
- attrs: { media: type },
596
- content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
597
- }
536
+ { tag: 'picture', attrs: { type, query: 'url' } }
598
537
  ]
599
538
  }, timeoutMs);
600
- const child = getBinaryNodeChild(result, 'link_create');
601
- return child?.attrs?.token;
539
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
540
+ return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
602
541
  };
603
542
  const sendPresenceUpdate = async (type, toJid) => {
604
543
  const me = authState.creds.me;
605
- const isAvailableType = type === 'available';
606
- if (isAvailableType || type === 'unavailable') {
544
+ if (type === 'available' || type === 'unavailable') {
607
545
  if (!me.name) {
608
546
  logger.warn('no name present, ignoring presence update request...');
609
547
  return;
610
548
  }
611
- ev.emit('connection.update', { isOnline: isAvailableType });
612
- if (isAvailableType) {
613
- void sendUnifiedSession();
614
- }
549
+ ev.emit('connection.update', { isOnline: type === 'available' });
615
550
  await sendNode({
616
551
  tag: 'presence',
617
552
  attrs: {
618
- name: me.name.replace(/@/g, ''),
553
+ name: me.name,
619
554
  type
620
555
  }
621
556
  });
622
557
  }
623
558
  else {
624
- const { server } = jidDecode(toJid);
625
- const isLid = server === 'lid';
626
559
  await sendNode({
627
560
  tag: 'chatstate',
628
561
  attrs: {
629
- from: isLid ? me.lid : me.id,
630
- to: toJid
562
+ from: me.id,
563
+ to: toJid,
631
564
  },
632
565
  content: [
633
566
  {
@@ -642,35 +575,35 @@ export const makeChatsSocket = (config) => {
642
575
  * @param toJid the jid to subscribe to
643
576
  * @param tcToken token for subscription, use if present
644
577
  */
645
- const presenceSubscribe = async (toJid) => {
646
- // Only include tctoken for user JIDs — groups/newsletters don't use tctokens
647
- const normalizedToJid = jidNormalizedUser(toJid);
648
- const isUserJid = isPnUser(normalizedToJid) || isLidUser(normalizedToJid);
649
- const tcTokenContent = isUserJid
650
- ? await buildTcTokenFromJid({ authState, jid: normalizedToJid, getLIDForPN })
651
- : undefined;
652
- return sendNode({
653
- tag: 'presence',
654
- attrs: {
655
- to: toJid,
656
- id: generateMessageTag(),
657
- type: 'subscribe'
658
- },
659
- content: tcTokenContent
660
- });
661
- };
578
+ const presenceSubscribe = (toJid, tcToken) => (sendNode({
579
+ tag: 'presence',
580
+ attrs: {
581
+ to: toJid,
582
+ id: generateMessageTag(),
583
+ type: 'subscribe'
584
+ },
585
+ content: tcToken ?
586
+ [
587
+ {
588
+ tag: 'tctoken',
589
+ attrs: {},
590
+ content: tcToken
591
+ }
592
+ ] :
593
+ undefined
594
+ }));
662
595
  const handlePresenceUpdate = ({ tag, attrs, content }) => {
596
+ var _a;
663
597
  let presence;
664
598
  const jid = attrs.from;
665
599
  const participant = attrs.participant || attrs.from;
666
- if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
600
+ if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
667
601
  return;
668
602
  }
669
603
  if (tag === 'presence') {
670
604
  presence = {
671
605
  lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
672
- lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
673
- groupOnlineCount: attrs.count ? +attrs.count : undefined
606
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
674
607
  };
675
608
  }
676
609
  else if (Array.isArray(content)) {
@@ -679,7 +612,7 @@ export const makeChatsSocket = (config) => {
679
612
  if (type === 'paused') {
680
613
  type = 'available';
681
614
  }
682
- if (firstChild.attrs?.media === 'audio') {
615
+ if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
683
616
  type = 'recording';
684
617
  }
685
618
  presence = { lastKnownPresence: type };
@@ -688,29 +621,31 @@ export const makeChatsSocket = (config) => {
688
621
  logger.error({ tag, attrs, content }, 'recv invalid presence node');
689
622
  }
690
623
  if (presence) {
691
- ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
624
+ ev.emit('presence.update', { id: jid, presences: {
625
+ [participant]: presence
626
+ } });
692
627
  }
693
628
  };
694
629
  const appPatch = async (patchCreate) => {
695
630
  const name = patchCreate.type;
696
631
  const myAppStateKeyId = authState.creds.myAppStateKeyId;
697
632
  if (!myAppStateKeyId) {
698
- throw new Boom('App state key not present!', { statusCode: 400 });
633
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
699
634
  }
700
635
  let initial;
701
636
  let encodeResult;
702
- await appStatePatchMutex.mutex(async () => {
637
+ await processingMutex.mutex(async () => {
703
638
  await authState.keys.transaction(async () => {
704
639
  logger.debug({ patch: patchCreate }, 'applying app patch');
705
640
  await resyncAppState([name], false);
706
641
  const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
707
- initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState();
708
- encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
642
+ initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
643
+ encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
709
644
  const { patch, state } = encodeResult;
710
645
  const node = {
711
646
  tag: 'iq',
712
647
  attrs: {
713
- to: S_WHATSAPP_NET,
648
+ to: WABinary_1.S_WHATSAPP_NET,
714
649
  type: 'set',
715
650
  xmlns: 'w:sync:app:state'
716
651
  },
@@ -724,13 +659,13 @@ export const makeChatsSocket = (config) => {
724
659
  attrs: {
725
660
  name,
726
661
  version: (state.version - 1).toString(),
727
- return_snapshot: 'false'
662
+ 'return_snapshot': 'false'
728
663
  },
729
664
  content: [
730
665
  {
731
666
  tag: 'patch',
732
667
  attrs: {},
733
- content: proto.SyncdPatch.encode(patch).finish()
668
+ content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
734
669
  }
735
670
  ]
736
671
  }
@@ -739,60 +674,49 @@ export const makeChatsSocket = (config) => {
739
674
  ]
740
675
  };
741
676
  await query(node);
742
- await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
743
- }, authState?.creds?.me?.id || 'app-patch');
677
+ await authState.keys.set({ 'app-state-sync-version': {
678
+ [name]: state
679
+ } });
680
+ });
744
681
  });
745
682
  if (config.emitOwnEvents) {
746
683
  const { onMutation } = newAppStateChunkHandler(false);
747
- const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
684
+ const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
748
685
  for (const key in mutationMap) {
749
686
  onMutation(mutationMap[key]);
750
687
  }
751
688
  }
752
689
  };
753
- /** fetch AB props */
690
+ /** sending non-abt props may fix QR scan fail if server expects */
754
691
  const fetchProps = async () => {
692
+ var _a, _b;
755
693
  const resultNode = await query({
756
694
  tag: 'iq',
757
695
  attrs: {
758
- to: S_WHATSAPP_NET,
759
- xmlns: 'abt',
760
- type: 'get'
696
+ to: WABinary_1.S_WHATSAPP_NET,
697
+ xmlns: 'w',
698
+ type: 'get',
761
699
  },
762
700
  content: [
763
701
  {
764
702
  tag: 'props',
765
703
  attrs: {
766
- protocol: '1',
767
- ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
704
+ protocol: '2',
705
+ hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
768
706
  }
769
707
  }
770
708
  ]
771
709
  });
772
- const propsNode = getBinaryNodeChild(resultNode, 'props');
710
+ const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
773
711
  let props = {};
774
712
  if (propsNode) {
775
- if (propsNode.attrs?.hash) {
776
- // on some clients, the hash is returning as undefined
777
- authState.creds.lastPropHash = propsNode?.attrs?.hash;
713
+ if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) { // on some clients, the hash is returning as undefined
714
+ authState.creds.lastPropHash = (_c = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _c === void 0 ? void 0 : _c.hash;
778
715
  ev.emit('creds.update', authState.creds);
779
716
  }
780
- props = reduceBinaryNodeToDictionary(propsNode, 'prop');
781
- }
782
- // Extract protocol-relevant AB props (only the ones we need)
783
- const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages'];
784
- if (privacyTokenProp !== undefined) {
785
- serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1';
786
- }
787
- const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq'];
788
- if (profilePicProp !== undefined) {
789
- serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1';
717
+ props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
790
718
  }
791
- const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid'];
792
- if (lidIssueProp !== undefined) {
793
- serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1';
794
- }
795
- logger.debug({ serverProps }, 'fetched props');
719
+ logger.debug('fetched props');
796
720
  return props;
797
721
  };
798
722
  /**
@@ -801,17 +725,9 @@ export const makeChatsSocket = (config) => {
801
725
  * requires the last messages till the last message received; required for archive & unread
802
726
  */
803
727
  const chatModify = (mod, jid) => {
804
- const patch = chatModificationToAppPatch(mod, jid);
728
+ const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
805
729
  return appPatch(patch);
806
730
  };
807
- /**
808
- * Enable/Disable link preview privacy, not related to baileys link preview generation
809
- */
810
- const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
811
- return chatModify({
812
- disableLinkPreviews: { isPreviewsDisabled }
813
- }, '');
814
- };
815
731
  /**
816
732
  * Star or Unstar a message
817
733
  */
@@ -823,22 +739,6 @@ export const makeChatsSocket = (config) => {
823
739
  }
824
740
  }, jid);
825
741
  };
826
- /**
827
- * Add or Edit Contact
828
- */
829
- const addOrEditContact = (jid, contact) => {
830
- return chatModify({
831
- contact
832
- }, jid);
833
- };
834
- /**
835
- * Remove Contact
836
- */
837
- const removeContact = (jid) => {
838
- return chatModify({
839
- contact: null
840
- }, jid);
841
- };
842
742
  /**
843
743
  * Adds label
844
744
  */
@@ -891,127 +791,49 @@ export const makeChatsSocket = (config) => {
891
791
  }
892
792
  }, jid);
893
793
  };
894
- /**
895
- * Add or Edit Quick Reply
896
- */
897
- const addOrEditQuickReply = (quickReply) => {
898
- return chatModify({
899
- quickReply
900
- }, '');
901
- };
902
- /**
903
- * Remove Quick Reply
904
- */
905
- const removeQuickReply = (timestamp) => {
906
- return chatModify({
907
- quickReply: { timestamp, deleted: true }
908
- }, '');
909
- };
910
794
  /**
911
795
  * queries need to be fired on connection open
912
796
  * help ensure parity with WA Web
913
797
  * */
914
798
  const executeInitQueries = async () => {
915
- await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
799
+ await Promise.all([
800
+ fetchProps(),
801
+ fetchBlocklist(),
802
+ fetchPrivacySettings(),
803
+ ]);
916
804
  };
917
805
  const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
806
+ var _a, _b, _c;
918
807
  ev.emit('messages.upsert', { messages: [msg], type });
919
808
  if (!!msg.pushName) {
920
- let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
921
- jid = jidNormalizedUser(jid);
809
+ let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
810
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
922
811
  if (!msg.key.fromMe) {
923
812
  ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
924
813
  }
925
814
  // update our pushname too
926
- if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
815
+ if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
927
816
  ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
928
817
  }
929
818
  }
930
- const historyMsg = getHistoryMsg(msg.message);
931
- const shouldProcessHistoryMsg = historyMsg
932
- ? shouldSyncHistoryMessage(historyMsg) &&
933
- PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
934
- : false;
935
- if (historyMsg && shouldProcessHistoryMsg) {
936
- const syncType = historyMsg.syncType;
937
- // INITIAL_BOOTSTRAP — fire immediately, no progress check (same as WA Web K function)
938
- if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
939
- !historySyncStatus.initialBootstrapComplete) {
940
- historySyncStatus.initialBootstrapComplete = true;
941
- ev.emit('messaging-history.status', {
942
- syncType,
943
- status: 'complete',
944
- explicit: true
945
- });
946
- }
947
- // RECENT with progress === 100 — explicit completion
948
- if (syncType === proto.HistorySync.HistorySyncType.RECENT &&
949
- historyMsg.progress === 100 &&
950
- !historySyncStatus.recentSyncComplete) {
951
- historySyncStatus.recentSyncComplete = true;
952
- clearTimeout(historySyncPausedTimeout);
953
- historySyncPausedTimeout = undefined;
954
- ev.emit('messaging-history.status', {
955
- syncType,
956
- status: 'complete',
957
- explicit: true
958
- });
959
- }
960
- // Reset 120s paused timeout on any RECENT chunk (like WA Web's handleChunkProgress)
961
- if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
962
- clearTimeout(historySyncPausedTimeout);
963
- historySyncPausedTimeout = setTimeout(() => {
964
- if (!historySyncStatus.recentSyncComplete) {
965
- historySyncStatus.recentSyncComplete = true;
966
- ev.emit('messaging-history.status', {
967
- syncType: proto.HistorySync.HistorySyncType.RECENT,
968
- status: 'paused',
969
- explicit: false
970
- });
971
- }
972
- historySyncPausedTimeout = undefined;
973
- }, HISTORY_SYNC_PAUSED_TIMEOUT_MS);
974
- }
975
- }
976
- // State machine: decide on sync and flush
977
- if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
978
- if (awaitingSyncTimeout) {
979
- clearTimeout(awaitingSyncTimeout);
980
- awaitingSyncTimeout = undefined;
981
- }
982
- if (shouldProcessHistoryMsg) {
983
- syncState = SyncState.Syncing;
984
- logger.info('Transitioned to Syncing state');
985
- // Let doAppStateSync handle the final flush after it's done
986
- }
987
- else {
988
- syncState = SyncState.Online;
989
- logger.info('History sync skipped, transitioning to Online state and flushing buffer');
990
- ev.flush();
991
- }
819
+ const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
820
+ const shouldProcessHistoryMsg = historyMsg ?
821
+ (shouldSyncHistoryMessage(historyMsg) &&
822
+ Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)) :
823
+ false;
824
+ if (historyMsg && !authState.creds.myAppStateKeyId) {
825
+ logger.warn('skipping app state sync, as myAppStateKeyId is not set');
826
+ pendingAppStateSync = true;
992
827
  }
993
- const doAppStateSync = async () => {
994
- if (syncState === SyncState.Syncing) {
995
- // All collections will be synced, so clear any blocked ones
996
- blockedCollections.clear();
997
- logger.info('Doing app state sync');
998
- await resyncAppState(ALL_WA_PATCH_NAMES, true);
999
- // Sync is complete, go online and flush everything
1000
- syncState = SyncState.Online;
1001
- logger.info('App state sync complete, transitioning to Online state and flushing buffer');
1002
- ev.flush();
1003
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1004
- ev.emit('creds.update', { accountSyncCounter });
1005
- }
1006
- };
1007
828
  await Promise.all([
1008
829
  (async () => {
1009
- if (shouldProcessHistoryMsg) {
830
+ if (historyMsg &&
831
+ authState.creds.myAppStateKeyId) {
832
+ pendingAppStateSync = false;
1010
833
  await doAppStateSync();
1011
834
  }
1012
835
  })(),
1013
- processMessage(msg, {
1014
- signalRepository,
836
+ (0, process_message_1.default)(msg, {
1015
837
  shouldProcessHistoryMsg,
1016
838
  placeholderResendCache,
1017
839
  ev,
@@ -1019,19 +841,31 @@ export const makeChatsSocket = (config) => {
1019
841
  keyStore: authState.keys,
1020
842
  logger,
1021
843
  options: config.options,
1022
- getMessage
844
+ getMessage: config.getMessage,
1023
845
  })
1024
846
  ]);
1025
- // If the app state key arrives and we are waiting to sync, trigger the sync now.
1026
- if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
1027
- logger.info('App state sync key arrived, triggering app state sync');
847
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare) &&
848
+ pendingAppStateSync) {
1028
849
  await doAppStateSync();
850
+ pendingAppStateSync = false;
851
+ }
852
+ async function doAppStateSync() {
853
+ if (!authState.creds.accountSyncCounter) {
854
+ logger.info('doing initial app state sync');
855
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
856
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
857
+ ev.emit('creds.update', { accountSyncCounter });
858
+ if (needToFlushWithAppStateSync) {
859
+ logger.debug('flushing with app state sync');
860
+ ev.flush();
861
+ }
862
+ }
1029
863
  }
1030
864
  });
1031
865
  ws.on('CB:presence', handlePresenceUpdate);
1032
866
  ws.on('CB:chatstate', handlePresenceUpdate);
1033
867
  ws.on('CB:ib,,dirty', async (node) => {
1034
- const { attrs } = getBinaryNodeChild(node, 'dirty');
868
+ const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
1035
869
  const type = attrs.type;
1036
870
  switch (type) {
1037
871
  case 'account_sync':
@@ -1053,113 +887,37 @@ export const makeChatsSocket = (config) => {
1053
887
  }
1054
888
  });
1055
889
  ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1056
- if (connection === 'close') {
1057
- blockedCollections.clear();
1058
- clearTimeout(historySyncPausedTimeout);
1059
- historySyncPausedTimeout = undefined;
1060
- }
890
+ var _a;
1061
891
  if (connection === 'open') {
1062
892
  if (fireInitQueries) {
1063
- executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
893
+ executeInitQueries()
894
+ .catch(error => onUnexpectedError(error, 'init queries'));
1064
895
  }
1065
- sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
1066
- }
1067
- if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
1068
- return;
1069
- }
1070
- historySyncStatus.initialBootstrapComplete = false;
1071
- historySyncStatus.recentSyncComplete = false;
1072
- clearTimeout(historySyncPausedTimeout);
1073
- historySyncPausedTimeout = undefined;
1074
- syncState = SyncState.AwaitingInitialSync;
1075
- logger.info('Connection is now AwaitingInitialSync, buffering events');
1076
- ev.buffer();
1077
- const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
1078
- syncType: proto.HistorySync.HistorySyncType.RECENT
1079
- }));
1080
- if (!willSyncHistory) {
1081
- logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
1082
- syncState = SyncState.Online;
1083
- setTimeout(() => ev.flush(), 0);
1084
- return;
1085
- }
1086
- // On reconnection (accountSyncCounter > 0), the server does not push
1087
- // history sync notifications — the device already has its data.
1088
- // Skip the 20s wait and go online immediately.
1089
- if (authState.creds.accountSyncCounter > 0) {
1090
- logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.');
1091
- syncState = SyncState.Online;
1092
- setTimeout(() => ev.flush(), 0);
1093
- return;
1094
- }
1095
- logger.info('First connection, awaiting history sync notification with a 20s timeout.');
1096
- if (awaitingSyncTimeout) {
1097
- clearTimeout(awaitingSyncTimeout);
1098
- }
1099
- awaitingSyncTimeout = setTimeout(() => {
1100
- if (syncState === SyncState.AwaitingInitialSync) {
1101
- logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1102
- syncState = SyncState.Online;
1103
- ev.flush();
1104
- // Increment so subsequent reconnections skip the 20s wait.
1105
- // Late-arriving history is still processed via processMessage
1106
- // regardless of the state machine phase.
1107
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1108
- ev.emit('creds.update', { accountSyncCounter });
1109
- }
1110
- }, 20000);
1111
- });
1112
- // When an app state sync key arrives (myAppStateKeyId is set) and there are
1113
- // collections blocked on a missing key, trigger a re-sync for just those collections.
1114
- // This mirrors WA Web's Blocked → retry-on-key-arrival behavior.
1115
- ev.on('creds.update', ({ myAppStateKeyId }) => {
1116
- if (!myAppStateKeyId || blockedCollections.size === 0) {
1117
- return;
1118
- }
1119
- // If we're in the middle of a full sync, doAppStateSync handles all collections
1120
- if (syncState === SyncState.Syncing) {
1121
- blockedCollections.clear();
1122
- return;
1123
- }
1124
- const collections = [...blockedCollections];
1125
- blockedCollections.clear();
1126
- logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections');
1127
- resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'));
1128
- });
1129
- ev.on('lid-mapping.update', async ({ lid, pn }) => {
1130
- try {
1131
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
1132
- }
1133
- catch (error) {
1134
- logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
1135
- }
1136
- });
1137
- registerSocketEndHandler(() => {
1138
- if (awaitingSyncTimeout) {
1139
- clearTimeout(awaitingSyncTimeout);
1140
- awaitingSyncTimeout = undefined;
896
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
897
+ .catch(error => onUnexpectedError(error, 'presence update requests'));
1141
898
  }
1142
- if (!config.placeholderResendCache && placeholderResendCache.close) {
1143
- placeholderResendCache.close();
899
+ if (receivedPendingNotifications && // if we don't have the app state key
900
+ // we keep buffering events until we finally have
901
+ // the key and can sync the messages
902
+ // todo scrutinize
903
+ !((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId)) {
904
+ ev.buffer();
905
+ needToFlushWithAppStateSync = true;
1144
906
  }
1145
- syncState = SyncState.Connecting;
1146
- privacySettings = undefined;
1147
907
  });
1148
908
  return {
1149
909
  ...sock,
1150
- serverProps,
1151
- createCallLink,
910
+ interactiveQuery,
1152
911
  getBotListV2,
1153
- messageMutex,
1154
- receiptMutex,
1155
- appStatePatchMutex,
1156
- notificationMutex,
912
+ processingMutex,
1157
913
  fetchPrivacySettings,
1158
914
  upsertMessage,
1159
915
  appPatch,
916
+ fetchUserLid,
1160
917
  sendPresenceUpdate,
1161
918
  presenceSubscribe,
1162
919
  profilePictureUrl,
920
+ onWhatsApp,
1163
921
  fetchBlocklist,
1164
922
  fetchStatus,
1165
923
  fetchDisappearingDuration,
@@ -1168,7 +926,6 @@ export const makeChatsSocket = (config) => {
1168
926
  updateProfileStatus,
1169
927
  updateProfileName,
1170
928
  updateBlockStatus,
1171
- updateDisableLinkPreviewsPrivacy,
1172
929
  updateCallPrivacy,
1173
930
  updateMessagesPrivacy,
1174
931
  updateLastSeenPrivacy,
@@ -1182,17 +939,12 @@ export const makeChatsSocket = (config) => {
1182
939
  resyncAppState,
1183
940
  chatModify,
1184
941
  cleanDirtyBits,
1185
- addOrEditContact,
1186
- removeContact,
1187
- placeholderResendCache,
1188
942
  addLabel,
1189
943
  addChatLabel,
1190
944
  removeChatLabel,
1191
945
  addMessageLabel,
1192
946
  removeMessageLabel,
1193
- star,
1194
- addOrEditQuickReply,
1195
- removeQuickReply
947
+ star
1196
948
  };
1197
949
  };
1198
- //# sourceMappingURL=chats.js.map
950
+ exports.makeChatsSocket = makeChatsSocket;