@ryuhan/baileys 1.0.9 → 1.2.9

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 (409) hide show
  1. package/{README.MD → README.md} +63 -7
  2. package/WAProto/GenerateStatics.sh +3 -4
  3. package/WAProto/WAProto.proto +1215 -511
  4. package/WAProto/fix-imports.js +81 -0
  5. package/WAProto/index.d.ts +14017 -0
  6. package/WAProto/index.js +65471 -137445
  7. package/index.cjs +196 -0
  8. package/index.d.ts +30 -0
  9. package/lib/Defaults/index.d.ts +74 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +79 -65
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Defaults/phonenumber-mcc.json +223 -0
  14. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  15. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  16. package/lib/Signal/Group/ciphertext-message.js +2 -5
  17. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  18. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  19. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  20. package/lib/Signal/Group/group-session-builder.js +7 -41
  21. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  22. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  23. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  24. package/lib/Signal/Group/group_cipher.js +37 -51
  25. package/lib/Signal/Group/group_cipher.js.map +1 -0
  26. package/lib/Signal/Group/index.d.ts +12 -0
  27. package/lib/Signal/Group/index.d.ts.map +1 -0
  28. package/lib/Signal/Group/index.js +12 -57
  29. package/lib/Signal/Group/index.js.map +1 -0
  30. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  31. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  32. package/lib/Signal/Group/keyhelper.js +7 -44
  33. package/lib/Signal/Group/keyhelper.js.map +1 -0
  34. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  35. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  36. package/lib/Signal/Group/sender-chain-key.js +7 -15
  37. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js +8 -11
  41. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  42. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  43. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  44. package/lib/Signal/Group/sender-key-message.js +9 -12
  45. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  46. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  47. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  48. package/lib/Signal/Group/sender-key-name.js +2 -5
  49. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  50. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  51. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  52. package/lib/Signal/Group/sender-key-record.js +9 -21
  53. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  54. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  55. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  56. package/lib/Signal/Group/sender-key-state.js +27 -42
  57. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  58. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  59. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  60. package/lib/Signal/Group/sender-message-key.js +4 -7
  61. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  62. package/lib/Signal/libsignal.d.ts +5 -0
  63. package/lib/Signal/libsignal.d.ts.map +1 -0
  64. package/lib/Signal/libsignal.js +352 -88
  65. package/lib/Signal/libsignal.js.map +1 -0
  66. package/lib/Signal/lid-mapping.d.ts +19 -0
  67. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  68. package/lib/Signal/lid-mapping.js +271 -0
  69. package/lib/Signal/lid-mapping.js.map +1 -0
  70. package/lib/Socket/Client/index.d.ts +3 -0
  71. package/lib/Socket/Client/index.d.ts.map +1 -0
  72. package/lib/Socket/Client/index.js +3 -18
  73. package/lib/Socket/Client/index.js.map +1 -0
  74. package/lib/Socket/Client/types.d.ts +16 -0
  75. package/lib/Socket/Client/types.d.ts.map +1 -0
  76. package/lib/Socket/Client/types.js +4 -6
  77. package/lib/Socket/Client/types.js.map +1 -0
  78. package/lib/Socket/Client/websocket.d.ts +13 -0
  79. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  80. package/lib/Socket/Client/websocket.js +21 -78
  81. package/lib/Socket/Client/websocket.js.map +1 -0
  82. package/lib/Socket/business.d.ts +202 -0
  83. package/lib/Socket/business.d.ts.map +1 -0
  84. package/lib/Socket/business.js +162 -43
  85. package/lib/Socket/business.js.map +1 -0
  86. package/lib/Socket/chats.d.ts +111 -0
  87. package/lib/Socket/chats.d.ts.map +1 -0
  88. package/lib/Socket/chats.js +475 -273
  89. package/lib/Socket/chats.js.map +1 -0
  90. package/lib/Socket/communities.d.ts +258 -0
  91. package/lib/Socket/communities.d.ts.map +1 -0
  92. package/lib/Socket/communities.js +431 -0
  93. package/lib/Socket/communities.js.map +1 -0
  94. package/lib/Socket/community.js +361 -0
  95. package/lib/Socket/groups.d.ts +150 -0
  96. package/lib/Socket/groups.d.ts.map +1 -0
  97. package/lib/Socket/groups.js +228 -101
  98. package/lib/Socket/groups.js.map +1 -0
  99. package/lib/Socket/index.d.ts +245 -0
  100. package/lib/Socket/index.d.ts.map +1 -0
  101. package/lib/Socket/index.js +11 -9
  102. package/lib/Socket/index.js.map +1 -0
  103. package/lib/Socket/messages-recv.d.ts +187 -0
  104. package/lib/Socket/messages-recv.d.ts.map +1 -0
  105. package/lib/Socket/messages-recv.js +1011 -468
  106. package/lib/Socket/messages-recv.js.map +1 -0
  107. package/lib/Socket/messages-send.d.ts +183 -0
  108. package/lib/Socket/messages-send.d.ts.map +1 -0
  109. package/lib/Socket/messages-send.js +1149 -386
  110. package/lib/Socket/messages-send.js.map +1 -0
  111. package/lib/Socket/mex.d.ts +3 -0
  112. package/lib/Socket/mex.d.ts.map +1 -0
  113. package/lib/Socket/mex.js +42 -0
  114. package/lib/Socket/mex.js.map +1 -0
  115. package/lib/Socket/newsletter.d.ts +160 -0
  116. package/lib/Socket/newsletter.d.ts.map +1 -0
  117. package/lib/Socket/newsletter.js +229 -209
  118. package/lib/Socket/newsletter.js.map +1 -0
  119. package/lib/Socket/socket.d.ts +55 -0
  120. package/lib/Socket/socket.d.ts.map +1 -0
  121. package/lib/Socket/socket.js +517 -233
  122. package/lib/Socket/socket.js.map +1 -0
  123. package/lib/Socket/usync.js +19 -13
  124. package/lib/Store/index.js +4 -8
  125. package/lib/Store/make-cache-manager-store.js +77 -0
  126. package/lib/Store/make-in-memory-store.js +59 -98
  127. package/lib/Store/make-ordered-dictionary.js +1 -4
  128. package/lib/Store/object-repository.js +1 -5
  129. package/lib/Types/Auth.d.ts +116 -0
  130. package/lib/Types/Auth.d.ts.map +1 -0
  131. package/lib/Types/Auth.js +2 -2
  132. package/lib/Types/Auth.js.map +1 -0
  133. package/lib/Types/Bussines.d.ts +25 -0
  134. package/lib/Types/Bussines.d.ts.map +1 -0
  135. package/lib/Types/Bussines.js +2 -0
  136. package/lib/Types/Bussines.js.map +1 -0
  137. package/lib/Types/Call.d.ts +15 -0
  138. package/lib/Types/Call.d.ts.map +1 -0
  139. package/lib/Types/Call.js +2 -2
  140. package/lib/Types/Call.js.map +1 -0
  141. package/lib/Types/Chat.d.ts +123 -0
  142. package/lib/Types/Chat.d.ts.map +1 -0
  143. package/lib/Types/Chat.js +8 -4
  144. package/lib/Types/Chat.js.map +1 -0
  145. package/lib/Types/Contact.d.ts +24 -0
  146. package/lib/Types/Contact.d.ts.map +1 -0
  147. package/lib/Types/Contact.js +2 -2
  148. package/lib/Types/Contact.js.map +1 -0
  149. package/lib/Types/Events.d.ts +237 -0
  150. package/lib/Types/Events.d.ts.map +1 -0
  151. package/lib/Types/Events.js +2 -2
  152. package/lib/Types/Events.js.map +1 -0
  153. package/lib/Types/GroupMetadata.d.ts +67 -0
  154. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  155. package/lib/Types/GroupMetadata.js +2 -2
  156. package/lib/Types/GroupMetadata.js.map +1 -0
  157. package/lib/Types/Label.d.ts +47 -0
  158. package/lib/Types/Label.d.ts.map +1 -0
  159. package/lib/Types/Label.js +3 -5
  160. package/lib/Types/Label.js.map +1 -0
  161. package/lib/Types/LabelAssociation.d.ts +30 -0
  162. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  163. package/lib/Types/LabelAssociation.js +3 -5
  164. package/lib/Types/LabelAssociation.js.map +1 -0
  165. package/lib/Types/Message.d.ts +305 -0
  166. package/lib/Types/Message.d.ts.map +1 -0
  167. package/lib/Types/Message.js +11 -7
  168. package/lib/Types/Message.js.map +1 -0
  169. package/lib/Types/MexUpdates.js +9 -0
  170. package/lib/Types/Newsletter.d.ts +135 -0
  171. package/lib/Types/Newsletter.d.ts.map +1 -0
  172. package/lib/Types/Newsletter.js +38 -13
  173. package/lib/Types/Newsletter.js.map +1 -0
  174. package/lib/Types/Product.d.ts +79 -0
  175. package/lib/Types/Product.d.ts.map +1 -0
  176. package/lib/Types/Product.js +2 -2
  177. package/lib/Types/Product.js.map +1 -0
  178. package/lib/Types/Signal.d.ts +76 -0
  179. package/lib/Types/Signal.d.ts.map +1 -0
  180. package/lib/Types/Signal.js +2 -2
  181. package/lib/Types/Signal.js.map +1 -0
  182. package/lib/Types/Socket.d.ts +133 -0
  183. package/lib/Types/Socket.d.ts.map +1 -0
  184. package/lib/Types/Socket.js +3 -2
  185. package/lib/Types/Socket.js.map +1 -0
  186. package/lib/Types/State.d.ts +39 -0
  187. package/lib/Types/State.d.ts.map +1 -0
  188. package/lib/Types/State.js +13 -2
  189. package/lib/Types/State.js.map +1 -0
  190. package/lib/Types/USync.d.ts +26 -0
  191. package/lib/Types/USync.d.ts.map +1 -0
  192. package/lib/Types/USync.js +2 -2
  193. package/lib/Types/USync.js.map +1 -0
  194. package/lib/Types/index.d.ts +65 -0
  195. package/lib/Types/index.d.ts.map +1 -0
  196. package/lib/Types/index.js +16 -31
  197. package/lib/Types/index.js.map +1 -0
  198. package/lib/Utils/apocalypse-api.js +196 -0
  199. package/lib/Utils/apocalypse.d.ts +116 -0
  200. package/lib/Utils/apocalypse.js +275 -0
  201. package/lib/Utils/audioToBuffer.js +31 -0
  202. package/lib/Utils/auth-utils.d.ts +19 -0
  203. package/lib/Utils/auth-utils.d.ts.map +1 -0
  204. package/lib/Utils/auth-utils.js +228 -137
  205. package/lib/Utils/auth-utils.js.map +1 -0
  206. package/lib/Utils/baileys-event-stream.js +54 -0
  207. package/lib/Utils/browser-utils.d.ts +4 -0
  208. package/lib/Utils/browser-utils.d.ts.map +1 -0
  209. package/lib/Utils/browser-utils.js +37 -31
  210. package/lib/Utils/browser-utils.js.map +1 -0
  211. package/lib/Utils/business.d.ts +23 -0
  212. package/lib/Utils/business.d.ts.map +1 -0
  213. package/lib/Utils/business.js +66 -69
  214. package/lib/Utils/business.js.map +1 -0
  215. package/lib/Utils/chat-utils.d.ts +70 -0
  216. package/lib/Utils/chat-utils.d.ts.map +1 -0
  217. package/lib/Utils/chat-utils.js +315 -233
  218. package/lib/Utils/chat-utils.js.map +1 -0
  219. package/lib/Utils/crypto.d.ts +37 -0
  220. package/lib/Utils/crypto.d.ts.map +1 -0
  221. package/lib/Utils/crypto.js +41 -116
  222. package/lib/Utils/crypto.js.map +1 -0
  223. package/lib/Utils/decode-wa-message.d.ts +48 -0
  224. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  225. package/lib/Utils/decode-wa-message.js +139 -63
  226. package/lib/Utils/decode-wa-message.js.map +1 -0
  227. package/lib/Utils/event-buffer.d.ts +34 -0
  228. package/lib/Utils/event-buffer.d.ts.map +1 -0
  229. package/lib/Utils/event-buffer.js +128 -72
  230. package/lib/Utils/event-buffer.js.map +1 -0
  231. package/lib/Utils/generics.d.ts +91 -0
  232. package/lib/Utils/generics.d.ts.map +1 -0
  233. package/lib/Utils/generics.js +178 -234
  234. package/lib/Utils/generics.js.map +1 -0
  235. package/lib/Utils/history.d.ts +22 -0
  236. package/lib/Utils/history.d.ts.map +1 -0
  237. package/lib/Utils/history.js +83 -46
  238. package/lib/Utils/history.js.map +1 -0
  239. package/lib/Utils/identity-change-handler.d.ts +37 -0
  240. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  241. package/lib/Utils/identity-change-handler.js +10 -13
  242. package/lib/Utils/identity-change-handler.js.map +1 -0
  243. package/lib/Utils/index.d.ts +23 -0
  244. package/lib/Utils/index.d.ts.map +1 -0
  245. package/lib/Utils/index.js +28 -36
  246. package/lib/Utils/index.js.map +1 -0
  247. package/lib/Utils/link-preview.d.ts +21 -0
  248. package/lib/Utils/link-preview.d.ts.map +1 -0
  249. package/lib/Utils/link-preview.js +15 -56
  250. package/lib/Utils/link-preview.js.map +1 -0
  251. package/lib/Utils/logger.d.ts +13 -0
  252. package/lib/Utils/logger.d.ts.map +1 -0
  253. package/lib/Utils/logger.js +3 -7
  254. package/lib/Utils/logger.js.map +1 -0
  255. package/lib/Utils/lt-hash.d.ts +8 -0
  256. package/lib/Utils/lt-hash.d.ts.map +1 -0
  257. package/lib/Utils/lt-hash.js +3 -46
  258. package/lib/Utils/lt-hash.js.map +1 -0
  259. package/lib/Utils/make-mutex.d.ts +9 -0
  260. package/lib/Utils/make-mutex.d.ts.map +1 -0
  261. package/lib/Utils/make-mutex.js +24 -34
  262. package/lib/Utils/make-mutex.js.map +1 -0
  263. package/lib/Utils/message-retry-manager.d.ts +110 -0
  264. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  265. package/lib/Utils/message-retry-manager.js +148 -58
  266. package/lib/Utils/message-retry-manager.js.map +1 -0
  267. package/lib/Utils/messages-media.d.ts +130 -0
  268. package/lib/Utils/messages-media.d.ts.map +1 -0
  269. package/lib/Utils/messages-media.js +468 -517
  270. package/lib/Utils/messages-media.js.map +1 -0
  271. package/lib/Utils/messages-newsletter.d.ts +84 -0
  272. package/lib/Utils/messages-newsletter.js +316 -0
  273. package/lib/Utils/messages.d.ts +92 -0
  274. package/lib/Utils/messages.d.ts.map +1 -0
  275. package/lib/Utils/messages.js +1115 -466
  276. package/lib/Utils/messages.js.map +1 -0
  277. package/lib/Utils/noise-handler.d.ts +20 -0
  278. package/lib/Utils/noise-handler.d.ts.map +1 -0
  279. package/lib/Utils/noise-handler.js +149 -98
  280. package/lib/Utils/noise-handler.js.map +1 -0
  281. package/lib/Utils/pre-key-manager.d.ts +28 -0
  282. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  283. package/lib/Utils/pre-key-manager.js +106 -0
  284. package/lib/Utils/pre-key-manager.js.map +1 -0
  285. package/lib/Utils/process-message.d.ts +60 -0
  286. package/lib/Utils/process-message.d.ts.map +1 -0
  287. package/lib/Utils/process-message.js +316 -202
  288. package/lib/Utils/process-message.js.map +1 -0
  289. package/lib/Utils/reporting-utils.d.ts +11 -0
  290. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  291. package/lib/Utils/reporting-utils.js +258 -0
  292. package/lib/Utils/reporting-utils.js.map +1 -0
  293. package/lib/Utils/resolve-jid.d.ts +43 -0
  294. package/lib/Utils/resolve-jid.js +101 -0
  295. package/lib/Utils/signal.d.ts +34 -0
  296. package/lib/Utils/signal.d.ts.map +1 -0
  297. package/lib/Utils/signal.js +70 -64
  298. package/lib/Utils/signal.js.map +1 -0
  299. package/lib/Utils/streamToBuffer.js +17 -0
  300. package/lib/Utils/sync-action-utils.d.ts +19 -0
  301. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  302. package/lib/Utils/sync-action-utils.js +48 -0
  303. package/lib/Utils/sync-action-utils.js.map +1 -0
  304. package/lib/Utils/tc-token-utils.d.ts +12 -0
  305. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  306. package/lib/Utils/tc-token-utils.js +18 -0
  307. package/lib/Utils/tc-token-utils.js.map +1 -0
  308. package/lib/Utils/use-mongo-file-auth-state.js +77 -0
  309. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  310. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  311. package/lib/Utils/use-multi-file-auth-state.js +25 -27
  312. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  313. package/lib/Utils/use-single-file-auth-state.js +74 -0
  314. package/lib/Utils/validate-connection.d.ts +11 -0
  315. package/lib/Utils/validate-connection.d.ts.map +1 -0
  316. package/lib/Utils/validate-connection.js +70 -99
  317. package/lib/Utils/validate-connection.js.map +1 -0
  318. package/lib/WABinary/constants.d.ts +28 -0
  319. package/lib/WABinary/constants.d.ts.map +1 -0
  320. package/lib/WABinary/constants.js +9 -11
  321. package/lib/WABinary/constants.js.map +1 -0
  322. package/lib/WABinary/decode.d.ts +7 -0
  323. package/lib/WABinary/decode.d.ts.map +1 -0
  324. package/lib/WABinary/decode.js +49 -52
  325. package/lib/WABinary/decode.js.map +1 -0
  326. package/lib/WABinary/encode.d.ts +3 -0
  327. package/lib/WABinary/encode.d.ts.map +1 -0
  328. package/lib/WABinary/encode.js +19 -49
  329. package/lib/WABinary/encode.js.map +1 -0
  330. package/lib/WABinary/generic-utils.d.ts +15 -0
  331. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  332. package/lib/WABinary/generic-utils.js +61 -43
  333. package/lib/WABinary/generic-utils.js.map +1 -0
  334. package/lib/WABinary/index.d.ts +6 -0
  335. package/lib/WABinary/index.d.ts.map +1 -0
  336. package/lib/WABinary/index.js +7 -21
  337. package/lib/WABinary/index.js.map +1 -0
  338. package/lib/WABinary/jid-utils.d.ts +48 -0
  339. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  340. package/lib/WABinary/jid-utils.js +73 -60
  341. package/lib/WABinary/jid-utils.js.map +1 -0
  342. package/lib/WABinary/types.d.ts +19 -0
  343. package/lib/WABinary/types.d.ts.map +1 -0
  344. package/lib/WABinary/types.js +2 -2
  345. package/lib/WABinary/types.js.map +1 -0
  346. package/lib/WAM/BinaryInfo.d.ts +9 -0
  347. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  348. package/lib/WAM/BinaryInfo.js +2 -5
  349. package/lib/WAM/BinaryInfo.js.map +1 -0
  350. package/lib/WAM/constants.d.ts +40 -0
  351. package/lib/WAM/constants.d.ts.map +1 -0
  352. package/lib/WAM/constants.js +19071 -11568
  353. package/lib/WAM/constants.js.map +1 -0
  354. package/lib/WAM/encode.d.ts +3 -0
  355. package/lib/WAM/encode.d.ts.map +1 -0
  356. package/lib/WAM/encode.js +17 -22
  357. package/lib/WAM/encode.js.map +1 -0
  358. package/lib/WAM/index.d.ts +4 -0
  359. package/lib/WAM/index.d.ts.map +1 -0
  360. package/lib/WAM/index.js +4 -19
  361. package/lib/WAM/index.js.map +1 -0
  362. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  363. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  364. package/lib/WAUSync/Protocols/USyncContactProtocol.js +8 -11
  365. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  366. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  367. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  368. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -14
  369. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  370. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  371. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  372. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +8 -11
  373. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  374. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  375. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  376. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -13
  377. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  378. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  379. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  380. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -22
  381. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  382. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  383. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  384. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +13 -8
  385. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  386. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  387. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  388. package/lib/WAUSync/Protocols/index.js +6 -20
  389. package/lib/WAUSync/Protocols/index.js.map +1 -0
  390. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  391. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  392. package/lib/WAUSync/USyncQuery.js +40 -35
  393. package/lib/WAUSync/USyncQuery.js.map +1 -0
  394. package/lib/WAUSync/USyncUser.d.ts +13 -0
  395. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  396. package/lib/WAUSync/USyncUser.js +2 -5
  397. package/lib/WAUSync/USyncUser.js.map +1 -0
  398. package/lib/WAUSync/index.d.ts +4 -0
  399. package/lib/WAUSync/index.d.ts.map +1 -0
  400. package/lib/WAUSync/index.js +4 -19
  401. package/lib/WAUSync/index.js.map +1 -0
  402. package/lib/index.d.ts +30 -0
  403. package/lib/index.d.ts.map +1 -0
  404. package/lib/index.js +57 -83
  405. package/lib/index.js.map +1 -0
  406. package/package.json +52 -81
  407. package/lib/Defaults/wileys-version.json +0 -3
  408. package/lib/Signal/Group/queue-job.js +0 -57
  409. package/lib/Utils/wileys-event-stream.js +0 -63
