fyoutoo 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (401) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +275 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +97691 -0
  8. package/engine-requirements.js +11 -0
  9. package/lib/Defaults/index.d.ts +75 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +129 -0
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  15. package/lib/Signal/Group/ciphertext-message.js +12 -0
  16. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  18. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  19. package/lib/Signal/Group/group-session-builder.js +30 -0
  20. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  21. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  22. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  23. package/lib/Signal/Group/group_cipher.js +82 -0
  24. package/lib/Signal/Group/group_cipher.js.map +1 -0
  25. package/lib/Signal/Group/index.d.ts +12 -0
  26. package/lib/Signal/Group/index.d.ts.map +1 -0
  27. package/lib/Signal/Group/index.js +12 -0
  28. package/lib/Signal/Group/index.js.map +1 -0
  29. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  30. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  31. package/lib/Signal/Group/keyhelper.js +18 -0
  32. package/lib/Signal/Group/keyhelper.js.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  34. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  35. package/lib/Signal/Group/sender-chain-key.js +26 -0
  36. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  42. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  43. package/lib/Signal/Group/sender-key-message.js +66 -0
  44. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  46. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  47. package/lib/Signal/Group/sender-key-name.js +48 -0
  48. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  50. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  51. package/lib/Signal/Group/sender-key-record.js +41 -0
  52. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  54. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  55. package/lib/Signal/Group/sender-key-state.js +84 -0
  56. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  58. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  59. package/lib/Signal/Group/sender-message-key.js +26 -0
  60. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  61. package/lib/Signal/libsignal.d.ts +5 -0
  62. package/lib/Signal/libsignal.d.ts.map +1 -0
  63. package/lib/Signal/libsignal.js +437 -0
  64. package/lib/Signal/libsignal.js.map +1 -0
  65. package/lib/Signal/lid-mapping.d.ts +23 -0
  66. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  67. package/lib/Signal/lid-mapping.js +277 -0
  68. package/lib/Signal/lid-mapping.js.map +1 -0
  69. package/lib/Socket/Client/index.d.ts +3 -0
  70. package/lib/Socket/Client/index.d.ts.map +1 -0
  71. package/lib/Socket/Client/index.js +3 -0
  72. package/lib/Socket/Client/index.js.map +1 -0
  73. package/lib/Socket/Client/types.d.ts +16 -0
  74. package/lib/Socket/Client/types.d.ts.map +1 -0
  75. package/lib/Socket/Client/types.js +11 -0
  76. package/lib/Socket/Client/types.js.map +1 -0
  77. package/lib/Socket/Client/websocket.d.ts +13 -0
  78. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  79. package/lib/Socket/Client/websocket.js +54 -0
  80. package/lib/Socket/Client/websocket.js.map +1 -0
  81. package/lib/Socket/business.d.ts +217 -0
  82. package/lib/Socket/business.d.ts.map +1 -0
  83. package/lib/Socket/business.js +379 -0
  84. package/lib/Socket/business.js.map +1 -0
  85. package/lib/Socket/chats.d.ts +124 -0
  86. package/lib/Socket/chats.d.ts.map +1 -0
  87. package/lib/Socket/chats.js +1193 -0
  88. package/lib/Socket/chats.js.map +1 -0
  89. package/lib/Socket/communities.d.ts +273 -0
  90. package/lib/Socket/communities.d.ts.map +1 -0
  91. package/lib/Socket/communities.js +431 -0
  92. package/lib/Socket/communities.js.map +1 -0
  93. package/lib/Socket/groups.d.ts +161 -0
  94. package/lib/Socket/groups.d.ts.map +1 -0
  95. package/lib/Socket/groups.js +347 -0
  96. package/lib/Socket/groups.js.map +1 -0
  97. package/lib/Socket/index.d.ts +260 -0
  98. package/lib/Socket/index.d.ts.map +1 -0
  99. package/lib/Socket/index.js +12 -0
  100. package/lib/Socket/index.js.map +1 -0
  101. package/lib/Socket/messages-recv.d.ts +203 -0
  102. package/lib/Socket/messages-recv.d.ts.map +1 -0
  103. package/lib/Socket/messages-recv.js +1772 -0
  104. package/lib/Socket/messages-recv.js.map +1 -0
  105. package/lib/Socket/messages-send.d.ts +199 -0
  106. package/lib/Socket/messages-send.d.ts.map +1 -0
  107. package/lib/Socket/messages-send.js +1476 -0
  108. package/lib/Socket/messages-send.js.map +1 -0
  109. package/lib/Socket/mex.d.ts +3 -0
  110. package/lib/Socket/mex.d.ts.map +1 -0
  111. package/lib/Socket/mex.js +42 -0
  112. package/lib/Socket/mex.js.map +1 -0
  113. package/lib/Socket/newsletter.d.ts +170 -0
  114. package/lib/Socket/newsletter.d.ts.map +1 -0
  115. package/lib/Socket/newsletter.js +387 -0
  116. package/lib/Socket/newsletter.js.map +1 -0
  117. package/lib/Socket/socket.d.ts +59 -0
  118. package/lib/Socket/socket.d.ts.map +1 -0
  119. package/lib/Socket/socket.js +967 -0
  120. package/lib/Socket/socket.js.map +1 -0
  121. package/lib/Types/Auth.d.ts +117 -0
  122. package/lib/Types/Auth.d.ts.map +1 -0
  123. package/lib/Types/Auth.js +2 -0
  124. package/lib/Types/Auth.js.map +1 -0
  125. package/lib/Types/Bussines.d.ts +25 -0
  126. package/lib/Types/Bussines.d.ts.map +1 -0
  127. package/lib/Types/Bussines.js +2 -0
  128. package/lib/Types/Bussines.js.map +1 -0
  129. package/lib/Types/Call.d.ts +15 -0
  130. package/lib/Types/Call.d.ts.map +1 -0
  131. package/lib/Types/Call.js +2 -0
  132. package/lib/Types/Call.js.map +1 -0
  133. package/lib/Types/Chat.d.ts +124 -0
  134. package/lib/Types/Chat.d.ts.map +1 -0
  135. package/lib/Types/Chat.js +8 -0
  136. package/lib/Types/Chat.js.map +1 -0
  137. package/lib/Types/Contact.d.ts +26 -0
  138. package/lib/Types/Contact.d.ts.map +1 -0
  139. package/lib/Types/Contact.js +2 -0
  140. package/lib/Types/Contact.js.map +1 -0
  141. package/lib/Types/Events.d.ts +256 -0
  142. package/lib/Types/Events.d.ts.map +1 -0
  143. package/lib/Types/Events.js +2 -0
  144. package/lib/Types/Events.js.map +1 -0
  145. package/lib/Types/GroupMetadata.d.ts +71 -0
  146. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  147. package/lib/Types/GroupMetadata.js +2 -0
  148. package/lib/Types/GroupMetadata.js.map +1 -0
  149. package/lib/Types/Label.d.ts +47 -0
  150. package/lib/Types/Label.d.ts.map +1 -0
  151. package/lib/Types/Label.js +25 -0
  152. package/lib/Types/Label.js.map +1 -0
  153. package/lib/Types/LabelAssociation.d.ts +30 -0
  154. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  155. package/lib/Types/LabelAssociation.js +7 -0
  156. package/lib/Types/LabelAssociation.js.map +1 -0
  157. package/lib/Types/Message.d.ts +320 -0
  158. package/lib/Types/Message.d.ts.map +1 -0
  159. package/lib/Types/Message.js +11 -0
  160. package/lib/Types/Message.js.map +1 -0
  161. package/lib/Types/Mex.d.ts +141 -0
  162. package/lib/Types/Mex.d.ts.map +1 -0
  163. package/lib/Types/Mex.js +37 -0
  164. package/lib/Types/Mex.js.map +1 -0
  165. package/lib/Types/Product.d.ts +79 -0
  166. package/lib/Types/Product.d.ts.map +1 -0
  167. package/lib/Types/Product.js +2 -0
  168. package/lib/Types/Product.js.map +1 -0
  169. package/lib/Types/Signal.d.ts +87 -0
  170. package/lib/Types/Signal.d.ts.map +1 -0
  171. package/lib/Types/Signal.js +2 -0
  172. package/lib/Types/Signal.js.map +1 -0
  173. package/lib/Types/Socket.d.ts +136 -0
  174. package/lib/Types/Socket.d.ts.map +1 -0
  175. package/lib/Types/Socket.js +3 -0
  176. package/lib/Types/Socket.js.map +1 -0
  177. package/lib/Types/State.d.ts +97 -0
  178. package/lib/Types/State.d.ts.map +1 -0
  179. package/lib/Types/State.js +56 -0
  180. package/lib/Types/State.js.map +1 -0
  181. package/lib/Types/USync.d.ts +26 -0
  182. package/lib/Types/USync.d.ts.map +1 -0
  183. package/lib/Types/USync.js +2 -0
  184. package/lib/Types/USync.js.map +1 -0
  185. package/lib/Types/index.d.ts +65 -0
  186. package/lib/Types/index.d.ts.map +1 -0
  187. package/lib/Types/index.js +26 -0
  188. package/lib/Types/index.js.map +1 -0
  189. package/lib/Utils/auth-utils.d.ts +24 -0
  190. package/lib/Utils/auth-utils.d.ts.map +1 -0
  191. package/lib/Utils/auth-utils.js +302 -0
  192. package/lib/Utils/auth-utils.js.map +1 -0
  193. package/lib/Utils/browser-utils.d.ts +4 -0
  194. package/lib/Utils/browser-utils.d.ts.map +1 -0
  195. package/lib/Utils/browser-utils.js +28 -0
  196. package/lib/Utils/browser-utils.js.map +1 -0
  197. package/lib/Utils/business.d.ts +23 -0
  198. package/lib/Utils/business.d.ts.map +1 -0
  199. package/lib/Utils/business.js +231 -0
  200. package/lib/Utils/business.js.map +1 -0
  201. package/lib/Utils/chat-utils.d.ts +100 -0
  202. package/lib/Utils/chat-utils.d.ts.map +1 -0
  203. package/lib/Utils/chat-utils.js +872 -0
  204. package/lib/Utils/chat-utils.js.map +1 -0
  205. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  206. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  207. package/lib/Utils/companion-reg-client-utils.js +35 -0
  208. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  209. package/lib/Utils/crypto.d.ts +37 -0
  210. package/lib/Utils/crypto.d.ts.map +1 -0
  211. package/lib/Utils/crypto.js +118 -0
  212. package/lib/Utils/crypto.js.map +1 -0
  213. package/lib/Utils/decode-wa-message.d.ts +66 -0
  214. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  215. package/lib/Utils/decode-wa-message.js +317 -0
  216. package/lib/Utils/decode-wa-message.js.map +1 -0
  217. package/lib/Utils/event-buffer.d.ts +36 -0
  218. package/lib/Utils/event-buffer.d.ts.map +1 -0
  219. package/lib/Utils/event-buffer.js +622 -0
  220. package/lib/Utils/event-buffer.js.map +1 -0
  221. package/lib/Utils/generics.d.ts +91 -0
  222. package/lib/Utils/generics.d.ts.map +1 -0
  223. package/lib/Utils/generics.js +393 -0
  224. package/lib/Utils/generics.js.map +1 -0
  225. package/lib/Utils/history.d.ts +24 -0
  226. package/lib/Utils/history.d.ts.map +1 -0
  227. package/lib/Utils/history.js +134 -0
  228. package/lib/Utils/history.js.map +1 -0
  229. package/lib/Utils/identity-change-handler.d.ts +44 -0
  230. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  231. package/lib/Utils/identity-change-handler.js +50 -0
  232. package/lib/Utils/identity-change-handler.js.map +1 -0
  233. package/lib/Utils/index.d.ts +22 -0
  234. package/lib/Utils/index.d.ts.map +1 -0
  235. package/lib/Utils/index.js +22 -0
  236. package/lib/Utils/index.js.map +1 -0
  237. package/lib/Utils/link-preview.d.ts +21 -0
  238. package/lib/Utils/link-preview.d.ts.map +1 -0
  239. package/lib/Utils/link-preview.js +85 -0
  240. package/lib/Utils/link-preview.js.map +1 -0
  241. package/lib/Utils/logger.d.ts +12 -0
  242. package/lib/Utils/logger.d.ts.map +1 -0
  243. package/lib/Utils/logger.js +3 -0
  244. package/lib/Utils/logger.js.map +1 -0
  245. package/lib/Utils/lt-hash.d.ts +8 -0
  246. package/lib/Utils/lt-hash.d.ts.map +1 -0
  247. package/lib/Utils/lt-hash.js +8 -0
  248. package/lib/Utils/lt-hash.js.map +1 -0
  249. package/lib/Utils/make-mutex.d.ts +9 -0
  250. package/lib/Utils/make-mutex.d.ts.map +1 -0
  251. package/lib/Utils/make-mutex.js +33 -0
  252. package/lib/Utils/make-mutex.js.map +1 -0
  253. package/lib/Utils/message-retry-manager.d.ts +115 -0
  254. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  255. package/lib/Utils/message-retry-manager.js +265 -0
  256. package/lib/Utils/message-retry-manager.js.map +1 -0
  257. package/lib/Utils/messages-media.d.ts +133 -0
  258. package/lib/Utils/messages-media.d.ts.map +1 -0
  259. package/lib/Utils/messages-media.js +718 -0
  260. package/lib/Utils/messages-media.js.map +1 -0
  261. package/lib/Utils/messages.d.ts +91 -0
  262. package/lib/Utils/messages.d.ts.map +1 -0
  263. package/lib/Utils/messages.js +1134 -0
  264. package/lib/Utils/messages.js.map +1 -0
  265. package/lib/Utils/noise-handler.d.ts +20 -0
  266. package/lib/Utils/noise-handler.d.ts.map +1 -0
  267. package/lib/Utils/noise-handler.js +201 -0
  268. package/lib/Utils/noise-handler.js.map +1 -0
  269. package/lib/Utils/offline-node-processor.d.ts +17 -0
  270. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  271. package/lib/Utils/offline-node-processor.js +40 -0
  272. package/lib/Utils/offline-node-processor.js.map +1 -0
  273. package/lib/Utils/pre-key-manager.d.ts +28 -0
  274. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  275. package/lib/Utils/pre-key-manager.js +106 -0
  276. package/lib/Utils/pre-key-manager.js.map +1 -0
  277. package/lib/Utils/process-message.d.ts +60 -0
  278. package/lib/Utils/process-message.d.ts.map +1 -0
  279. package/lib/Utils/process-message.js +630 -0
  280. package/lib/Utils/process-message.js.map +1 -0
  281. package/lib/Utils/reporting-utils.d.ts +11 -0
  282. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  283. package/lib/Utils/reporting-utils.js +258 -0
  284. package/lib/Utils/reporting-utils.js.map +1 -0
  285. package/lib/Utils/signal.d.ts +47 -0
  286. package/lib/Utils/signal.d.ts.map +1 -0
  287. package/lib/Utils/signal.js +201 -0
  288. package/lib/Utils/signal.js.map +1 -0
  289. package/lib/Utils/stanza-ack.d.ts +11 -0
  290. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  291. package/lib/Utils/stanza-ack.js +38 -0
  292. package/lib/Utils/stanza-ack.js.map +1 -0
  293. package/lib/Utils/sync-action-utils.d.ts +19 -0
  294. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  295. package/lib/Utils/sync-action-utils.js +49 -0
  296. package/lib/Utils/sync-action-utils.js.map +1 -0
  297. package/lib/Utils/tc-token-utils.d.ts +37 -0
  298. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  299. package/lib/Utils/tc-token-utils.js +163 -0
  300. package/lib/Utils/tc-token-utils.js.map +1 -0
  301. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  302. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  303. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  304. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  305. package/lib/Utils/validate-connection.d.ts +11 -0
  306. package/lib/Utils/validate-connection.d.ts.map +1 -0
  307. package/lib/Utils/validate-connection.js +203 -0
  308. package/lib/Utils/validate-connection.js.map +1 -0
  309. package/lib/WABinary/constants.d.ts +28 -0
  310. package/lib/WABinary/constants.d.ts.map +1 -0
  311. package/lib/WABinary/constants.js +1301 -0
  312. package/lib/WABinary/constants.js.map +1 -0
  313. package/lib/WABinary/decode.d.ts +7 -0
  314. package/lib/WABinary/decode.d.ts.map +1 -0
  315. package/lib/WABinary/decode.js +262 -0
  316. package/lib/WABinary/decode.js.map +1 -0
  317. package/lib/WABinary/encode.d.ts +3 -0
  318. package/lib/WABinary/encode.d.ts.map +1 -0
  319. package/lib/WABinary/encode.js +220 -0
  320. package/lib/WABinary/encode.js.map +1 -0
  321. package/lib/WABinary/generic-utils.d.ts +15 -0
  322. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  323. package/lib/WABinary/generic-utils.js +113 -0
  324. package/lib/WABinary/generic-utils.js.map +1 -0
  325. package/lib/WABinary/index.d.ts +6 -0
  326. package/lib/WABinary/index.d.ts.map +1 -0
  327. package/lib/WABinary/index.js +6 -0
  328. package/lib/WABinary/index.js.map +1 -0
  329. package/lib/WABinary/jid-utils.d.ts +48 -0
  330. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  331. package/lib/WABinary/jid-utils.js +96 -0
  332. package/lib/WABinary/jid-utils.js.map +1 -0
  333. package/lib/WABinary/types.d.ts +19 -0
  334. package/lib/WABinary/types.d.ts.map +1 -0
  335. package/lib/WABinary/types.js +2 -0
  336. package/lib/WABinary/types.js.map +1 -0
  337. package/lib/WAM/BinaryInfo.d.ts +9 -0
  338. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  339. package/lib/WAM/BinaryInfo.js +10 -0
  340. package/lib/WAM/BinaryInfo.js.map +1 -0
  341. package/lib/WAM/constants.d.ts +40 -0
  342. package/lib/WAM/constants.d.ts.map +1 -0
  343. package/lib/WAM/constants.js +22853 -0
  344. package/lib/WAM/constants.js.map +1 -0
  345. package/lib/WAM/encode.d.ts +3 -0
  346. package/lib/WAM/encode.d.ts.map +1 -0
  347. package/lib/WAM/encode.js +150 -0
  348. package/lib/WAM/encode.js.map +1 -0
  349. package/lib/WAM/index.d.ts +4 -0
  350. package/lib/WAM/index.d.ts.map +1 -0
  351. package/lib/WAM/index.js +4 -0
  352. package/lib/WAM/index.js.map +1 -0
  353. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  354. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  355. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  356. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  357. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  358. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  359. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  360. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  361. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  362. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  363. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  364. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  365. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  366. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  367. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  368. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  369. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  370. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  371. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  372. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  373. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  374. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  375. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  376. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  377. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  378. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  379. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  380. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  381. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  382. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  383. package/lib/WAUSync/Protocols/index.js +6 -0
  384. package/lib/WAUSync/Protocols/index.js.map +1 -0
  385. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  386. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  387. package/lib/WAUSync/USyncQuery.js +98 -0
  388. package/lib/WAUSync/USyncQuery.js.map +1 -0
  389. package/lib/WAUSync/USyncUser.d.ts +17 -0
  390. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  391. package/lib/WAUSync/USyncUser.js +31 -0
  392. package/lib/WAUSync/USyncUser.js.map +1 -0
  393. package/lib/WAUSync/index.d.ts +4 -0
  394. package/lib/WAUSync/index.d.ts.map +1 -0
  395. package/lib/WAUSync/index.js +4 -0
  396. package/lib/WAUSync/index.js.map +1 -0
  397. package/lib/index.d.ts +12 -0
  398. package/lib/index.d.ts.map +1 -0
  399. package/lib/index.js +60 -0
  400. package/lib/index.js.map +1 -0
  401. package/package.json +115 -0
