@yui-bails/yui-bails 0.0.0-stage → 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 (457) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1685 -2
  3. package/WAProto/GenerateStatics.sh +3 -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 +10 -0
  9. package/lib/Defaults/index.d.ts +75 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +139 -0
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  15. package/lib/Signal/Group/ciphertext-message.js +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 +431 -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 +125 -0
  86. package/lib/Socket/chats.d.ts.map +1 -0
  87. package/lib/Socket/chats.js +1198 -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 +322 -0
  98. package/lib/Socket/index.d.ts.map +1 -0
  99. package/lib/Socket/index.js +105 -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 +1159 -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 +181 -0
  116. package/lib/Socket/newsletter.js.map +1 -0
  117. package/lib/Socket/session-manager.d.ts +408 -0
  118. package/lib/Socket/session-manager.d.ts.map +1 -0
  119. package/lib/Socket/session-manager.js +177 -0
  120. package/lib/Socket/session-manager.js.map +1 -0
  121. package/lib/Socket/socket.d.ts +59 -0
  122. package/lib/Socket/socket.d.ts.map +1 -0
  123. package/lib/Socket/socket.js +1039 -0
  124. package/lib/Socket/socket.js.map +1 -0
  125. package/lib/Types/Auth.d.ts +117 -0
  126. package/lib/Types/Auth.d.ts.map +1 -0
  127. package/lib/Types/Auth.js +2 -0
  128. package/lib/Types/Auth.js.map +1 -0
  129. package/lib/Types/Bussines.d.ts +25 -0
  130. package/lib/Types/Bussines.d.ts.map +1 -0
  131. package/lib/Types/Bussines.js +2 -0
  132. package/lib/Types/Bussines.js.map +1 -0
  133. package/lib/Types/Call.d.ts +15 -0
  134. package/lib/Types/Call.d.ts.map +1 -0
  135. package/lib/Types/Call.js +2 -0
  136. package/lib/Types/Call.js.map +1 -0
  137. package/lib/Types/Chat.d.ts +124 -0
  138. package/lib/Types/Chat.d.ts.map +1 -0
  139. package/lib/Types/Chat.js +8 -0
  140. package/lib/Types/Chat.js.map +1 -0
  141. package/lib/Types/Contact.d.ts +26 -0
  142. package/lib/Types/Contact.d.ts.map +1 -0
  143. package/lib/Types/Contact.js +2 -0
  144. package/lib/Types/Contact.js.map +1 -0
  145. package/lib/Types/Events.d.ts +274 -0
  146. package/lib/Types/Events.d.ts.map +1 -0
  147. package/lib/Types/Events.js +2 -0
  148. package/lib/Types/Events.js.map +1 -0
  149. package/lib/Types/GroupMetadata.d.ts +71 -0
  150. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  151. package/lib/Types/GroupMetadata.js +2 -0
  152. package/lib/Types/GroupMetadata.js.map +1 -0
  153. package/lib/Types/Label.d.ts +47 -0
  154. package/lib/Types/Label.d.ts.map +1 -0
  155. package/lib/Types/Label.js +25 -0
  156. package/lib/Types/Label.js.map +1 -0
  157. package/lib/Types/LabelAssociation.d.ts +30 -0
  158. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  159. package/lib/Types/LabelAssociation.js +7 -0
  160. package/lib/Types/LabelAssociation.js.map +1 -0
  161. package/lib/Types/Message.d.ts +402 -0
  162. package/lib/Types/Message.d.ts.map +1 -0
  163. package/lib/Types/Message.js +11 -0
  164. package/lib/Types/Message.js.map +1 -0
  165. package/lib/Types/Mex.d.ts +141 -0
  166. package/lib/Types/Mex.d.ts.map +1 -0
  167. package/lib/Types/Mex.js +37 -0
  168. package/lib/Types/Mex.js.map +1 -0
  169. package/lib/Types/Product.d.ts +79 -0
  170. package/lib/Types/Product.d.ts.map +1 -0
  171. package/lib/Types/Product.js +2 -0
  172. package/lib/Types/Product.js.map +1 -0
  173. package/lib/Types/Signal.d.ts +87 -0
  174. package/lib/Types/Signal.d.ts.map +1 -0
  175. package/lib/Types/Signal.js +2 -0
  176. package/lib/Types/Signal.js.map +1 -0
  177. package/lib/Types/Socket.d.ts +172 -0
  178. package/lib/Types/Socket.d.ts.map +1 -0
  179. package/lib/Types/Socket.js +3 -0
  180. package/lib/Types/Socket.js.map +1 -0
  181. package/lib/Types/State.d.ts +97 -0
  182. package/lib/Types/State.d.ts.map +1 -0
  183. package/lib/Types/State.js +56 -0
  184. package/lib/Types/State.js.map +1 -0
  185. package/lib/Types/USync.d.ts +26 -0
  186. package/lib/Types/USync.d.ts.map +1 -0
  187. package/lib/Types/USync.js +2 -0
  188. package/lib/Types/USync.js.map +1 -0
  189. package/lib/Types/index.d.ts +66 -0
  190. package/lib/Types/index.d.ts.map +1 -0
  191. package/lib/Types/index.js +26 -0
  192. package/lib/Types/index.js.map +1 -0
  193. package/lib/Utils/auth-utils.d.ts +24 -0
  194. package/lib/Utils/auth-utils.d.ts.map +1 -0
  195. package/lib/Utils/auth-utils.js +302 -0
  196. package/lib/Utils/auth-utils.js.map +1 -0
  197. package/lib/Utils/banner.d.ts +28 -0
  198. package/lib/Utils/banner.d.ts.map +1 -0
  199. package/lib/Utils/banner.js +99 -0
  200. package/lib/Utils/banner.js.map +1 -0
  201. package/lib/Utils/browser-utils.d.ts +4 -0
  202. package/lib/Utils/browser-utils.d.ts.map +1 -0
  203. package/lib/Utils/browser-utils.js +29 -0
  204. package/lib/Utils/browser-utils.js.map +1 -0
  205. package/lib/Utils/business.d.ts +23 -0
  206. package/lib/Utils/business.d.ts.map +1 -0
  207. package/lib/Utils/business.js +231 -0
  208. package/lib/Utils/business.js.map +1 -0
  209. package/lib/Utils/button-builder.d.ts +10 -0
  210. package/lib/Utils/button-builder.d.ts.map +1 -0
  211. package/lib/Utils/button-builder.js +48 -0
  212. package/lib/Utils/button-builder.js.map +1 -0
  213. package/lib/Utils/chat-utils.d.ts +100 -0
  214. package/lib/Utils/chat-utils.d.ts.map +1 -0
  215. package/lib/Utils/chat-utils.js +872 -0
  216. package/lib/Utils/chat-utils.js.map +1 -0
  217. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  218. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  219. package/lib/Utils/companion-reg-client-utils.js +35 -0
  220. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  221. package/lib/Utils/console-filter.d.ts +10 -0
  222. package/lib/Utils/console-filter.d.ts.map +1 -0
  223. package/lib/Utils/console-filter.js +44 -0
  224. package/lib/Utils/console-filter.js.map +1 -0
  225. package/lib/Utils/crypto.d.ts +37 -0
  226. package/lib/Utils/crypto.d.ts.map +1 -0
  227. package/lib/Utils/crypto.js +118 -0
  228. package/lib/Utils/crypto.js.map +1 -0
  229. package/lib/Utils/decode-wa-message.d.ts +66 -0
  230. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  231. package/lib/Utils/decode-wa-message.js +317 -0
  232. package/lib/Utils/decode-wa-message.js.map +1 -0
  233. package/lib/Utils/event-buffer.d.ts +36 -0
  234. package/lib/Utils/event-buffer.d.ts.map +1 -0
  235. package/lib/Utils/event-buffer.js +622 -0
  236. package/lib/Utils/event-buffer.js.map +1 -0
  237. package/lib/Utils/generics.d.ts +92 -0
  238. package/lib/Utils/generics.d.ts.map +1 -0
  239. package/lib/Utils/generics.js +395 -0
  240. package/lib/Utils/generics.js.map +1 -0
  241. package/lib/Utils/group-cache.d.ts +22 -0
  242. package/lib/Utils/group-cache.d.ts.map +1 -0
  243. package/lib/Utils/group-cache.js +31 -0
  244. package/lib/Utils/group-cache.js.map +1 -0
  245. package/lib/Utils/group-fetch.d.ts +19 -0
  246. package/lib/Utils/group-fetch.d.ts.map +1 -0
  247. package/lib/Utils/group-fetch.js +43 -0
  248. package/lib/Utils/group-fetch.js.map +1 -0
  249. package/lib/Utils/group-tools.d.ts +38 -0
  250. package/lib/Utils/group-tools.d.ts.map +1 -0
  251. package/lib/Utils/group-tools.js +75 -0
  252. package/lib/Utils/group-tools.js.map +1 -0
  253. package/lib/Utils/helpers.d.ts +180 -0
  254. package/lib/Utils/helpers.d.ts.map +1 -0
  255. package/lib/Utils/helpers.js +279 -0
  256. package/lib/Utils/helpers.js.map +1 -0
  257. package/lib/Utils/history.d.ts +24 -0
  258. package/lib/Utils/history.d.ts.map +1 -0
  259. package/lib/Utils/history.js +134 -0
  260. package/lib/Utils/history.js.map +1 -0
  261. package/lib/Utils/identity-change-handler.d.ts +44 -0
  262. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  263. package/lib/Utils/identity-change-handler.js +50 -0
  264. package/lib/Utils/identity-change-handler.js.map +1 -0
  265. package/lib/Utils/index.d.ts +33 -0
  266. package/lib/Utils/index.d.ts.map +1 -0
  267. package/lib/Utils/index.js +33 -0
  268. package/lib/Utils/index.js.map +1 -0
  269. package/lib/Utils/insights.d.ts +80 -0
  270. package/lib/Utils/insights.d.ts.map +1 -0
  271. package/lib/Utils/insights.js +188 -0
  272. package/lib/Utils/insights.js.map +1 -0
  273. package/lib/Utils/link-preview.d.ts +21 -0
  274. package/lib/Utils/link-preview.d.ts.map +1 -0
  275. package/lib/Utils/link-preview.js +85 -0
  276. package/lib/Utils/link-preview.js.map +1 -0
  277. package/lib/Utils/logger.d.ts +13 -0
  278. package/lib/Utils/logger.d.ts.map +1 -0
  279. package/lib/Utils/logger.js +9 -0
  280. package/lib/Utils/logger.js.map +1 -0
  281. package/lib/Utils/lt-hash.d.ts +8 -0
  282. package/lib/Utils/lt-hash.d.ts.map +1 -0
  283. package/lib/Utils/lt-hash.js +8 -0
  284. package/lib/Utils/lt-hash.js.map +1 -0
  285. package/lib/Utils/make-mutex.d.ts +9 -0
  286. package/lib/Utils/make-mutex.d.ts.map +1 -0
  287. package/lib/Utils/make-mutex.js +33 -0
  288. package/lib/Utils/make-mutex.js.map +1 -0
  289. package/lib/Utils/mentions.d.ts +11 -0
  290. package/lib/Utils/mentions.d.ts.map +1 -0
  291. package/lib/Utils/mentions.js +29 -0
  292. package/lib/Utils/mentions.js.map +1 -0
  293. package/lib/Utils/message-retry-manager.d.ts +115 -0
  294. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  295. package/lib/Utils/message-retry-manager.js +265 -0
  296. package/lib/Utils/message-retry-manager.js.map +1 -0
  297. package/lib/Utils/message-store.d.ts +19 -0
  298. package/lib/Utils/message-store.d.ts.map +1 -0
  299. package/lib/Utils/message-store.js +26 -0
  300. package/lib/Utils/message-store.js.map +1 -0
  301. package/lib/Utils/messages-media.d.ts +133 -0
  302. package/lib/Utils/messages-media.d.ts.map +1 -0
  303. package/lib/Utils/messages-media.js +788 -0
  304. package/lib/Utils/messages-media.js.map +1 -0
  305. package/lib/Utils/messages.d.ts +95 -0
  306. package/lib/Utils/messages.d.ts.map +1 -0
  307. package/lib/Utils/messages.js +1094 -0
  308. package/lib/Utils/messages.js.map +1 -0
  309. package/lib/Utils/noise-handler.d.ts +20 -0
  310. package/lib/Utils/noise-handler.d.ts.map +1 -0
  311. package/lib/Utils/noise-handler.js +201 -0
  312. package/lib/Utils/noise-handler.js.map +1 -0
  313. package/lib/Utils/offline-node-processor.d.ts +17 -0
  314. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  315. package/lib/Utils/offline-node-processor.js +40 -0
  316. package/lib/Utils/offline-node-processor.js.map +1 -0
  317. package/lib/Utils/pre-key-manager.d.ts +28 -0
  318. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  319. package/lib/Utils/pre-key-manager.js +106 -0
  320. package/lib/Utils/pre-key-manager.js.map +1 -0
  321. package/lib/Utils/process-message.d.ts +60 -0
  322. package/lib/Utils/process-message.d.ts.map +1 -0
  323. package/lib/Utils/process-message.js +630 -0
  324. package/lib/Utils/process-message.js.map +1 -0
  325. package/lib/Utils/replies.d.ts +60 -0
  326. package/lib/Utils/replies.d.ts.map +1 -0
  327. package/lib/Utils/replies.js +154 -0
  328. package/lib/Utils/replies.js.map +1 -0
  329. package/lib/Utils/reporting-utils.d.ts +11 -0
  330. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  331. package/lib/Utils/reporting-utils.js +258 -0
  332. package/lib/Utils/reporting-utils.js.map +1 -0
  333. package/lib/Utils/send-queue.d.ts +50 -0
  334. package/lib/Utils/send-queue.d.ts.map +1 -0
  335. package/lib/Utils/send-queue.js +124 -0
  336. package/lib/Utils/send-queue.js.map +1 -0
  337. package/lib/Utils/signal.d.ts +47 -0
  338. package/lib/Utils/signal.d.ts.map +1 -0
  339. package/lib/Utils/signal.js +201 -0
  340. package/lib/Utils/signal.js.map +1 -0
  341. package/lib/Utils/stanza-ack.d.ts +11 -0
  342. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  343. package/lib/Utils/stanza-ack.js +38 -0
  344. package/lib/Utils/stanza-ack.js.map +1 -0
  345. package/lib/Utils/sync-action-utils.d.ts +19 -0
  346. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  347. package/lib/Utils/sync-action-utils.js +49 -0
  348. package/lib/Utils/sync-action-utils.js.map +1 -0
  349. package/lib/Utils/tc-token-utils.d.ts +37 -0
  350. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  351. package/lib/Utils/tc-token-utils.js +164 -0
  352. package/lib/Utils/tc-token-utils.js.map +1 -0
  353. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  354. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  355. package/lib/Utils/use-multi-file-auth-state.js +154 -0
  356. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  357. package/lib/Utils/validate-connection.d.ts +11 -0
  358. package/lib/Utils/validate-connection.d.ts.map +1 -0
  359. package/lib/Utils/validate-connection.js +210 -0
  360. package/lib/Utils/validate-connection.js.map +1 -0
  361. package/lib/Utils/wa-version.d.ts +33 -0
  362. package/lib/Utils/wa-version.d.ts.map +1 -0
  363. package/lib/Utils/wa-version.js +92 -0
  364. package/lib/Utils/wa-version.js.map +1 -0
  365. package/lib/WABinary/constants.d.ts +28 -0
  366. package/lib/WABinary/constants.d.ts.map +1 -0
  367. package/lib/WABinary/constants.js +1301 -0
  368. package/lib/WABinary/constants.js.map +1 -0
  369. package/lib/WABinary/decode.d.ts +7 -0
  370. package/lib/WABinary/decode.d.ts.map +1 -0
  371. package/lib/WABinary/decode.js +262 -0
  372. package/lib/WABinary/decode.js.map +1 -0
  373. package/lib/WABinary/encode.d.ts +3 -0
  374. package/lib/WABinary/encode.d.ts.map +1 -0
  375. package/lib/WABinary/encode.js +220 -0
  376. package/lib/WABinary/encode.js.map +1 -0
  377. package/lib/WABinary/generic-utils.d.ts +17 -0
  378. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  379. package/lib/WABinary/generic-utils.js +213 -0
  380. package/lib/WABinary/generic-utils.js.map +1 -0
  381. package/lib/WABinary/index.d.ts +6 -0
  382. package/lib/WABinary/index.d.ts.map +1 -0
  383. package/lib/WABinary/index.js +6 -0
  384. package/lib/WABinary/index.js.map +1 -0
  385. package/lib/WABinary/jid-utils.d.ts +48 -0
  386. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  387. package/lib/WABinary/jid-utils.js +96 -0
  388. package/lib/WABinary/jid-utils.js.map +1 -0
  389. package/lib/WABinary/types.d.ts +19 -0
  390. package/lib/WABinary/types.d.ts.map +1 -0
  391. package/lib/WABinary/types.js +2 -0
  392. package/lib/WABinary/types.js.map +1 -0
  393. package/lib/WAM/BinaryInfo.d.ts +9 -0
  394. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  395. package/lib/WAM/BinaryInfo.js +10 -0
  396. package/lib/WAM/BinaryInfo.js.map +1 -0
  397. package/lib/WAM/constants.d.ts +40 -0
  398. package/lib/WAM/constants.d.ts.map +1 -0
  399. package/lib/WAM/constants.js +22853 -0
  400. package/lib/WAM/constants.js.map +1 -0
  401. package/lib/WAM/encode.d.ts +3 -0
  402. package/lib/WAM/encode.d.ts.map +1 -0
  403. package/lib/WAM/encode.js +150 -0
  404. package/lib/WAM/encode.js.map +1 -0
  405. package/lib/WAM/index.d.ts +4 -0
  406. package/lib/WAM/index.d.ts.map +1 -0
  407. package/lib/WAM/index.js +4 -0
  408. package/lib/WAM/index.js.map +1 -0
  409. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  410. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  411. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  412. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  413. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  414. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  415. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  416. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  417. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  418. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  419. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  420. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  421. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  422. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  423. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  424. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  425. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  426. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  427. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  428. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  429. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  430. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  431. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  432. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  433. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  434. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  435. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  436. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  437. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  438. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  439. package/lib/WAUSync/Protocols/index.js +6 -0
  440. package/lib/WAUSync/Protocols/index.js.map +1 -0
  441. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  442. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  443. package/lib/WAUSync/USyncQuery.js +98 -0
  444. package/lib/WAUSync/USyncQuery.js.map +1 -0
  445. package/lib/WAUSync/USyncUser.d.ts +17 -0
  446. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  447. package/lib/WAUSync/USyncUser.js +31 -0
  448. package/lib/WAUSync/USyncUser.js.map +1 -0
  449. package/lib/WAUSync/index.d.ts +4 -0
  450. package/lib/WAUSync/index.d.ts.map +1 -0
  451. package/lib/WAUSync/index.js +4 -0
  452. package/lib/WAUSync/index.js.map +1 -0
  453. package/lib/index.d.ts +13 -0
  454. package/lib/index.d.ts.map +1 -0
  455. package/lib/index.js +12 -0
  456. package/lib/index.js.map +1 -0
  457. package/package.json +150 -3