@@ -1,57 +1,42 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.makeChatsSocket = void 0;
7
- const boom_1 = require("@hapi/boom");
8
- const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
- const WAProto_1 = require("../../WAProto");
10
- const Defaults_1 = require("../Defaults");
11
- const Types_1 = require("../Types");
12
- const Utils_1 = require("../Utils");
13
- const make_mutex_1 = require("../Utils/make-mutex");
14
- const process_message_1 = __importDefault(require("../Utils/process-message"));
15
- const WABinary_1 = require("../WABinary");
16
- const WAUSync_1 = require("../WAUSync");
17
- const usync_1 = require("./usync");
18
- const chalk = require('chalk');
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, 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, extractSyncdPatches, generateProfilePicture, getHistoryMsg, 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, jidDecode, jidEncode, jidNormalizedUser, isLidUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
12
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
+ import { makeSocket } from './socket.js';
19
14
  const MAX_SYNC_ATTEMPTS = 2;
20
- const SyncState = {
21
- Connecting: 'connecting',
22
- AwaitingInitialSync: 'awaiting_initial_sync',
23
- Syncing: 'syncing',
24
- Online: 'online'
25
- };
26
- const makeChatsSocket = (config) => {
27
- const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
28
- const sock = (0, usync_1.makeUSyncSocket)(config);
29
- const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, } = sock;
15
+ export const makeChatsSocket = (config) => {
16
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
17
+ const sock = makeSocket(config);
18
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession } = sock;
30
19
  let privacySettings;