@@ -0,0 +1,1476 @@
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, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
5
+ import {
6
+ aggregateMessageKeysNotFromMe,
7
+ assertMediaContent,
8
+ assertMeId,
9
+ bindWaitForEvent,
10
+ decryptMediaRetryData,
11
+ DEF_MEDIA_HOST,
12
+ encodeNewsletterMessage,
13
+ encodeSignedDeviceIdentity,
14
+ encodeWAMessage,
15
+ encryptMediaRetryRequest,
16
+ extractDeviceJids,
17
+ generateMessageIDV2,
18
+ generateParticipantHashV2,
19
+ generateWAMessage,
20
+ getStatusCodeForMediaRetry,
21
+ getUrlFromDirectPath,
22
+ getWAUploadToServer,
23
+ MessageRetryManager,
24
+ normalizeMessageContent,
25
+ parseAndInjectE2ESessions,
26
+ unixTimestampSeconds
27
+ } from '../Utils/index.js';
28
+ import { getUrlInfo } from '../Utils/link-preview.js';
29
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
30
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
31
+ import {
32
+ buildMergedTcTokenIndexWrite,
33
+ isTcTokenExpired,
34
+ resolveIssuanceJid,
35
+ resolveTcTokenJid,
36
+ shouldSendNewTcToken,
37
+ storeTcTokensFromIqResult
38
+ } from '../Utils/tc-token-utils.js';
39
+ import {
40
+ areJidsSameUser,
41
+ getBinaryNodeChild,
42
+ getBinaryNodeChildren,
43
+ isHostedLidUser,
44
+ isHostedPnUser,
45
+ isJidBot,
46
+ isJidGroup,
47
+ isJidMetaAI,
48
+ isLidUser,
49
+ isPnUser,
50
+ jidDecode,
51
+ jidEncode,
52
+ jidNormalizedUser,
53
+ PSA_WID,
54
+ S_WHATSAPP_NET
55
+ } from '../WABinary/index.js';
56
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
57
+ import { makeNewsletterSocket } from './newsletter.js';
58
+
59
+ export const makeMessagesSocket = (config) => {
60
+ const {
61
+ logger,
62
+ linkPreviewImageThumbnailWidth,
63
+ generateHighQualityLinkPreview,
64
+ options: httpRequestOptions,
65
+ patchMessageBeforeSending,
66
+ cachedGroupMetadata,
67
+ enableRecentMessageCache,
68
+ maxMsgRetryCount
69
+ } = config;
70
+
71
+ const sock = makeNewsletterSocket(config);
72
+ const {
73
+ ev,
74
+ authState,
75
+ messageMutex,
76
+ signalRepository,
77
+ upsertMessage,
78
+ query,
79
+ fetchPrivacySettings,
80
+ sendNode,
81
+ groupMetadata,
82
+ groupToggleEphemeral,
83
+ registerSocketEndHandler
84
+ } = sock;
85
+
86
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
87
+
88
+ /**
89
+ * Set of tctoken storage JIDs with a fire-and-forget issuePrivacyTokens IQ in flight.
90
+ * Prevents duplicate IQs from rapid back-to-back sends before senderTimestamp persists.
91
+ */
92
+ const inFlightTcTokenIssuance = new Set();
93
+
94
+ const userDevicesCache =
95
+ config.userDevicesCache ||
96
+ new NodeCache({ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, useClones: false });
97
+
98
+ /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
99
+ const devicesMutex = makeMutex();
100
+
101
+ // Initialize message retry manager if enabled
102
+ const messageRetryManager = enableRecentMessageCache
103
+ ? new MessageRetryManager(logger, maxMsgRetryCount)
104
+ : null;
105
+
106
+ // Prevent race conditions in Signal session encryption by user
107
+ const encryptionMutex = makeKeyedMutex();
108
+
109
+ let mediaConn;
110
+ /** Per-socket media host; updated whenever media_conn is fetched. */
111
+ let mediaHost = DEF_MEDIA_HOST;
112
+
113
+ // ── Media connection ──────────────────────────────────────────────────────
114
+
115
+ const refreshMediaConn = async (forceGet = false) => {
116
+ const media = await mediaConn;
117
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
118
+ mediaConn = (async () => {
119
+ const result = await query({
120
+ tag: 'iq',
121
+ attrs: { type: 'set', xmlns: 'w:m', to: S_WHATSAPP_NET },
122
+ content: [{ tag: 'media_conn', attrs: {} }]
123
+ });
124
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
125
+ const node = {
126
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
127
+ hostname: attrs.hostname,
128
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
129
+ })),
130
+ auth: mediaConnNode.attrs.auth,
131
+ ttl: +mediaConnNode.attrs.ttl,
132
+ fetchDate: new Date()
133
+ };
134
+ logger.debug('fetched media conn');
135
+ if (node.hosts[0]) {
136
+ mediaHost = node.hosts[0].hostname;
137
+ }
138
+ return node;
139
+ })();
140
+ }
141
+ return mediaConn;
142
+ };
143
+
144
+ // ── Receipts ──────────────────────────────────────────────────────────────
145
+
146
+ const sendReceipt = async (jid, participant, messageIds, type) => {
147
+ if (!messageIds || messageIds.length === 0) {
148
+ throw new Boom('missing ids in receipt');
149
+ }
150
+ const node = {
151
+ tag: 'receipt',
152
+ attrs: { id: messageIds[0] }
153
+ };
154
+ const isReadReceipt = type === 'read' || type === 'read-self';
155
+ if (isReadReceipt) {
156
+ node.attrs.t = unixTimestampSeconds().toString();
157
+ }
158
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
159
+ node.attrs.recipient = jid;
160
+ node.attrs.to = participant;
161
+ } else {
162
+ node.attrs.to = jid;
163
+ if (participant) node.attrs.participant = participant;
164
+ }
165
+ if (type) node.attrs.type = type;
166
+ const remainingMessageIds = messageIds.slice(1);
167
+ if (remainingMessageIds.length) {
168
+ node.content = [
169
+ {
170
+ tag: 'list',
171
+ attrs: {},
172
+ content: remainingMessageIds.map((id) => ({ tag: 'item', attrs: { id } }))
173
+ }
174
+ ];
175
+ }
176
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
177
+ await sendNode(node);
178
+ };
179
+
180
+ const sendReceipts = async (keys, type) => {
181
+ const recps = aggregateMessageKeysNotFromMe(keys);
182
+ for (const { jid, participant, messageIds } of recps) {
183
+ await sendReceipt(jid, participant, messageIds, type);
184
+ }
185
+ };
186
+
187
+ const readMessages = async (keys) => {
188
+ const privacySettings = await fetchPrivacySettings();
189
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
190
+ await sendReceipts(keys, readType);
191
+ };
192
+
193
+ // ── Device resolution ─────────────────────────────────────────────────────
194
+
195
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
196
+ const deviceResults = [];
197
+ if (!useCache) logger.debug('not using cache for devices');
198
+
199
+ const toFetch = [];
200
+ const jidsWithUser = jids
201
+ .map((jid) => {
202
+ const decoded = jidDecode(jid);
203
+ const user = decoded?.user;
204
+ const device = decoded?.device;
205
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
206
+ if (isExplicitDevice && user) {
207
+ deviceResults.push({ user, device, jid });
208
+ return null;
209
+ }
210
+ jid = jidNormalizedUser(jid);
211
+ return { jid, user };
212
+ })
213
+ .filter((jid) => jid !== null);
214
+
215
+ let mgetDevices;
216
+ if (useCache && userDevicesCache.mget) {
217
+ const usersToFetch = jidsWithUser.map((j) => j?.user).filter(Boolean);
218
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
219
+ }
220
+
221
+ for (const { jid, user } of jidsWithUser) {
222
+ if (useCache) {
223
+ const devices =
224
+ mgetDevices?.[user] ||
225
+ (userDevicesCache.mget ? undefined : await userDevicesCache.get(user));
226
+ if (devices) {
227
+ const devicesWithJid = devices.map((d) => ({
228
+ ...d,
229
+ jid: jidEncode(d.user, d.server, d.device)
230
+ }));
231
+ deviceResults.push(...devicesWithJid);
232
+ logger.trace({ user }, 'using cache for devices');
233
+ } else {
234
+ toFetch.push(jid);
235
+ }
236
+ } else {
237
+ toFetch.push(jid);
238
+ }
239
+ }
240
+
241
+ if (!toFetch.length) return deviceResults;
242
+
243
+ const requestedLidUsers = new Set();
244
+ for (const jid of toFetch) {
245
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
246
+ const user = jidDecode(jid)?.user;
247
+ if (user) requestedLidUsers.add(user);
248
+ }
249
+ }
250
+
251
+ const uSyncQuery = new USyncQuery()
252
+ .withContext('message')
253
+ .withDeviceProtocol()
254
+ .withLIDProtocol();
255
+ for (const jid of toFetch) uSyncQuery.withUser(new USyncUser().withId(jid));
256
+
257
+ const result = await sock.executeUSyncQuery(uSyncQuery);
258
+ if (result) {
259
+ const lidResults = result.list.filter((a) => !!a.lid);
260
+ if (lidResults.length > 0) {
261
+ logger.trace('Storing LID maps from device call');
262
+ await signalRepository.lidMapping.storeLIDPNMappings(
263
+ lidResults.map((a) => ({ lid: a.lid, pn: a.id }))
264
+ );
265
+ try {
266
+ const lids = lidResults.map((a) => a.lid);
267
+ if (lids.length) await assertSessions(lids, true);
268
+ } catch (e) {
269
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
270
+ }
271
+ }
272
+
273
+ const extracted = extractDeviceJids(
274
+ result?.list,
275
+ authState.creds.me.id,
276
+ authState.creds.me.lid,
277
+ ignoreZeroDevices
278
+ );
279
+ const deviceMap = {};
280
+ for (const item of extracted) {
281
+ deviceMap[item.user] = deviceMap[item.user] || [];
282
+ deviceMap[item.user]?.push(item);
283
+ }
284
+
285
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
286
+ const isLidUsr = requestedLidUsers.has(user);
287
+ for (const item of userDevices) {
288
+ const finalJid = isLidUsr
289
+ ? jidEncode(user, item.server, item.device)
290
+ : jidEncode(item.user, item.server, item.device);
291
+ deviceResults.push({ ...item, jid: finalJid });
292
+ logger.debug(
293
+ { user: item.user, device: item.device, finalJid, usedLid: isLidUsr },
294
+ 'Processed device with LID priority'
295
+ );
296
+ }
297
+ }
298
+
299
+ await devicesMutex.mutex(async () => {
300
+ if (userDevicesCache.mset) {
301
+ await userDevicesCache.mset(
302
+ Object.entries(deviceMap).map(([key, value]) => ({ key, value }))
303
+ );
304
+ } else {
305
+ for (const key in deviceMap) {
306
+ if (deviceMap[key]) await userDevicesCache.set(key, deviceMap[key]);
307
+ }
308
+ }
309
+ });
310
+
311
+ const userDeviceUpdates = {};
312
+ for (const [userId, devices] of Object.entries(deviceMap)) {
313
+ if (devices && devices.length > 0) {
314
+ userDeviceUpdates[userId] = devices.map((d) => d.device?.toString() || '0');
315
+ }
316
+ }
317
+ if (Object.keys(userDeviceUpdates).length > 0) {
318
+ try {
319
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
320
+ logger.debug(
321
+ { userCount: Object.keys(userDeviceUpdates).length },
322
+ 'stored user device lists for bulk migration'
323
+ );
324
+ } catch (error) {
325
+ logger.warn({ error }, 'failed to store user device lists');
326
+ }
327
+ }
328
+ }
329
+
330
+ return deviceResults;
331
+ };
332
+
333
+ // ── Member label ──────────────────────────────────────────────────────────
334
+
335
+ const updateMemberLabel = (jid, memberLabel) => {
336
+ return relayMessage(
337
+ jid,
338
+ {
339
+ protocolMessage: {
340
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
341
+ memberLabel: {
342
+ label: memberLabel?.slice(0, 30),
343
+ labelTimestamp: unixTimestampSeconds()
344
+ }
345
+ }
346
+ },
347
+ {
348
+ additionalNodes: [
349
+ {
350
+ tag: 'meta',
351
+ attrs: { tag_reason: 'user_update', appdata: 'member_tag' },
352
+ content: undefined
353
+ }
354
+ ]
355
+ }
356
+ );
357
+ };
358
+
359
+ // ── Session assertion ─────────────────────────────────────────────────────
360
+
361
+ const assertSessions = async (jids, force) => {
362
+ let didFetchNewSession = false;
363
+ const uniqueJids = [...new Set(jids)];
364
+ const jidsRequiringFetch = [];
365
+ logger.debug({ jids }, 'assertSessions call with jids');
366
+
367
+ for (const jid of uniqueJids) {
368
+ if (!force) {
369
+ const sessionValidation = await signalRepository.validateSession(jid);
370
+ if (sessionValidation.exists) continue;
371
+ }
372
+ jidsRequiringFetch.push(jid);
373
+ }
374
+
375
+ if (jidsRequiringFetch.length) {
376
+ const wireJids = [
377
+ ...jidsRequiringFetch.filter((jid) => !!isLidUser(jid) || !!isHostedLidUser(jid)),
378
+ ...((await signalRepository.lidMapping.getLIDsForPNs(
379
+ jidsRequiringFetch.filter((jid) => !!isPnUser(jid) || !!isHostedPnUser(jid))
380
+ )) || []).map((a) => a.lid)
381
+ ];
382
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
383
+ const result = await query({
384
+ tag: 'iq',
385
+ attrs: { xmlns: 'encrypt', type: 'get', to: S_WHATSAPP_NET },
386
+ content: [
387
+ {
388
+ tag: 'key',
389
+ attrs: {},
390
+ content: wireJids.map((jid) => {
391
+ const attrs = { jid };
392
+ if (force) attrs.reason = 'identity';
393
+ return { tag: 'user', attrs };
394
+ })
395
+ }
396
+ ]
397
+ });
398
+ await parseAndInjectE2ESessions(result, signalRepository);
399
+ didFetchNewSession = true;
400
+ }
401
+
402
+ return didFetchNewSession;
403
+ };
404
+
405
+ // ── Peer data operation ───────────────────────────────────────────────────
406
+
407
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
408
+ if (!authState.creds.me?.id) throw new Boom('Not authenticated');
409
+ const protocolMessage = {
410
+ protocolMessage: {
411
+ peerDataOperationRequestMessage: pdoMessage,
412
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
413
+ }
414
+ };
415
+ const meJid = jidNormalizedUser(authState.creds.me.id);
416
+ const msgId = await relayMessage(meJid, protocolMessage, {
417
+ additionalAttributes: { category: 'peer', push_priority: 'high_force' },
418
+ additionalNodes: [{ tag: 'meta', attrs: { appdata: 'default' } }]
419
+ });
420
+ return msgId;
421
+ };
422
+
423
+ // ── Participant node creation ──────────────────────────────────────────────
424
+
425
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
426
+ if (!recipientJids.length) {
427
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
428
+ }
429
+ const patched = await patchMessageBeforeSending(message, recipientJids);
430
+ const patchedMessages = Array.isArray(patched)
431
+ ? patched
432
+ : recipientJids.map((jid) => ({ recipientJid: jid, message: patched }));
433
+
434
+ let shouldIncludeDeviceIdentity = false;
435
+ const meId = authState.creds.me.id;
436
+ const meLid = authState.creds.me?.lid;
437
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
438
+
439
+ const encryptionPromises = patchedMessages.map(
440
+ async ({ recipientJid: jid, message: patchedMessage }) => {
441
+ try {
442
+ if (!jid) return null;
443
+ let msgToEncrypt = patchedMessage;
444
+ if (dsmMessage) {
445
+ const { user: targetUser } = jidDecode(jid);
446
+ const { user: ownPnUser } = jidDecode(meId);
447
+ const ownLidUser = meLidUser;
448
+ const isOwnUser =
449
+ targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
450
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
451
+ if (isOwnUser && !isExactSenderDevice) {
452
+ msgToEncrypt = dsmMessage;
453
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
454
+ }
455
+ }
456
+ const bytes = encodeWAMessage(msgToEncrypt);
457
+ const node = await encryptionMutex.mutex(jid, async () => {
458
+ const { type, ciphertext } = await signalRepository.encryptMessage({
459
+ jid,
460
+ data: bytes
461
+ });
462
+ if (type === 'pkmsg') shouldIncludeDeviceIdentity = true;
463
+ return {
464
+ tag: 'to',
465
+ attrs: { jid },
466
+ content: [
467
+ {
468
+ tag: 'enc',
469
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
470
+ content: ciphertext
471
+ }
472
+ ]
473
+ };
474
+ });
475
+ return node;
476
+ } catch (err) {
477
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
478
+ return null;
479
+ }
480
+ }
481
+ );
482
+
483
+ const nodes = (await Promise.all(encryptionPromises)).filter((node) => node !== null);
484
+ if (recipientJids.length > 0 && nodes.length === 0) {
485
+ throw new Boom('All encryptions failed', { statusCode: 500 });
486
+ }
487
+ return { nodes, shouldIncludeDeviceIdentity };
488
+ };
489
+
490
+ // ── Button helpers (addition) ─────────────────────────────────────────────
491
+
492
+ /** True when the normalised message contains button content needing a <biz> node */
493
+ const hasButtonContent = (message) => {
494
+ const content = normalizeMessageContent(message);
495
+ if (!content) return false;
496
+ return !!(
497
+ content.buttonsMessage ||
498
+ content.buttonsResponseMessage ||
499
+ content.listMessage ||
500
+ content.listResponseMessage ||
501
+ content.interactiveMessage ||
502
+ content.interactiveResponseMessage ||
503
+ content.nativeFlowMessage ||
504
+ content.templateMessage
505
+ );
506
+ };
507
+
508
+ /** Builds the correct <biz> child node for the given button message type */
509
+ const getBizNodeForButtons = (message) => {
510
+ const content = normalizeMessageContent(message);
511
+ if (!content) return null;
512
+
513
+ if (content.buttonsMessage || content.interactiveMessage || content.nativeFlowMessage) {
514
+ return {
515
+ tag: 'biz',
516
+ attrs: {},
517
+ content: [
518
+ {
519
+ tag: 'interactive',
520
+ attrs: { type: 'native_flow', v: '1' },
521
+ content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }]
522
+ }
523
+ ]
524
+ };
525
+ }
526
+
527
+ if (content.listMessage) {
528
+ return {
529
+ tag: 'biz',
530
+ attrs: {},
531
+ content: [{ tag: 'list', attrs: { type: 'product_list', v: '2' } }]
532
+ };
533
+ }
534
+
535
+ return null;
536
+ };
537
+
538
+ /** True for groupStatusMessage / groupStatusMessageV2 */
539
+ const isGroupStatusMessage = (message) => {
540
+ const content = normalizeMessageContent(message);
541
+ if (!content) return false;
542
+ return !!(content.groupStatusMessage || content.groupStatusMessageV2);
543
+ };
544
+
545
+ // ── Message-type helpers (original Baileys logic — DO NOT SIMPLIFY) ───────
546
+
547
+ /**
548
+ * Returns the WA `type` stanza attribute.
549
+ * CRITICAL: reactionMessage must return 'reaction' — this is what makes
550
+ * status reactions work. Never collapse this to always return 'text'.
551
+ */
552
+ const getMessageType = (message) => {
553
+ const normalizedMessage = normalizeMessageContent(message);
554
+ if (!normalizedMessage) return 'text';
555
+
556
+ // reactions — must be 'reaction' type for status reactions to work
557
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
558
+ return 'reaction';
559
+ }
560
+
561
+ // polls
562
+ if (
563
+ normalizedMessage.pollCreationMessage ||
564
+ normalizedMessage.pollCreationMessageV2 ||
565
+ normalizedMessage.pollCreationMessageV3 ||
566
+ normalizedMessage.pollUpdateMessage
567
+ ) {
568
+ return 'poll';
569
+ }
570
+
571
+ // events
572
+ if (normalizedMessage.eventMessage) {
573
+ return 'event';
574
+ }
575
+
576
+ // media
577
+ if (getMediaType(normalizedMessage) !== '') {
578
+ return 'media';
579
+ }
580
+
581
+ return 'text';
582
+ };
583
+
584
+ const getMediaType = (message) => {
585
+ if (message.imageMessage) return 'image';
586
+ if (message.videoMessage) return message.videoMessage.gifPlayback ? 'gif' : 'video';
587
+ if (message.audioMessage) return message.audioMessage.ptt ? 'ptt' : 'audio';
588
+ if (message.contactMessage) return 'vcard';
589
+ if (message.documentMessage) return 'document';
590
+ if (message.contactsArrayMessage) return 'contact_array';
591
+ if (message.liveLocationMessage) return 'livelocation';
592
+ if (message.stickerMessage) return 'sticker';
593
+ if (message.listMessage) return 'list';
594
+ if (message.listResponseMessage) return 'list_response';
595
+ if (message.buttonsResponseMessage) return 'buttons_response';
596
+ if (message.orderMessage) return 'order';
597
+ if (message.productMessage) return 'product';
598
+ if (message.interactiveResponseMessage) return 'native_flow_response';
599
+ if (message.groupInviteMessage) return 'url';
600
+ return '';
601
+ };
602
+
603
+ // ── Privacy tokens ────────────────────────────────────────────────────────
604
+
605
+ const issuePrivacyTokens = async (jids, timestamp) => {
606
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
607
+ return query({
608
+ tag: 'iq',
609
+ attrs: { to: S_WHATSAPP_NET, type: 'set', xmlns: 'privacy' },
610
+ content: [
611
+ {
612
+ tag: 'tokens',
613
+ attrs: {},
614
+ content: jids.map((jid) => ({
615
+ tag: 'token',
616
+ attrs: { jid: jidNormalizedUser(jid), t, type: 'trusted_contact' }
617
+ }))
618
+ }
619
+ ]
620
+ });
621
+ };
622
+
623
+ // ── relayMessage ──────────────────────────────────────────────────────────
624
+
625
+ const relayMessage = async (
626
+ jid,
627
+ message,
628
+ {
629
+ messageId: msgId,
630
+ participant,
631
+ additionalAttributes,
632
+ additionalNodes,
633
+ useUserDevicesCache,
634
+ useCachedGroupMetadata,
635
+ statusJidList
636
+ } = {}
637
+ ) => {
638
+ const meId = assertMeId(authState.creds);
639
+ const meLid = authState.creds.me?.lid;
640
+ const isRetryResend = Boolean(participant?.jid);
641
+ let shouldIncludeDeviceIdentity = isRetryResend;
642
+
643
+ const statusJid = 'status@broadcast';
644
+ const { user, server } = jidDecode(jid);
645
+ const isGroup = server === 'g.us';
646
+ const isStatus = jid === statusJid;
647
+ const isLid = server === 'lid';
648
+ const isNewsletter = server === 'newsletter';
649
+ const isGroupOrStatus = isGroup || isStatus;
650
+ const finalJid = jid;
651
+
652
+ msgId = msgId || generateMessageIDV2(meId);
653
+ useUserDevicesCache = useUserDevicesCache !== false;
654
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
655
+
656
+ const participants = [];
657
+ const destinationJid = !isStatus ? finalJid : statusJid;
658
+ const binaryNodeContent = [];
659
+ const devices = [];
660
+ let reportingMessage;
661
+
662
+ const meMsg = {
663
+ deviceSentMessage: { destinationJid, message },
664
+ messageContextInfo: message.messageContextInfo
665
+ };
666
+ const extraAttrs = {};
667
+
668
+ if (participant) {
669
+ if (!isGroup && !isStatus) {
670
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
671
+ }
672
+ const { user: pUser, device } = jidDecode(participant.jid);
673
+ devices.push({ user: pUser, device, jid: participant.jid });
674
+ }
675
+
676
+ await authState.keys.transaction(async () => {
677
+ const mediaType = getMediaType(normalizeMessageContent(message) || message);
678
+ if (mediaType) extraAttrs['mediatype'] = mediaType;
679
+
680
+ // ── Newsletter path ───────────────────────────────────────────────
681
+ if (isNewsletter) {
682
+ // Use the newsletter send method from sock if available
683
+ if (sock.newsletterSendDirect) {
684
+ const result = await sock.newsletterSendDirect(jid, message, {
685
+ messageId: msgId,
686
+ additionalAttributes
687
+ });
688
+ if (result) return;
689
+ }
690
+
691
+ // Fallback: direct send
692
+ const patched = patchMessageBeforeSending
693
+ ? await patchMessageBeforeSending(message, [])
694
+ : message;
695
+ const bytes = encodeNewsletterMessage(patched);
696
+ binaryNodeContent.push({ tag: 'plaintext', attrs: {}, content: bytes });
697
+ const stanza = {
698
+ tag: 'message',
699
+ attrs: {
700
+ to: jid,
701
+ id: msgId,
702
+ type: getMessageType(message),
703
+ ...(additionalAttributes || {})
704
+ },
705
+ content: binaryNodeContent
706
+ };
707
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
708
+ await sendNode(stanza);
709
+ return;
710
+ }
711
+
712
+ // decrypt-fail: hide for pin AND reaction messages (original Baileys behaviour)
713
+ const normalizedForAttrs = normalizeMessageContent(message);
714
+ if (
715
+ normalizedForAttrs?.pinInChatMessage ||
716
+ normalizedForAttrs?.reactionMessage
717
+ ) {
718
+ extraAttrs['decrypt-fail'] = 'hide';
719
+ }
720
+
721
+ // ── Group / Status path ───────────────────────────────────────────
722
+ if (isGroupOrStatus && !isRetryResend) {
723
+ const [groupData, senderKeyMap] = await Promise.all([
724
+ (async () => {
725
+ let gd = useCachedGroupMetadata && cachedGroupMetadata
726
+ ? await cachedGroupMetadata(jid)
727
+ : undefined;
728
+ if (gd && Array.isArray(gd?.participants)) {
729
+ logger.trace(
730
+ { jid, participants: gd.participants.length },
731
+ 'using cached group metadata'
732
+ );
733
+ } else if (!isStatus) {
734
+ gd = await groupMetadata(jid);
735
+ }
736
+ return gd;
737
+ })(),
738
+ (async () => {
739
+ if (!participant && !isStatus) {
740
+ const result = await authState.keys.get('sender-key-memory', [jid]);
741
+ return result[jid] || {};
742
+ }
743
+ return {};
744
+ })()
745
+ ]);
746
+
747
+ const participantsList = groupData ? groupData.participants.map((p) => p.id) : [];
748
+
749
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
750
+ additionalAttributes = {
751
+ ...additionalAttributes,
752
+ expiration: groupData.ephemeralDuration.toString()
753
+ };
754
+ }
755
+
756
+ // For status broadcasts, push the recipient list directly (original Baileys)
757
+ if (isStatus && statusJidList) {
758
+ participantsList.push(...statusJidList);
759
+ }
760
+
761
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
762
+ devices.push(...additionalDevices);
763
+
764
+ if (isGroup) {
765
+ additionalAttributes = {
766
+ ...additionalAttributes,
767
+ addressing_mode: groupData?.addressingMode || 'lid'
768
+ };
769
+ }
770
+
771
+ const patched = await patchMessageBeforeSending(message);
772
+ if (Array.isArray(patched)) {
773
+ throw new Boom('Per-jid patching is not supported in groups');
774
+ }
775
+ const bytes = encodeWAMessage(patched);
776
+ reportingMessage = patched;
777
+
778
+ const groupAddressingMode =
779
+ additionalAttributes?.['addressing_mode'] ||
780
+ groupData?.addressingMode ||
781
+ 'lid';
782
+ const groupSenderIdentity =
783
+ groupAddressingMode === 'lid' && meLid ? meLid : meId;
784
+
785
+ const { ciphertext, senderKeyDistributionMessage } =
786
+ await signalRepository.encryptGroupMessage({
787
+ group: destinationJid,
788
+ data: bytes,
789
+ meId: groupSenderIdentity
790
+ });
791
+
792
+ const senderKeyRecipients = [];
793
+ for (const device of devices) {
794
+ const deviceJid = device.jid;
795
+ const hasKey = !!senderKeyMap[deviceJid];
796
+ if (
797
+ (!hasKey || !!participant) &&
798
+ !isHostedLidUser(deviceJid) &&
799
+ !isHostedPnUser(deviceJid) &&
800
+ device.device !== 99
801
+ ) {
802
+ senderKeyRecipients.push(deviceJid);
803
+ senderKeyMap[deviceJid] = true;
804
+ }
805
+ }
806
+
807
+ if (senderKeyRecipients.length) {
808
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
809
+ const senderKeyMsg = {
810
+ senderKeyDistributionMessage: {
811
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
812
+ groupId: destinationJid
813
+ }
814
+ };
815
+ await assertSessions(senderKeyRecipients);
816
+ const result = await createParticipantNodes(
817
+ senderKeyRecipients,
818
+ senderKeyMsg,
819
+ extraAttrs
820
+ );
821
+ shouldIncludeDeviceIdentity =
822
+ shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
823
+ participants.push(...result.nodes);
824
+ }
825
+
826
+ binaryNodeContent.push({
827
+ tag: 'enc',
828
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
829
+ content: ciphertext
830
+ });
831
+
832
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
833
+
834
+ } else if (!isGroupOrStatus) {
835
+ // ── 1-to-1 path ───────────────────────────────────────────────
836
+ let ownId = meId;
837
+ if (isLid && meLid) {
838
+ ownId = meLid;
839
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
840
+ } else {
841
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
842
+ }
843
+ const { user: ownUser } = jidDecode(ownId);
844
+
845
+ if (!participant) {
846
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
847
+ reportingMessage = Array.isArray(patchedForReporting)
848
+ ? patchedForReporting.find((item) => item.recipientJid === jid) ||
849
+ patchedForReporting[0]
850
+ : patchedForReporting;
851
+ }
852
+
853
+ if (!isRetryResend) {
854
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
855
+ devices.push({
856
+ user,
857
+ device: 0,
858
+ jid: jidEncode(user, targetUserServer, 0)
859
+ });
860
+ if (user !== ownUser) {
861
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
862
+ const ownUserForAddressing =
863
+ isLid && meLid
864
+ ? jidDecode(meLid).user
865
+ : jidDecode(meId).user;
866
+ devices.push({
867
+ user: ownUserForAddressing,
868
+ device: 0,
869
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
870
+ });
871
+ }
872
+ if (additionalAttributes?.['category'] !== 'peer') {
873
+ devices.length = 0;
874
+ const senderIdentity =
875
+ isLid && meLid
876
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
877
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
878
+ const sessionDevices = await getUSyncDevices(
879
+ [senderIdentity, jid],
880
+ true,
881
+ false
882
+ );
883
+ devices.push(...sessionDevices);
884
+ logger.debug(
885
+ {
886
+ deviceCount: devices.length,
887
+ devices: devices.map(
888
+ (d) => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`
889
+ )
890
+ },
891
+ 'Device enumeration complete with unified addressing'
892
+ );
893
+ }
894
+ }
895
+
896
+ const allRecipients = [];
897
+ const meRecipients = [];
898
+ const otherRecipients = [];
899
+ const { user: mePnUser } = jidDecode(meId);
900
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
901
+
902
+ for (const { user: devUser, jid: devJid } of devices) {
903
+ const isExactSenderDevice = devJid === meId || (meLid && devJid === meLid);
904
+ if (isExactSenderDevice) {
905
+ logger.debug({ jid: devJid, meId, meLid }, 'Skipping exact sender device');
906
+ continue;
907
+ }
908
+ const isMe = devUser === mePnUser || devUser === meLidUser;
909
+ if (isMe) meRecipients.push(devJid);
910
+ else otherRecipients.push(devJid);
911
+ allRecipients.push(devJid);
912
+ }
913
+
914
+ await assertSessions(allRecipients);
915
+
916
+ const [
917
+ { nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
918
+ { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }
919
+ ] = await Promise.all([
920
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
921
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
922
+ ]);
923
+
924
+ participants.push(...meNodes, ...otherNodes);
925
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
926
+ extraAttrs['phash'] = generateParticipantHashV2([
927
+ ...meRecipients,
928
+ ...otherRecipients
929
+ ]);
930
+ }
931
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
932
+ }
933
+
934
+ // ── Retry resend path ─────────────────────────────────────────────
935
+ if (isRetryResend) {
936
+ const isParticipantLid = isLidUser(participant.jid);
937
+ const isMe = areJidsSameUser(
938
+ participant.jid,
939
+ isParticipantLid ? meLid : meId
940
+ );
941
+ let messageToSend = message;
942
+ if (isGroupOrStatus) {
943
+ let groupSenderIdentity;
944
+ if (
945
+ meLid &&
946
+ (await signalRepository.hasSenderKey({
947
+ group: destinationJid,
948
+ meId: meLid
949
+ }))
950
+ ) {
951
+ groupSenderIdentity = meLid;
952
+ } else if (
953
+ await signalRepository.hasSenderKey({ group: destinationJid, meId })
954
+ ) {
955
+ groupSenderIdentity = meId;
956
+ }
957
+ if (groupSenderIdentity) {
958
+ try {
959
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
960
+ group: destinationJid,
961
+ meId: groupSenderIdentity
962
+ });
963
+ messageToSend = {
964
+ ...message,
965
+ senderKeyDistributionMessage: {
966
+ groupId: destinationJid,
967
+ axolotlSenderKeyDistributionMessage: skdm
968
+ }
969
+ };
970
+ } catch (err) {
971
+ logger.warn(
972
+ { err, jid: destinationJid },
973
+ 'failed to build SKDM for retry, sending without it'
974
+ );
975
+ }
976
+ }
977
+ }
978
+ const encodedMessageToSend = isMe
979
+ ? encodeWAMessage({ deviceSentMessage: { destinationJid, message: messageToSend } })
980
+ : encodeWAMessage(messageToSend);
981
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
982
+ data: encodedMessageToSend,
983
+ jid: participant.jid
984
+ });
985
+ binaryNodeContent.push({
986
+ tag: 'enc',
987
+ attrs: { v: '2', type, count: participant.count.toString() },
988
+ content: encryptedContent
989
+ });
990
+ }
991
+
992
+ // ── Assemble participants ─────────────────────────────────────────
993
+ if (participants.length) {
994
+ if (additionalAttributes?.['category'] === 'peer') {
995
+ const peerNode = participants[0]?.content?.[0];
996
+ if (peerNode) binaryNodeContent.push(peerNode);
997
+ } else {
998
+ binaryNodeContent.push({
999
+ tag: 'participants',
1000
+ attrs: {},
1001
+ content: participants
1002
+ });
1003
+ }
1004
+ }
1005
+
1006
+ // ── Biz node for button messages (addition) ───────────────────────
1007
+ const normalizedForBiz = normalizeMessageContent(message);
1008
+ const isLocationButtonMessage = !!(normalizedForBiz?.buttonsMessage && normalizedForBiz?.locationMessage);
1009
+ const isMediaMsg = !!(
1010
+ normalizedForBiz?.imageMessage ||
1011
+ normalizedForBiz?.videoMessage ||
1012
+ normalizedForBiz?.audioMessage ||
1013
+ normalizedForBiz?.documentMessage ||
1014
+ normalizedForBiz?.stickerMessage
1015
+ );
1016
+
1017
+ // Check for button content more thoroughly
1018
+ const hasButtonContentCheck = (msg) => {
1019
+ const content = normalizeMessageContent(msg);
1020
+ if (!content) return false;
1021
+ return !!(
1022
+ content.buttonsMessage ||
1023
+ content.buttonsResponseMessage ||
1024
+ content.listMessage ||
1025
+ content.listResponseMessage ||
1026
+ content.interactiveMessage ||
1027
+ content.interactiveResponseMessage ||
1028
+ content.nativeFlowMessage ||
1029
+ content.templateMessage
1030
+ );
1031
+ };
1032
+
1033
+ if (
1034
+ !isNewsletter &&
1035
+ !isGroupStatusMessage(message) &&
1036
+ hasButtonContentCheck(message) &&
1037
+ (!isMediaMsg || isLocationButtonMessage)
1038
+ ) {
1039
+ // Check if user already provided biz node
1040
+ let hasBizNode = false;
1041
+ if (additionalNodes && additionalNodes.length > 0) {
1042
+ hasBizNode = additionalNodes.some(node => node.tag === 'biz');
1043
+ }
1044
+
1045
+ // Only add auto biz node if user didn't provide one
1046
+ if (!hasBizNode) {
1047
+ const bizNode = getBizNodeForButtons(message);
1048
+ if (bizNode) {
1049
+ binaryNodeContent.push(bizNode);
1050
+ logger.debug({ jid }, 'adding auto biz node for button message');
1051
+ }
1052
+ } else {
1053
+ logger.debug({ jid }, 'using user-provided biz node for button message');
1054
+ }
1055
+ }
1056
+
1057
+ // ── Build final stanza ────────────────────────────────────────────
1058
+ const stanza = {
1059
+ tag: 'message',
1060
+ attrs: {
1061
+ id: msgId,
1062
+ to: destinationJid,
1063
+ type: getMessageType(message),
1064
+ ...(additionalAttributes || {})
1065
+ },
1066
+ content: binaryNodeContent
1067
+ };
1068
+
1069
+ if (participant) {
1070
+ if (isJidGroup(destinationJid)) {
1071
+ stanza.attrs.to = destinationJid;
1072
+ stanza.attrs.participant = participant.jid;
1073
+ } else if (areJidsSameUser(participant.jid, meId)) {
1074
+ stanza.attrs.to = participant.jid;
1075
+ stanza.attrs.recipient = destinationJid;
1076
+ } else {
1077
+ stanza.attrs.to = participant.jid;
1078
+ }
1079
+ } else {
1080
+ stanza.attrs.to = destinationJid;
1081
+ }
1082
+
1083
+ if (shouldIncludeDeviceIdentity) {
1084
+ stanza.content.push({
1085
+ tag: 'device-identity',
1086
+ attrs: {},
1087
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
1088
+ });
1089
+ logger.debug({ jid }, 'adding device identity');
1090
+ }
1091
+
1092
+ // ── Reporting token ───────────────────────────────────────────────
1093
+ if (
1094
+ !isNewsletter &&
1095
+ !isRetryResend &&
1096
+ reportingMessage?.messageContextInfo?.messageSecret &&
1097
+ shouldIncludeReportingToken(reportingMessage)
1098
+ ) {
1099
+ try {
1100
+ const encoded = encodeWAMessage(reportingMessage);
1101
+ const reportingKey = {
1102
+ id: msgId,
1103
+ fromMe: true,
1104
+ remoteJid: destinationJid,
1105
+ participant: participant?.jid
1106
+ };
1107
+ const reportingNode = await getMessageReportingToken(
1108
+ encoded,
1109
+ reportingMessage,
1110
+ reportingKey
1111
+ );
1112
+ if (reportingNode) {
1113
+ stanza.content.push(reportingNode);
1114
+ logger.trace({ jid }, 'added reporting token to message');
1115
+ }
1116
+ } catch (error) {
1117
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
1118
+ }
1119
+ }
1120
+
1121
+ // ── TC Token (1-to-1 only) ────────────────────────────────────────
1122
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
1123
+ const is1on1Send =
1124
+ !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
1125
+ const tcTokenJid = is1on1Send
1126
+ ? await resolveTcTokenJid(destinationJid, getLIDForPN)
1127
+ : destinationJid;
1128
+ const contactTcTokenData = is1on1Send
1129
+ ? await authState.keys.get('tctoken', [tcTokenJid])
1130
+ : {};
1131
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
1132
+ let tcTokenBuffer = existingTokenEntry?.token;
1133
+
1134
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
1135
+ logger.debug(
1136
+ { jid: destinationJid, timestamp: existingTokenEntry?.timestamp },
1137
+ 'tctoken expired, clearing'
1138
+ );
1139
+ tcTokenBuffer = undefined;
1140
+ const cleared =
1141
+ existingTokenEntry?.senderTimestamp !== undefined
1142
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
1143
+ : null;
1144
+ try {
1145
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
1146
+ } catch (err) {
1147
+ logger.debug(
1148
+ { jid: destinationJid, err: err?.message },
1149
+ 'failed to persist tctoken expiry cleanup'
1150
+ );
1151
+ }
1152
+ }
1153
+
1154
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
1155
+ stanza.content.push({ tag: 'tctoken', attrs: {}, content: tcTokenBuffer });
1156
+ }
1157
+
1158
+ if (additionalNodes && additionalNodes.length > 0) {
1159
+ stanza.content.push(...additionalNodes);
1160
+ }
1161
+
1162
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
1163
+ await sendNode(stanza);
1164
+
1165
+ // ── Fire-and-forget: issue TC token to contact after send ─────────
1166
+ const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
1167
+ const isBotOrPSA =
1168
+ destinationJid === PSA_WID ||
1169
+ isJidBot(destinationJid) ||
1170
+ isJidMetaAI(destinationJid);
1171
+ if (
1172
+ is1on1Send &&
1173
+ !isProtocolMsg &&
1174
+ !isBotOrPSA &&
1175
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
1176
+ !inFlightTcTokenIssuance.has(tcTokenJid)
1177
+ ) {
1178
+ inFlightTcTokenIssuance.add(tcTokenJid);
1179
+ const issueTimestamp = unixTimestampSeconds();
1180
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(
1181
+ signalRepository.lidMapping
1182
+ );
1183
+ resolveIssuanceJid(
1184
+ destinationJid,
1185
+ sock.serverProps.lidTrustedTokenIssueToLid,
1186
+ getLIDForPN,
1187
+ getPNForLID
1188
+ )
1189
+ .then((issueJid) => issuePrivacyTokens([issueJid], issueTimestamp))
1190
+ .then(async (result) => {
1191
+ await storeTcTokensFromIqResult({
1192
+ result,
1193
+ fallbackJid: tcTokenJid,
1194
+ keys: authState.keys,
1195
+ getLIDForPN
1196
+ });
1197
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
1198
+ const currentEntry = currentData[tcTokenJid];
1199
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [
1200
+ tcTokenJid
1201
+ ]);
1202
+ await authState.keys.set({
1203
+ tctoken: {
1204
+ [tcTokenJid]: {
1205
+ token: Buffer.alloc(0),
1206
+ ...currentEntry,
1207
+ senderTimestamp: issueTimestamp
1208
+ },
1209
+ ...indexWrite
1210
+ }
1211
+ });
1212
+ })
1213
+ .catch((err) => {
1214
+ logger.debug(
1215
+ { jid: destinationJid, err: err?.message },
1216
+ 'fire-and-forget tctoken issuance failed'
1217
+ );
1218
+ })
1219
+ .finally(() => {
1220
+ inFlightTcTokenIssuance.delete(tcTokenJid);
1221
+ });
1222
+ }
1223
+
1224
+ // ── Message retry cache ───────────────────────────────────────────
1225
+ if (messageRetryManager && !participant) {
1226
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1227
+ }
1228
+ }, meId);
1229
+
1230
+ return msgId;
1231
+ };
1232
+
1233
+ // ── Upload helper ─────────────────────────────────────────────────────────
1234
+
1235
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1236
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1237
+
1238
+ // Cleanup on socket close
1239
+ registerSocketEndHandler(() => {
1240
+ if (!config.userDevicesCache && userDevicesCache.close) {
1241
+ userDevicesCache.close();
1242
+ }
1243
+ mediaConn = undefined;
1244
+ if (messageRetryManager) {
1245
+ messageRetryManager.clear();
1246
+ }
1247
+ });
1248
+
1249
+ // ── Public API ────────────────────────────────────────────────────────────
1250
+
1251
+ return {
1252
+ ...sock,
1253
+ userDevicesCache,
1254
+ devicesMutex,
1255
+ issuePrivacyTokens,
1256
+ assertSessions,
1257
+ relayMessage,
1258
+ sendReceipt,
1259
+ sendReceipts,
1260
+ readMessages,
1261
+ refreshMediaConn,
1262
+ getMediaHost: () => mediaHost,
1263
+ waUploadToServer,
1264
+ fetchPrivacySettings,
1265
+ sendPeerDataOperationMessage,
1266
+ createParticipantNodes,
1267
+ getUSyncDevices,
1268
+ messageRetryManager,
1269
+ updateMemberLabel,
1270
+
1271
+ updateMediaMessage: async (message) => {
1272
+ const content = assertMediaContent(message.message);
1273
+ const mediaKey = content.mediaKey;
1274
+ const meId = authState.creds.me.id;
1275
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1276
+ let error;
1277
+
1278
+ await Promise.all([
1279
+ sendNode(node),
1280
+ waitForMsgMediaUpdate(async (update) => {
1281
+ const result = update.find((c) => c.key.id === message.key.id);
1282
+ if (result) {
1283
+ if (result.error) {
1284
+ error = result.error;
1285
+ } else {
1286
+ try {
1287
+ const media = decryptMediaRetryData(
1288
+ result.media,
1289
+ mediaKey,
1290
+ result.key.id
1291
+ );
1292
+ if (
1293
+ media.result !==
1294
+ proto.MediaRetryNotification.ResultType.SUCCESS
1295
+ ) {
1296
+ const resultStr =
1297
+ proto.MediaRetryNotification.ResultType[media.result];
1298
+ throw new Boom(
1299
+ `Media re-upload failed by device (${resultStr})`,
1300
+ {
1301
+ data: media,
1302
+ statusCode:
1303
+ getStatusCodeForMediaRetry(media.result) || 404
1304
+ }
1305
+ );
1306
+ }
1307
+ content.directPath = media.directPath;
1308
+ content.url = getUrlFromDirectPath(
1309
+ content.directPath,
1310
+ mediaHost
1311
+ );
1312
+ logger.debug(
1313
+ { directPath: media.directPath, key: result.key },
1314
+ 'media update successful'
1315
+ );
1316
+ } catch (err) {
1317
+ error = err;
1318
+ }
1319
+ }
1320
+ return true;
1321
+ }
1322
+ })
1323
+ ]);
1324
+
1325
+ if (error) throw error;
1326
+ ev.emit('messages.update', [
1327
+ { key: message.key, update: { message: message.message } }
1328
+ ]);
1329
+ return message;
1330
+ },
1331
+
1332
+ sendMessage: async (jid, content, options = {}) => {
1333
+ const userJid = authState.creds.me.id;
1334
+
1335
+ // Check if this is a newsletter JID
1336
+ const isNewsletterJid = jid && (jid.includes('@newsletter') || jid.endsWith('@newsletter'));
1337
+
1338
+ // If it's a newsletter, use the newsletter send function
1339
+ if (isNewsletterJid && sock.newsletterSend) {
1340
+ try {
1341
+ // Use the working newsletter send method
1342
+ const result = await sock.newsletterSend(jid, content, waUploadToServer, {
1343
+ ...options,
1344
+ messageId: options.messageId || generateMessageIDV2(sock.user?.id || userJid)
1345
+ });
1346
+
1347
+ if (config.emitOwnEvents && result.message) {
1348
+ // Create a full message structure for events
1349
+ const fullMsg = {
1350
+ key: result.key,
1351
+ message: result.message,
1352
+ messageTimestamp: unixTimestampSeconds(),
1353
+ messageStubParameters: [],
1354
+ participant: userJid,
1355
+ status: 'PENDING',
1356
+ messageStubType: 0
1357
+ };
1358
+
1359
+ process.nextTick(async () => {
1360
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1361
+ });
1362
+ }
1363
+
1364
+ return result;
1365
+ } catch (error) {
1366
+ logger.error({ jid, error }, 'Failed to send newsletter message, falling back to regular send');
1367
+ // Fall through to regular send if newsletter send fails
1368
+ }
1369
+ }
1370
+
1371
+ // ── Group story / status (addition) ───────────────────────────────
1372
+ if (typeof content === 'object' && content.groupStatusMessage) {
1373
+ const { generateWAMessageContent, generateMessageIDV2: genId } =
1374
+ await import('../Utils/index.js');
1375
+ const waMsgContent = await generateWAMessageContent(
1376
+ content.groupStatusMessage,
1377
+ {
1378
+ upload: waUploadToServer,
1379
+ logger: config.logger,
1380
+ mediaCache: config.mediaCache,
1381
+ options: config.options
1382
+ }
1383
+ );
1384
+ const wrappedMsg = {
1385
+ groupStatusMessageV2: {
1386
+ message: waMsgContent.message || waMsgContent
1387
+ }
1388
+ };
1389
+ return relayMessage(jid, wrappedMsg, {
1390
+ messageId: options.messageId || genId(sock.user?.id),
1391
+ ...options
1392
+ });
1393
+ }
1394
+
1395
+ // ── Disappearing messages toggle ───────────────────────────────────
1396
+ if (
1397
+ typeof content === 'object' &&
1398
+ 'disappearingMessagesInChat' in content &&
1399
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1400
+ isJidGroup(jid)
1401
+ ) {
1402
+ const { disappearingMessagesInChat } = content;
1403
+ const value =
1404
+ typeof disappearingMessagesInChat === 'boolean'
1405
+ ? disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0
1406
+ : disappearingMessagesInChat;
1407
+ await groupToggleEphemeral(jid, value);
1408
+ return;
1409
+ }
1410
+
1411
+ // ── Regular message ───────────────────────────────────────────────
1412
+ const fullMsg = await generateWAMessage(jid, content, {
1413
+ logger,
1414
+ userJid,
1415
+ getUrlInfo: (text) =>
1416
+ getUrlInfo(text, {
1417
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1418
+ fetchOpts: { timeout: 3000, ...(httpRequestOptions || {}) },
1419
+ logger,
1420
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1421
+ }),
1422
+ getProfilePicUrl: sock.profilePictureUrl,
1423
+ getCallLink: sock.createCallLink,
1424
+ upload: waUploadToServer,
1425
+ mediaCache: config.mediaCache,
1426
+ options: config.options,
1427
+ messageId: generateMessageIDV2(sock.user?.id || userJid),
1428
+ ...options
1429
+ });
1430
+
1431
+ const isEventMsg = 'event' in content && !!content.event;
1432
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1433
+ const isEditMsg = 'edit' in content && !!content.edit;
1434
+ const isPinMsg = 'pin' in content && !!content.pin;
1435
+ const isPollMessage = 'poll' in content && !!content.poll;
1436
+
1437
+ const additionalAttributes = {};
1438
+ const additionalNodes = [];
1439
+
1440
+ if (isDeleteMsg) {
1441
+ additionalAttributes.edit =
1442
+ isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe ? '8' : '7';
1443
+ } else if (isEditMsg) {
1444
+ additionalAttributes.edit = '1';
1445
+ } else if (isPinMsg) {
1446
+ additionalAttributes.edit = '2';
1447
+ } else if (isPollMessage) {
1448
+ additionalNodes.push({ tag: 'meta', attrs: { polltype: 'creation' } });
1449
+ } else if (isEventMsg) {
1450
+ additionalNodes.push({ tag: 'meta', attrs: { event_type: 'creation' } });
1451
+ }
1452
+
1453
+ if ('cachedGroupMetadata' in options) {
1454
+ console.warn(
1455
+ 'cachedGroupMetadata in sendMessage is deprecated; pass it via socket config.'
1456
+ );
1457
+ }
1458
+
1459
+ await relayMessage(jid, fullMsg.message, {
1460
+ messageId: fullMsg.key.id,
1461
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1462
+ additionalAttributes,
1463
+ statusJidList: options.statusJidList,
1464
+ additionalNodes
1465
+ });
1466
+
1467
+ if (config.emitOwnEvents) {
1468
+ process.nextTick(async () => {
1469
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1470
+ });
1471
+ }
1472
+
1473
+ return fullMsg;
1474
+ }
1475
+ };
1476
+ };