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