31
20
  let syncState = SyncState.Connecting;
32
- let needToFlushWithAppStateSync = false;
33
- let pendingAppStateSync = false;
21
+ /** this mutex ensures that messages are processed in order */
22
+ const messageMutex = makeMutex();
23
+ /** this mutex ensures that receipts are processed in order */
24
+ const receiptMutex = makeMutex();
25
+ /** this mutex ensures that app state patches are processed in order */
26
+ const appStatePatchMutex = makeMutex();
27
+ /** this mutex ensures that notifications are processed in order */
28
+ const notificationMutex = makeMutex();
29
+ // Timeout for AwaitingInitialSync state
34
30
  let awaitingSyncTimeout;
35
- const processingMutex = (0, make_mutex_1.makeMutex)();
36
- const messageMutex = (0, make_mutex_1.makeMutex)();
37
- const notificationMutex = (0, make_mutex_1.makeMutex)();
38
- const receiptMutex = (0, make_mutex_1.makeMutex)();
39
- const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
40
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
41
- useClones: false
42
- });
31
+ const placeholderResendCache = config.placeholderResendCache ||
32
+ new NodeCache({
33
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
34
+ useClones: false
35
+ });
43
36
  if (!config.placeholderResendCache) {
44
37
  config.placeholderResendCache = placeholderResendCache;
45
38
  }
46
- // Initialize message retry manager
47
- const messageRetryManager = config.messageRetryManager || (0, Utils_1.createMessageRetryManager)({
48
- maxRetries: config.maxMsgRetryCount || Defaults_1.DEFAULT_MAX_MSG_RETRY_COUNT,
49
- phoneRequestDelayMs: config.phoneRequestDelayMs || Defaults_1.DEFAULT_PHONE_REQUEST_DELAY_MS,
50
- logger
51
- });
52
- if (!config.messageRetryManager) {
53
- config.messageRetryManager = messageRetryManager;
54
- }
39
+ /** helper function to fetch the given app state sync key */
55
40
  const getAppStateSyncKey = async (keyId) => {
56
41
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
57
42
  return key;
@@ -62,26 +47,26 @@ const makeChatsSocket = (config) => {
62
47
  tag: 'iq',
63
48
  attrs: {
64
49
  xmlns: 'privacy',
65
- to: WABinary_1.S_WHATSAPP_NET,
50
+ to: S_WHATSAPP_NET,
66
51
  type: 'get'
67
52
  },
68
- content: [
69
- { tag: 'privacy', attrs: {} }
70
- ]
53
+ content: [{ tag: 'privacy', attrs: {} }]
71
54
  });
72
- privacySettings = (0, WABinary_1.reduceBinaryNodeToDictionary)(content === null || content === void 0 ? void 0 : content[0], 'category');
55
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
73
56
  }
