@rakku-kun/baileys 2.0.2

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 (405) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +647 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +81 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +97687 -0
  8. package/engine-requirements.js +10 -0
  9. package/index.cjs +196 -0
  10. package/index.d.ts +30 -0
  11. package/lib/Defaults/index.d.ts +74 -0
  12. package/lib/Defaults/index.d.ts.map +1 -0
  13. package/lib/Defaults/index.js +135 -0
  14. package/lib/Defaults/index.js.map +1 -0
  15. package/lib/Defaults/phonenumber-mcc.json +223 -0
  16. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  17. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  18. package/lib/Signal/Group/ciphertext-message.js +12 -0
  19. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  20. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  21. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  22. package/lib/Signal/Group/group-session-builder.js +30 -0
  23. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  24. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  25. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  26. package/lib/Signal/Group/group_cipher.js +82 -0
  27. package/lib/Signal/Group/group_cipher.js.map +1 -0
  28. package/lib/Signal/Group/index.d.ts +12 -0
  29. package/lib/Signal/Group/index.d.ts.map +1 -0
  30. package/lib/Signal/Group/index.js +12 -0
  31. package/lib/Signal/Group/index.js.map +1 -0
  32. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  33. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  34. package/lib/Signal/Group/keyhelper.js +18 -0
  35. package/lib/Signal/Group/keyhelper.js.map +1 -0
  36. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  37. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  38. package/lib/Signal/Group/sender-chain-key.js +26 -0
  39. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  41. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  42. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  43. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  44. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  45. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  46. package/lib/Signal/Group/sender-key-message.js +66 -0
  47. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  48. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  49. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  50. package/lib/Signal/Group/sender-key-name.js +48 -0
  51. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  52. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  53. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  54. package/lib/Signal/Group/sender-key-record.js +41 -0
  55. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  56. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  57. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  58. package/lib/Signal/Group/sender-key-state.js +84 -0
  59. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  60. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  61. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  62. package/lib/Signal/Group/sender-message-key.js +26 -0
  63. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  64. package/lib/Signal/libsignal.d.ts +5 -0
  65. package/lib/Signal/libsignal.d.ts.map +1 -0
  66. package/lib/Signal/libsignal.js +438 -0
  67. package/lib/Signal/libsignal.js.map +1 -0
  68. package/lib/Signal/lid-mapping.d.ts +19 -0
  69. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  70. package/lib/Signal/lid-mapping.js +271 -0
  71. package/lib/Signal/lid-mapping.js.map +1 -0
  72. package/lib/Socket/Client/index.d.ts +3 -0
  73. package/lib/Socket/Client/index.d.ts.map +1 -0
  74. package/lib/Socket/Client/index.js +3 -0
  75. package/lib/Socket/Client/index.js.map +1 -0
  76. package/lib/Socket/Client/types.d.ts +16 -0
  77. package/lib/Socket/Client/types.d.ts.map +1 -0
  78. package/lib/Socket/Client/types.js +11 -0
  79. package/lib/Socket/Client/types.js.map +1 -0
  80. package/lib/Socket/Client/websocket.d.ts +13 -0
  81. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  82. package/lib/Socket/Client/websocket.js +54 -0
  83. package/lib/Socket/Client/websocket.js.map +1 -0
  84. package/lib/Socket/business.d.ts +202 -0
  85. package/lib/Socket/business.d.ts.map +1 -0
  86. package/lib/Socket/business.js +379 -0
  87. package/lib/Socket/business.js.map +1 -0
  88. package/lib/Socket/chats.d.ts +111 -0
  89. package/lib/Socket/chats.d.ts.map +1 -0
  90. package/lib/Socket/chats.js +1133 -0
  91. package/lib/Socket/chats.js.map +1 -0
  92. package/lib/Socket/communities.d.ts +258 -0
  93. package/lib/Socket/communities.d.ts.map +1 -0
  94. package/lib/Socket/communities.js +431 -0
  95. package/lib/Socket/communities.js.map +1 -0
  96. package/lib/Socket/community.js +361 -0
  97. package/lib/Socket/groups.d.ts +150 -0
  98. package/lib/Socket/groups.d.ts.map +1 -0
  99. package/lib/Socket/groups.js +459 -0
  100. package/lib/Socket/groups.js.map +1 -0
  101. package/lib/Socket/index.d.ts +245 -0
  102. package/lib/Socket/index.d.ts.map +1 -0
  103. package/lib/Socket/index.js +12 -0
  104. package/lib/Socket/index.js.map +1 -0
  105. package/lib/Socket/messages-recv.d.ts +187 -0
  106. package/lib/Socket/messages-recv.d.ts.map +1 -0
  107. package/lib/Socket/messages-recv.js +1681 -0
  108. package/lib/Socket/messages-recv.js.map +1 -0
  109. package/lib/Socket/messages-send.d.ts +183 -0
  110. package/lib/Socket/messages-send.d.ts.map +1 -0
  111. package/lib/Socket/messages-send.js +1635 -0
  112. package/lib/Socket/messages-send.js.map +1 -0
  113. package/lib/Socket/mex.d.ts +3 -0
  114. package/lib/Socket/mex.d.ts.map +1 -0
  115. package/lib/Socket/mex.js +42 -0
  116. package/lib/Socket/mex.js.map +1 -0
  117. package/lib/Socket/newsletter.d.ts +160 -0
  118. package/lib/Socket/newsletter.d.ts.map +1 -0
  119. package/lib/Socket/newsletter.js +270 -0
  120. package/lib/Socket/newsletter.js.map +1 -0
  121. package/lib/Socket/socket.d.ts +55 -0
  122. package/lib/Socket/socket.d.ts.map +1 -0
  123. package/lib/Socket/socket.js +944 -0
  124. package/lib/Socket/socket.js.map +1 -0
  125. package/lib/Socket/usync.js +76 -0
  126. package/lib/Store/index.js +4 -0
  127. package/lib/Store/make-cache-manager-store.js +77 -0
  128. package/lib/Store/make-in-memory-store.js +400 -0
  129. package/lib/Store/make-ordered-dictionary.js +78 -0
  130. package/lib/Store/object-repository.js +23 -0
  131. package/lib/Types/Auth.d.ts +116 -0
  132. package/lib/Types/Auth.d.ts.map +1 -0
  133. package/lib/Types/Auth.js +2 -0
  134. package/lib/Types/Auth.js.map +1 -0
  135. package/lib/Types/Bussines.d.ts +25 -0
  136. package/lib/Types/Bussines.d.ts.map +1 -0
  137. package/lib/Types/Bussines.js +2 -0
  138. package/lib/Types/Bussines.js.map +1 -0
  139. package/lib/Types/Call.d.ts +15 -0
  140. package/lib/Types/Call.d.ts.map +1 -0
  141. package/lib/Types/Call.js +2 -0
  142. package/lib/Types/Call.js.map +1 -0
  143. package/lib/Types/Chat.d.ts +123 -0
  144. package/lib/Types/Chat.d.ts.map +1 -0
  145. package/lib/Types/Chat.js +8 -0
  146. package/lib/Types/Chat.js.map +1 -0
  147. package/lib/Types/Contact.d.ts +24 -0
  148. package/lib/Types/Contact.d.ts.map +1 -0
  149. package/lib/Types/Contact.js +2 -0
  150. package/lib/Types/Contact.js.map +1 -0
  151. package/lib/Types/Events.d.ts +237 -0
  152. package/lib/Types/Events.d.ts.map +1 -0
  153. package/lib/Types/Events.js +2 -0
  154. package/lib/Types/Events.js.map +1 -0
  155. package/lib/Types/GroupMetadata.d.ts +67 -0
  156. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  157. package/lib/Types/GroupMetadata.js +2 -0
  158. package/lib/Types/GroupMetadata.js.map +1 -0
  159. package/lib/Types/Label.d.ts +47 -0
  160. package/lib/Types/Label.d.ts.map +1 -0
  161. package/lib/Types/Label.js +25 -0
  162. package/lib/Types/Label.js.map +1 -0
  163. package/lib/Types/LabelAssociation.d.ts +30 -0
  164. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  165. package/lib/Types/LabelAssociation.js +7 -0
  166. package/lib/Types/LabelAssociation.js.map +1 -0
  167. package/lib/Types/Message.d.ts +495 -0
  168. package/lib/Types/Message.d.ts.map +1 -0
  169. package/lib/Types/Message.js +11 -0
  170. package/lib/Types/Message.js.map +1 -0
  171. package/lib/Types/MexUpdates.js +9 -0
  172. package/lib/Types/Newsletter.d.ts +135 -0
  173. package/lib/Types/Newsletter.d.ts.map +1 -0
  174. package/lib/Types/Newsletter.js +43 -0
  175. package/lib/Types/Newsletter.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 +2 -0
  179. package/lib/Types/Product.js.map +1 -0
  180. package/lib/Types/Signal.d.ts +76 -0
  181. package/lib/Types/Signal.d.ts.map +1 -0
  182. package/lib/Types/Signal.js +2 -0
  183. package/lib/Types/Signal.js.map +1 -0
  184. package/lib/Types/Socket.d.ts +133 -0
  185. package/lib/Types/Socket.d.ts.map +1 -0
  186. package/lib/Types/Socket.js +3 -0
  187. package/lib/Types/Socket.js.map +1 -0
  188. package/lib/Types/State.d.ts +39 -0
  189. package/lib/Types/State.d.ts.map +1 -0
  190. package/lib/Types/State.js +13 -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 +2 -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 +27 -0
  199. package/lib/Types/index.js.map +1 -0
  200. package/lib/Utils/audioToBuffer.js +31 -0
  201. package/lib/Utils/auth-utils.d.ts +19 -0
  202. package/lib/Utils/auth-utils.d.ts.map +1 -0
  203. package/lib/Utils/auth-utils.js +290 -0
  204. package/lib/Utils/auth-utils.js.map +1 -0
  205. package/lib/Utils/baileys-event-stream.js +54 -0
  206. package/lib/Utils/browser-utils.d.ts +4 -0
  207. package/lib/Utils/browser-utils.d.ts.map +1 -0
  208. package/lib/Utils/browser-utils.js +41 -0
  209. package/lib/Utils/browser-utils.js.map +1 -0
  210. package/lib/Utils/business.d.ts +23 -0
  211. package/lib/Utils/business.d.ts.map +1 -0
  212. package/lib/Utils/business.js +231 -0
  213. package/lib/Utils/business.js.map +1 -0
  214. package/lib/Utils/chat-utils.d.ts +70 -0
  215. package/lib/Utils/chat-utils.d.ts.map +1 -0
  216. package/lib/Utils/chat-utils.js +812 -0
  217. package/lib/Utils/chat-utils.js.map +1 -0
  218. package/lib/Utils/crypto.d.ts +37 -0
  219. package/lib/Utils/crypto.d.ts.map +1 -0
  220. package/lib/Utils/crypto.js +118 -0
  221. package/lib/Utils/crypto.js.map +1 -0
  222. package/lib/Utils/decode-wa-message.d.ts +48 -0
  223. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  224. package/lib/Utils/decode-wa-message.js +283 -0
  225. package/lib/Utils/decode-wa-message.js.map +1 -0
  226. package/lib/Utils/event-buffer.d.ts +34 -0
  227. package/lib/Utils/event-buffer.d.ts.map +1 -0
  228. package/lib/Utils/event-buffer.js +574 -0
  229. package/lib/Utils/event-buffer.js.map +1 -0
  230. package/lib/Utils/generics.d.ts +91 -0
  231. package/lib/Utils/generics.d.ts.map +1 -0
  232. package/lib/Utils/generics.js +411 -0
  233. package/lib/Utils/generics.js.map +1 -0
  234. package/lib/Utils/history.d.ts +22 -0
  235. package/lib/Utils/history.d.ts.map +1 -0
  236. package/lib/Utils/history.js +131 -0
  237. package/lib/Utils/history.js.map +1 -0
  238. package/lib/Utils/identity-change-handler.d.ts +37 -0
  239. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  240. package/lib/Utils/identity-change-handler.js +49 -0
  241. package/lib/Utils/identity-change-handler.js.map +1 -0
  242. package/lib/Utils/index.d.ts +22 -0
  243. package/lib/Utils/index.d.ts.map +1 -0
  244. package/lib/Utils/index.js +27 -0
  245. package/lib/Utils/index.js.map +1 -0
  246. package/lib/Utils/link-preview.d.ts +21 -0
  247. package/lib/Utils/link-preview.d.ts.map +1 -0
  248. package/lib/Utils/link-preview.js +85 -0
  249. package/lib/Utils/link-preview.js.map +1 -0
  250. package/lib/Utils/logger.d.ts +13 -0
  251. package/lib/Utils/logger.d.ts.map +1 -0
  252. package/lib/Utils/logger.js +3 -0
  253. package/lib/Utils/logger.js.map +1 -0
  254. package/lib/Utils/lt-hash.d.ts +8 -0
  255. package/lib/Utils/lt-hash.d.ts.map +1 -0
  256. package/lib/Utils/lt-hash.js +8 -0
  257. package/lib/Utils/lt-hash.js.map +1 -0
  258. package/lib/Utils/make-mutex.d.ts +9 -0
  259. package/lib/Utils/make-mutex.d.ts.map +1 -0
  260. package/lib/Utils/make-mutex.js +33 -0
  261. package/lib/Utils/make-mutex.js.map +1 -0
  262. package/lib/Utils/message-retry-manager.d.ts +110 -0
  263. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  264. package/lib/Utils/message-retry-manager.js +225 -0
  265. package/lib/Utils/message-retry-manager.js.map +1 -0
  266. package/lib/Utils/messages-media.d.ts +130 -0
  267. package/lib/Utils/messages-media.d.ts.map +1 -0
  268. package/lib/Utils/messages-media.js +830 -0
  269. package/lib/Utils/messages-media.js.map +1 -0
  270. package/lib/Utils/messages-newsletter.d.ts +84 -0
  271. package/lib/Utils/messages-newsletter.js +316 -0
  272. package/lib/Utils/messages.d.ts +92 -0
  273. package/lib/Utils/messages.d.ts.map +1 -0
  274. package/lib/Utils/messages.js +1699 -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 +201 -0
  279. package/lib/Utils/noise-handler.js.map +1 -0
  280. package/lib/Utils/pre-key-manager.d.ts +28 -0
  281. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  282. package/lib/Utils/pre-key-manager.js +106 -0
  283. package/lib/Utils/pre-key-manager.js.map +1 -0
  284. package/lib/Utils/process-message.d.ts +60 -0
  285. package/lib/Utils/process-message.d.ts.map +1 -0
  286. package/lib/Utils/process-message.js +528 -0
  287. package/lib/Utils/process-message.js.map +1 -0
  288. package/lib/Utils/reporting-utils.d.ts +11 -0
  289. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  290. package/lib/Utils/reporting-utils.js +258 -0
  291. package/lib/Utils/reporting-utils.js.map +1 -0
  292. package/lib/Utils/resolve-jid.d.ts +43 -0
  293. package/lib/Utils/resolve-jid.js +101 -0
  294. package/lib/Utils/signal.d.ts +34 -0
  295. package/lib/Utils/signal.d.ts.map +1 -0
  296. package/lib/Utils/signal.js +159 -0
  297. package/lib/Utils/signal.js.map +1 -0
  298. package/lib/Utils/streamToBuffer.js +17 -0
  299. package/lib/Utils/sync-action-utils.d.ts +19 -0
  300. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  301. package/lib/Utils/sync-action-utils.js +48 -0
  302. package/lib/Utils/sync-action-utils.js.map +1 -0
  303. package/lib/Utils/tc-token-utils.d.ts +12 -0
  304. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  305. package/lib/Utils/tc-token-utils.js +18 -0
  306. package/lib/Utils/tc-token-utils.js.map +1 -0
  307. package/lib/Utils/use-mongo-file-auth-state.js +77 -0
  308. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  309. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  310. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  311. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  312. package/lib/Utils/use-single-file-auth-state.js +74 -0
  313. package/lib/Utils/validate-connection.d.ts +11 -0
  314. package/lib/Utils/validate-connection.d.ts.map +1 -0
  315. package/lib/Utils/validate-connection.js +200 -0
  316. package/lib/Utils/validate-connection.js.map +1 -0
  317. package/lib/WABinary/constants.d.ts +28 -0
  318. package/lib/WABinary/constants.d.ts.map +1 -0
  319. package/lib/WABinary/constants.js +1301 -0
  320. package/lib/WABinary/constants.js.map +1 -0
  321. package/lib/WABinary/decode.d.ts +7 -0
  322. package/lib/WABinary/decode.d.ts.map +1 -0
  323. package/lib/WABinary/decode.js +262 -0
  324. package/lib/WABinary/decode.js.map +1 -0
  325. package/lib/WABinary/encode.d.ts +3 -0
  326. package/lib/WABinary/encode.d.ts.map +1 -0
  327. package/lib/WABinary/encode.js +220 -0
  328. package/lib/WABinary/encode.js.map +1 -0
  329. package/lib/WABinary/generic-utils.d.ts +15 -0
  330. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  331. package/lib/WABinary/generic-utils.js +128 -0
  332. package/lib/WABinary/generic-utils.js.map +1 -0
  333. package/lib/WABinary/index.d.ts +6 -0
  334. package/lib/WABinary/index.d.ts.map +1 -0
  335. package/lib/WABinary/index.js +7 -0
  336. package/lib/WABinary/index.js.map +1 -0
  337. package/lib/WABinary/jid-utils.d.ts +48 -0
  338. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  339. package/lib/WABinary/jid-utils.js +98 -0
  340. package/lib/WABinary/jid-utils.js.map +1 -0
  341. package/lib/WABinary/types.d.ts +19 -0
  342. package/lib/WABinary/types.d.ts.map +1 -0
  343. package/lib/WABinary/types.js +2 -0
  344. package/lib/WABinary/types.js.map +1 -0
  345. package/lib/WAM/BinaryInfo.d.ts +9 -0
  346. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  347. package/lib/WAM/BinaryInfo.js +10 -0
  348. package/lib/WAM/BinaryInfo.js.map +1 -0
  349. package/lib/WAM/constants.d.ts +40 -0
  350. package/lib/WAM/constants.d.ts.map +1 -0
  351. package/lib/WAM/constants.js +22853 -0
  352. package/lib/WAM/constants.js.map +1 -0
  353. package/lib/WAM/encode.d.ts +3 -0
  354. package/lib/WAM/encode.d.ts.map +1 -0
  355. package/lib/WAM/encode.js +150 -0
  356. package/lib/WAM/encode.js.map +1 -0
  357. package/lib/WAM/index.d.ts +4 -0
  358. package/lib/WAM/index.d.ts.map +1 -0
  359. package/lib/WAM/index.js +4 -0
  360. package/lib/WAM/index.js.map +1 -0
  361. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  362. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  363. package/lib/WAUSync/Protocols/USyncContactProtocol.js +29 -0
  364. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  365. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  366. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  367. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  368. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  369. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  370. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  371. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  372. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  373. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  374. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  375. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  376. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  377. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  378. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  379. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  380. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  381. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  382. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  383. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  384. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  385. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  386. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  387. package/lib/WAUSync/Protocols/index.js +6 -0
  388. package/lib/WAUSync/Protocols/index.js.map +1 -0
  389. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  390. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  391. package/lib/WAUSync/USyncQuery.js +94 -0
  392. package/lib/WAUSync/USyncQuery.js.map +1 -0
  393. package/lib/WAUSync/USyncUser.d.ts +13 -0
  394. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  395. package/lib/WAUSync/USyncUser.js +23 -0
  396. package/lib/WAUSync/USyncUser.js.map +1 -0
  397. package/lib/WAUSync/index.d.ts +4 -0
  398. package/lib/WAUSync/index.d.ts.map +1 -0
  399. package/lib/WAUSync/index.js +4 -0
  400. package/lib/WAUSync/index.js.map +1 -0
  401. package/lib/index.d.ts +12 -0
  402. package/lib/index.d.ts.map +1 -0
  403. package/lib/index.js +31 -0
  404. package/lib/index.js.map +1 -0
  405. package/package.json +94 -0
