@fenrys/baileys 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (401) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +166 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +97691 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.d.ts +75 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +129 -0
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  15. package/lib/Signal/Group/ciphertext-message.js +12 -0
  16. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  18. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  19. package/lib/Signal/Group/group-session-builder.js +30 -0
  20. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  21. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  22. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  23. package/lib/Signal/Group/group_cipher.js +82 -0
  24. package/lib/Signal/Group/group_cipher.js.map +1 -0
  25. package/lib/Signal/Group/index.d.ts +12 -0
  26. package/lib/Signal/Group/index.d.ts.map +1 -0
  27. package/lib/Signal/Group/index.js +12 -0
  28. package/lib/Signal/Group/index.js.map +1 -0
  29. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  30. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  31. package/lib/Signal/Group/keyhelper.js +18 -0
  32. package/lib/Signal/Group/keyhelper.js.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  34. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  35. package/lib/Signal/Group/sender-chain-key.js +26 -0
  36. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  42. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  43. package/lib/Signal/Group/sender-key-message.js +66 -0
  44. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  46. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  47. package/lib/Signal/Group/sender-key-name.js +48 -0
  48. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  50. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  51. package/lib/Signal/Group/sender-key-record.js +41 -0
  52. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  54. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  55. package/lib/Signal/Group/sender-key-state.js +84 -0
  56. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  58. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  59. package/lib/Signal/Group/sender-message-key.js +26 -0
  60. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  61. package/lib/Signal/libsignal.d.ts +5 -0
  62. package/lib/Signal/libsignal.d.ts.map +1 -0
  63. package/lib/Signal/libsignal.js +431 -0
  64. package/lib/Signal/libsignal.js.map +1 -0
  65. package/lib/Signal/lid-mapping.d.ts +23 -0
  66. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  67. package/lib/Signal/lid-mapping.js +277 -0
  68. package/lib/Signal/lid-mapping.js.map +1 -0
  69. package/lib/Socket/Client/index.d.ts +3 -0
  70. package/lib/Socket/Client/index.d.ts.map +1 -0
  71. package/lib/Socket/Client/index.js +3 -0
  72. package/lib/Socket/Client/index.js.map +1 -0
  73. package/lib/Socket/Client/types.d.ts +16 -0
  74. package/lib/Socket/Client/types.d.ts.map +1 -0
  75. package/lib/Socket/Client/types.js +11 -0
  76. package/lib/Socket/Client/types.js.map +1 -0
  77. package/lib/Socket/Client/websocket.d.ts +13 -0
  78. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  79. package/lib/Socket/Client/websocket.js +54 -0
  80. package/lib/Socket/Client/websocket.js.map +1 -0
  81. package/lib/Socket/business.d.ts +217 -0
  82. package/lib/Socket/business.d.ts.map +1 -0
  83. package/lib/Socket/business.js +379 -0
  84. package/lib/Socket/business.js.map +1 -0
  85. package/lib/Socket/chats.d.ts +125 -0
  86. package/lib/Socket/chats.d.ts.map +1 -0
  87. package/lib/Socket/chats.js +1198 -0
  88. package/lib/Socket/chats.js.map +1 -0
  89. package/lib/Socket/communities.d.ts +273 -0
  90. package/lib/Socket/communities.d.ts.map +1 -0
  91. package/lib/Socket/communities.js +431 -0
  92. package/lib/Socket/communities.js.map +1 -0
  93. package/lib/Socket/groups.d.ts +161 -0
  94. package/lib/Socket/groups.d.ts.map +1 -0
  95. package/lib/Socket/groups.js +347 -0
  96. package/lib/Socket/groups.js.map +1 -0
  97. package/lib/Socket/index.d.ts +260 -0
  98. package/lib/Socket/index.d.ts.map +1 -0
  99. package/lib/Socket/index.js +12 -0
  100. package/lib/Socket/index.js.map +1 -0
  101. package/lib/Socket/messages-recv.d.ts +203 -0
  102. package/lib/Socket/messages-recv.d.ts.map +1 -0
  103. package/lib/Socket/messages-recv.js +1772 -0
  104. package/lib/Socket/messages-recv.js.map +1 -0
  105. package/lib/Socket/messages-send.d.ts +199 -0
  106. package/lib/Socket/messages-send.d.ts.map +1 -0
  107. package/lib/Socket/messages-send.js +1145 -0
  108. package/lib/Socket/messages-send.js.map +1 -0
  109. package/lib/Socket/mex.d.ts +3 -0
  110. package/lib/Socket/mex.d.ts.map +1 -0
  111. package/lib/Socket/mex.js +42 -0
  112. package/lib/Socket/mex.js.map +1 -0
  113. package/lib/Socket/newsletter.d.ts +170 -0
  114. package/lib/Socket/newsletter.d.ts.map +1 -0
  115. package/lib/Socket/newsletter.js +181 -0
  116. package/lib/Socket/newsletter.js.map +1 -0
  117. package/lib/Socket/socket.d.ts +59 -0
  118. package/lib/Socket/socket.d.ts.map +1 -0
  119. package/lib/Socket/socket.js +970 -0
  120. package/lib/Socket/socket.js.map +1 -0
  121. package/lib/Types/Auth.d.ts +117 -0
  122. package/lib/Types/Auth.d.ts.map +1 -0
  123. package/lib/Types/Auth.js +2 -0
  124. package/lib/Types/Auth.js.map +1 -0
  125. package/lib/Types/Bussines.d.ts +25 -0
  126. package/lib/Types/Bussines.d.ts.map +1 -0
  127. package/lib/Types/Bussines.js +2 -0
  128. package/lib/Types/Bussines.js.map +1 -0
  129. package/lib/Types/Call.d.ts +15 -0
  130. package/lib/Types/Call.d.ts.map +1 -0
  131. package/lib/Types/Call.js +2 -0
  132. package/lib/Types/Call.js.map +1 -0
  133. package/lib/Types/Chat.d.ts +124 -0
  134. package/lib/Types/Chat.d.ts.map +1 -0
  135. package/lib/Types/Chat.js +8 -0
  136. package/lib/Types/Chat.js.map +1 -0
  137. package/lib/Types/Contact.d.ts +26 -0
  138. package/lib/Types/Contact.d.ts.map +1 -0
  139. package/lib/Types/Contact.js +2 -0
  140. package/lib/Types/Contact.js.map +1 -0
  141. package/lib/Types/Events.d.ts +256 -0
  142. package/lib/Types/Events.d.ts.map +1 -0
  143. package/lib/Types/Events.js +2 -0
  144. package/lib/Types/Events.js.map +1 -0
  145. package/lib/Types/GroupMetadata.d.ts +71 -0
  146. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  147. package/lib/Types/GroupMetadata.js +2 -0
  148. package/lib/Types/GroupMetadata.js.map +1 -0
  149. package/lib/Types/Label.d.ts +47 -0
  150. package/lib/Types/Label.d.ts.map +1 -0
  151. package/lib/Types/Label.js +25 -0
  152. package/lib/Types/Label.js.map +1 -0
  153. package/lib/Types/LabelAssociation.d.ts +30 -0
  154. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  155. package/lib/Types/LabelAssociation.js +7 -0
  156. package/lib/Types/LabelAssociation.js.map +1 -0
  157. package/lib/Types/Message.d.ts +320 -0
  158. package/lib/Types/Message.d.ts.map +1 -0
  159. package/lib/Types/Message.js +11 -0
  160. package/lib/Types/Message.js.map +1 -0
  161. package/lib/Types/Mex.d.ts +141 -0
  162. package/lib/Types/Mex.d.ts.map +1 -0
  163. package/lib/Types/Mex.js +37 -0
  164. package/lib/Types/Mex.js.map +1 -0
  165. package/lib/Types/Product.d.ts +79 -0
  166. package/lib/Types/Product.d.ts.map +1 -0
  167. package/lib/Types/Product.js +2 -0
  168. package/lib/Types/Product.js.map +1 -0
  169. package/lib/Types/Signal.d.ts +87 -0
  170. package/lib/Types/Signal.d.ts.map +1 -0
  171. package/lib/Types/Signal.js +2 -0
  172. package/lib/Types/Signal.js.map +1 -0
  173. package/lib/Types/Socket.d.ts +136 -0
  174. package/lib/Types/Socket.d.ts.map +1 -0
  175. package/lib/Types/Socket.js +3 -0
  176. package/lib/Types/Socket.js.map +1 -0
  177. package/lib/Types/State.d.ts +97 -0
  178. package/lib/Types/State.d.ts.map +1 -0
  179. package/lib/Types/State.js +56 -0
  180. package/lib/Types/State.js.map +1 -0
  181. package/lib/Types/USync.d.ts +26 -0
  182. package/lib/Types/USync.d.ts.map +1 -0
  183. package/lib/Types/USync.js +2 -0
  184. package/lib/Types/USync.js.map +1 -0
  185. package/lib/Types/index.d.ts +66 -0
  186. package/lib/Types/index.d.ts.map +1 -0
  187. package/lib/Types/index.js +26 -0
  188. package/lib/Types/index.js.map +1 -0
  189. package/lib/Utils/auth-utils.d.ts +24 -0
  190. package/lib/Utils/auth-utils.d.ts.map +1 -0
  191. package/lib/Utils/auth-utils.js +302 -0
  192. package/lib/Utils/auth-utils.js.map +1 -0
  193. package/lib/Utils/browser-utils.d.ts +4 -0
  194. package/lib/Utils/browser-utils.d.ts.map +1 -0
  195. package/lib/Utils/browser-utils.js +29 -0
  196. package/lib/Utils/browser-utils.js.map +1 -0
  197. package/lib/Utils/business.d.ts +23 -0
  198. package/lib/Utils/business.d.ts.map +1 -0
  199. package/lib/Utils/business.js +231 -0
  200. package/lib/Utils/business.js.map +1 -0
  201. package/lib/Utils/chat-utils.d.ts +100 -0
  202. package/lib/Utils/chat-utils.d.ts.map +1 -0
  203. package/lib/Utils/chat-utils.js +872 -0
  204. package/lib/Utils/chat-utils.js.map +1 -0
  205. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  206. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  207. package/lib/Utils/companion-reg-client-utils.js +35 -0
  208. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  209. package/lib/Utils/crypto.d.ts +37 -0
  210. package/lib/Utils/crypto.d.ts.map +1 -0
  211. package/lib/Utils/crypto.js +118 -0
  212. package/lib/Utils/crypto.js.map +1 -0
  213. package/lib/Utils/decode-wa-message.d.ts +66 -0
  214. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  215. package/lib/Utils/decode-wa-message.js +317 -0
  216. package/lib/Utils/decode-wa-message.js.map +1 -0
  217. package/lib/Utils/event-buffer.d.ts +36 -0
  218. package/lib/Utils/event-buffer.d.ts.map +1 -0
  219. package/lib/Utils/event-buffer.js +622 -0
  220. package/lib/Utils/event-buffer.js.map +1 -0
  221. package/lib/Utils/generics.d.ts +92 -0
  222. package/lib/Utils/generics.d.ts.map +1 -0
  223. package/lib/Utils/generics.js +393 -0
  224. package/lib/Utils/generics.js.map +1 -0
  225. package/lib/Utils/history.d.ts +24 -0
  226. package/lib/Utils/history.d.ts.map +1 -0
  227. package/lib/Utils/history.js +134 -0
  228. package/lib/Utils/history.js.map +1 -0
  229. package/lib/Utils/identity-change-handler.d.ts +44 -0
  230. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  231. package/lib/Utils/identity-change-handler.js +50 -0
  232. package/lib/Utils/identity-change-handler.js.map +1 -0
  233. package/lib/Utils/index.d.ts +22 -0
  234. package/lib/Utils/index.d.ts.map +1 -0
  235. package/lib/Utils/index.js +22 -0
  236. package/lib/Utils/index.js.map +1 -0
  237. package/lib/Utils/link-preview.d.ts +21 -0
  238. package/lib/Utils/link-preview.d.ts.map +1 -0
  239. package/lib/Utils/link-preview.js +85 -0
  240. package/lib/Utils/link-preview.js.map +1 -0
  241. package/lib/Utils/logger.d.ts +13 -0
  242. package/lib/Utils/logger.d.ts.map +1 -0
  243. package/lib/Utils/logger.js +3 -0
  244. package/lib/Utils/logger.js.map +1 -0
  245. package/lib/Utils/lt-hash.d.ts +8 -0
  246. package/lib/Utils/lt-hash.d.ts.map +1 -0
  247. package/lib/Utils/lt-hash.js +8 -0
  248. package/lib/Utils/lt-hash.js.map +1 -0
  249. package/lib/Utils/make-mutex.d.ts +9 -0
  250. package/lib/Utils/make-mutex.d.ts.map +1 -0
  251. package/lib/Utils/make-mutex.js +33 -0
  252. package/lib/Utils/make-mutex.js.map +1 -0
  253. package/lib/Utils/message-retry-manager.d.ts +115 -0
  254. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  255. package/lib/Utils/message-retry-manager.js +265 -0
  256. package/lib/Utils/message-retry-manager.js.map +1 -0
  257. package/lib/Utils/messages-media.d.ts +133 -0
  258. package/lib/Utils/messages-media.d.ts.map +1 -0
  259. package/lib/Utils/messages-media.js +788 -0
  260. package/lib/Utils/messages-media.js.map +1 -0
  261. package/lib/Utils/messages.d.ts +91 -0
  262. package/lib/Utils/messages.d.ts.map +1 -0
  263. package/lib/Utils/messages.js +893 -0
  264. package/lib/Utils/messages.js.map +1 -0
  265. package/lib/Utils/noise-handler.d.ts +20 -0
  266. package/lib/Utils/noise-handler.d.ts.map +1 -0
  267. package/lib/Utils/noise-handler.js +201 -0
  268. package/lib/Utils/noise-handler.js.map +1 -0
  269. package/lib/Utils/offline-node-processor.d.ts +17 -0
  270. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  271. package/lib/Utils/offline-node-processor.js +40 -0
  272. package/lib/Utils/offline-node-processor.js.map +1 -0
  273. package/lib/Utils/pre-key-manager.d.ts +28 -0
  274. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  275. package/lib/Utils/pre-key-manager.js +106 -0
  276. package/lib/Utils/pre-key-manager.js.map +1 -0
  277. package/lib/Utils/process-message.d.ts +60 -0
  278. package/lib/Utils/process-message.d.ts.map +1 -0
  279. package/lib/Utils/process-message.js +630 -0
  280. package/lib/Utils/process-message.js.map +1 -0
  281. package/lib/Utils/reporting-utils.d.ts +11 -0
  282. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  283. package/lib/Utils/reporting-utils.js +258 -0
  284. package/lib/Utils/reporting-utils.js.map +1 -0
  285. package/lib/Utils/signal.d.ts +47 -0
  286. package/lib/Utils/signal.d.ts.map +1 -0
  287. package/lib/Utils/signal.js +201 -0
  288. package/lib/Utils/signal.js.map +1 -0
  289. package/lib/Utils/stanza-ack.d.ts +11 -0
  290. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  291. package/lib/Utils/stanza-ack.js +38 -0
  292. package/lib/Utils/stanza-ack.js.map +1 -0
  293. package/lib/Utils/sync-action-utils.d.ts +19 -0
  294. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  295. package/lib/Utils/sync-action-utils.js +49 -0
  296. package/lib/Utils/sync-action-utils.js.map +1 -0
  297. package/lib/Utils/tc-token-utils.d.ts +37 -0
  298. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  299. package/lib/Utils/tc-token-utils.js +164 -0
  300. package/lib/Utils/tc-token-utils.js.map +1 -0
  301. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  302. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  303. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  304. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  305. package/lib/Utils/validate-connection.d.ts +11 -0
  306. package/lib/Utils/validate-connection.d.ts.map +1 -0
  307. package/lib/Utils/validate-connection.js +210 -0
  308. package/lib/Utils/validate-connection.js.map +1 -0
  309. package/lib/WABinary/constants.d.ts +28 -0
  310. package/lib/WABinary/constants.d.ts.map +1 -0
  311. package/lib/WABinary/constants.js +1301 -0
  312. package/lib/WABinary/constants.js.map +1 -0
  313. package/lib/WABinary/decode.d.ts +7 -0
  314. package/lib/WABinary/decode.d.ts.map +1 -0
  315. package/lib/WABinary/decode.js +262 -0
  316. package/lib/WABinary/decode.js.map +1 -0
  317. package/lib/WABinary/encode.d.ts +3 -0
  318. package/lib/WABinary/encode.d.ts.map +1 -0
  319. package/lib/WABinary/encode.js +220 -0
  320. package/lib/WABinary/encode.js.map +1 -0
  321. package/lib/WABinary/generic-utils.d.ts +15 -0
  322. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  323. package/lib/WABinary/generic-utils.js +113 -0
  324. package/lib/WABinary/generic-utils.js.map +1 -0
  325. package/lib/WABinary/index.d.ts +6 -0
  326. package/lib/WABinary/index.d.ts.map +1 -0
  327. package/lib/WABinary/index.js +6 -0
  328. package/lib/WABinary/index.js.map +1 -0
  329. package/lib/WABinary/jid-utils.d.ts +48 -0
  330. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  331. package/lib/WABinary/jid-utils.js +96 -0
  332. package/lib/WABinary/jid-utils.js.map +1 -0
  333. package/lib/WABinary/types.d.ts +19 -0
  334. package/lib/WABinary/types.d.ts.map +1 -0
  335. package/lib/WABinary/types.js +2 -0
  336. package/lib/WABinary/types.js.map +1 -0
  337. package/lib/WAM/BinaryInfo.d.ts +9 -0
  338. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  339. package/lib/WAM/BinaryInfo.js +10 -0
  340. package/lib/WAM/BinaryInfo.js.map +1 -0
  341. package/lib/WAM/constants.d.ts +40 -0
  342. package/lib/WAM/constants.d.ts.map +1 -0
  343. package/lib/WAM/constants.js +22853 -0
  344. package/lib/WAM/constants.js.map +1 -0
  345. package/lib/WAM/encode.d.ts +3 -0
  346. package/lib/WAM/encode.d.ts.map +1 -0
  347. package/lib/WAM/encode.js +150 -0
  348. package/lib/WAM/encode.js.map +1 -0
  349. package/lib/WAM/index.d.ts +4 -0
  350. package/lib/WAM/index.d.ts.map +1 -0
  351. package/lib/WAM/index.js +4 -0
  352. package/lib/WAM/index.js.map +1 -0
  353. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  354. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  355. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  356. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  357. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  358. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  359. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  360. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  361. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  362. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  363. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  364. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  365. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  366. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  367. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  368. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  369. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  370. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  371. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  372. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  373. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  374. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  375. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  376. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  377. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  378. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  379. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  380. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  381. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  382. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  383. package/lib/WAUSync/Protocols/index.js +6 -0
  384. package/lib/WAUSync/Protocols/index.js.map +1 -0
  385. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  386. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  387. package/lib/WAUSync/USyncQuery.js +98 -0
  388. package/lib/WAUSync/USyncQuery.js.map +1 -0
  389. package/lib/WAUSync/USyncUser.d.ts +17 -0
  390. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  391. package/lib/WAUSync/USyncUser.js +31 -0
  392. package/lib/WAUSync/USyncUser.js.map +1 -0
  393. package/lib/WAUSync/index.d.ts +4 -0
  394. package/lib/WAUSync/index.d.ts.map +1 -0
  395. package/lib/WAUSync/index.js +4 -0
  396. package/lib/WAUSync/index.js.map +1 -0
  397. package/lib/index.d.ts +12 -0
  398. package/lib/index.d.ts.map +1 -0
  399. package/lib/index.js +11 -0
  400. package/lib/index.js.map +1 -0
  401. package/package.json +139 -0