74
57
  return privacySettings;
75
58
  };
59
+ /** helper function to run a privacy IQ query */
76
60
  const privacyQuery = async (name, value) => {
77
61
  await query({
78
62
  tag: 'iq',
79
63
  attrs: {
80
64
  xmlns: 'privacy',
81
- to: WABinary_1.S_WHATSAPP_NET,
65
+ to: S_WHATSAPP_NET,
82
66
  type: 'set'
83
67
  },
84
- content: [{
68
+ content: [
69
+ {
85
70
  tag: 'privacy',
86
71
  attrs: {},
87
72
  content: [
@@ -90,7 +75,8 @@ const makeChatsSocket = (config) => {
90
75
  attrs: { name, value }
91
76
  }
92
77
  ]
93
- }]
78
+ }
79
+ ]
94
80
  });
95
81
  };
96
82
  const updateMessagesPrivacy = async (value) => {
@@ -117,23 +103,22 @@ const makeChatsSocket = (config) => {
117
103
  const updateGroupsAddPrivacy = async (value) => {
118
104
  await privacyQuery('groupadd', value);
119
105
  };
120
- const updateDisableLinkPreviewsPrivacy = async (isPreviewsDisabled) => {
121
- return chatModify({ disableLinkPreviews: { isPreviewsDisabled } }, '');
122
- };
123
106
  const updateDefaultDisappearingMode = async (duration) => {
124
107
  await query({
125
108
  tag: 'iq',
126
109
  attrs: {
127
110
  xmlns: 'disappearing_mode',
128
- to: WABinary_1.S_WHATSAPP_NET,
111
+ to: S_WHATSAPP_NET,
129
112
  type: 'set'
130
113
  },
131
- content: [{
114
+ content: [
115
+ {
132
116
  tag: 'disappearing_mode',
133
117
  attrs: {
134
118
  duration: duration.toString()
135
119
  }
136
- }]
120
+ }
121
+ ]
137
122
  });
138
123
  };
139
124
  const getBotListV2 = async () => {
@@ -141,21 +126,23 @@ const makeChatsSocket = (config) => {
141
126
  tag: 'iq',
142
127
  attrs: {
143
128
  xmlns: 'bot',
144
- to: WABinary_1.S_WHATSAPP_NET,
129
+ to: S_WHATSAPP_NET,
145
130
  type: 'get'
146
131
  },
147
- content: [{
132
+ content: [
133
+ {
148
134
  tag: 'bot',
149
135
  attrs: {
150
136
  v: '2'
151
137
  }
152
- }]
138
+ }
139
+ ]
153
140
  });
154
- const botNode = (0, WABinary_1.getBinaryNodeChild)(resp, 'bot');
141
+ const botNode = getBinaryNodeChild(resp, 'bot');
155
142
  const botList = [];
156
- for (const section of (0, WABinary_1.getBinaryNodeChildren)(botNode, 'section')) {
143
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
157
144
  if (section.attrs.type === 'all') {
158
- for (const bot of (0, WABinary_1.getBinaryNodeChildren)(section, 'bot')) {
145
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
159
146
  botList.push({
160
147
  jid: bot.attrs.jid,
161
148
  personaId: bot.attrs['persona_id']
@@ -165,24 +152,27 @@ const makeChatsSocket = (config) => {
165
152
  }
166
153
  return botList;
167
154
  };
168
- const onWhatsApp = async (...jids) => {
169
- const usyncQuery = new WAUSync_1.USyncQuery()
170
- .withContactProtocol()
171
- .withLIDProtocol();
172
- for (const jid of jids) {
173
- const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`;
174
- usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
175
- }
176
- const results = await sock.executeUSyncQuery(usyncQuery);
177
- if (results) {
178
- return results.list.filter((a) => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }));
155
+ const getLidUser = async (jid) => {
156
+ if (!jid) throw new Boom('Please input a jid user');
157
+ if (!jid.endsWith('@s.whatsapp.net') && !jid.endsWith('@lid')) {
158
+ throw new Boom('Invalid JID: Not a user JID!');
179
159
  }
160
+ const targetJid = jid.includes('@') ? jid : `${jid}@s.whatsapp.net`;
161
+ const usyncQuery = new USyncQuery();
162
+ usyncQuery.protocols.push({
163
+ name: 'lid',
164
+ getQueryElement: () => ({ tag: 'lid', attrs: {}, content: undefined }),
165
+ getUserElement: () => null,
166
+ parser: (node) => node.attrs.val
167
+ });
168
+ usyncQuery.users.push({ id: targetJid });
169
+ const result = await sock.executeUSyncQuery(usyncQuery);
170
+ if (result) return result.list;
180
171
  };
181
172
  const fetchStatus = async (...jids) => {
182
- const usyncQuery = new WAUSync_1.USyncQuery()
183
- .withStatusProtocol();
173
+ const usyncQuery = new USyncQuery().withStatusProtocol();
184
174
  for (const jid of jids) {
185
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
175
+ usyncQuery.withUser(new USyncUser().withId(jid));
186
176
  }
187
177
  const result = await sock.executeUSyncQuery(usyncQuery);
188
178
  if (result) {
@@ -190,32 +180,35 @@ const makeChatsSocket = (config) => {
190
180
  }
191
181
  };
192
182
  const fetchDisappearingDuration = async (...jids) => {
193
- const usyncQuery = new WAUSync_1.USyncQuery()
194
- .withDisappearingModeProtocol();
183
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
195
184
  for (const jid of jids) {
196
- usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
185
+ usyncQuery.withUser(new USyncUser().withId(jid));
197
186
  }
198
187
  const result = await sock.executeUSyncQuery(usyncQuery);
199
188
  if (result) {
200
189
  return result.list;
201
190
  }
202
191
  };
192
+ /** update the profile picture for yourself or a group */
203
193
  const updateProfilePicture = async (jid, content, dimensions) => {
204
194
  let targetJid;
205
195
  if (!jid) {
206
- throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
196
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
197
+ }
198
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
199
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
207
200
  }
208
- if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
209
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
201
+ else {
202
+ targetJid = undefined;
210
203
  }
211
- const { img } = await (0, Utils_1.generateProfilePicture)(content, dimensions);
204
+ const { img } = await generateProfilePicture(content, dimensions);
212
205
  await query({
213
206
  tag: 'iq',
214
207
  attrs: {
215
- target: targetJid,
216
- to: WABinary_1.S_WHATSAPP_NET,
208
+ to: S_WHATSAPP_NET,
217
209
  type: 'set',
218
- xmlns: 'w:profile:picture'
210
+ xmlns: 'w:profile:picture',
211
+ ...(targetJid ? { target: targetJid } : {})
219
212
  },
220
213
  content: [
221
214
  {
@@ -226,29 +219,34 @@ const makeChatsSocket = (config) => {
226
219
  ]
227
220
  });
228
221
  };
222
+ /** remove the profile picture for yourself or a group */
229
223
  const removeProfilePicture = async (jid) => {
230
224
  let targetJid;
231
225
  if (!jid) {
232
- throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
226
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
233
227
  }
234
- if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
235
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
228
+ if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
229
+ targetJid = jidNormalizedUser(jid); // in case it is someone other than us
230
+ }
231
+ else {
232
+ targetJid = undefined;
236
233
  }
237
234
  await query({
238
235
  tag: 'iq',
239
236
  attrs: {
240
- target: targetJid,
241
- to: WABinary_1.S_WHATSAPP_NET,
237
+ to: S_WHATSAPP_NET,
242
238
  type: 'set',
243
- xmlns: 'w:profile:picture'
239
+ xmlns: 'w:profile:picture',
240
+ ...(targetJid ? { target: targetJid } : {})
244
241
  }
245
242
  });
246
243
  };
244
+ /** update the profile status for yourself */
247
245
  const updateProfileStatus = async (status) => {
248
246
  await query({
249
247
  tag: 'iq',
250
248
  attrs: {
251
- to: WABinary_1.S_WHATSAPP_NET,
249
+ to: S_WHATSAPP_NET,
252
250
  type: 'set',
253
251
  xmlns: 'status'
254
252
  },
@@ -269,35 +267,48 @@ const makeChatsSocket = (config) => {
269
267
  tag: 'iq',
270
268
  attrs: {
271
269
  xmlns: 'blocklist',
272
- to: WABinary_1.S_WHATSAPP_NET,
270
+ to: S_WHATSAPP_NET,
273
271
  type: 'get'
274
272
  }
275
273
  });
276
- const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
277
- return (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item')
278
- .map(n => n.attrs.jid);
274
+ const listNode = getBinaryNodeChild(result, 'list');
275
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
279
276
  };
280
277
  const updateBlockStatus = async (jid, action) => {
278
+ jid = jidNormalizedUser(jid);
279
+ // Jika input adalah LID, resolve ke PN dulu
280
+ if (jid.endsWith('@lid')) {
281
+ try {
282
+ const pn = await signalRepository?.lidMapping?.getPNForLID?.(jid).catch(() => null);
283
+ if (pn) jid = jidNormalizedUser(pn);
284
+ } catch {}
285
+ }
286
+ const dhash = String(Date.now());
287
+ const itemAttrs = {
288
+ dhash,
289
+ action,
290
+ jid, // selalu PN
291
+ };
292
+ // Block: tambah pn_jid juga
293
+ if (action === 'block') {
294
+ itemAttrs.pn_jid = jid;
295
+ }
281
296
  await query({
282
297
  tag: 'iq',
283
298
  attrs: {
284
299
  xmlns: 'blocklist',
285
- to: WABinary_1.S_WHATSAPP_NET,
300
+ to: S_WHATSAPP_NET,
286
301
  type: 'set'
287
302
  },
288
303
  content: [
289
304
  {
290
305
  tag: 'item',
291
- attrs: {
292
- action,
293
- jid
294
- }
306
+ attrs: itemAttrs
295
307
  }
296
308
  ]
297
309
  });
298
310
  };
299
311
  const getBusinessProfile = async (jid) => {
300
- var _a, _b, _c, _d, _e, _f, _g;
301
312
  const results = await query({
302
313
  tag: 'iq',
303
314
  attrs: {
@@ -305,38 +316,42 @@ const makeChatsSocket = (config) => {
305
316
  xmlns: 'w:biz',
306
317
  type: 'get'
307
318
  },
308
- content: [{
319
+ content: [
320
+ {
309
321
  tag: 'business_profile',
310
322
  attrs: { v: '244' },
311
- content: [{
323
+ content: [
324
+ {
312
325
  tag: 'profile',
313
326
  attrs: { jid }
314
- }]
315
- }]
327
+ }
328
+ ]
329
+ }
330
+ ]
316
331
  });
317
- const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile');
318
- const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile');
332
+ const profileNode = getBinaryNodeChild(results, 'business_profile');
333
+ const profiles = getBinaryNodeChild(profileNode, 'profile');
319
334
  if (profiles) {
320
- const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address');
321
- const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description');
322
- const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website');
323
- const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
324
- const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
325
- const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
335
+ const address = getBinaryNodeChild(profiles, 'address');
336
+ const description = getBinaryNodeChild(profiles, 'description');
337
+ const website = getBinaryNodeChild(profiles, 'website');
338
+ const email = getBinaryNodeChild(profiles, 'email');
339
+ const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
340
+ const businessHours = getBinaryNodeChild(profiles, 'business_hours');
326
341
  const businessHoursConfig = businessHours
327
- ? (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config')
342
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
328
343
  : undefined;
329
- const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
344
+ const websiteStr = website?.content?.toString();
330
345
  return {
331
- wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
332
- address: (_c = address === null || address === void 0 ? void 0 : address.content) === null || _c === void 0 ? void 0 : _c.toString(),
333
- description: ((_d = description === null || description === void 0 ? void 0 : description.content) === null || _d === void 0 ? void 0 : _d.toString()) || '',
346
+ wid: profiles.attrs?.jid,
347
+ address: address?.content?.toString(),
348
+ description: description?.content?.toString() || '',
334
349
  website: websiteStr ? [websiteStr] : [],
335
- email: (_e = email === null || email === void 0 ? void 0 : email.content) === null || _e === void 0 ? void 0 : _e.toString(),
336
- category: (_f = category === null || category === void 0 ? void 0 : category.content) === null || _f === void 0 ? void 0 : _f.toString(),
337
- 'business_hours': {
338
- timezone: (_g = businessHours === null || businessHours === void 0 ? void 0 : businessHours.attrs) === null || _g === void 0 ? void 0 : _g.timezone,
339
- 'business_config': businessHoursConfig === null || businessHoursConfig === void 0 ? void 0 : businessHoursConfig.map(({ attrs }) => attrs)
350
+ email: email?.content?.toString(),
351
+ category: category?.content?.toString(),
352
+ business_hours: {
353
+ timezone: businessHours?.attrs?.timezone,
354
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
340
355
  }
341
356
  };
342
357
  }
@@ -346,17 +361,17 @@ const makeChatsSocket = (config) => {
346
361
  await sendNode({
347
362
  tag: 'iq',
348
363
  attrs: {
349
- to: WABinary_1.S_WHATSAPP_NET,
364
+ to: S_WHATSAPP_NET,
350
365
  type: 'set',
351
366
  xmlns: 'urn:xmpp:whatsapp:dirty',
352
- id: generateMessageTag(),
367
+ id: generateMessageTag()
353
368
  },
354
369
  content: [
355
370
  {
356
371
  tag: 'clean',
357
372
  attrs: {
358
373
  type,
359
- ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
374
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
360
375
  }
361
376
  }
362
377
  ]
@@ -365,17 +380,31 @@ const makeChatsSocket = (config) => {
365
380
  const newAppStateChunkHandler = (isInitialSync) => {
366
381
  return {
367
382
  onMutation(mutation) {
368
- (0, Utils_1.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
383
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
369
384
  }
370
385
  };
371
386
  };
372
387
  const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
388
+ const appStateSyncKeyCache = new Map();
389
+ const getCachedAppStateSyncKey = async (keyId) => {
390
+ if (appStateSyncKeyCache.has(keyId)) {
391
+ return appStateSyncKeyCache.get(keyId) ?? undefined;
392
+ }
393
+ const key = await getAppStateSyncKey(keyId);
394
+ appStateSyncKeyCache.set(keyId, key ?? null);
395
+ return key;
396
+ };
397
+ // we use this to determine which events to fire
398
+ // otherwise when we resync from scratch -- all notifications will fire
373
399
  const initialVersionMap = {};
374
400
  const globalMutationMap = {};
375
401
  await authState.keys.transaction(async () => {
376
- var _a;
377
402
  const collectionsToHandle = new Set(collections);
403
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
378
404
  const attemptsMap = {};
405
+ // keep executing till all collections are done
406
+ // sometimes a single patch request will not return all the patches (God knows why)
407
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
379
408
  while (collectionsToHandle.size) {
380
409
  const states = {};
381
410
  const nodes = [];
@@ -388,7 +417,7 @@ const makeChatsSocket = (config) => {
388
417
  }
389
418
  }
390
419
  else {
391
- state = (0, Utils_1.newLTHashState)();
420
+ state = newLTHashState();
392
421
  }
393
422
  states[name] = state;
394
423
  logger.info(`resyncing ${name} from v${state.version}`);
@@ -397,14 +426,15 @@ const makeChatsSocket = (config) => {
397
426
  attrs: {
398
427
  name,
399
428
  version: state.version.toString(),
400
- 'return_snapshot': (!state.version).toString()
429
+ // return snapshot if being synced from scratch
430
+ return_snapshot: (!state.version).toString()
401
431
  }
402
432
  });
403
433
  }
404
434
  const result = await query({
405
435
  tag: 'iq',
406
436
  attrs: {
407
- to: WABinary_1.S_WHATSAPP_NET,
437
+ to: S_WHATSAPP_NET,
408
438
  xmlns: 'w:sync:app:state',
409
439
  type: 'set'
410
440
  },
@@ -416,20 +446,22 @@ const makeChatsSocket = (config) => {
416
446
  }
417
447
  ]
418
448
  });
419
- const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
449
+ // extract from binary node
450
+ const decoded = await extractSyncdPatches(result, config?.options);
420
451
  for (const key in decoded) {
421
452
  const name = key;
422
453
  const { patches, hasMorePatches, snapshot } = decoded[name];
423
454
  try {
424
455
  if (snapshot) {
425
- const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
456
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
426
457
  states[name] = newState;
427
458
  Object.assign(globalMutationMap, mutationMap);
428
459
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
429
460
  await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
430
461
  }
462
+ // only process if there are syncd patches
431
463
  if (patches.length) {
432
- const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
464
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
433
465
  await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
434
466
  logger.info(`synced ${name} to v${newState.version}`);
435
467
  initialVersionMap[name] = newState.version;
@@ -439,60 +471,54 @@ const makeChatsSocket = (config) => {
439
471
  logger.info(`${name} has more patches...`);
440
472
  }
441
473
  else {
474
+ // collection is done with sync
442
475
  collectionsToHandle.delete(name);
443
476
  }
444
477
  }
445
478
  catch (error) {
446
- const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
447
- || ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404
448
- || error.name === 'TypeError';
479
+ // if retry attempts overshoot
480
+ // or key not found
481
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
482
+ error.output?.statusCode === 404 ||
483
+ error.name === 'TypeError';
449
484
  logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
450
485
  await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
486
+ // increment number of retries
451
487
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
452
488
  if (isIrrecoverableError) {
489
+ // stop retrying
453
490
  collectionsToHandle.delete(name);
454
491
  }
455
492
  }
456
493
  }
457
494
  }
458
- });
495
+ }, authState?.creds?.me?.id || 'resync-app-state');
459
496
  const { onMutation } = newAppStateChunkHandler(isInitialSync);
460
497
  for (const key in globalMutationMap) {
461
498
  onMutation(globalMutationMap[key]);
462
499
  }
463
500
  });
501
+ /**
502
+ * fetch the profile picture of a user/group
503
+ * type = "preview" for a low res picture
504
+ * type = "image for the high res picture"
505
+ */
464
506
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
465
- var _a;
466
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
467
- try {
468
- const result = await query({
469
- tag: 'iq',
470
- attrs: {
471
- target: jid,
472
- to: WABinary_1.S_WHATSAPP_NET,
473
- type: 'get',
474
- xmlns: 'w:profile:picture'
475
- },
476
- content: [
477
- { tag: 'picture', attrs: { type, query: 'url' } }
478
- ]
479
- }, timeoutMs);
480
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
481
- return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
482
- } catch (error) {
483
- if (error.message?.includes('item-not-found') ||
484
- error.output?.payload?.statusCode === 404 ||
485
- error.statusCode === 404) {
486
- logger.info(chalk.gray(`[INFO] Profile pic not found for ${jid}, using fallback`));
487
- return {
488
- eurl: undefined,
489
- id: jid.split('@')[0],
490
- status: null,
491
- img: null
492
- };
493
- }
494
- throw error;
495
- }
507
+ const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
508
+ const tcTokenContent = await buildTcTokenFromJid({ authState, jid, baseContent });
509
+ jid = jidNormalizedUser(jid);
510
+ const result = await query({
511
+ tag: 'iq',
512
+ attrs: {
513
+ target: jid,
514
+ to: S_WHATSAPP_NET,
515
+ type: 'get',
516
+ xmlns: 'w:profile:picture'
517
+ },
518
+ content: tcTokenContent
519
+ }, timeoutMs);
520
+ const child = getBinaryNodeChild(result, 'picture');
521
+ return child?.attrs?.url;
496
522
  };
497
523
  const createCallLink = async (type, event, timeoutMs) => {
498
524
  const result = await query({
@@ -509,17 +535,21 @@ const makeChatsSocket = (config) => {
509
535
  }
510
536
  ]
511
537
  }, timeoutMs);
512
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'link_create');
538
+ const child = getBinaryNodeChild(result, 'link_create');
513
539
  return child?.attrs?.token;
514
540
  };
515
541
  const sendPresenceUpdate = async (type, toJid) => {
516
542
  const me = authState.creds.me;
517
- if (type === 'available' || type === 'unavailable') {
543
+ const isAvailableType = type === 'available';
544
+ if (isAvailableType || type === 'unavailable') {
518
545
  if (!me.name) {
519
546
  logger.warn('no name present, ignoring presence update request...');
520
547
  return;
521
548
  }
522
- ev.emit('connection.update', { isOnline: type === 'available' });
549
+ ev.emit('connection.update', { isOnline: isAvailableType });
550
+ if (isAvailableType) {
551
+ void sendUnifiedSession();
552
+ }
523
553
  await sendNode({
524
554
  tag: 'presence',
525
555
  attrs: {
@@ -529,13 +559,13 @@ const makeChatsSocket = (config) => {
529
559
  });
530
560
  }
531
561
  else {
532
- const { server } = (0, WABinary_1.jidDecode)(toJid);
562
+ const { server } = jidDecode(toJid);
533
563
  const isLid = server === 'lid';
534
564
  await sendNode({
535
565
  tag: 'chatstate',
536
566
  attrs: {
537
567
  from: isLid ? me.lid : me.id,
538
- to: toJid,
568
+ to: toJid
539
569
  },
540
570
  content: [
541
571
  {
@@ -546,29 +576,27 @@ const makeChatsSocket = (config) => {
546
576
  });
547
577
  }
548
578
  };
549
- const presenceSubscribe = (toJid, tcToken) => (sendNode({
550
- tag: 'presence',
551
- attrs: {
552
- to: toJid,
553
- id: generateMessageTag(),
554
- type: 'subscribe'
555
- },
556
- content: tcToken
557
- ? [
558
- {
559
- tag: 'tctoken',
560
- attrs: {},
561
- content: tcToken
562
- }
563
- ]
564
- : undefined
565
- }));
579
+ /**
580
+ * @param toJid the jid to subscribe to
581
+ * @param tcToken token for subscription, use if present
582
+ */
583
+ const presenceSubscribe = async (toJid) => {
584
+ const tcTokenContent = await buildTcTokenFromJid({ authState, jid: toJid });
585
+ return sendNode({
586
+ tag: 'presence',
587
+ attrs: {
588
+ to: toJid,
589
+ id: generateMessageTag(),
590
+ type: 'subscribe'
591
+ },
592
+ content: tcTokenContent
593
+ });
594
+ };
566
595
  const handlePresenceUpdate = ({ tag, attrs, content }) => {
567
- var _a;
568
596
  let presence;
569
597
  const jid = attrs.from;
570
598
  const participant = attrs.participant || attrs.from;
571
- if (shouldIgnoreJid(jid) && jid != '@s.whatsapp.net') {
599
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
572
600
  return;
573
601
  }
574
602
  if (tag === 'presence') {
@@ -583,7 +611,7 @@ const makeChatsSocket = (config) => {
583
611
  if (type === 'paused') {
584
612
  type = 'available';
585
613
  }
586
- if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
614
+ if (firstChild.attrs?.media === 'audio') {
587
615
  type = 'recording';
588
616
  }
589
617
  presence = { lastKnownPresence: type };
@@ -599,22 +627,22 @@ const makeChatsSocket = (config) => {
599
627
  const name = patchCreate.type;
600
628
  const myAppStateKeyId = authState.creds.myAppStateKeyId;
601
629
  if (!myAppStateKeyId) {
602
- throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
630
+ throw new Boom('App state key not present!', { statusCode: 400 });
603
631
  }
604
632
  let initial;
605
633
  let encodeResult;
606
- await processingMutex.mutex(async () => {
634
+ await appStatePatchMutex.mutex(async () => {
607
635
  await authState.keys.transaction(async () => {
608
636
  logger.debug({ patch: patchCreate }, 'applying app patch');
609
637
  await resyncAppState([name], false);
610
638
  const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
611
- initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
612
- encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
639
+ initial = currentSyncVersion || newLTHashState();
640
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
613
641
  const { patch, state } = encodeResult;
614
642
  const node = {
615
643
  tag: 'iq',
616
644
  attrs: {
617
- to: WABinary_1.S_WHATSAPP_NET,
645
+ to: S_WHATSAPP_NET,
618
646
  type: 'set',
619
647
  xmlns: 'w:sync:app:state'
620
648
  },
@@ -628,13 +656,13 @@ const makeChatsSocket = (config) => {
628
656
  attrs: {
629
657
  name,
630
658
  version: (state.version - 1).toString(),
631
- 'return_snapshot': 'false'
659
+ return_snapshot: 'false'
632
660
  },
633
661
  content: [
634
662
  {
635
663
  tag: 'patch',
636
664
  attrs: {},
637
- content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
665
+ content: proto.SyncdPatch.encode(patch).finish()
638
666
  }
639
667
  ]
640
668
  }
@@ -644,48 +672,69 @@ const makeChatsSocket = (config) => {
644
672
  };
645
673
  await query(node);
646
674
  await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
647
- });
675
+ }, authState?.creds?.me?.id || 'app-patch');
648
676
  });
649
677
  if (config.emitOwnEvents) {
650
678
  const { onMutation } = newAppStateChunkHandler(false);
651
- const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
679
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
652
680
  for (const key in mutationMap) {
653
681
  onMutation(mutationMap[key]);
654
682
  }
655
683
  }
656
684
  };
685
+ /** sending non-abt props may fix QR scan fail if server expects */
657
686
  const fetchProps = async () => {
658
- var _a, _b, _c;
687
+ //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
659
688
  const resultNode = await query({
660
689
  tag: 'iq',
661
690
  attrs: {
662
- to: WABinary_1.S_WHATSAPP_NET,
691
+ to: S_WHATSAPP_NET,
663
692
  xmlns: 'w',
664
- type: 'get',
693
+ type: 'get'
665
694
  },
666
695
  content: [
667
- { tag: 'props', attrs: {
696
+ {
697
+ tag: 'props',
698
+ attrs: {
668
699
  protocol: '2',
669
- hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
670
- } }
700
+ hash: authState?.creds?.lastPropHash || ''
701
+ }
702
+ }
671
703
  ]
672
704
  });
673
- const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
705
+ const propsNode = getBinaryNodeChild(resultNode, 'props');
674
706
  let props = {};
675
707
  if (propsNode) {
676
- if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) {
677
- authState.creds.lastPropHash = (_c = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _c === void 0 ? void 0 : _c.hash;
708
+ if (propsNode.attrs?.hash) {
709
+ // on some clients, the hash is returning as undefined
710
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
678
711
  ev.emit('creds.update', authState.creds);
679
712
  }
680
- props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
713
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop');
681
714
  }
682
715
  logger.debug('fetched props');
683
716
  return props;
684
717
  };
718
+ /**
719
+ * modify a chat -- mark unread, read etc.
720
+ * lastMessages must be sorted in reverse chronologically
721
+ * requires the last messages till the last message received; required for archive & unread
722
+ */
685
723
  const chatModify = (mod, jid) => {
686
- const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
724
+ const patch = chatModificationToAppPatch(mod, jid);
687
725
  return appPatch(patch);
688
726
  };
727
+ /**
728
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
729
+ */
730
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
731
+ return chatModify({
732
+ disableLinkPreviews: { isPreviewsDisabled }
733
+ }, '');
734
+ };
735
+ /**
736
+ * Star or Unstar a message
737
+ */
689
738
  const star = (jid, messages, star) => {
690
739
  return chatModify({
691
740
  star: {
@@ -694,15 +743,35 @@ const makeChatsSocket = (config) => {
694
743
  }
695
744
  }, jid);
696
745
  };
746
+ /**
747
+ * Add or Edit Contact
748
+ */
697
749
  const addOrEditContact = (jid, contact) => {
698
- return chatModify({ contact }, jid);
750
+ return chatModify({
751
+ contact
752
+ }, jid);
699
753
  };
754
+ /**
755
+ * Remove Contact
756
+ */
700
757
  const removeContact = (jid) => {
701
- return chatModify({ contact: null }, jid);
758
+ return chatModify({
759
+ contact: null
760
+ }, jid);
702
761
  };
762
+ /**
763
+ * Adds label
764
+ */
703
765
  const addLabel = (jid, labels) => {
704
- return chatModify({ addLabel: { ...labels } }, jid);
766
+ return chatModify({
767
+ addLabel: {
768
+ ...labels
769
+ }
770
+ }, jid);
705
771
  };
772
+ /**
773
+ * Adds label for the chats
774
+ */
706
775
  const addChatLabel = (jid, labelId) => {
707
776
  return chatModify({
708
777
  addChatLabel: {
@@ -710,6 +779,9 @@ const makeChatsSocket = (config) => {
710
779
  }
711
780
  }, jid);
712
781
  };
782
+ /**
783
+ * Removes label for the chat
784
+ */
713
785
  const removeChatLabel = (jid, labelId) => {
714
786
  return chatModify({
715
787
  removeChatLabel: {
@@ -717,6 +789,9 @@ const makeChatsSocket = (config) => {
717
789
  }
718
790
  }, jid);
719
791
  };
792
+ /**
793
+ * Adds label for the message
794
+ */
720
795
  const addMessageLabel = (jid, messageId, labelId) => {
721
796
  return chatModify({
722
797
  addMessageLabel: {
@@ -725,6 +800,9 @@ const makeChatsSocket = (config) => {
725
800
  }
726
801
  }, jid);
727
802
  };
803
+ /**
804
+ * Removes label for the message
805
+ */
728
806
  const removeMessageLabel = (jid, messageId, labelId) => {
729
807
  return chatModify({
730
808
  removeMessageLabel: {
@@ -733,31 +811,102 @@ const makeChatsSocket = (config) => {
733
811
  }
734
812
  }, jid);
735
813
  };
814
+ /**
815
+ * Add or Edit Quick Reply
816
+ */
817
+ const addOrEditQuickReply = (quickReply) => {
818
+ return chatModify({
819
+ quickReply
820
+ }, '');
821
+ };
822
+ /**
823
+ * Remove Quick Reply
824
+ */
825
+ const removeQuickReply = (timestamp) => {
826
+ return chatModify({
827
+ quickReply: { timestamp, deleted: true }
828
+ }, '');
829
+ };
830
+ /**
831
+ * queries need to be fired on connection open
832
+ * help ensure parity with WA Web
833
+ * */
736
834
  const executeInitQueries = async () => {
737
- await Promise.all([
738
- fetchProps(),
739
- fetchBlocklist(),
740
- fetchPrivacySettings(),
741
- ]);
835
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
742
836
  };
743
837
  const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
744
- var _a, _b, _c;
838
+ // ── Auto-inject isAdmin, isBotAdmin, metadata ─────────────────────────
839
+ try {
840
+ const remoteJid = msg.key?.remoteJid || '';
841
+ const isGroup = remoteJid.endsWith('@g.us');
842
+ if (isGroup) {
843
+ const _normalizeJid = (jid) => {
844
+ if (!jid) return null;
845
+ try { return jidNormalizedUser(jid).split('@')[0]; }
846
+ catch { return String(jid).split('@')[0]; }
847
+ };
848
+ // Fetch metadata (pakai cache jika tersedia)
849
+ let meta = null;
850
+ try { meta = await sock.groupMetadata(remoteJid); } catch {}
851
+ if (meta && Array.isArray(meta.participants)) {
852
+ msg.metadata = meta;
853
+ const botJid = authState.creds?.me?.id;
854
+ const senderJid = msg.key.fromMe
855
+ ? authState.creds?.me?.id
856
+ : (msg.key.participant || remoteJid);
857
+ const senderNorm = _normalizeJid(senderJid);
858
+ const botNorm = _normalizeJid(botJid);
859
+ // isAdmin
860
+ msg.isAdmin = meta.participants.some(p => {
861
+ const pid = _normalizeJid(p.jid || p.id || p.lid);
862
+ return pid === senderNorm && (p.admin === 'admin' || p.admin === 'superadmin');
863
+ });
864
+ // isBotAdmin: via m.isBotAdmin jika sudah di-set
865
+ let isBotAdmin = typeof msg.isBotAdmin === 'boolean' ? msg.isBotAdmin : false;
866
+ // fallback via owner
867
+ if (!isBotAdmin) {
868
+ const owners = [meta.owner, meta.subjectOwner, meta.ownerPn]
869
+ .filter(Boolean).map(_normalizeJid);
870
+ if (owners.includes(botNorm)) isBotAdmin = true;
871
+ }
872
+ // fallback via participants
873
+ if (!isBotAdmin) {
874
+ isBotAdmin = meta.participants.some(p => {
875
+ const pid = _normalizeJid(p.jid || p.id || p.lid);
876
+ return pid === botNorm && (p.admin === 'admin' || p.admin === 'superadmin');
877
+ });
878
+ }
879
+ msg.isBotAdmin = isBotAdmin;
880
+ } else {
881
+ msg.metadata = {};
882
+ msg.isAdmin = false;
883
+ msg.isBotAdmin = false;
884
+ }
885
+ } else {
886
+ msg.metadata = {};
887
+ msg.isAdmin = false;
888
+ msg.isBotAdmin = false;
889
+ }
890
+ } catch {}
891
+ // ─────────────────────────────────────────────────────────────────────
745
892
  ev.emit('messages.upsert', { messages: [msg], type });
746
893
  if (!!msg.pushName) {
747
- let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
748
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
894
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
895
+ jid = jidNormalizedUser(jid);
749
896
  if (!msg.key.fromMe) {
750
897
  ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
751
898
  }
752
- if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
899
+ // update our pushname too
900
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
753
901
  ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
754
902
  }
755
903
  }
756
- const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
904
+ const historyMsg = getHistoryMsg(msg.message);
757
905
  const shouldProcessHistoryMsg = historyMsg
758
- ? (shouldSyncHistoryMessage(historyMsg)
759
- && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
906
+ ? shouldSyncHistoryMessage(historyMsg) &&
907
+ PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
760
908
  : false;
909
+ // State machine: decide on sync and flush
761
910
  if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
762
911
  if (awaitingSyncTimeout) {
763
912
  clearTimeout(awaitingSyncTimeout);
@@ -766,7 +915,9 @@ const makeChatsSocket = (config) => {
766
915
  if (shouldProcessHistoryMsg) {
767
916
  syncState = SyncState.Syncing;
768
917
  logger.info('Transitioned to Syncing state');
769
- } else {
918
+ // Let doAppStateSync handle the final flush after it's done
919
+ }
920
+ else {
770
921
  syncState = SyncState.Online;
771
922
  logger.info('History sync skipped, transitioning to Online state and flushing buffer');
772
923
  ev.flush();
@@ -775,7 +926,8 @@ const makeChatsSocket = (config) => {
775
926
  const doAppStateSync = async () => {
776
927
  if (syncState === SyncState.Syncing) {
777
928
  logger.info('Doing app state sync');
778
- await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
929
+ await resyncAppState(ALL_WA_PATCH_NAMES, true);
930
+ // Sync is complete, go online and flush everything
779
931
  syncState = SyncState.Online;
780
932
  logger.info('App state sync complete, transitioning to Online state and flushing buffer');
781
933
  ev.flush();
@@ -783,19 +935,13 @@ const makeChatsSocket = (config) => {
783
935
  ev.emit('creds.update', { accountSyncCounter });
784
936
  }
785
937
  };
786
- if (historyMsg && !authState.creds.myAppStateKeyId) {
787
- logger.warn('skipping app state sync, as myAppStateKeyId is not set');
788
- pendingAppStateSync = true;
789
- }
790
938
  await Promise.all([
791
939
  (async () => {
792
- if (historyMsg
793
- && authState.creds.myAppStateKeyId) {
794
- pendingAppStateSync = false;
940
+ if (shouldProcessHistoryMsg) {
795
941
  await doAppStateSync();
796
942
  }
797
943
  })(),
798
- (0, process_message_1.default)(msg, {
944
+ processMessage(msg, {
799
945
  signalRepository,
800
946
  shouldProcessHistoryMsg,
801
947
  placeholderResendCache,
@@ -804,19 +950,19 @@ const makeChatsSocket = (config) => {
804
950
  keyStore: authState.keys,
805
951
  logger,
806
952
  options: config.options,
807
- getMessage: config.getMessage,
953
+ getMessage
808
954
  })
809
955
  ]);
810
- if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare)
811
- && pendingAppStateSync) {
956
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
957
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
958
+ logger.info('App state sync key arrived, triggering app state sync');
812
959
  await doAppStateSync();
813
- pendingAppStateSync = false;
814
960
  }
815
961
  });
816
962
  ws.on('CB:presence', handlePresenceUpdate);
817
963
  ws.on('CB:chatstate', handlePresenceUpdate);
818
964
  ws.on('CB:ib,,dirty', async (node) => {
819
- const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
965
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
820
966
  const type = attrs.type;
821
967
  switch (type) {
822
968
  case 'account_sync':
@@ -830,6 +976,7 @@ const makeChatsSocket = (config) => {
830
976
  }
831
977
  break;
832
978
  case 'groups':
979
+ // handled in groups.ts
833
980
  break;
834
981
  default:
835
982
  logger.info({ node }, 'received unknown sync');
@@ -837,19 +984,11 @@ const makeChatsSocket = (config) => {
837
984
  }
838
985
  });
839
986
  ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
840
- var _a;
841
987
  if (connection === 'open') {
842
988
  if (fireInitQueries) {
843
- executeInitQueries()
844
- .catch(error => onUnexpectedError(error, 'init queries'));
989
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
845
990
  }
846
- sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
847
- .catch(error => onUnexpectedError(error, 'presence update requests'));
848
- }
849
- if (receivedPendingNotifications &&
850
- !((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId)) {
851
- ev.buffer();
852
- needToFlushWithAppStateSync = true;
991
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
853
992
  }
854
993
  if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
855
994
  return;
@@ -857,11 +996,9 @@ const makeChatsSocket = (config) => {
857
996
  syncState = SyncState.AwaitingInitialSync;
858
997
  logger.info('Connection is now AwaitingInitialSync, buffering events');
859
998
  ev.buffer();
860
- const willSyncHistory = shouldSyncHistoryMessage(
861
- WAProto_1.proto.Message.HistorySyncNotification.create({
862
- syncType: WAProto_1.proto.HistorySync.HistorySyncType.RECENT
863
- })
864
- );
999
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
1000
+ syncType: proto.HistorySync.HistorySyncType.RECENT
1001
+ }));
865
1002
  if (!willSyncHistory) {
866
1003
  logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
867
1004
  syncState = SyncState.Online;
@@ -874,31 +1011,84 @@ const makeChatsSocket = (config) => {
874
1011
  }
875
1012
  awaitingSyncTimeout = setTimeout(() => {
876
1013
  if (syncState === SyncState.AwaitingInitialSync) {
1014
+ // TODO: investigate
877
1015
  logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
878
1016
  syncState = SyncState.Online;
879
1017
  ev.flush();
880
1018
  }
881
1019
  }, 20000);
882
1020
  });
1021
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
1022
+ try {
1023
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
1024
+ }
1025
+ catch (error) {
1026
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
1027
+ }
1028
+ });
1029
+ ev.on('groups.upsert', async (groups) => {
1030
+ try {
1031
+ const mappings = [];
1032
+ for (const group of groups) {
1033
+ for (const p of group.participants || []) {
1034
+ const lidJid = p.id?.endsWith('@lid') ? p.id : p.lid;
1035
+ const pnJid = p.phoneNumber?.endsWith('@s.whatsapp.net')
1036
+ ? p.phoneNumber
1037
+ : p.id?.endsWith('@s.whatsapp.net') ? p.id : undefined;
1038
+ if (lidJid && pnJid) {
1039
+ mappings.push({ lid: lidJid, pn: pnJid });
1040
+ }
1041
+ }
1042
+ }
1043
+ if (mappings.length > 0) {
1044
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings);
1045
+ logger.debug({ count: mappings.length }, 'groups.upsert: stored LID-PN mappings from participants');
1046
+ }
1047
+ }
1048
+ catch (error) {
1049
+ logger.warn({ error }, 'groups.upsert: failed to store LID-PN mappings');
1050
+ }
1051
+ });
1052
+ ev.on('groups.update', async (updates) => {
1053
+ try {
1054
+ const mappings = [];
1055
+ for (const update of updates) {
1056
+ for (const p of update.participants || []) {
1057
+ const lidJid = p.id?.endsWith('@lid') ? p.id : p.lid;
1058
+ const pnJid = p.phoneNumber?.endsWith('@s.whatsapp.net')
1059
+ ? p.phoneNumber
1060
+ : p.id?.endsWith('@s.whatsapp.net') ? p.id : undefined;
1061
+ if (lidJid && pnJid) {
1062
+ mappings.push({ lid: lidJid, pn: pnJid });
1063
+ }
1064
+ }
1065
+ }
1066
+ if (mappings.length > 0) {
1067
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings);
1068
+ logger.debug({ count: mappings.length }, 'groups.update: stored LID-PN mappings from participants');
1069
+ }
1070
+ }
1071
+ catch (error) {
1072
+ logger.warn({ error }, 'groups.update: failed to store LID-PN mappings');
1073
+ }
1074
+ });
883
1075
  return {
884
1076
  ...sock,
885
1077
  createCallLink,
886
1078
  getBotListV2,
887
- processingMutex,
888
1079
  messageMutex,
889
- notificationMutex,
890
1080
  receiptMutex,
891
- messageRetryManager,
1081
+ appStatePatchMutex,
1082
+ notificationMutex,
892
1083
  fetchPrivacySettings,
893
1084
  upsertMessage,
894
1085
  appPatch,
895
1086
  sendPresenceUpdate,
896
1087
  presenceSubscribe,
897
1088
  profilePictureUrl,
898
- onWhatsApp,
899
1089
  fetchBlocklist,
900
- fetchDisappearingDuration,
901
1090
  fetchStatus,
1091
+ fetchDisappearingDuration,
902
1092
  updateProfilePicture,
903
1093
  removeProfilePicture,
904
1094
  updateProfileStatus,
@@ -925,7 +1115,19 @@ const makeChatsSocket = (config) => {
925
1115
  removeChatLabel,
926
1116
  addMessageLabel,
927
1117
  removeMessageLabel,
928
- star
1118
+ star,
1119
+ addOrEditQuickReply,
1120
+ removeQuickReply,
1121
+ clearMessage: (jid, key, timeStamp) => {
1122
+ return chatModify({
1123
+ delete: true,
1124
+ lastMessages: [{
1125
+ key: key,
1126
+ messageTimestamp: timeStamp
1127
+ }]
1128
+ }, jid);
1129
+ },
1130
+ getLidUser
929
1131
  };
930
1132
  };
931
- exports.makeChatsSocket = makeChatsSocket;
1133
+ //# sourceMappingURL=chats.js.map