@@ -0,0 +1,1133 @@
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';
14
+ const MAX_SYNC_ATTEMPTS = 2;
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;
19
+ let privacySettings;
20
+ let syncState = SyncState.Connecting;
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
30
+ let awaitingSyncTimeout;
31
+ const placeholderResendCache = config.placeholderResendCache ||
32
+ new NodeCache({
33
+ stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
34
+ useClones: false
35
+ });
36
+ if (!config.placeholderResendCache) {
37
+ config.placeholderResendCache = placeholderResendCache;
38
+ }
39
+ /** helper function to fetch the given app state sync key */
40
+ const getAppStateSyncKey = async (keyId) => {
41
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
42
+ return key;
43
+ };
44
+ const fetchPrivacySettings = async (force = false) => {
45
+ if (!privacySettings || force) {
46
+ const { content } = await query({
47
+ tag: 'iq',
48
+ attrs: {
49
+ xmlns: 'privacy',
50
+ to: S_WHATSAPP_NET,
51
+ type: 'get'
52
+ },
53
+ content: [{ tag: 'privacy', attrs: {} }]
54
+ });
55
+ privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
56
+ }
57
+ return privacySettings;
58
+ };
59
+ /** helper function to run a privacy IQ query */
60
+ const privacyQuery = async (name, value) => {
61
+ await query({
62
+ tag: 'iq',
63
+ attrs: {
64
+ xmlns: 'privacy',
65
+ to: S_WHATSAPP_NET,
66
+ type: 'set'
67
+ },
68
+ content: [
69
+ {
70
+ tag: 'privacy',
71
+ attrs: {},
72
+ content: [
73
+ {
74
+ tag: 'category',
75
+ attrs: { name, value }
76
+ }
77
+ ]
78
+ }
79
+ ]
80
+ });
81
+ };
82
+ const updateMessagesPrivacy = async (value) => {
83
+ await privacyQuery('messages', value);
84
+ };
85
+ const updateCallPrivacy = async (value) => {
86
+ await privacyQuery('calladd', value);
87
+ };
88
+ const updateLastSeenPrivacy = async (value) => {
89
+ await privacyQuery('last', value);
90
+ };
91
+ const updateOnlinePrivacy = async (value) => {
92
+ await privacyQuery('online', value);
93
+ };
94
+ const updateProfilePicturePrivacy = async (value) => {
95
+ await privacyQuery('profile', value);
96
+ };
97
+ const updateStatusPrivacy = async (value) => {
98
+ await privacyQuery('status', value);
99
+ };
100
+ const updateReadReceiptsPrivacy = async (value) => {
101
+ await privacyQuery('readreceipts', value);
102
+ };
103
+ const updateGroupsAddPrivacy = async (value) => {
104
+ await privacyQuery('groupadd', value);
105
+ };
106
+ const updateDefaultDisappearingMode = async (duration) => {
107
+ await query({
108
+ tag: 'iq',
109
+ attrs: {
110
+ xmlns: 'disappearing_mode',
111
+ to: S_WHATSAPP_NET,
112
+ type: 'set'
113
+ },
114
+ content: [
115
+ {
116
+ tag: 'disappearing_mode',
117
+ attrs: {
118
+ duration: duration.toString()
119
+ }
120
+ }
121
+ ]
122
+ });
123
+ };
124
+ const getBotListV2 = async () => {
125
+ const resp = await query({
126
+ tag: 'iq',
127
+ attrs: {
128
+ xmlns: 'bot',
129
+ to: S_WHATSAPP_NET,
130
+ type: 'get'
131
+ },
132
+ content: [
133
+ {
134
+ tag: 'bot',
135
+ attrs: {
136
+ v: '2'
137
+ }
138
+ }
139
+ ]
140
+ });
141
+ const botNode = getBinaryNodeChild(resp, 'bot');
142
+ const botList = [];
143
+ for (const section of getBinaryNodeChildren(botNode, 'section')) {
144
+ if (section.attrs.type === 'all') {
145
+ for (const bot of getBinaryNodeChildren(section, 'bot')) {
146
+ botList.push({
147
+ jid: bot.attrs.jid,
148
+ personaId: bot.attrs['persona_id']
149
+ });
150
+ }
151
+ }
152
+ }
153
+ return botList;
154
+ };
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!');
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;
171
+ };
172
+ const fetchStatus = async (...jids) => {
173
+ const usyncQuery = new USyncQuery().withStatusProtocol();
174
+ for (const jid of jids) {
175
+ usyncQuery.withUser(new USyncUser().withId(jid));
176
+ }
177
+ const result = await sock.executeUSyncQuery(usyncQuery);
178
+ if (result) {
179
+ return result.list;
180
+ }
181
+ };
182
+ const fetchDisappearingDuration = async (...jids) => {
183
+ const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
184
+ for (const jid of jids) {
185
+ usyncQuery.withUser(new USyncUser().withId(jid));
186
+ }
187
+ const result = await sock.executeUSyncQuery(usyncQuery);
188
+ if (result) {
189
+ return result.list;
190
+ }
191
+ };
192
+ /** update the profile picture for yourself or a group */
193
+ const updateProfilePicture = async (jid, content, dimensions) => {
194
+ let targetJid;
195
+ if (!jid) {
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
200
+ }
201
+ else {
202
+ targetJid = undefined;
203
+ }
204
+ const { img } = await generateProfilePicture(content, dimensions);
205
+ await query({
206
+ tag: 'iq',
207
+ attrs: {
208
+ to: S_WHATSAPP_NET,
209
+ type: 'set',
210
+ xmlns: 'w:profile:picture',
211
+ ...(targetJid ? { target: targetJid } : {})
212
+ },
213
+ content: [
214
+ {
215
+ tag: 'picture',
216
+ attrs: { type: 'image' },
217
+ content: img
218
+ }
219
+ ]
220
+ });
221
+ };
222
+ /** remove the profile picture for yourself or a group */
223
+ const removeProfilePicture = async (jid) => {
224
+ let targetJid;
225
+ if (!jid) {
226
+ throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
227
+ }
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;
233
+ }
234
+ await query({
235
+ tag: 'iq',
236
+ attrs: {
237
+ to: S_WHATSAPP_NET,
238
+ type: 'set',
239
+ xmlns: 'w:profile:picture',
240
+ ...(targetJid ? { target: targetJid } : {})
241
+ }
242
+ });
243
+ };
244
+ /** update the profile status for yourself */
245
+ const updateProfileStatus = async (status) => {
246
+ await query({
247
+ tag: 'iq',
248
+ attrs: {
249
+ to: S_WHATSAPP_NET,
250
+ type: 'set',
251
+ xmlns: 'status'
252
+ },
253
+ content: [
254
+ {
255
+ tag: 'status',
256
+ attrs: {},
257
+ content: Buffer.from(status, 'utf-8')
258
+ }
259
+ ]
260
+ });
261
+ };
262
+ const updateProfileName = async (name) => {
263
+ await chatModify({ pushNameSetting: name }, '');
264
+ };
265
+ const fetchBlocklist = async () => {
266
+ const result = await query({
267
+ tag: 'iq',
268
+ attrs: {
269
+ xmlns: 'blocklist',
270
+ to: S_WHATSAPP_NET,
271
+ type: 'get'
272
+ }
273
+ });
274
+ const listNode = getBinaryNodeChild(result, 'list');
275
+ return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
276
+ };
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
+ }
296
+ await query({
297
+ tag: 'iq',
298
+ attrs: {
299
+ xmlns: 'blocklist',
300
+ to: S_WHATSAPP_NET,
301
+ type: 'set'
302
+ },
303
+ content: [
304
+ {
305
+ tag: 'item',
306
+ attrs: itemAttrs
307
+ }
308
+ ]
309
+ });
310
+ };
311
+ const getBusinessProfile = async (jid) => {
312
+ const results = await query({
313
+ tag: 'iq',
314
+ attrs: {
315
+ to: 's.whatsapp.net',
316
+ xmlns: 'w:biz',
317
+ type: 'get'
318
+ },
319
+ content: [
320
+ {
321
+ tag: 'business_profile',
322
+ attrs: { v: '244' },
323
+ content: [
324
+ {
325
+ tag: 'profile',
326
+ attrs: { jid }
327
+ }
328
+ ]
329
+ }
330
+ ]
331
+ });
332
+ const profileNode = getBinaryNodeChild(results, 'business_profile');
333
+ const profiles = getBinaryNodeChild(profileNode, 'profile');
334
+ if (profiles) {
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');
341
+ const businessHoursConfig = businessHours
342
+ ? getBinaryNodeChildren(businessHours, 'business_hours_config')
343
+ : undefined;
344
+ const websiteStr = website?.content?.toString();
345
+ return {
346
+ wid: profiles.attrs?.jid,
347
+ address: address?.content?.toString(),
348
+ description: description?.content?.toString() || '',
349
+ website: websiteStr ? [websiteStr] : [],
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)
355
+ }
356
+ };
357
+ }
358
+ };
359
+ const cleanDirtyBits = async (type, fromTimestamp) => {
360
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
361
+ await sendNode({
362
+ tag: 'iq',
363
+ attrs: {
364
+ to: S_WHATSAPP_NET,
365
+ type: 'set',
366
+ xmlns: 'urn:xmpp:whatsapp:dirty',
367
+ id: generateMessageTag()
368
+ },
369
+ content: [
370
+ {
371
+ tag: 'clean',
372
+ attrs: {
373
+ type,
374
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
375
+ }
376
+ }
377
+ ]
378
+ });
379
+ };
380
+ const newAppStateChunkHandler = (isInitialSync) => {
381
+ return {
382
+ onMutation(mutation) {
383
+ processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
384
+ }
385
+ };
386
+ };
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
399
+ const initialVersionMap = {};
400
+ const globalMutationMap = {};
401
+ await authState.keys.transaction(async () => {
402
+ const collectionsToHandle = new Set(collections);
403
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
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)
408
+ while (collectionsToHandle.size) {
409
+ const states = {};
410
+ const nodes = [];
411
+ for (const name of collectionsToHandle) {
412
+ const result = await authState.keys.get('app-state-sync-version', [name]);
413
+ let state = result[name];
414
+ if (state) {
415
+ if (typeof initialVersionMap[name] === 'undefined') {
416
+ initialVersionMap[name] = state.version;
417
+ }
418
+ }
419
+ else {
420
+ state = newLTHashState();
421
+ }
422
+ states[name] = state;
423
+ logger.info(`resyncing ${name} from v${state.version}`);
424
+ nodes.push({
425
+ tag: 'collection',
426
+ attrs: {
427
+ name,
428
+ version: state.version.toString(),
429
+ // return snapshot if being synced from scratch
430
+ return_snapshot: (!state.version).toString()
431
+ }
432
+ });
433
+ }
434
+ const result = await query({
435
+ tag: 'iq',
436
+ attrs: {
437
+ to: S_WHATSAPP_NET,
438
+ xmlns: 'w:sync:app:state',
439
+ type: 'set'
440
+ },
441
+ content: [
442
+ {
443
+ tag: 'sync',
444
+ attrs: {},
445
+ content: nodes
446
+ }
447
+ ]
448
+ });
449
+ // extract from binary node
450
+ const decoded = await extractSyncdPatches(result, config?.options);
451
+ for (const key in decoded) {
452
+ const name = key;
453
+ const { patches, hasMorePatches, snapshot } = decoded[name];
454
+ try {
455
+ if (snapshot) {
456
+ const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
457
+ states[name] = newState;
458
+ Object.assign(globalMutationMap, mutationMap);
459
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
460
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
461
+ }
462
+ // only process if there are syncd patches
463
+ if (patches.length) {
464
+ const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
465
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
466
+ logger.info(`synced ${name} to v${newState.version}`);
467
+ initialVersionMap[name] = newState.version;
468
+ Object.assign(globalMutationMap, mutationMap);
469
+ }
470
+ if (hasMorePatches) {
471
+ logger.info(`${name} has more patches...`);
472
+ }
473
+ else {
474
+ // collection is done with sync
475
+ collectionsToHandle.delete(name);
476
+ }
477
+ }
478
+ catch (error) {
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';
484
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
485
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
486
+ // increment number of retries
487
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
488
+ if (isIrrecoverableError) {
489
+ // stop retrying
490
+ collectionsToHandle.delete(name);
491
+ }
492
+ }
493
+ }
494
+ }
495
+ }, authState?.creds?.me?.id || 'resync-app-state');
496
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
497
+ for (const key in globalMutationMap) {
498
+ onMutation(globalMutationMap[key]);
499
+ }
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
+ */
506
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
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;
522
+ };
523
+ const createCallLink = async (type, event, timeoutMs) => {
524
+ const result = await query({
525
+ tag: 'call',
526
+ attrs: {
527
+ id: generateMessageTag(),
528
+ to: '@call'
529
+ },
530
+ content: [
531
+ {
532
+ tag: 'link_create',
533
+ attrs: { media: type },
534
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
535
+ }
536
+ ]
537
+ }, timeoutMs);
538
+ const child = getBinaryNodeChild(result, 'link_create');
539
+ return child?.attrs?.token;
540
+ };
541
+ const sendPresenceUpdate = async (type, toJid) => {
542
+ const me = authState.creds.me;
543
+ const isAvailableType = type === 'available';
544
+ if (isAvailableType || type === 'unavailable') {
545
+ if (!me.name) {
546
+ logger.warn('no name present, ignoring presence update request...');
547
+ return;
548
+ }
549
+ ev.emit('connection.update', { isOnline: isAvailableType });
550
+ if (isAvailableType) {
551
+ void sendUnifiedSession();
552
+ }
553
+ await sendNode({
554
+ tag: 'presence',
555
+ attrs: {
556
+ name: me.name.replace(/@/g, ''),
557
+ type
558
+ }
559
+ });
560
+ }
561
+ else {
562
+ const { server } = jidDecode(toJid);
563
+ const isLid = server === 'lid';
564
+ await sendNode({
565
+ tag: 'chatstate',
566
+ attrs: {
567
+ from: isLid ? me.lid : me.id,
568
+ to: toJid
569
+ },
570
+ content: [
571
+ {
572
+ tag: type === 'recording' ? 'composing' : type,
573
+ attrs: type === 'recording' ? { media: 'audio' } : {}
574
+ }
575
+ ]
576
+ });
577
+ }
578
+ };
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
+ };
595
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
596
+ let presence;
597
+ const jid = attrs.from;
598
+ const participant = attrs.participant || attrs.from;
599
+ if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
600
+ return;
601
+ }
602
+ if (tag === 'presence') {
603
+ presence = {
604
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
605
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
606
+ };
607
+ }
608
+ else if (Array.isArray(content)) {
609
+ const [firstChild] = content;
610
+ let type = firstChild.tag;
611
+ if (type === 'paused') {
612
+ type = 'available';
613
+ }
614
+ if (firstChild.attrs?.media === 'audio') {
615
+ type = 'recording';
616
+ }
617
+ presence = { lastKnownPresence: type };
618
+ }
619
+ else {
620
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
621
+ }
622
+ if (presence) {
623
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
624
+ }
625
+ };
626
+ const appPatch = async (patchCreate) => {
627
+ const name = patchCreate.type;
628
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
629
+ if (!myAppStateKeyId) {
630
+ throw new Boom('App state key not present!', { statusCode: 400 });
631
+ }
632
+ let initial;
633
+ let encodeResult;
634
+ await appStatePatchMutex.mutex(async () => {
635
+ await authState.keys.transaction(async () => {
636
+ logger.debug({ patch: patchCreate }, 'applying app patch');
637
+ await resyncAppState([name], false);
638
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
639
+ initial = currentSyncVersion || newLTHashState();
640
+ encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
641
+ const { patch, state } = encodeResult;
642
+ const node = {
643
+ tag: 'iq',
644
+ attrs: {
645
+ to: S_WHATSAPP_NET,
646
+ type: 'set',
647
+ xmlns: 'w:sync:app:state'
648
+ },
649
+ content: [
650
+ {
651
+ tag: 'sync',
652
+ attrs: {},
653
+ content: [
654
+ {
655
+ tag: 'collection',
656
+ attrs: {
657
+ name,
658
+ version: (state.version - 1).toString(),
659
+ return_snapshot: 'false'
660
+ },
661
+ content: [
662
+ {
663
+ tag: 'patch',
664
+ attrs: {},
665
+ content: proto.SyncdPatch.encode(patch).finish()
666
+ }
667
+ ]
668
+ }
669
+ ]
670
+ }
671
+ ]
672
+ };
673
+ await query(node);
674
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
675
+ }, authState?.creds?.me?.id || 'app-patch');
676
+ });
677
+ if (config.emitOwnEvents) {
678
+ const { onMutation } = newAppStateChunkHandler(false);
679
+ const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
680
+ for (const key in mutationMap) {
681
+ onMutation(mutationMap[key]);
682
+ }
683
+ }
684
+ };
685
+ /** sending non-abt props may fix QR scan fail if server expects */
686
+ const fetchProps = async () => {
687
+ //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
688
+ const resultNode = await query({
689
+ tag: 'iq',
690
+ attrs: {
691
+ to: S_WHATSAPP_NET,
692
+ xmlns: 'w',
693
+ type: 'get'
694
+ },
695
+ content: [
696
+ {
697
+ tag: 'props',
698
+ attrs: {
699
+ protocol: '2',
700
+ hash: authState?.creds?.lastPropHash || ''
701
+ }
702
+ }
703
+ ]
704
+ });
705
+ const propsNode = getBinaryNodeChild(resultNode, 'props');
706
+ let props = {};
707
+ if (propsNode) {
708
+ if (propsNode.attrs?.hash) {
709
+ // on some clients, the hash is returning as undefined
710
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
711
+ ev.emit('creds.update', authState.creds);
712
+ }
713
+ props = reduceBinaryNodeToDictionary(propsNode, 'prop');
714
+ }
715
+ logger.debug('fetched props');
716
+ return props;
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
+ */
723
+ const chatModify = (mod, jid) => {
724
+ const patch = chatModificationToAppPatch(mod, jid);
725
+ return appPatch(patch);
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
+ */
738
+ const star = (jid, messages, star) => {
739
+ return chatModify({
740
+ star: {
741
+ messages,
742
+ star
743
+ }
744
+ }, jid);
745
+ };
746
+ /**
747
+ * Add or Edit Contact
748
+ */
749
+ const addOrEditContact = (jid, contact) => {
750
+ return chatModify({
751
+ contact
752
+ }, jid);
753
+ };
754
+ /**
755
+ * Remove Contact
756
+ */
757
+ const removeContact = (jid) => {
758
+ return chatModify({
759
+ contact: null
760
+ }, jid);
761
+ };
762
+ /**
763
+ * Adds label
764
+ */
765
+ const addLabel = (jid, labels) => {
766
+ return chatModify({
767
+ addLabel: {
768
+ ...labels
769
+ }
770
+ }, jid);
771
+ };
772
+ /**
773
+ * Adds label for the chats
774
+ */
775
+ const addChatLabel = (jid, labelId) => {
776
+ return chatModify({
777
+ addChatLabel: {
778
+ labelId
779
+ }
780
+ }, jid);
781
+ };
782
+ /**
783
+ * Removes label for the chat
784
+ */
785
+ const removeChatLabel = (jid, labelId) => {
786
+ return chatModify({
787
+ removeChatLabel: {
788
+ labelId
789
+ }
790
+ }, jid);
791
+ };
792
+ /**
793
+ * Adds label for the message
794
+ */
795
+ const addMessageLabel = (jid, messageId, labelId) => {
796
+ return chatModify({
797
+ addMessageLabel: {
798
+ messageId,
799
+ labelId
800
+ }
801
+ }, jid);
802
+ };
803
+ /**
804
+ * Removes label for the message
805
+ */
806
+ const removeMessageLabel = (jid, messageId, labelId) => {
807
+ return chatModify({
808
+ removeMessageLabel: {
809
+ messageId,
810
+ labelId
811
+ }
812
+ }, jid);
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
+ * */
834
+ const executeInitQueries = async () => {
835
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
836
+ };
837
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
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
+ // ─────────────────────────────────────────────────────────────────────
892
+ ev.emit('messages.upsert', { messages: [msg], type });
893
+ if (!!msg.pushName) {
894
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
895
+ jid = jidNormalizedUser(jid);
896
+ if (!msg.key.fromMe) {
897
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
898
+ }
899
+ // update our pushname too
900
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
901
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
902
+ }
903
+ }
904
+ const historyMsg = getHistoryMsg(msg.message);
905
+ const shouldProcessHistoryMsg = historyMsg
906
+ ? shouldSyncHistoryMessage(historyMsg) &&
907
+ PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
908
+ : false;
909
+ // State machine: decide on sync and flush
910
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
911
+ if (awaitingSyncTimeout) {
912
+ clearTimeout(awaitingSyncTimeout);
913
+ awaitingSyncTimeout = undefined;
914
+ }
915
+ if (shouldProcessHistoryMsg) {
916
+ syncState = SyncState.Syncing;
917
+ logger.info('Transitioned to Syncing state');
918
+ // Let doAppStateSync handle the final flush after it's done
919
+ }
920
+ else {
921
+ syncState = SyncState.Online;
922
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
923
+ ev.flush();
924
+ }
925
+ }
926
+ const doAppStateSync = async () => {
927
+ if (syncState === SyncState.Syncing) {
928
+ logger.info('Doing app state sync');
929
+ await resyncAppState(ALL_WA_PATCH_NAMES, true);
930
+ // Sync is complete, go online and flush everything
931
+ syncState = SyncState.Online;
932
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
933
+ ev.flush();
934
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
935
+ ev.emit('creds.update', { accountSyncCounter });
936
+ }
937
+ };
938
+ await Promise.all([
939
+ (async () => {
940
+ if (shouldProcessHistoryMsg) {
941
+ await doAppStateSync();
942
+ }
943
+ })(),
944
+ processMessage(msg, {
945
+ signalRepository,
946
+ shouldProcessHistoryMsg,
947
+ placeholderResendCache,
948
+ ev,
949
+ creds: authState.creds,
950
+ keyStore: authState.keys,
951
+ logger,
952
+ options: config.options,
953
+ getMessage
954
+ })
955
+ ]);
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');
959
+ await doAppStateSync();
960
+ }
961
+ });
962
+ ws.on('CB:presence', handlePresenceUpdate);
963
+ ws.on('CB:chatstate', handlePresenceUpdate);
964
+ ws.on('CB:ib,,dirty', async (node) => {
965
+ const { attrs } = getBinaryNodeChild(node, 'dirty');
966
+ const type = attrs.type;
967
+ switch (type) {
968
+ case 'account_sync':
969
+ if (attrs.timestamp) {
970
+ let { lastAccountSyncTimestamp } = authState.creds;
971
+ if (lastAccountSyncTimestamp) {
972
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
973
+ }
974
+ lastAccountSyncTimestamp = +attrs.timestamp;
975
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
976
+ }
977
+ break;
978
+ case 'groups':
979
+ // handled in groups.ts
980
+ break;
981
+ default:
982
+ logger.info({ node }, 'received unknown sync');
983
+ break;
984
+ }
985
+ });
986
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
987
+ if (connection === 'open') {
988
+ if (fireInitQueries) {
989
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
990
+ }
991
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
992
+ }
993
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
994
+ return;
995
+ }
996
+ syncState = SyncState.AwaitingInitialSync;
997
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
998
+ ev.buffer();
999
+ const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
1000
+ syncType: proto.HistorySync.HistorySyncType.RECENT
1001
+ }));
1002
+ if (!willSyncHistory) {
1003
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
1004
+ syncState = SyncState.Online;
1005
+ setTimeout(() => ev.flush(), 0);
1006
+ return;
1007
+ }
1008
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
1009
+ if (awaitingSyncTimeout) {
1010
+ clearTimeout(awaitingSyncTimeout);
1011
+ }
1012
+ awaitingSyncTimeout = setTimeout(() => {
1013
+ if (syncState === SyncState.AwaitingInitialSync) {
1014
+ // TODO: investigate
1015
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1016
+ syncState = SyncState.Online;
1017
+ ev.flush();
1018
+ }
1019
+ }, 20000);
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
+ });
1075
+ return {
1076
+ ...sock,
1077
+ createCallLink,
1078
+ getBotListV2,
1079
+ messageMutex,
1080
+ receiptMutex,
1081
+ appStatePatchMutex,
1082
+ notificationMutex,
1083
+ fetchPrivacySettings,
1084
+ upsertMessage,
1085
+ appPatch,
1086
+ sendPresenceUpdate,
1087
+ presenceSubscribe,
1088
+ profilePictureUrl,
1089
+ fetchBlocklist,
1090
+ fetchStatus,
1091
+ fetchDisappearingDuration,
1092
+ updateProfilePicture,
1093
+ removeProfilePicture,
1094
+ updateProfileStatus,
1095
+ updateProfileName,
1096
+ updateBlockStatus,
1097
+ updateDisableLinkPreviewsPrivacy,
1098
+ updateCallPrivacy,
1099
+ updateMessagesPrivacy,
1100
+ updateLastSeenPrivacy,
1101
+ updateOnlinePrivacy,
1102
+ updateProfilePicturePrivacy,
1103
+ updateStatusPrivacy,
1104
+ updateReadReceiptsPrivacy,
1105
+ updateGroupsAddPrivacy,
1106
+ updateDefaultDisappearingMode,
1107
+ getBusinessProfile,
1108
+ resyncAppState,
1109
+ chatModify,
1110
+ cleanDirtyBits,
1111
+ addOrEditContact,
1112
+ removeContact,
1113
+ addLabel,
1114
+ addChatLabel,
1115
+ removeChatLabel,
1116
+ addMessageLabel,
1117
+ removeMessageLabel,
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
1131
+ };
1132
+ };
1133
+ //# sourceMappingURL=chats.js.map