xspacesocket 0.0.0-stage → 1.3.1

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