@@ -0,0 +1,1198 @@
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];
20
+ };
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);
26
+ 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
+ });
61
+ /** helper function to fetch the given app state sync key */
62
+ const getAppStateSyncKey = async (keyId) => {
63
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
64
+ return key;
65
+ };
66
+ const fetchPrivacySettings = async (force = false) => {
67
+ if (!privacySettings || force) {
68
+ const { content } = await query({
69
+ tag: 'iq',
70
+ attrs: {
71
+ xmlns: 'privacy',
72
+ to: S_WHATSAPP_NET,
73
+ type: 'get'
74
+ },
75
+ content: [{ tag: 'privacy', attrs: {} }]
76
+ });
77
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
78
+ }
79
+ return privacySettings;
80
+ };
81
+ /** helper function to run a privacy IQ query */
82
+ const privacyQuery = async (name, value) => {
83
+ await query({
84
+ tag: 'iq',
85
+ attrs: {
86
+ xmlns: 'privacy',
87
+ to: S_WHATSAPP_NET,
88
+ type: 'set'
89
+ },
90
+ content: [
91
+ {
92
+ tag: 'privacy',
93
+ attrs: {},
94
+ content: [
95
+ {
96
+ tag: 'category',
97
+ attrs: { name, value }
98
+ }
99
+ ]
100
+ }
101
+ ]
102
+ });
103
+ };
104
+ const updateMessagesPrivacy = async (value) => {
105
+ await privacyQuery('messages', value);
106
+ };
107
+ const updateCallPrivacy = async (value) => {
108
+ await privacyQuery('calladd', value);
109
+ };
110
+ const updateLastSeenPrivacy = async (value) => {
111
+ await privacyQuery('last', value);
112
+ };
113
+ const updateOnlinePrivacy = async (value) => {
114
+ await privacyQuery('online', value);
115
+ };
116
+ const updateProfilePicturePrivacy = async (value) => {
117
+ await privacyQuery('profile', value);
118
+ };
119
+ const updateStatusPrivacy = async (value) => {
120
+ await privacyQuery('status', value);
121
+ };
122
+ const updateReadReceiptsPrivacy = async (value) => {
123
+ await privacyQuery('readreceipts', value);
124
+ };
125
+ const updateGroupsAddPrivacy = async (value) => {
126
+ await privacyQuery('groupadd', value);
127
+ };
128
+ const updateDefaultDisappearingMode = async (duration) => {
129
+ await query({
130
+ tag: 'iq',
131
+ attrs: {
132
+ xmlns: 'disappearing_mode',
133
+ to: S_WHATSAPP_NET,
134
+ type: 'set'
135
+ },
136
+ content: [
137
+ {
138
+ tag: 'disappearing_mode',
139
+ attrs: {
140
+ duration: duration.toString()
141
+ }
142
+ }
143
+ ]
144
+ });
145
+ };
146
+ const getBotListV2 = async () => {
147
+ const resp = await query({
148
+ tag: 'iq',
149
+ attrs: {
150
+ xmlns: 'bot',
151
+ to: S_WHATSAPP_NET,
152
+ type: 'get'
153
+ },
154
+ content: [
155
+ {
156
+ tag: 'bot',
157
+ attrs: {
158
+ v: '2'
159
+ }
160
+ }
161
+ ]
162
+ });
163
+ const botNode = getBinaryNodeChild(resp, 'bot');
164
+ const botList = [];
165
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
166
+ if (section.attrs.type === 'all') {
167
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
168
+ botList.push({
169
+ jid: bot.attrs.jid,
170
+ personaId: bot.attrs['persona_id']
171
+ });
172
+ }
173
+ }
174
+ }
175
+ return botList;
176
+ };
177
+ const fetchStatus = async (...jids) => {
178
+ const usyncQuery = new USyncQuery().withStatusProtocol();
179
+ for (const jid of jids) {
180
+ usyncQuery.withUser(new USyncUser().withId(jid));
181
+ }
182
+ const result = await sock.executeUSyncQuery(usyncQuery);
183
+ if (result) {
184
+ return result.list;
185
+ }
186
+ };
187
+ const fetchDisappearingDuration = async (...jids) => {
188
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
189
+ for (const jid of jids) {
190
+ usyncQuery.withUser(new USyncUser().withId(jid));
191
+ }
192
+ const result = await sock.executeUSyncQuery(usyncQuery);
193
+ if (result) {
194
+ return result.list;
195
+ }
196
+ };
197
+ /** update the profile picture for yourself or a group */
198
+ const updateProfilePicture = async (jid, content, dimensions) => {
199
+ let targetJid;
200
+ 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
205
+ }
206
+ else {
207
+ targetJid = undefined;
208
+ }
209
+ const { img } = await generateProfilePicture(content, dimensions);
210
+ await query({
211
+ tag: 'iq',
212
+ attrs: {
213
+ to: S_WHATSAPP_NET,
214
+ type: 'set',
215
+ xmlns: 'w:profile:picture',
216
+ ...(targetJid ? { target: targetJid } : {})
217
+ },
218
+ content: [
219
+ {
220
+ tag: 'picture',
221
+ attrs: { type: 'image' },
222
+ content: img
223
+ }
224
+ ]
225
+ });
226
+ };
227
+ /** remove the profile picture for yourself or a group */
228
+ const removeProfilePicture = async (jid) => {
229
+ let targetJid;
230
+ 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');
232
+ }
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;
238
+ }
239
+ await query({
240
+ tag: 'iq',
241
+ attrs: {
242
+ to: S_WHATSAPP_NET,
243
+ type: 'set',
244
+ xmlns: 'w:profile:picture',
245
+ ...(targetJid ? { target: targetJid } : {})
246
+ }
247
+ });
248
+ };
249
+ /** update the profile status for yourself */
250
+ const updateProfileStatus = async (status) => {
251
+ await query({
252
+ tag: 'iq',
253
+ attrs: {
254
+ to: S_WHATSAPP_NET,
255
+ type: 'set',
256
+ xmlns: 'status'
257
+ },
258
+ content: [
259
+ {
260
+ tag: 'status',
261
+ attrs: {},
262
+ content: Buffer.from(status, 'utf-8')
263
+ }
264
+ ]
265
+ });
266
+ };
267
+ const updateProfileName = async (name) => {
268
+ await chatModify({ pushNameSetting: name }, '');
269
+ };
270
+ const fetchBlocklist = async () => {
271
+ const result = await query({
272
+ tag: 'iq',
273
+ attrs: {
274
+ xmlns: 'blocklist',
275
+ to: S_WHATSAPP_NET,
276
+ type: 'get'
277
+ }
278
+ });
279
+ const listNode = getBinaryNodeChild(result, 'list');
280
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
281
+ };
282
+ 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
+ await query({
320
+ tag: 'iq',
321
+ attrs: {
322
+ xmlns: 'blocklist',
323
+ to: S_WHATSAPP_NET,
324
+ type: 'set'
325
+ },
326
+ content: [
327
+ {
328
+ tag: 'item',
329
+ attrs: itemAttrs
330
+ }
331
+ ]
332
+ });
333
+ };
334
+ const getBusinessProfile = async (jid) => {
335
+ const results = await query({
336
+ tag: 'iq',
337
+ attrs: {
338
+ to: 's.whatsapp.net',
339
+ xmlns: 'w:biz',
340
+ type: 'get'
341
+ },
342
+ content: [
343
+ {
344
+ tag: 'business_profile',
345
+ attrs: { v: '244' },
346
+ content: [
347
+ {
348
+ tag: 'profile',
349
+ attrs: { jid }
350
+ }
351
+ ]
352
+ }
353
+ ]
354
+ });
355
+ const profileNode = getBinaryNodeChild(results, 'business_profile');
356
+ const profiles = getBinaryNodeChild(profileNode, 'profile');
357
+ 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();
368
+ return {
369
+ wid: profiles.attrs?.jid,
370
+ address: address?.content?.toString(),
371
+ description: description?.content?.toString() || '',
372
+ 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)
378
+ }
379
+ };
380
+ }
381
+ };
382
+ const cleanDirtyBits = async (type, fromTimestamp) => {
383
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
384
+ await sendNode({
385
+ tag: 'iq',
386
+ attrs: {
387
+ to: S_WHATSAPP_NET,
388
+ type: 'set',
389
+ xmlns: 'urn:xmpp:whatsapp:dirty',
390
+ id: generateMessageTag()
391
+ },
392
+ content: [
393
+ {
394
+ tag: 'clean',
395
+ attrs: {
396
+ type,
397
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
398
+ }
399
+ }
400
+ ]
401
+ });
402
+ };
403
+ const newAppStateChunkHandler = (isInitialSync) => {
404
+ return {
405
+ onMutation(mutation) {
406
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
407
+ }
408
+ };
409
+ };
410
+ 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
+ // we use this to determine which events to fire
421
+ // otherwise when we resync from scratch -- all notifications will fire
422
+ const initialVersionMap = {};
423
+ const globalMutationMap = {};
424
+ await authState.keys.transaction(async () => {
425
+ const collectionsToHandle = new Set(collections);
426
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
427
+ 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
+ // keep executing till all collections are done
432
+ // sometimes a single patch request will not return all the patches (God knows why)
433
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
434
+ while (collectionsToHandle.size) {
435
+ const states = {};
436
+ const nodes = [];
437
+ for (const name of collectionsToHandle) {
438
+ const result = await authState.keys.get('app-state-sync-version', [name]);
439
+ let state = result[name];
440
+ if (state) {
441
+ state = ensureLTHashStateVersion(state);
442
+ if (typeof initialVersionMap[name] === 'undefined') {
443
+ initialVersionMap[name] = state.version;
444
+ }
445
+ }
446
+ else {
447
+ state = newLTHashState();
448
+ }
449
+ 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)' : ''}`);
455
+ nodes.push({
456
+ tag: 'collection',
457
+ attrs: {
458
+ name,
459
+ version: state.version.toString(),
460
+ // return snapshot if syncing from scratch or forcing after a failed attempt
461
+ return_snapshot: (shouldForceSnapshot || !state.version).toString()
462
+ }
463
+ });
464
+ }
465
+ const result = await query({
466
+ tag: 'iq',
467
+ attrs: {
468
+ to: S_WHATSAPP_NET,
469
+ xmlns: 'w:sync:app:state',
470
+ type: 'set'
471
+ },
472
+ content: [
473
+ {
474
+ tag: 'sync',
475
+ attrs: {},
476
+ content: nodes
477
+ }
478
+ ]
479
+ });
480
+ // extract from binary node
481
+ const decoded = await extractSyncdPatches(result, config?.options);
482
+ for (const key in decoded) {
483
+ const name = key;
484
+ const { patches, hasMorePatches, snapshot } = decoded[name];
485
+ try {
486
+ if (snapshot) {
487
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
488
+ states[name] = newState;
489
+ Object.assign(globalMutationMap, mutationMap);
490
+ 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 } });
492
+ }
493
+ // only process if there are syncd patches
494
+ 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 } });
497
+ logger.info(`synced ${name} to v${newState.version}`);
498
+ initialVersionMap[name] = newState.version;
499
+ Object.assign(globalMutationMap, mutationMap);
500
+ }
501
+ if (hasMorePatches) {
502
+ logger.info(`${name} has more patches...`);
503
+ }
504
+ else {
505
+ // collection is done with sync
506
+ collectionsToHandle.delete(name);
507
+ }
508
+ }
509
+ catch (error) {
510
+ 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);
524
+ collectionsToHandle.delete(name);
525
+ }
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
+ }
542
+ }
543
+ }
544
+ }, authState?.creds?.me?.id || 'resync-app-state');
545
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
546
+ for (const key in globalMutationMap) {
547
+ onMutation(globalMutationMap[key]);
548
+ }
549
+ });
550
+ /**
551
+ * fetch the profile picture of a user/group
552
+ * type = "preview" for a low res picture
553
+ * type = "image for the high res picture"
554
+ */
555
+ 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);
572
+ const result = await query({
573
+ tag: 'iq',
574
+ attrs: {
575
+ target: jid,
576
+ to: S_WHATSAPP_NET,
577
+ type: 'get',
578
+ xmlns: 'w:profile:picture'
579
+ },
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
+ content: [
593
+ {
594
+ tag: 'link_create',
595
+ attrs: { media: type },
596
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
597
+ }
598
+ ]
599
+ }, timeoutMs);
600
+ const child = getBinaryNodeChild(result, 'link_create');
601
+ return child?.attrs?.token;
602
+ };
603
+ const sendPresenceUpdate = async (type, toJid) => {
604
+ const me = authState.creds.me;
605
+ const isAvailableType = type === 'available';
606
+ if (isAvailableType || type === 'unavailable') {
607
+ if (!me.name) {
608
+ logger.warn('no name present, ignoring presence update request...');
609
+ return;
610
+ }
611
+ ev.emit('connection.update', { isOnline: isAvailableType });
612
+ if (isAvailableType) {
613
+ void sendUnifiedSession();
614
+ }
615
+ await sendNode({
616
+ tag: 'presence',
617
+ attrs: {
618
+ name: me.name.replace(/@/g, ''),
619
+ type
620
+ }
621
+ });
622
+ }
623
+ else {
624
+ const { server } = jidDecode(toJid);
625
+ const isLid = server === 'lid';
626
+ await sendNode({
627
+ tag: 'chatstate',
628
+ attrs: {
629
+ from: isLid ? me.lid : me.id,
630
+ to: toJid
631
+ },
632
+ content: [
633
+ {
634
+ tag: type === 'recording' ? 'composing' : type,
635
+ attrs: type === 'recording' ? { media: 'audio' } : {}
636
+ }
637
+ ]
638
+ });
639
+ }
640
+ };
641
+ /**
642
+ * @param toJid the jid to subscribe to
643
+ * @param tcToken token for subscription, use if present
644
+ */
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
+ };
662
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
663
+ let presence;
664
+ const jid = attrs.from;
665
+ const participant = attrs.participant || attrs.from;
666
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
667
+ return;
668
+ }
669
+ if (tag === 'presence') {
670
+ presence = {
671
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
672
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
673
+ groupOnlineCount: attrs.count ? +attrs.count : undefined
674
+ };
675
+ }
676
+ else if (Array.isArray(content)) {
677
+ const [firstChild] = content;
678
+ let type = firstChild.tag;
679
+ if (type === 'paused') {
680
+ type = 'available';
681
+ }
682
+ if (firstChild.attrs?.media === 'audio') {
683
+ type = 'recording';
684
+ }
685
+ presence = { lastKnownPresence: type };
686
+ }
687
+ else {
688
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
689
+ }
690
+ if (presence) {
691
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
692
+ }
693
+ };
694
+ const appPatch = async (patchCreate) => {
695
+ const name = patchCreate.type;
696
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
697
+ if (!myAppStateKeyId) {
698
+ throw new Boom('App state key not present!', { statusCode: 400 });
699
+ }
700
+ let initial;
701
+ let encodeResult;
702
+ await appStatePatchMutex.mutex(async () => {
703
+ await authState.keys.transaction(async () => {
704
+ logger.debug({ patch: patchCreate }, 'applying app patch');
705
+ await resyncAppState([name], false);
706
+ 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);
709
+ const { patch, state } = encodeResult;
710
+ const node = {
711
+ tag: 'iq',
712
+ attrs: {
713
+ to: S_WHATSAPP_NET,
714
+ type: 'set',
715
+ xmlns: 'w:sync:app:state'
716
+ },
717
+ content: [
718
+ {
719
+ tag: 'sync',
720
+ attrs: {},
721
+ content: [
722
+ {
723
+ tag: 'collection',
724
+ attrs: {
725
+ name,
726
+ version: (state.version - 1).toString(),
727
+ return_snapshot: 'false'
728
+ },
729
+ content: [
730
+ {
731
+ tag: 'patch',
732
+ attrs: {},
733
+ content: proto.SyncdPatch.encode(patch).finish()
734
+ }
735
+ ]
736
+ }
737
+ ]
738
+ }
739
+ ]
740
+ };
741
+ await query(node);
742
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
743
+ }, authState?.creds?.me?.id || 'app-patch');
744
+ });
745
+ if (config.emitOwnEvents) {
746
+ const { onMutation } = newAppStateChunkHandler(false);
747
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
748
+ for (const key in mutationMap) {
749
+ onMutation(mutationMap[key]);
750
+ }
751
+ }
752
+ };
753
+ /** fetch AB props */
754
+ const fetchProps = async () => {
755
+ const resultNode = await query({
756
+ tag: 'iq',
757
+ attrs: {
758
+ to: S_WHATSAPP_NET,
759
+ xmlns: 'abt',
760
+ type: 'get'
761
+ },
762
+ content: [
763
+ {
764
+ tag: 'props',
765
+ attrs: {
766
+ protocol: '1',
767
+ ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
768
+ }
769
+ }
770
+ ]
771
+ });
772
+ const propsNode = getBinaryNodeChild(resultNode, 'props');
773
+ let props = {};
774
+ if (propsNode) {
775
+ if (propsNode.attrs?.hash) {
776
+ // on some clients, the hash is returning as undefined
777
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
778
+ ev.emit('creds.update', authState.creds);
779
+ }
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';
790
+ }
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');
796
+ return props;
797
+ };
798
+ /**
799
+ * modify a chat -- mark unread, read etc.
800
+ * lastMessages must be sorted in reverse chronologically
801
+ * requires the last messages till the last message received; required for archive & unread
802
+ */
803
+ const chatModify = (mod, jid) => {
804
+ const patch = chatModificationToAppPatch(mod, jid);
805
+ return appPatch(patch);
806
+ };
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
+ /**
816
+ * Star or Unstar a message
817
+ */
818
+ const star = (jid, messages, star) => {
819
+ return chatModify({
820
+ star: {
821
+ messages,
822
+ star
823
+ }
824
+ }, jid);
825
+ };
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
+ /**
843
+ * Adds label
844
+ */
845
+ const addLabel = (jid, labels) => {
846
+ return chatModify({
847
+ addLabel: {
848
+ ...labels
849
+ }
850
+ }, jid);
851
+ };
852
+ /**
853
+ * Adds label for the chats
854
+ */
855
+ const addChatLabel = (jid, labelId) => {
856
+ return chatModify({
857
+ addChatLabel: {
858
+ labelId
859
+ }
860
+ }, jid);
861
+ };
862
+ /**
863
+ * Removes label for the chat
864
+ */
865
+ const removeChatLabel = (jid, labelId) => {
866
+ return chatModify({
867
+ removeChatLabel: {
868
+ labelId
869
+ }
870
+ }, jid);
871
+ };
872
+ /**
873
+ * Adds label for the message
874
+ */
875
+ const addMessageLabel = (jid, messageId, labelId) => {
876
+ return chatModify({
877
+ addMessageLabel: {
878
+ messageId,
879
+ labelId
880
+ }
881
+ }, jid);
882
+ };
883
+ /**
884
+ * Removes label for the message
885
+ */
886
+ const removeMessageLabel = (jid, messageId, labelId) => {
887
+ return chatModify({
888
+ removeMessageLabel: {
889
+ messageId,
890
+ labelId
891
+ }
892
+ }, jid);
893
+ };
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
+ /**
911
+ * queries need to be fired on connection open
912
+ * help ensure parity with WA Web
913
+ * */
914
+ const executeInitQueries = async () => {
915
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
916
+ };
917
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
918
+ ev.emit('messages.upsert', { messages: [msg], type });
919
+ if (!!msg.pushName) {
920
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
921
+ jid = jidNormalizedUser(jid);
922
+ if (!msg.key.fromMe) {
923
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
924
+ }
925
+ // update our pushname too
926
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
927
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
928
+ }
929
+ }
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
+ }
992
+ }
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
+ await Promise.all([
1008
+ (async () => {
1009
+ if (shouldProcessHistoryMsg) {
1010
+ await doAppStateSync();
1011
+ }
1012
+ })(),
1013
+ processMessage(msg, {
1014
+ signalRepository,
1015
+ shouldProcessHistoryMsg,
1016
+ placeholderResendCache,
1017
+ ev,
1018
+ creds: authState.creds,
1019
+ keyStore: authState.keys,
1020
+ logger,
1021
+ options: config.options,
1022
+ getMessage
1023
+ })
1024
+ ]);
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');
1028
+ await doAppStateSync();
1029
+ }
1030
+ });
1031
+ ws.on('CB:presence', handlePresenceUpdate);
1032
+ ws.on('CB:chatstate', handlePresenceUpdate);
1033
+ ws.on('CB:ib,,dirty', async (node) => {
1034
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
1035
+ const type = attrs.type;
1036
+ switch (type) {
1037
+ case 'account_sync':
1038
+ if (attrs.timestamp) {
1039
+ let { lastAccountSyncTimestamp } = authState.creds;
1040
+ if (lastAccountSyncTimestamp) {
1041
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
1042
+ }
1043
+ lastAccountSyncTimestamp = +attrs.timestamp;
1044
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
1045
+ }
1046
+ break;
1047
+ case 'groups':
1048
+ // handled in groups.ts
1049
+ break;
1050
+ default:
1051
+ logger.info({ node }, 'received unknown sync');
1052
+ break;
1053
+ }
1054
+ });
1055
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1056
+ if (connection === 'close') {
1057
+ blockedCollections.clear();
1058
+ clearTimeout(historySyncPausedTimeout);
1059
+ historySyncPausedTimeout = undefined;
1060
+ }
1061
+ if (connection === 'open') {
1062
+ if (fireInitQueries) {
1063
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
1064
+ }
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;
1141
+ }
1142
+ if (!config.placeholderResendCache && placeholderResendCache.close) {
1143
+ placeholderResendCache.close();
1144
+ }
1145
+ syncState = SyncState.Connecting;
1146
+ privacySettings = undefined;
1147
+ });
1148
+ return {
1149
+ ...sock,
1150
+ serverProps,
1151
+ createCallLink,
1152
+ getBotListV2,
1153
+ messageMutex,
1154
+ receiptMutex,
1155
+ appStatePatchMutex,
1156
+ notificationMutex,
1157
+ fetchPrivacySettings,
1158
+ upsertMessage,
1159
+ appPatch,
1160
+ sendPresenceUpdate,
1161
+ presenceSubscribe,
1162
+ profilePictureUrl,
1163
+ fetchBlocklist,
1164
+ fetchStatus,
1165
+ fetchDisappearingDuration,
1166
+ updateProfilePicture,
1167
+ removeProfilePicture,
1168
+ updateProfileStatus,
1169
+ updateProfileName,
1170
+ updateBlockStatus,
1171
+ updateDisableLinkPreviewsPrivacy,
1172
+ updateCallPrivacy,
1173
+ updateMessagesPrivacy,
1174
+ updateLastSeenPrivacy,
1175
+ updateOnlinePrivacy,
1176
+ updateProfilePicturePrivacy,
1177
+ updateStatusPrivacy,
1178
+ updateReadReceiptsPrivacy,
1179
+ updateGroupsAddPrivacy,
1180
+ updateDefaultDisappearingMode,
1181
+ getBusinessProfile,
1182
+ resyncAppState,
1183
+ chatModify,
1184
+ cleanDirtyBits,
1185
+ addOrEditContact,
1186
+ removeContact,
1187
+ placeholderResendCache,
1188
+ addLabel,
1189
+ addChatLabel,
1190
+ removeChatLabel,
1191
+ addMessageLabel,
1192
+ removeMessageLabel,
1193
+ star,
1194
+ addOrEditQuickReply,
1195
+ removeQuickReply
1196
+ };
1197
+ };
1198
+ //# sourceMappingURL=chats.js.map