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