@@ -0,0 +1,1159 @@
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 { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/index.js';
6
+ import { getUrlInfo } from '../Utils/link-preview.js';
7
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
8
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
9
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
10
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, getBizBinaryNode, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET, shouldIncludeBizBinaryNode } from '../WABinary/index.js';
11
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
+ import { makeNewsletterSocket } from './newsletter.js';
13
+ export const makeMessagesSocket = (config) => {
14
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
15
+ const sock = makeNewsletterSocket(config);
16
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
17
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
18
+ /**
19
+ * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
20
+ * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
21
+ * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
22
+ */
23
+ const inFlightTcTokenIssuance = new Set();
24
+ const userDevicesCache = config.userDevicesCache ||
25
+ new NodeCache({
26
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
27
+ useClones: false
28
+ });
29
+ /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
30
+ const devicesMutex = makeMutex();
31
+ // Initialize message retry manager if enabled
32
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
33
+ // Prevent race conditions in Signal session encryption by user
34
+ const encryptionMutex = makeKeyedMutex();
35
+ let mediaConn;
36
+ /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
37
+ let mediaHost = DEF_MEDIA_HOST;
38
+ const refreshMediaConn = async (forceGet = false) => {
39
+ const media = await mediaConn;
40
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
41
+ mediaConn = (async () => {
42
+ const result = await query({
43
+ tag: 'iq',
44
+ attrs: {
45
+ type: 'set',
46
+ xmlns: 'w:m',
47
+ to: S_WHATSAPP_NET
48
+ },
49
+ content: [{ tag: 'media_conn', attrs: {} }]
50
+ });
51
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
52
+ // TODO: explore full length of data that whatsapp provides
53
+ const node = {
54
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
55
+ hostname: attrs.hostname,
56
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
57
+ })),
58
+ auth: mediaConnNode.attrs.auth,
59
+ ttl: +mediaConnNode.attrs.ttl,
60
+ fetchDate: new Date()
61
+ };
62
+ logger.debug('fetched media conn');
63
+ if (node.hosts[0]) {
64
+ mediaHost = node.hosts[0].hostname;
65
+ }
66
+ return node;
67
+ })();
68
+ }
69
+ return mediaConn;
70
+ };
71
+ /**
72
+ * generic send receipt function
73
+ * used for receipts of phone call, read, delivery etc.
74
+ * */
75
+ const sendReceipt = async (jid, participant, messageIds, type) => {
76
+ if (!messageIds || messageIds.length === 0) {
77
+ throw new Boom('missing ids in receipt');
78
+ }
79
+ const node = {
80
+ tag: 'receipt',
81
+ attrs: {
82
+ id: messageIds[0]
83
+ }
84
+ };
85
+ const isReadReceipt = type === 'read' || type === 'read-self';
86
+ if (isReadReceipt) {
87
+ node.attrs.t = unixTimestampSeconds().toString();
88
+ }
89
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
90
+ node.attrs.recipient = jid;
91
+ node.attrs.to = participant;
92
+ }
93
+ else {
94
+ node.attrs.to = jid;
95
+ if (participant) {
96
+ node.attrs.participant = participant;
97
+ }
98
+ }
99
+ if (type) {
100
+ node.attrs.type = type;
101
+ }
102
+ const remainingMessageIds = messageIds.slice(1);
103
+ if (remainingMessageIds.length) {
104
+ node.content = [
105
+ {
106
+ tag: 'list',
107
+ attrs: {},
108
+ content: remainingMessageIds.map(id => ({
109
+ tag: 'item',
110
+ attrs: { id }
111
+ }))
112
+ }
113
+ ];
114
+ }
115
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
116
+ await sendNode(node);
117
+ };
118
+ /** Correctly bulk send receipts to multiple chats, participants */
119
+ const sendReceipts = async (keys, type) => {
120
+ const recps = aggregateMessageKeysNotFromMe(keys);
121
+ for (const { jid, participant, messageIds } of recps) {
122
+ await sendReceipt(jid, participant, messageIds, type);
123
+ }
124
+ };
125
+ /** Bulk read messages. Keys can be from different chats & participants */
126
+ const readMessages = async (keys) => {
127
+ const privacySettings = await fetchPrivacySettings();
128
+ // based on privacy settings, we have to change the read type
129
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
130
+ await sendReceipts(keys, readType);
131
+ };
132
+ /** Fetch all the devices we've to send a message to */
133
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
134
+ const deviceResults = [];
135
+ if (!useCache) {
136
+ logger.debug('not using cache for devices');
137
+ }
138
+ const toFetch = [];
139
+ const jidsWithUser = jids
140
+ .map(jid => {
141
+ const decoded = jidDecode(jid);
142
+ const user = decoded?.user;
143
+ const device = decoded?.device;
144
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
145
+ if (isExplicitDevice && user) {
146
+ deviceResults.push({
147
+ user,
148
+ device,
149
+ jid
150
+ });
151
+ return null;
152
+ }
153
+ jid = jidNormalizedUser(jid);
154
+ return { jid, user };
155
+ })
156
+ .filter(jid => jid !== null);
157
+ let mgetDevices;
158
+ if (useCache && userDevicesCache.mget) {
159
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
160
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
161
+ }
162
+ for (const { jid, user } of jidsWithUser) {
163
+ if (useCache) {
164
+ const devices = mgetDevices?.[user] ||
165
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
166
+ if (devices) {
167
+ const devicesWithJid = devices.map(d => ({
168
+ ...d,
169
+ jid: jidEncode(d.user, d.server, d.device)
170
+ }));
171
+ deviceResults.push(...devicesWithJid);
172
+ logger.trace({ user }, 'using cache for devices');
173
+ }
174
+ else {
175
+ toFetch.push(jid);
176
+ }
177
+ }
178
+ else {
179
+ toFetch.push(jid);
180
+ }
181
+ }
182
+ if (!toFetch.length) {
183
+ return deviceResults;
184
+ }
185
+ const requestedLidUsers = new Set();
186
+ for (const jid of toFetch) {
187
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
188
+ const user = jidDecode(jid)?.user;
189
+ if (user)
190
+ requestedLidUsers.add(user);
191
+ }
192
+ }
193
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
194
+ for (const jid of toFetch) {
195
+ query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
196
+ }
197
+ const result = await sock.executeUSyncQuery(query);
198
+ if (result) {
199
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
200
+ const lidResults = result.list.filter(a => !!a.lid);
201
+ if (lidResults.length > 0) {
202
+ logger.trace('Storing LID maps from device call');
203
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
204
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
205
+ try {
206
+ const lids = lidResults.map(a => a.lid);
207
+ if (lids.length) {
208
+ await assertSessions(lids, true);
209
+ }
210
+ }
211
+ catch (e) {
212
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
213
+ }
214
+ }
215
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
216
+ const deviceMap = {};
217
+ for (const item of extracted) {
218
+ deviceMap[item.user] = deviceMap[item.user] || [];
219
+ deviceMap[item.user]?.push(item);
220
+ }
221
+ // Process each user's devices as a group for bulk LID migration
222
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
223
+ const isLidUser = requestedLidUsers.has(user);
224
+ // Process all devices for this user
225
+ for (const item of userDevices) {
226
+ const finalJid = isLidUser
227
+ ? jidEncode(user, item.server, item.device)
228
+ : jidEncode(item.user, item.server, item.device);
229
+ deviceResults.push({
230
+ ...item,
231
+ jid: finalJid
232
+ });
233
+ logger.debug({
234
+ user: item.user,
235
+ device: item.device,
236
+ finalJid,
237
+ usedLid: isLidUser
238
+ }, 'Processed device with LID priority');
239
+ }
240
+ }
241
+ await devicesMutex.mutex(async () => {
242
+ if (userDevicesCache.mset) {
243
+ // if the cache supports mset, we can set all devices in one go
244
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
245
+ }
246
+ else {
247
+ for (const key in deviceMap) {
248
+ if (deviceMap[key])
249
+ await userDevicesCache.set(key, deviceMap[key]);
250
+ }
251
+ }
252
+ });
253
+ const userDeviceUpdates = {};
254
+ for (const [userId, devices] of Object.entries(deviceMap)) {
255
+ if (devices && devices.length > 0) {
256
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
257
+ }
258
+ }
259
+ if (Object.keys(userDeviceUpdates).length > 0) {
260
+ try {
261
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
262
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
263
+ }
264
+ catch (error) {
265
+ logger.warn({ error }, 'failed to store user device lists');
266
+ }
267
+ }
268
+ }
269
+ return deviceResults;
270
+ };
271
+ /**
272
+ * Update Member Label
273
+ */
274
+ const updateMemberLabel = (jid, memberLabel) => {
275
+ return relayMessage(jid, {
276
+ protocolMessage: {
277
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
278
+ memberLabel: {
279
+ label: memberLabel?.slice(0, 30),
280
+ labelTimestamp: unixTimestampSeconds()
281
+ }
282
+ }
283
+ }, {
284
+ additionalNodes: [
285
+ {
286
+ tag: 'meta',
287
+ attrs: {
288
+ tag_reason: 'user_update',
289
+ appdata: 'member_tag'
290
+ },
291
+ content: undefined
292
+ }
293
+ ]
294
+ });
295
+ };
296
+ const assertSessions = async (jids, force) => {
297
+ let didFetchNewSession = false;
298
+ const uniqueJids = [...new Set(jids)];
299
+ const jidsRequiringFetch = [];
300
+ logger.debug({ jids }, 'assertSessions call with jids');
301
+ for (const jid of uniqueJids) {
302
+ if (!force) {
303
+ const sessionValidation = await signalRepository.validateSession(jid);
304
+ if (sessionValidation.exists) {
305
+ continue;
306
+ }
307
+ }
308
+ jidsRequiringFetch.push(jid);
309
+ }
310
+ if (jidsRequiringFetch.length) {
311
+ // LID if mapped, otherwise original
312
+ const wireJids = [
313
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
314
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
315
+ ];
316
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
317
+ const result = await query({
318
+ tag: 'iq',
319
+ attrs: {
320
+ xmlns: 'encrypt',
321
+ type: 'get',
322
+ to: S_WHATSAPP_NET
323
+ },
324
+ content: [
325
+ {
326
+ tag: 'key',
327
+ attrs: {},
328
+ content: wireJids.map(jid => {
329
+ const attrs = { jid };
330
+ if (force)
331
+ attrs.reason = 'identity';
332
+ return { tag: 'user', attrs };
333
+ })
334
+ }
335
+ ]
336
+ });
337
+ await parseAndInjectE2ESessions(result, signalRepository);
338
+ didFetchNewSession = true;
339
+ }
340
+ return didFetchNewSession;
341
+ };
342
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
343
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
344
+ if (!authState.creds.me?.id) {
345
+ throw new Boom('Not authenticated');
346
+ }
347
+ const protocolMessage = {
348
+ protocolMessage: {
349
+ peerDataOperationRequestMessage: pdoMessage,
350
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
351
+ }
352
+ };
353
+ const meJid = jidNormalizedUser(authState.creds.me.id);
354
+ const msgId = await relayMessage(meJid, protocolMessage, {
355
+ additionalAttributes: {
356
+ category: 'peer',
357
+ push_priority: 'high_force'
358
+ },
359
+ additionalNodes: [
360
+ {
361
+ tag: 'meta',
362
+ attrs: { appdata: 'default' }
363
+ }
364
+ ]
365
+ });
366
+ return msgId;
367
+ };
368
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
369
+ if (!recipientJids.length) {
370
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
371
+ }
372
+ const patched = await patchMessageBeforeSending(message, recipientJids);
373
+ const patchedMessages = Array.isArray(patched)
374
+ ? patched
375
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
376
+ let shouldIncludeDeviceIdentity = false;
377
+ const meId = authState.creds.me.id;
378
+ const meLid = authState.creds.me?.lid;
379
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
380
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
381
+ try {
382
+ if (!jid)
383
+ return null;
384
+ let msgToEncrypt = patchedMessage;
385
+ if (dsmMessage) {
386
+ const { user: targetUser } = jidDecode(jid);
387
+ const { user: ownPnUser } = jidDecode(meId);
388
+ const ownLidUser = meLidUser;
389
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
390
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
391
+ if (isOwnUser && !isExactSenderDevice) {
392
+ msgToEncrypt = dsmMessage;
393
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
394
+ }
395
+ }
396
+ const bytes = encodeWAMessage(msgToEncrypt);
397
+ const mutexKey = jid;
398
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
399
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
400
+ if (type === 'pkmsg') {
401
+ shouldIncludeDeviceIdentity = true;
402
+ }
403
+ return {
404
+ tag: 'to',
405
+ attrs: { jid },
406
+ content: [
407
+ {
408
+ tag: 'enc',
409
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
410
+ content: ciphertext
411
+ }
412
+ ]
413
+ };
414
+ });
415
+ return node;
416
+ }
417
+ catch (err) {
418
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
419
+ return null;
420
+ }
421
+ });
422
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
423
+ if (recipientJids.length > 0 && nodes.length === 0) {
424
+ throw new Boom('All encryptions failed', { statusCode: 500 });
425
+ }
426
+ return { nodes, shouldIncludeDeviceIdentity };
427
+ };
428
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
429
+ const meId = assertMeId(authState.creds);
430
+ const meLid = authState.creds.me?.lid;
431
+ const isRetryResend = Boolean(participant?.jid);
432
+ let shouldIncludeDeviceIdentity = isRetryResend;
433
+ const statusJid = 'status@broadcast';
434
+ const { user, server } = jidDecode(jid);
435
+ const isGroup = server === 'g.us';
436
+ const isStatus = jid === statusJid;
437
+ const isLid = server === 'lid';
438
+ const isNewsletter = server === 'newsletter';
439
+ const isGroupOrStatus = isGroup || isStatus;
440
+ const finalJid = jid;
441
+ msgId = msgId || generateMessageIDV2(meId);
442
+ useUserDevicesCache = useUserDevicesCache !== false;
443
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
444
+ const participants = [];
445
+ const destinationJid = !isStatus ? finalJid : statusJid;
446
+ const binaryNodeContent = [];
447
+ const devices = [];
448
+ let reportingMessage;
449
+ const meMsg = {
450
+ deviceSentMessage: {
451
+ destinationJid,
452
+ message
453
+ },
454
+ messageContextInfo: message.messageContextInfo
455
+ };
456
+ const extraAttrs = {};
457
+ if (participant) {
458
+ if (!isGroup && !isStatus) {
459
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
460
+ }
461
+ const { user, device } = jidDecode(participant.jid);
462
+ devices.push({
463
+ user,
464
+ device,
465
+ jid: participant.jid
466
+ });
467
+ }
468
+ await authState.keys.transaction(async () => {
469
+ const mediaType = getMediaType(message);
470
+ if (mediaType) {
471
+ extraAttrs['mediatype'] = mediaType;
472
+ }
473
+ if (isNewsletter) {
474
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
475
+ const bytes = encodeNewsletterMessage(patched);
476
+ binaryNodeContent.push({
477
+ tag: 'plaintext',
478
+ attrs: {},
479
+ content: bytes
480
+ });
481
+ const stanza = {
482
+ tag: 'message',
483
+ attrs: {
484
+ to: jid,
485
+ id: msgId,
486
+ type: getMessageType(message),
487
+ ...(additionalAttributes || {})
488
+ },
489
+ content: binaryNodeContent
490
+ };
491
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
492
+ await sendNode(stanza);
493
+ return;
494
+ }
495
+ if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
496
+ extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
497
+ }
498
+ if (isGroupOrStatus && !isRetryResend) {
499
+ const [groupData, senderKeyMap] = await Promise.all([
500
+ (async () => {
501
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
502
+ if (groupData && Array.isArray(groupData?.participants)) {
503
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
504
+ }
505
+ else if (!isStatus) {
506
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
507
+ config.onGroupMetadata?.(jid, groupData);
508
+ }
509
+ return groupData;
510
+ })(),
511
+ (async () => {
512
+ if (!participant && !isStatus) {
513
+ // what if sender memory is less accurate than the cached metadata
514
+ // on participant change in group, we should do sender memory manipulation
515
+ const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
516
+ return result[jid] || {};
517
+ }
518
+ return {};
519
+ })()
520
+ ]);
521
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
522
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
523
+ additionalAttributes = {
524
+ ...additionalAttributes,
525
+ expiration: groupData.ephemeralDuration.toString()
526
+ };
527
+ }
528
+ if (isStatus && statusJidList) {
529
+ participantsList.push(...statusJidList);
530
+ }
531
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
532
+ devices.push(...additionalDevices);
533
+ if (isGroup) {
534
+ additionalAttributes = {
535
+ ...additionalAttributes,
536
+ addressing_mode: groupData?.addressingMode || 'lid'
537
+ };
538
+ }
539
+ const patched = await patchMessageBeforeSending(message);
540
+ if (Array.isArray(patched)) {
541
+ throw new Boom('Per-jid patching is not supported in groups');
542
+ }
543
+ const bytes = encodeWAMessage(patched);
544
+ reportingMessage = patched;
545
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
546
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
547
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
548
+ group: destinationJid,
549
+ data: bytes,
550
+ meId: groupSenderIdentity
551
+ });
552
+ const senderKeyRecipients = [];
553
+ for (const device of devices) {
554
+ const deviceJid = device.jid;
555
+ const hasKey = !!senderKeyMap[deviceJid];
556
+ if ((!hasKey || !!participant) &&
557
+ !isHostedLidUser(deviceJid) &&
558
+ !isHostedPnUser(deviceJid) &&
559
+ device.device !== 99) {
560
+ //todo: revamp all this logic
561
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
562
+ senderKeyRecipients.push(deviceJid);
563
+ senderKeyMap[deviceJid] = true;
564
+ }
565
+ }
566
+ if (senderKeyRecipients.length) {
567
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
568
+ const senderKeyMsg = {
569
+ senderKeyDistributionMessage: {
570
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
571
+ groupId: destinationJid
572
+ }
573
+ };
574
+ const senderKeySessionTargets = senderKeyRecipients;
575
+ await assertSessions(senderKeySessionTargets);
576
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
577
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
578
+ participants.push(...result.nodes);
579
+ }
580
+ binaryNodeContent.push({
581
+ tag: 'enc',
582
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
583
+ content: ciphertext
584
+ });
585
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
586
+ }
587
+ else {
588
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
589
+ // TODO: investigate if this is true
590
+ let ownId = meId;
591
+ if (isLid && meLid) {
592
+ ownId = meLid;
593
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
594
+ }
595
+ else {
596
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
597
+ }
598
+ const { user: ownUser } = jidDecode(ownId);
599
+ if (!participant) {
600
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
601
+ reportingMessage = Array.isArray(patchedForReporting)
602
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
603
+ : patchedForReporting;
604
+ }
605
+ if (!isRetryResend) {
606
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
607
+ devices.push({
608
+ user,
609
+ device: 0,
610
+ jid: jidEncode(user, targetUserServer, 0) // todo: this entire logic is convoluted and weird.
611
+ });
612
+ if (user !== ownUser) {
613
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
614
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
615
+ devices.push({
616
+ user: ownUserForAddressing,
617
+ device: 0,
618
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
619
+ });
620
+ }
621
+ if (additionalAttributes?.['category'] !== 'peer') {
622
+ // Clear placeholders and enumerate actual devices
623
+ devices.length = 0;
624
+ // Use conversation-appropriate sender identity
625
+ const senderIdentity = isLid && meLid
626
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
627
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
628
+ // Enumerate devices for sender and target with consistent addressing
629
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
630
+ devices.push(...sessionDevices);
631
+ logger.debug({
632
+ deviceCount: devices.length,
633
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
634
+ }, 'Device enumeration complete with unified addressing');
635
+ }
636
+ }
637
+ const allRecipients = [];
638
+ const meRecipients = [];
639
+ const otherRecipients = [];
640
+ const { user: mePnUser } = jidDecode(meId);
641
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
642
+ for (const { user, jid } of devices) {
643
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
644
+ if (isExactSenderDevice) {
645
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
646
+ continue;
647
+ }
648
+ // Check if this is our device (could match either PN or LID user)
649
+ const isMe = user === mePnUser || user === meLidUser;
650
+ if (isMe) {
651
+ meRecipients.push(jid);
652
+ }
653
+ else {
654
+ otherRecipients.push(jid);
655
+ }
656
+ allRecipients.push(jid);
657
+ }
658
+ await assertSessions(allRecipients);
659
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
660
+ // For own devices: use DSM if available (1:1 chats only)
661
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
662
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
663
+ ]);
664
+ participants.push(...meNodes);
665
+ participants.push(...otherNodes);
666
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
667
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
668
+ }
669
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
670
+ }
671
+ if (isRetryResend) {
672
+ const isParticipantLid = isLidUser(participant.jid);
673
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
674
+ let messageToSend = message;
675
+ if (isGroupOrStatus) {
676
+ let groupSenderIdentity;
677
+ if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
678
+ groupSenderIdentity = meLid;
679
+ }
680
+ else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
681
+ groupSenderIdentity = meId;
682
+ }
683
+ if (groupSenderIdentity) {
684
+ try {
685
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
686
+ group: destinationJid,
687
+ meId: groupSenderIdentity
688
+ });
689
+ messageToSend = {
690
+ ...message,
691
+ senderKeyDistributionMessage: {
692
+ groupId: destinationJid,
693
+ axolotlSenderKeyDistributionMessage: skdm
694
+ }
695
+ };
696
+ }
697
+ catch (err) {
698
+ logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
699
+ }
700
+ }
701
+ }
702
+ const encodedMessageToSend = isMe
703
+ ? encodeWAMessage({
704
+ deviceSentMessage: {
705
+ destinationJid,
706
+ message: messageToSend
707
+ }
708
+ })
709
+ : encodeWAMessage(messageToSend);
710
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
711
+ data: encodedMessageToSend,
712
+ jid: participant.jid
713
+ });
714
+ binaryNodeContent.push({
715
+ tag: 'enc',
716
+ attrs: {
717
+ v: '2',
718
+ type,
719
+ count: participant.count.toString()
720
+ },
721
+ content: encryptedContent
722
+ });
723
+ }
724
+ if (participants.length) {
725
+ if (additionalAttributes?.['category'] === 'peer') {
726
+ const peerNode = participants[0]?.content?.[0];
727
+ if (peerNode) {
728
+ binaryNodeContent.push(peerNode); // push only enc
729
+ }
730
+ }
731
+ else {
732
+ binaryNodeContent.push({
733
+ tag: 'participants',
734
+ attrs: {},
735
+ content: participants
736
+ });
737
+ }
738
+ }
739
+ const stanza = {
740
+ tag: 'message',
741
+ attrs: {
742
+ id: msgId,
743
+ to: destinationJid,
744
+ type: getMessageType(message),
745
+ ...(additionalAttributes || {})
746
+ },
747
+ content: binaryNodeContent
748
+ };
749
+ // if the participant to send to is explicitly specified (generally retry recp)
750
+ // ensure the message is only sent to that person
751
+ // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
752
+ if (participant) {
753
+ if (isJidGroup(destinationJid)) {
754
+ stanza.attrs.to = destinationJid;
755
+ stanza.attrs.participant = participant.jid;
756
+ }
757
+ else if (areJidsSameUser(participant.jid, meId)) {
758
+ stanza.attrs.to = participant.jid;
759
+ stanza.attrs.recipient = destinationJid;
760
+ }
761
+ else {
762
+ stanza.attrs.to = participant.jid;
763
+ }
764
+ }
765
+ else {
766
+ stanza.attrs.to = destinationJid;
767
+ }
768
+ if (shouldIncludeDeviceIdentity) {
769
+ ;
770
+ stanza.content.push({
771
+ tag: 'device-identity',
772
+ attrs: {},
773
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
774
+ });
775
+ logger.debug({ jid }, 'adding device identity');
776
+ }
777
+ if (!isNewsletter &&
778
+ !isRetryResend &&
779
+ reportingMessage?.messageContextInfo?.messageSecret &&
780
+ shouldIncludeReportingToken(reportingMessage)) {
781
+ try {
782
+ const encoded = encodeWAMessage(reportingMessage);
783
+ const reportingKey = {
784
+ id: msgId,
785
+ fromMe: true,
786
+ remoteJid: destinationJid,
787
+ participant: participant?.jid
788
+ };
789
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
790
+ if (reportingNode) {
791
+ ;
792
+ stanza.content.push(reportingNode);
793
+ logger.trace({ jid }, 'added reporting token to message');
794
+ }
795
+ }
796
+ catch (error) {
797
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
798
+ }
799
+ }
800
+ // WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
801
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
802
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
803
+ // Resolve destination to LID for tctoken storage — matches Signal session key pattern
804
+ const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
805
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
806
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
807
+ let tcTokenBuffer = existingTokenEntry?.token;
808
+ // Treat expired tokens the same as missing — clear from cache
809
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
810
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
811
+ tcTokenBuffer = undefined;
812
+ // Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
813
+ const cleared = existingTokenEntry?.senderTimestamp !== undefined
814
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
815
+ : null;
816
+ try {
817
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
818
+ }
819
+ catch (err) {
820
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
821
+ }
822
+ }
823
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
824
+ ;
825
+ stanza.content.push({
826
+ tag: 'tctoken',
827
+ attrs: {},
828
+ content: tcTokenBuffer
829
+ });
830
+ }
831
+ if (additionalNodes && additionalNodes.length > 0) {
832
+ ;
833
+ stanza.content.push(...additionalNodes);
834
+ }
835
+ // button/list/template messages need a <biz> node in the stanza,
836
+ // otherwise recipients' clients never render them
837
+ const bizContent = normalizeMessageContent(message);
838
+ if (bizContent && shouldIncludeBizBinaryNode(bizContent) && !additionalNodes?.some(node => node.tag === 'biz')) {
839
+ ;
840
+ stanza.content.push(getBizBinaryNode(bizContent));
841
+ }
842
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
843
+ await sendNode(stanza);
844
+ // Fire-and-forget: issue our token to the contact AFTER message send.
845
+ // WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
846
+ const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
847
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
848
+ if (is1on1Send &&
849
+ !isProtocolMsg &&
850
+ !isBotOrPSA &&
851
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
852
+ !inFlightTcTokenIssuance.has(tcTokenJid)) {
853
+ inFlightTcTokenIssuance.add(tcTokenJid);
854
+ const issueTimestamp = unixTimestampSeconds();
855
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
856
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
857
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
858
+ .then(async (result) => {
859
+ await storeTcTokensFromIqResult({
860
+ result,
861
+ fallbackJid: tcTokenJid,
862
+ keys: authState.keys,
863
+ getLIDForPN
864
+ });
865
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
866
+ const currentEntry = currentData[tcTokenJid];
867
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
868
+ await authState.keys.set({
869
+ tctoken: {
870
+ [tcTokenJid]: {
871
+ token: Buffer.alloc(0),
872
+ ...currentEntry,
873
+ senderTimestamp: issueTimestamp
874
+ },
875
+ ...indexWrite
876
+ }
877
+ });
878
+ })
879
+ .catch(err => {
880
+ logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
881
+ })
882
+ .finally(() => {
883
+ inFlightTcTokenIssuance.delete(tcTokenJid);
884
+ });
885
+ }
886
+ // Add message to retry cache if enabled
887
+ if (messageRetryManager && !participant) {
888
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
889
+ }
890
+ }, meId);
891
+ return msgId;
892
+ };
893
+ const getMessageType = (message) => {
894
+ const normalizedMessage = normalizeMessageContent(message);
895
+ if (!normalizedMessage)
896
+ return 'text';
897
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
898
+ return 'reaction';
899
+ }
900
+ if (normalizedMessage.pollCreationMessage ||
901
+ normalizedMessage.pollCreationMessageV2 ||
902
+ normalizedMessage.pollCreationMessageV3 ||
903
+ normalizedMessage.pollUpdateMessage) {
904
+ return 'poll';
905
+ }
906
+ if (normalizedMessage.eventMessage) {
907
+ return 'event';
908
+ }
909
+ if (getMediaType(normalizedMessage) !== '') {
910
+ return 'media';
911
+ }
912
+ return 'text';
913
+ };
914
+ const getMediaType = (message) => {
915
+ if (message.imageMessage) {
916
+ return 'image';
917
+ }
918
+ else if (message.videoMessage) {
919
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
920
+ }
921
+ else if (message.audioMessage) {
922
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
923
+ }
924
+ else if (message.contactMessage) {
925
+ return 'vcard';
926
+ }
927
+ else if (message.documentMessage) {
928
+ return 'document';
929
+ }
930
+ else if (message.contactsArrayMessage) {
931
+ return 'contact_array';
932
+ }
933
+ else if (message.liveLocationMessage) {
934
+ return 'livelocation';
935
+ }
936
+ else if (message.stickerMessage) {
937
+ return 'sticker';
938
+ }
939
+ else if (message.listMessage) {
940
+ return 'list';
941
+ }
942
+ else if (message.listResponseMessage) {
943
+ return 'list_response';
944
+ }
945
+ else if (message.buttonsResponseMessage) {
946
+ return 'buttons_response';
947
+ }
948
+ else if (message.orderMessage) {
949
+ return 'order';
950
+ }
951
+ else if (message.productMessage) {
952
+ return 'product';
953
+ }
954
+ else if (message.interactiveResponseMessage) {
955
+ return 'native_flow_response';
956
+ }
957
+ else if (message.groupInviteMessage) {
958
+ return 'url';
959
+ }
960
+ return '';
961
+ };
962
+ const issuePrivacyTokens = async (jids, timestamp) => {
963
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
964
+ const result = await query({
965
+ tag: 'iq',
966
+ attrs: {
967
+ to: S_WHATSAPP_NET,
968
+ type: 'set',
969
+ xmlns: 'privacy'
970
+ },
971
+ content: [
972
+ {
973
+ tag: 'tokens',
974
+ attrs: {},
975
+ content: jids.map(jid => ({
976
+ tag: 'token',
977
+ attrs: {
978
+ jid: jidNormalizedUser(jid),
979
+ t,
980
+ type: 'trusted_contact'
981
+ }
982
+ }))
983
+ }
984
+ ]
985
+ });
986
+ return result;
987
+ };
988
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
989
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
990
+ registerSocketEndHandler(() => {
991
+ if (!config.userDevicesCache && userDevicesCache.close) {
992
+ userDevicesCache.close();
993
+ }
994
+ mediaConn = undefined;
995
+ if (messageRetryManager) {
996
+ messageRetryManager.clear();
997
+ }
998
+ });
999
+ return {
1000
+ ...sock,
1001
+ userDevicesCache,
1002
+ devicesMutex,
1003
+ issuePrivacyTokens,
1004
+ assertSessions,
1005
+ relayMessage,
1006
+ sendReceipt,
1007
+ sendReceipts,
1008
+ readMessages,
1009
+ refreshMediaConn,
1010
+ // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1011
+ getMediaHost: () => mediaHost,
1012
+ waUploadToServer,
1013
+ fetchPrivacySettings,
1014
+ sendPeerDataOperationMessage,
1015
+ createParticipantNodes,
1016
+ getUSyncDevices,
1017
+ messageRetryManager,
1018
+ updateMemberLabel,
1019
+ updateMediaMessage: async (message) => {
1020
+ const content = assertMediaContent(message.message);
1021
+ const mediaKey = content.mediaKey;
1022
+ const meId = authState.creds.me.id;
1023
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1024
+ let error = undefined;
1025
+ await Promise.all([
1026
+ sendNode(node),
1027
+ waitForMsgMediaUpdate(async (update) => {
1028
+ const result = update.find(c => c.key.id === message.key.id);
1029
+ if (result) {
1030
+ if (result.error) {
1031
+ error = result.error;
1032
+ }
1033
+ else {
1034
+ try {
1035
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1036
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1037
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1038
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1039
+ data: media,
1040
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1041
+ });
1042
+ }
1043
+ content.directPath = media.directPath;
1044
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1045
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1046
+ }
1047
+ catch (err) {
1048
+ error = err;
1049
+ }
1050
+ }
1051
+ return true;
1052
+ }
1053
+ })
1054
+ ]);
1055
+ if (error) {
1056
+ throw error;
1057
+ }
1058
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1059
+ return message;
1060
+ },
1061
+ sendMessage: async (jid, content, options = {}) => {
1062
+ const userJid = authState.creds.me.id;
1063
+ if (typeof content === 'object' &&
1064
+ 'disappearingMessagesInChat' in content &&
1065
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1066
+ isJidGroup(jid)) {
1067
+ const { disappearingMessagesInChat } = content;
1068
+ const value = typeof disappearingMessagesInChat === 'boolean'
1069
+ ? disappearingMessagesInChat
1070
+ ? WA_DEFAULT_EPHEMERAL
1071
+ : 0
1072
+ : disappearingMessagesInChat;
1073
+ await groupToggleEphemeral(jid, value);
1074
+ }
1075
+ else {
1076
+ const fullMsg = await generateWAMessage(jid, content, {
1077
+ logger,
1078
+ userJid,
1079
+ getUrlInfo: text => getUrlInfo(text, {
1080
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1081
+ fetchOpts: {
1082
+ // preview fetch blocks the send of any text containing a URL —
1083
+ // cap it so slow sites can't add seconds of latency
1084
+ timeout: 1500,
1085
+ ...(httpRequestOptions || {})
1086
+ },
1087
+ logger,
1088
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1089
+ }),
1090
+ //TODO: CACHE
1091
+ getProfilePicUrl: sock.profilePictureUrl,
1092
+ getCallLink: sock.createCallLink,
1093
+ upload: waUploadToServer,
1094
+ mediaCache: config.mediaCache,
1095
+ options: config.options,
1096
+ messageId: generateMessageIDV2(sock.user?.id),
1097
+ ...options
1098
+ });
1099
+ const isEventMsg = 'event' in content && !!content.event;
1100
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1101
+ const isEditMsg = 'edit' in content && !!content.edit;
1102
+ const isPinMsg = 'pin' in content && !!content.pin;
1103
+ const isPollMessage = 'poll' in content && !!content.poll;
1104
+ const additionalAttributes = {};
1105
+ const additionalNodes = [];
1106
+ // required for delete
1107
+ if (isDeleteMsg) {
1108
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1109
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1110
+ additionalAttributes.edit = '8';
1111
+ }
1112
+ else {
1113
+ additionalAttributes.edit = '7';
1114
+ }
1115
+ }
1116
+ else if (isEditMsg) {
1117
+ additionalAttributes.edit = '1';
1118
+ }
1119
+ else if (isPinMsg) {
1120
+ additionalAttributes.edit = '2';
1121
+ }
1122
+ else if (isPollMessage) {
1123
+ additionalNodes.push({
1124
+ tag: 'meta',
1125
+ attrs: {
1126
+ polltype: 'creation'
1127
+ }
1128
+ });
1129
+ }
1130
+ else if (isEventMsg) {
1131
+ additionalNodes.push({
1132
+ tag: 'meta',
1133
+ attrs: {
1134
+ event_type: 'creation'
1135
+ }
1136
+ });
1137
+ }
1138
+ // `ai: true` marks the message as sent by a business bot (shows the AI icon)
1139
+ if ('ai' in content && content.ai) {
1140
+ additionalNodes.push({ tag: 'bot', attrs: { biz_bot: '1' } });
1141
+ }
1142
+ await relayMessage(jid, fullMsg.message, {
1143
+ messageId: fullMsg.key.id,
1144
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1145
+ additionalAttributes,
1146
+ statusJidList: options.statusJidList,
1147
+ additionalNodes
1148
+ });
1149
+ if (config.emitOwnEvents) {
1150
+ process.nextTick(async () => {
1151
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1152
+ });
1153
+ }
1154
+ return fullMsg;
1155
+ }
1156
+ }
1157
+ };
1158
+ };
1159
+ //# sourceMappingURL=messages-send.js.map