@vanzxysenpai/baileys 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (431) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +25 -0
  3. package/NOTICE.md +158 -0
  4. package/README.md +5294 -2
  5. package/VanzxyBanner.js +134 -0
  6. package/WAProto/index.d.ts +13317 -0
  7. package/WAProto/index.js +147553 -0
  8. package/lib/Builders/A2UI.d.ts +131 -0
  9. package/lib/Builders/A2UI.js +343 -0
  10. package/lib/Builders/AIRich.d.ts +1021 -0
  11. package/lib/Builders/AIRich.js +2889 -0
  12. package/lib/Builders/Album.d.ts +51 -0
  13. package/lib/Builders/Album.js +99 -0
  14. package/lib/Builders/Button.d.ts +137449 -0
  15. package/lib/Builders/Button.js +1054 -0
  16. package/lib/Builders/ButtonV2.d.ts +43 -0
  17. package/lib/Builders/ButtonV2.js +175 -0
  18. package/lib/Builders/ButtonV3.d.ts +35 -0
  19. package/lib/Builders/ButtonV3.js +189 -0
  20. package/lib/Builders/Carousel.d.ts +68 -0
  21. package/lib/Builders/Carousel.js +161 -0
  22. package/lib/Builders/Event.d.ts +61 -0
  23. package/lib/Builders/Event.js +118 -0
  24. package/lib/Builders/Expiring.d.ts +17 -0
  25. package/lib/Builders/Expiring.js +27 -0
  26. package/lib/Builders/Poll.d.ts +63 -0
  27. package/lib/Builders/Poll.js +139 -0
  28. package/lib/Builders/VanzxyBaileys.d.ts +42 -0
  29. package/lib/Builders/VanzxyBaileys.js +110 -0
  30. package/lib/Builders/errors.d.ts +25 -0
  31. package/lib/Builders/errors.js +29 -0
  32. package/lib/Builders/index.d.ts +14 -0
  33. package/lib/Builders/index.js +23 -0
  34. package/lib/Builders/shared.d.ts +395 -0
  35. package/lib/Builders/shared.js +738 -0
  36. package/lib/Defaults/bot-jid.d.ts +1 -0
  37. package/lib/Defaults/bot-jid.js +1 -0
  38. package/lib/Defaults/index.d.ts +161 -0
  39. package/lib/Defaults/index.js +165 -0
  40. package/lib/Defaults/version.d.ts +1 -0
  41. package/lib/Defaults/version.js +1 -0
  42. package/lib/Framework/Bot.d.ts +865 -0
  43. package/lib/Framework/Bot.js +230 -0
  44. package/lib/Framework/Context.d.ts +17 -0
  45. package/lib/Framework/Context.js +90 -0
  46. package/lib/Framework/MediaManager.d.ts +15 -0
  47. package/lib/Framework/MediaManager.js +154 -0
  48. package/lib/Framework/SessionManager.d.ts +10 -0
  49. package/lib/Framework/SessionManager.js +34 -0
  50. package/lib/Framework/StatsManager.d.ts +20 -0
  51. package/lib/Framework/StatsManager.js +117 -0
  52. package/lib/Framework/Store/SQLiteStore.d.ts +13 -0
  53. package/lib/Framework/Store/SQLiteStore.js +68 -0
  54. package/lib/Framework/index.d.ts +6 -0
  55. package/lib/Framework/index.js +11 -0
  56. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  57. package/lib/Signal/Group/ciphertext-message.js +11 -0
  58. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  59. package/lib/Signal/Group/group-session-builder.js +29 -0
  60. package/lib/Signal/Group/group_cipher.d.ts +10 -0
  61. package/lib/Signal/Group/group_cipher.js +81 -0
  62. package/lib/Signal/Group/index.d.ts +11 -0
  63. package/lib/Signal/Group/index.js +11 -0
  64. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  65. package/lib/Signal/Group/keyhelper.js +17 -0
  66. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  67. package/lib/Signal/Group/sender-chain-key.js +25 -0
  68. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  69. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  70. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  71. package/lib/Signal/Group/sender-key-message.js +65 -0
  72. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  73. package/lib/Signal/Group/sender-key-name.js +47 -0
  74. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  75. package/lib/Signal/Group/sender-key-record.js +40 -0
  76. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  77. package/lib/Signal/Group/sender-key-state.js +83 -0
  78. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  79. package/lib/Signal/Group/sender-message-key.js +25 -0
  80. package/lib/Signal/libsignal.d.ts +58 -0
  81. package/lib/Signal/libsignal.js +436 -0
  82. package/lib/Signal/lid-mapping.d.ts +20 -0
  83. package/lib/Signal/lid-mapping.js +276 -0
  84. package/lib/Socket/Client/index.d.ts +2 -0
  85. package/lib/Socket/Client/index.js +2 -0
  86. package/lib/Socket/Client/types.d.ts +5 -0
  87. package/lib/Socket/Client/types.js +10 -0
  88. package/lib/Socket/Client/websocket.d.ts +12 -0
  89. package/lib/Socket/Client/websocket.js +53 -0
  90. package/lib/Socket/business.d.ts +674 -0
  91. package/lib/Socket/business.js +379 -0
  92. package/lib/Socket/chats.d.ts +137 -0
  93. package/lib/Socket/chats.js +1299 -0
  94. package/lib/Socket/communities.d.ts +805 -0
  95. package/lib/Socket/communities.js +454 -0
  96. package/lib/Socket/dugong.d.ts +118 -0
  97. package/lib/Socket/dugong.js +810 -0
  98. package/lib/Socket/groups.d.ts +287 -0
  99. package/lib/Socket/groups.js +386 -0
  100. package/lib/Socket/index.d.ts +826 -0
  101. package/lib/Socket/index.js +35 -0
  102. package/lib/Socket/messages-recv.d.ts +613 -0
  103. package/lib/Socket/messages-recv.js +1851 -0
  104. package/lib/Socket/messages-send.d.ts +608 -0
  105. package/lib/Socket/messages-send.js +1574 -0
  106. package/lib/Socket/mex-fallback.d.ts +51 -0
  107. package/lib/Socket/mex-fallback.js +97 -0
  108. package/lib/Socket/mex.d.ts +1 -0
  109. package/lib/Socket/mex.js +41 -0
  110. package/lib/Socket/newsletter-ext.d.ts +47 -0
  111. package/lib/Socket/newsletter-ext.js +262 -0
  112. package/lib/Socket/newsletter.d.ts +285 -0
  113. package/lib/Socket/newsletter.js +223 -0
  114. package/lib/Socket/socket.d.ts +60 -0
  115. package/lib/Socket/socket.js +1001 -0
  116. package/lib/Socket/username.d.ts +842 -0
  117. package/lib/Socket/username.js +156 -0
  118. package/lib/Store/index.d.ts +3 -0
  119. package/lib/Store/index.js +3 -0
  120. package/lib/Store/make-in-memory-store.d.ts +62 -0
  121. package/lib/Store/make-in-memory-store.js +425 -0
  122. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  123. package/lib/Store/make-ordered-dictionary.js +78 -0
  124. package/lib/Store/object-repository.d.ts +10 -0
  125. package/lib/Store/object-repository.js +23 -0
  126. package/lib/Types/Auth.d.ts +1 -0
  127. package/lib/Types/Auth.js +1 -0
  128. package/lib/Types/Bussines.d.ts +1 -0
  129. package/lib/Types/Bussines.js +1 -0
  130. package/lib/Types/Call.d.ts +1 -0
  131. package/lib/Types/Call.js +1 -0
  132. package/lib/Types/Chat.d.ts +1 -0
  133. package/lib/Types/Chat.js +7 -0
  134. package/lib/Types/Contact.d.ts +1 -0
  135. package/lib/Types/Contact.js +1 -0
  136. package/lib/Types/Events.d.ts +1 -0
  137. package/lib/Types/Events.js +1 -0
  138. package/lib/Types/GroupMetadata.d.ts +1 -0
  139. package/lib/Types/GroupMetadata.js +1 -0
  140. package/lib/Types/Label.d.ts +2 -0
  141. package/lib/Types/Label.js +24 -0
  142. package/lib/Types/LabelAssociation.d.ts +2 -0
  143. package/lib/Types/LabelAssociation.js +6 -0
  144. package/lib/Types/Message.d.ts +11 -0
  145. package/lib/Types/Message.js +17 -0
  146. package/lib/Types/Mex.d.ts +2 -0
  147. package/lib/Types/Mex.js +38 -0
  148. package/lib/Types/Product.d.ts +1 -0
  149. package/lib/Types/Product.js +1 -0
  150. package/lib/Types/RichType.d.ts +2 -0
  151. package/lib/Types/RichType.js +22 -0
  152. package/lib/Types/Signal.d.ts +1 -0
  153. package/lib/Types/Signal.js +1 -0
  154. package/lib/Types/Socket.d.ts +1 -0
  155. package/lib/Types/Socket.js +1 -0
  156. package/lib/Types/State.d.ts +5 -0
  157. package/lib/Types/State.js +55 -0
  158. package/lib/Types/USync.d.ts +1 -0
  159. package/lib/Types/USync.js +1 -0
  160. package/lib/Types/index.d.ts +15 -0
  161. package/lib/Types/index.js +27 -0
  162. package/lib/Utils/PersistentStore.d.ts +83 -0
  163. package/lib/Utils/PersistentStore.js +592 -0
  164. package/lib/Utils/anchor-guard.d.ts +31 -0
  165. package/lib/Utils/anchor-guard.js +329 -0
  166. package/lib/Utils/android-stanza-id.d.ts +4 -0
  167. package/lib/Utils/android-stanza-id.js +21 -0
  168. package/lib/Utils/anti-delete.d.ts +62 -0
  169. package/lib/Utils/anti-delete.js +212 -0
  170. package/lib/Utils/auth-secure.d.ts +180 -0
  171. package/lib/Utils/auth-secure.js +791 -0
  172. package/lib/Utils/auth-utils.d.ts +59 -0
  173. package/lib/Utils/auth-utils.js +326 -0
  174. package/lib/Utils/auto-reconnect.d.ts +8 -0
  175. package/lib/Utils/auto-reconnect.js +204 -0
  176. package/lib/Utils/auto-reply.d.ts +35 -0
  177. package/lib/Utils/auto-reply.js +152 -0
  178. package/lib/Utils/bad-mac-handler.d.ts +59 -0
  179. package/lib/Utils/bad-mac-handler.js +119 -0
  180. package/lib/Utils/baileys-event-stream.d.ts +5 -0
  181. package/lib/Utils/baileys-event-stream.js +62 -0
  182. package/lib/Utils/browser-utils.d.ts +9 -0
  183. package/lib/Utils/browser-utils.js +29 -0
  184. package/lib/Utils/business.d.ts +49 -0
  185. package/lib/Utils/business.js +236 -0
  186. package/lib/Utils/button-helper-utils.d.ts +59 -0
  187. package/lib/Utils/button-helper-utils.js +266 -0
  188. package/lib/Utils/button-sender.d.ts +164 -0
  189. package/lib/Utils/button-sender.js +845 -0
  190. package/lib/Utils/chat-control.d.ts +98 -0
  191. package/lib/Utils/chat-control.js +231 -0
  192. package/lib/Utils/chat-history-helpers.d.ts +4 -0
  193. package/lib/Utils/chat-history-helpers.js +70 -0
  194. package/lib/Utils/chat-utils.d.ts +408 -0
  195. package/lib/Utils/chat-utils.js +879 -0
  196. package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  197. package/lib/Utils/companion-reg-client-utils.js +39 -0
  198. package/lib/Utils/connection-watchdog.d.ts +10 -0
  199. package/lib/Utils/connection-watchdog.js +74 -0
  200. package/lib/Utils/crypto.d.ts +41 -0
  201. package/lib/Utils/crypto.js +145 -0
  202. package/lib/Utils/decode-wa-message.d.ts +83 -0
  203. package/lib/Utils/decode-wa-message.js +315 -0
  204. package/lib/Utils/disconnect-reason.d.ts +13 -0
  205. package/lib/Utils/disconnect-reason.js +36 -0
  206. package/lib/Utils/event-buffer.d.ts +12 -0
  207. package/lib/Utils/event-buffer.js +640 -0
  208. package/lib/Utils/fetch-timeout.d.ts +4 -0
  209. package/lib/Utils/fetch-timeout.js +14 -0
  210. package/lib/Utils/ffmpeg-path.d.ts +5 -0
  211. package/lib/Utils/ffmpeg-path.js +130 -0
  212. package/lib/Utils/generics.d.ts +79 -0
  213. package/lib/Utils/generics.js +426 -0
  214. package/lib/Utils/group-metadata-cache.d.ts +3 -0
  215. package/lib/Utils/group-metadata-cache.js +25 -0
  216. package/lib/Utils/group-status-detection.d.ts +5 -0
  217. package/lib/Utils/group-status-detection.js +114 -0
  218. package/lib/Utils/history.d.ts +91 -0
  219. package/lib/Utils/history.js +144 -0
  220. package/lib/Utils/html-app.d.ts +14 -0
  221. package/lib/Utils/html-app.js +97 -0
  222. package/lib/Utils/html-multiplayer.d.ts +8 -0
  223. package/lib/Utils/html-multiplayer.js +90 -0
  224. package/lib/Utils/humanizer.d.ts +8 -0
  225. package/lib/Utils/humanizer.js +74 -0
  226. package/lib/Utils/identity-change-handler.d.ts +13 -0
  227. package/lib/Utils/identity-change-handler.js +49 -0
  228. package/lib/Utils/index.d.ts +88 -0
  229. package/lib/Utils/index.js +93 -0
  230. package/lib/Utils/jid-tools.d.ts +3 -0
  231. package/lib/Utils/jid-tools.js +78 -0
  232. package/lib/Utils/link-preview-metadata.d.ts +47 -0
  233. package/lib/Utils/link-preview-metadata.js +90 -0
  234. package/lib/Utils/link-preview.d.ts +12 -0
  235. package/lib/Utils/link-preview.js +84 -0
  236. package/lib/Utils/lock-manager.d.ts +5 -0
  237. package/lib/Utils/lock-manager.js +50 -0
  238. package/lib/Utils/logger.d.ts +2 -0
  239. package/lib/Utils/logger.js +2 -0
  240. package/lib/Utils/lt-hash.d.ts +12 -0
  241. package/lib/Utils/lt-hash.js +26 -0
  242. package/lib/Utils/make-mutex.d.ts +6 -0
  243. package/lib/Utils/make-mutex.js +32 -0
  244. package/lib/Utils/media-messages.d.ts +35 -0
  245. package/lib/Utils/media-messages.js +70 -0
  246. package/lib/Utils/media-processor.d.ts +6 -0
  247. package/lib/Utils/media-processor.js +174 -0
  248. package/lib/Utils/media-set.d.ts +6 -0
  249. package/lib/Utils/media-set.js +169 -0
  250. package/lib/Utils/message-kind.d.ts +26 -0
  251. package/lib/Utils/message-kind.js +138 -0
  252. package/lib/Utils/message-retry-manager.d.ts +79 -0
  253. package/lib/Utils/message-retry-manager.js +264 -0
  254. package/lib/Utils/message-search.d.ts +40 -0
  255. package/lib/Utils/message-search.js +181 -0
  256. package/lib/Utils/messages-media.d.ts +136 -0
  257. package/lib/Utils/messages-media.js +867 -0
  258. package/lib/Utils/messages.d.ts +66 -0
  259. package/lib/Utils/messages.js +2271 -0
  260. package/lib/Utils/meta-ai-msmsg.d.ts +3 -0
  261. package/lib/Utils/meta-ai-msmsg.js +132 -0
  262. package/lib/Utils/meta-ai.d.ts +4 -0
  263. package/lib/Utils/meta-ai.js +75 -0
  264. package/lib/Utils/migrate-auth-state.d.ts +23 -0
  265. package/lib/Utils/migrate-auth-state.js +126 -0
  266. package/lib/Utils/mini-app.d.ts +20 -0
  267. package/lib/Utils/mini-app.js +215 -0
  268. package/lib/Utils/mock-socket.d.ts +67 -0
  269. package/lib/Utils/mock-socket.js +254 -0
  270. package/lib/Utils/modern-messages.d.ts +64 -0
  271. package/lib/Utils/modern-messages.js +497 -0
  272. package/lib/Utils/native-flow.d.ts +19 -0
  273. package/lib/Utils/native-flow.js +112 -0
  274. package/lib/Utils/newsletter-status.d.ts +157 -0
  275. package/lib/Utils/newsletter-status.js +652 -0
  276. package/lib/Utils/noise-handler.d.ts +20 -0
  277. package/lib/Utils/noise-handler.js +200 -0
  278. package/lib/Utils/offline-node-processor.d.ts +9 -0
  279. package/lib/Utils/offline-node-processor.js +39 -0
  280. package/lib/Utils/pairing-utils.d.ts +5 -0
  281. package/lib/Utils/pairing-utils.js +29 -0
  282. package/lib/Utils/passkey.d.ts +4 -0
  283. package/lib/Utils/passkey.js +11 -0
  284. package/lib/Utils/past-participants.d.ts +2 -0
  285. package/lib/Utils/past-participants.js +40 -0
  286. package/lib/Utils/payment-detection.d.ts +40 -0
  287. package/lib/Utils/payment-detection.js +213 -0
  288. package/lib/Utils/payment-guard.d.ts +28 -0
  289. package/lib/Utils/payment-guard.js +143 -0
  290. package/lib/Utils/payment-messages.d.ts +42 -0
  291. package/lib/Utils/payment-messages.js +161 -0
  292. package/lib/Utils/payment-utils.d.ts +75 -0
  293. package/lib/Utils/payment-utils.js +145 -0
  294. package/lib/Utils/phone-utils.d.ts +3 -0
  295. package/lib/Utils/phone-utils.js +29 -0
  296. package/lib/Utils/pre-key-manager.d.ts +25 -0
  297. package/lib/Utils/pre-key-manager.js +105 -0
  298. package/lib/Utils/process-message.d.ts +103 -0
  299. package/lib/Utils/process-message.js +868 -0
  300. package/lib/Utils/qr-terminal.d.ts +1 -0
  301. package/lib/Utils/qr-terminal.js +16 -0
  302. package/lib/Utils/reconnect-backoff.d.ts +25 -0
  303. package/lib/Utils/reconnect-backoff.js +47 -0
  304. package/lib/Utils/reporting-utils.d.ts +12 -0
  305. package/lib/Utils/reporting-utils.js +257 -0
  306. package/lib/Utils/rich-message-utils.d.ts +54 -0
  307. package/lib/Utils/rich-message-utils.js +435 -0
  308. package/lib/Utils/rich-messages.d.ts +298 -0
  309. package/lib/Utils/rich-messages.js +1145 -0
  310. package/lib/Utils/scheduled-message.d.ts +81 -0
  311. package/lib/Utils/scheduled-message.js +101 -0
  312. package/lib/Utils/scheduling.d.ts +59 -0
  313. package/lib/Utils/scheduling.js +139 -0
  314. package/lib/Utils/signal.d.ts +82 -0
  315. package/lib/Utils/signal.js +200 -0
  316. package/lib/Utils/stanza-ack.d.ts +16 -0
  317. package/lib/Utils/stanza-ack.js +37 -0
  318. package/lib/Utils/status-stickers.d.ts +79 -0
  319. package/lib/Utils/status-stickers.js +261 -0
  320. package/lib/Utils/status.d.ts +107 -0
  321. package/lib/Utils/status.js +131 -0
  322. package/lib/Utils/sticker-pack-maker.d.ts +20 -0
  323. package/lib/Utils/sticker-pack-maker.js +112 -0
  324. package/lib/Utils/stickerpack.d.ts +18 -0
  325. package/lib/Utils/stickerpack.js +316 -0
  326. package/lib/Utils/sync-action-utils.d.ts +2 -0
  327. package/lib/Utils/sync-action-utils.js +48 -0
  328. package/lib/Utils/tag.d.ts +8 -0
  329. package/lib/Utils/tag.js +45 -0
  330. package/lib/Utils/tc-token-utils.d.ts +29 -0
  331. package/lib/Utils/tc-token-utils.js +162 -0
  332. package/lib/Utils/templates.d.ts +86 -0
  333. package/lib/Utils/templates.js +148 -0
  334. package/lib/Utils/text-format.d.ts +13 -0
  335. package/lib/Utils/text-format.js +81 -0
  336. package/lib/Utils/text-tools.d.ts +3 -0
  337. package/lib/Utils/text-tools.js +38 -0
  338. package/lib/Utils/ttl-cache.d.ts +29 -0
  339. package/lib/Utils/ttl-cache.js +123 -0
  340. package/lib/Utils/use-cache-manager-auth-state.d.ts +22 -0
  341. package/lib/Utils/use-cache-manager-auth-state.js +86 -0
  342. package/lib/Utils/use-multi-file-auth-state.d.ts +20 -0
  343. package/lib/Utils/use-multi-file-auth-state.js +201 -0
  344. package/lib/Utils/use-single-file-auth-state.d.ts +10 -0
  345. package/lib/Utils/use-single-file-auth-state.js +111 -0
  346. package/lib/Utils/use-sqlite-auth-state.d.ts +13 -0
  347. package/lib/Utils/use-sqlite-auth-state.js +171 -0
  348. package/lib/Utils/username.d.ts +22 -0
  349. package/lib/Utils/username.js +59 -0
  350. package/lib/Utils/validate-connection.d.ts +43 -0
  351. package/lib/Utils/validate-connection.js +197 -0
  352. package/lib/Utils/vcard.d.ts +40 -0
  353. package/lib/Utils/vcard.js +92 -0
  354. package/lib/Utils/voice-note.d.ts +13 -0
  355. package/lib/Utils/voice-note.js +47 -0
  356. package/lib/VoIP/audio-feeder.d.ts +15 -0
  357. package/lib/VoIP/audio-feeder.js +132 -0
  358. package/lib/VoIP/index.d.ts +22 -0
  359. package/lib/VoIP/index.js +277 -0
  360. package/lib/VoIP/relay-transport.d.ts +16 -0
  361. package/lib/VoIP/relay-transport.js +559 -0
  362. package/lib/VoIP/signaling.d.ts +16 -0
  363. package/lib/VoIP/signaling.js +624 -0
  364. package/lib/VoIP/types.d.ts +11 -0
  365. package/lib/VoIP/types.js +17 -0
  366. package/lib/VoIP/wasm-engine.d.ts +28 -0
  367. package/lib/VoIP/wasm-engine.js +1214 -0
  368. package/lib/VoIP/worker-bootstrap.d.ts +1 -0
  369. package/lib/VoIP/worker-bootstrap.js +1042 -0
  370. package/lib/WABinary/constants.d.ts +61 -0
  371. package/lib/WABinary/constants.js +1466 -0
  372. package/lib/WABinary/decode.d.ts +9 -0
  373. package/lib/WABinary/decode.js +261 -0
  374. package/lib/WABinary/encode.d.ts +2 -0
  375. package/lib/WABinary/encode.js +219 -0
  376. package/lib/WABinary/generic-utils.d.ts +45 -0
  377. package/lib/WABinary/generic-utils.js +285 -0
  378. package/lib/WABinary/index.d.ts +5 -0
  379. package/lib/WABinary/index.js +5 -0
  380. package/lib/WABinary/jid-utils.d.ts +32 -0
  381. package/lib/WABinary/jid-utils.js +102 -0
  382. package/lib/WABinary/types.d.ts +1 -0
  383. package/lib/WABinary/types.js +1 -0
  384. package/lib/WAM/BinaryInfo.d.ts +7 -0
  385. package/lib/WAM/BinaryInfo.js +9 -0
  386. package/lib/WAM/constants.d.ts +34926 -0
  387. package/lib/WAM/constants.js +22852 -0
  388. package/lib/WAM/encode.d.ts +1 -0
  389. package/lib/WAM/encode.js +149 -0
  390. package/lib/WAM/index.d.ts +3 -0
  391. package/lib/WAM/index.js +3 -0
  392. package/lib/WAUSync/Protocols/USyncBusinessProtocol.d.ts +43 -0
  393. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +32 -0
  394. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  395. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  396. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +29 -0
  397. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +60 -0
  398. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  399. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  400. package/lib/WAUSync/Protocols/USyncFeatureProtocol.d.ts +13 -0
  401. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +28 -0
  402. package/lib/WAUSync/Protocols/USyncPictureProtocol.d.ts +22 -0
  403. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  404. package/lib/WAUSync/Protocols/USyncSidelistProtocol.d.ts +20 -0
  405. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +23 -0
  406. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  407. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  408. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.d.ts +14 -0
  409. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +24 -0
  410. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  411. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  412. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  413. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +49 -0
  414. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  415. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  416. package/lib/WAUSync/Protocols/index.d.ts +12 -0
  417. package/lib/WAUSync/Protocols/index.js +12 -0
  418. package/lib/WAUSync/USyncQuery.d.ts +25 -0
  419. package/lib/WAUSync/USyncQuery.js +140 -0
  420. package/lib/WAUSync/USyncUser.d.ts +24 -0
  421. package/lib/WAUSync/USyncUser.js +47 -0
  422. package/lib/WAUSync/index.d.ts +3 -0
  423. package/lib/WAUSync/index.js +3 -0
  424. package/lib/assets/wasm/loader.js +5 -0
  425. package/lib/assets/wasm/whatsapp.wasm +0 -0
  426. package/lib/assets/wasm/worker-modules.js +273 -0
  427. package/lib/exports-extra.d.ts +45 -0
  428. package/lib/exports-extra.js +47 -0
  429. package/lib/index.d.ts +16 -0
  430. package/lib/index.js +24 -0
  431. package/package.json +161 -4
@@ -0,0 +1,2271 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { createHash, randomBytes } from 'crypto';
3
+ import { zip } from 'fflate';
4
+ import { promises as fs } from 'fs';
5
+ import { proto } from '../../WAProto/index.js';
6
+ import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, DONATE_URL, LIBRARY_NAME, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
7
+ import { AssociationType, ButtonHeaderType, ButtonType, CarouselCardType, ListType, ProtocolType, WAMessageStatus, WAProto } from '../Types/index.js';
8
+ import { isLidUser, isPnUser, isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
9
+ import { sha256 } from './crypto.js';
10
+ import { NATIVE_FLOW_BUTTON_LIMIT, WEB_SUPPORTED_INTERACTIVE_FLOWS, getNativeFlowNameByButtonName } from './native-flow.js';
11
+ import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
12
+ import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getImageProcessingLibrary, getRawMediaUploadData, getStream, toBuffer } from './messages-media.js';
13
+ import { prepareRichResponseMessage } from './rich-message-utils.js';
14
+ import { shouldIncludeReportingToken } from './reporting-utils.js';
15
+ import { fetchWithTimeout } from './fetch-timeout.js';
16
+ const CONCURRENCY_LIMIT = 15;
17
+ const MIMETYPE_MAP = {
18
+ image: 'image/jpeg',
19
+ video: 'video/mp4',
20
+ document: 'application/pdf',
21
+ audio: 'audio/ogg; codecs=opus',
22
+ sticker: 'image/webp',
23
+ 'product-catalog-image': 'image/jpeg'
24
+ };
25
+ const MessageTypeProto = {
26
+ image: WAProto.Message.ImageMessage,
27
+ video: WAProto.Message.VideoMessage,
28
+ audio: WAProto.Message.AudioMessage,
29
+ sticker: WAProto.Message.StickerMessage,
30
+ document: WAProto.Message.DocumentMessage
31
+ };
32
+ /**
33
+ * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
34
+ * @param text eg. hello https://google.com
35
+ * @returns the URL, eg. https://google.com
36
+ */
37
+ export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
38
+ export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
39
+ const url = extractUrlFromText(text);
40
+ if (!!getUrlInfo && url) {
41
+ try {
42
+ const urlInfo = await getUrlInfo(url);
43
+ return urlInfo;
44
+ }
45
+ catch (error) {
46
+ // ignore if fails
47
+ logger?.warn({ trace: error.stack }, 'url generation failed');
48
+ }
49
+ }
50
+ };
51
+ const assertColor = async (color) => {
52
+ let assertedColor;
53
+ if (typeof color === 'number') {
54
+ assertedColor = color > 0 ? color : 0xffffffff + Number(color) + 1;
55
+ }
56
+ else {
57
+ let hex = color.trim().replace('#', '');
58
+ if (hex.length <= 6) {
59
+ hex = 'FF' + hex.padStart(6, '0');
60
+ }
61
+ assertedColor = parseInt(hex, 16);
62
+ return assertedColor;
63
+ }
64
+ };
65
+ export const prepareWAMessageMedia = async (message, options) => {
66
+ const logger = options.logger;
67
+ let mediaType;
68
+ for (const key of MEDIA_KEYS) {
69
+ if (key in message) {
70
+ mediaType = key;
71
+ }
72
+ }
73
+ if (!mediaType) {
74
+ throw new Boom('Invalid media type', { statusCode: 400 });
75
+ }
76
+ const uploadData = {
77
+ ...message,
78
+ media: message[mediaType]
79
+ };
80
+ // Vanzxy@Fix: Removed mediaAnnotation injection that caused "Lihat saluran" (newsletter) button
81
+ // to appear on every image/video sent. Original itslia code injected newsletter contextInfo
82
+ // into all media uploads which is unnecessary and annoying for regular bot usage.
83
+ delete uploadData[mediaType];
84
+ // check if cacheable + generate cache key
85
+ const cacheableKey = typeof uploadData.media === 'object' &&
86
+ 'url' in uploadData.media &&
87
+ !!uploadData.media.url &&
88
+ !!options.mediaCache &&
89
+ mediaType + ':' + uploadData.media.url.toString();
90
+ if (mediaType === 'document' && !uploadData.fileName) {
91
+ uploadData.fileName = 'file';
92
+ }
93
+ if (!uploadData.mimetype) {
94
+ uploadData.mimetype = MIMETYPE_MAP[mediaType];
95
+ }
96
+ if (cacheableKey) {
97
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
98
+ if (mediaBuff) {
99
+ logger?.debug({ cacheableKey }, 'got media cache hit');
100
+ const obj = proto.Message.decode(mediaBuff);
101
+ const key = `${mediaType}Message`;
102
+ Object.assign(obj[key], { ...uploadData, media: undefined });
103
+ return obj;
104
+ }
105
+ }
106
+ const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
107
+ if (isNewsletter) {
108
+ logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
109
+ const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
110
+ const fileSha256B64 = fileSha256.toString('base64');
111
+ const { mediaUrl, directPath, thumbnailDirectPath, thumbnailSha256 } = await options.upload(filePath, {
112
+ fileEncSha256B64: fileSha256B64,
113
+ mediaType: mediaType,
114
+ timeoutMs: options.mediaUploadTimeoutMs,
115
+ newsletter: isNewsletter
116
+ });
117
+ await fs.unlink(filePath);
118
+ const obj = WAProto.Message.fromObject({
119
+ // todo: add more support here
120
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
121
+ url: mediaUrl,
122
+ directPath,
123
+ fileSha256,
124
+ fileLength,
125
+ thumbnailDirectPath,
126
+ thumbnailSha256,
127
+ ...uploadData,
128
+ media: undefined
129
+ })
130
+ });
131
+ if (uploadData.ptv) {
132
+ obj.ptvMessage = obj.videoMessage;
133
+ delete obj.videoMessage;
134
+ }
135
+ if (obj.stickerMessage) {
136
+ obj.stickerMessage.stickerSentTs = Date.now();
137
+ }
138
+ if (cacheableKey) {
139
+ logger?.debug({ cacheableKey }, 'set cache');
140
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
141
+ }
142
+ return obj;
143
+ }
144
+ const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
145
+ const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
146
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined';
147
+ const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
148
+ const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
149
+ const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
150
+ logger,
151
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
152
+ opts: options.options
153
+ });
154
+ const fileEncSha256B64 = fileEncSha256.toString('base64');
155
+ const [{ mediaUrl, directPath }] = await Promise.all([
156
+ (async () => {
157
+ const result = await options.upload(encFilePath, {
158
+ fileEncSha256B64,
159
+ mediaType,
160
+ timeoutMs: options.mediaUploadTimeoutMs
161
+ });
162
+ logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
163
+ return result;
164
+ })(),
165
+ (async () => {
166
+ try {
167
+ if (requiresThumbnailComputation) {
168
+ const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options);
169
+ uploadData.jpegThumbnail = thumbnail;
170
+ if (!uploadData.width && originalImageDimensions) {
171
+ uploadData.width = originalImageDimensions.width;
172
+ uploadData.height = originalImageDimensions.height;
173
+ logger?.debug('set dimensions');
174
+ }
175
+ logger?.debug('generated thumbnail');
176
+ }
177
+ if (requiresDurationComputation) {
178
+ uploadData.seconds = await getAudioDuration(originalFilePath);
179
+ logger?.debug('computed audio duration');
180
+ }
181
+ if (requiresWaveformProcessing) {
182
+ uploadData.waveform = await getAudioWaveform(originalFilePath, logger);
183
+ logger?.debug('processed waveform');
184
+ }
185
+ if (requiresAudioBackground) {
186
+ uploadData.backgroundArgb = await assertColor(options.backgroundColor);
187
+ logger?.debug('computed backgroundColor audio status');
188
+ }
189
+ }
190
+ catch (error) {
191
+ logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
192
+ }
193
+ })()
194
+ ]).finally(async () => {
195
+ try {
196
+ await fs.unlink(encFilePath);
197
+ if (originalFilePath) {
198
+ await fs.unlink(originalFilePath);
199
+ }
200
+ logger?.debug('removed tmp files');
201
+ }
202
+ catch (error) {
203
+ logger?.warn('failed to remove tmp file');
204
+ }
205
+ });
206
+ const obj = WAProto.Message.fromObject({
207
+ [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
208
+ url: mediaUrl,
209
+ directPath,
210
+ mediaKey,
211
+ fileEncSha256,
212
+ fileSha256,
213
+ fileLength,
214
+ mediaKeyTimestamp: unixTimestampSeconds(),
215
+ ...uploadData,
216
+ media: undefined
217
+ })
218
+ });
219
+ if (uploadData.ptv) {
220
+ obj.ptvMessage = obj.videoMessage;
221
+ delete obj.videoMessage;
222
+ }
223
+ if (cacheableKey) {
224
+ logger?.debug({ cacheableKey }, 'set cache');
225
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
226
+ }
227
+ return obj;
228
+ };
229
+ // Lia@Changes 31-01-26 --- Extract product message into a standalone function so it can also be reused as the header for interactive messages
230
+ const prepareProductMessage = async (message, options) => {
231
+ if (!message.businessOwnerJid) {
232
+ throw new Boom('"businessOwnerJid" is missing from the content', { statusCode: 400 });
233
+ }
234
+ const { imageMessage } = await prepareWAMessageMedia({ image: message.image || message.product.productImage }, options);
235
+ // Lia@Changes 01-02-26 --- Add product message default value
236
+ const { image, ...content } = message;
237
+ content.product = {
238
+ currencyCode: 'IDR',
239
+ priceAmount1000: 1000,
240
+ title: LIBRARY_NAME,
241
+ ...message.product,
242
+ productImage: imageMessage
243
+ };
244
+ return content;
245
+ };
246
+ /**
247
+ * Lia@Note 30-01-26
248
+ * ---
249
+ * Credits: Work on ensuring stickerPackMessage fields are valid by @jlucaso1 (https://github.com/jlucaso1).
250
+ * based on https://github.com/WhiskeySockets/Baileys/pull/1561
251
+ */
252
+ // Lia@Changes 21-04-26 --- Enhanced prepareStickerPackMessage
253
+ const prepareStickerPackMessage = async (message, options) => {
254
+ const { cover, stickers = [], name = '📦 Sticker Pack', publisher = 'GitHub: vanzxy', description = '🏷️ vanzxy/baileys' } = message;
255
+ if (stickers.length > 60) {
256
+ throw new Boom('Sticker pack exceeds the maximum limit of 60 stickers', { statusCode: 400 });
257
+ }
258
+ if (stickers.length === 0) {
259
+ throw new Boom('Sticker pack must contain at least one sticker', { statusCode: 400 });
260
+ }
261
+ if (!cover) {
262
+ throw new Boom('Sticker pack must contain a cover', { statusCode: 400 });
263
+ }
264
+ const logger = options.logger;
265
+ // Lia@Changes 01-02-26 --- Add caching for sticker pack
266
+ let cacheableKey = false;
267
+ if (Array.isArray(stickers) && stickers.length && options.mediaCache) {
268
+ const urls = [];
269
+ for (let i = 0; i < stickers.length; i++) {
270
+ const data = stickers[i].data;
271
+ if (typeof data === 'object' && data?.url) {
272
+ urls.push(data.url);
273
+ }
274
+ }
275
+ if (urls.length > 0) {
276
+ cacheableKey = 'sticker:' + urls.join('@');
277
+ }
278
+ }
279
+ if (cacheableKey) {
280
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
281
+ if (mediaBuff) {
282
+ logger?.debug({ cacheableKey }, 'got media cache hit');
283
+ return proto.Message.StickerPackMessage.decode(mediaBuff);
284
+ }
285
+ }
286
+ const lib = await getImageProcessingLibrary();
287
+ const hasSharp = 'sharp' in lib && !!lib.sharp?.default;
288
+ const hasImage = 'image' in lib && !!lib.image?.Transformer;
289
+ const hasJimp = 'jimp' in lib && !!lib.jimp?.Jimp;
290
+ if (!hasSharp && !hasImage) {
291
+ throw new Boom('No image processing library (sharp or @napi-rs/image) available for converting sticker to WebP.');
292
+ }
293
+ const stickerPackIdValue = generateMessageIDV2();
294
+ const stickerData = {};
295
+ const stickerMetadata = new Array(stickers.length);
296
+ for (let i = 0; i < stickers.length; i += CONCURRENCY_LIMIT) {
297
+ const promises = [];
298
+ const chunkEnd = Math.min(i + CONCURRENCY_LIMIT, stickers.length);
299
+ for (let j = i; j < chunkEnd; j++) {
300
+ promises.push((async (index) => {
301
+ const sticker = stickers[index];
302
+ const { stream } = await getStream(sticker.data);
303
+ const buffer = await toBuffer(stream);
304
+ let webpBuffer;
305
+ let isAnimated = false;
306
+ if (isWebPBuffer(buffer)) {
307
+ webpBuffer = buffer;
308
+ isAnimated = isAnimatedWebP(buffer);
309
+ }
310
+ else if (hasSharp) {
311
+ webpBuffer = await lib.sharp.default(buffer)
312
+ .resize(512, 512, { fit: 'inside' })
313
+ .webp({ quality: 80 })
314
+ .toBuffer();
315
+ }
316
+ else {
317
+ webpBuffer = await new lib.image.Transformer(buffer)
318
+ .resize(512, 512)
319
+ .webp(80);
320
+ }
321
+ if (webpBuffer.length > 1024 * 1024) {
322
+ throw new Boom(`Sticker at index ${index} exceeds the 1MB size limit`, { statusCode: 400 });
323
+ }
324
+ const hash = sha256(webpBuffer).toString('base64').replace(/\//g, '-');
325
+ const fileName = `${hash}.webp`;
326
+ stickerData[fileName] = [new Uint8Array(webpBuffer), { level: 0 }];
327
+ stickerMetadata[index] = {
328
+ fileName,
329
+ mimetype: 'image/webp',
330
+ isAnimated,
331
+ emojis: sticker.emojis || ['✨'],
332
+ accessibilityLabel: sticker.accessibilityLabel || '‎'
333
+ };
334
+ })(j));
335
+ }
336
+ await Promise.all(promises);
337
+ }
338
+ const trayIconFileName = `${stickerPackIdValue}.webp`;
339
+ const { stream: coverStream } = await getStream(cover);
340
+ const coverBuffer = await toBuffer(coverStream);
341
+ let coverWebpBuffer;
342
+ if (isWebPBuffer(coverBuffer)) {
343
+ coverWebpBuffer = coverBuffer;
344
+ }
345
+ else if (hasSharp) {
346
+ coverWebpBuffer = await lib.sharp.default(coverBuffer)
347
+ .resize(512, 512, { fit: 'inside' })
348
+ .webp({ quality: 80 })
349
+ .toBuffer();
350
+ }
351
+ else {
352
+ coverWebpBuffer = await new lib.image.Transformer(coverBuffer)
353
+ .resize(512, 512)
354
+ .webp(80);
355
+ }
356
+ stickerData[trayIconFileName] = [new Uint8Array(coverWebpBuffer), { level: 0 }];
357
+ const zipBuffer = await new Promise((resolve, reject) => {
358
+ zip(stickerData, (error, data) => error ? reject(error) : resolve(Buffer.from(data)));
359
+ });
360
+ const stickerPackUpload = await encryptedStream(zipBuffer, 'sticker-pack', {
361
+ logger,
362
+ opts: options.options
363
+ });
364
+ let stickerPackUploadResult;
365
+ try {
366
+ stickerPackUploadResult = await options.upload(stickerPackUpload.encFilePath, {
367
+ fileEncSha256B64: stickerPackUpload.fileEncSha256.toString('base64'),
368
+ mediaType: 'sticker-pack',
369
+ timeoutMs: options.mediaUploadTimeoutMs
370
+ });
371
+ }
372
+ finally {
373
+ fs.unlink(stickerPackUpload.encFilePath).catch(() => logger?.warn('failed to remove tmp file'));
374
+ }
375
+ const obj = {
376
+ name,
377
+ publisher,
378
+ stickerPackId: stickerPackIdValue,
379
+ packDescription: description,
380
+ stickerPackOrigin: proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED,
381
+ stickerPackSize: zipBuffer.length,
382
+ stickers: stickerMetadata,
383
+ fileSha256: stickerPackUpload.fileSha256,
384
+ fileEncSha256: stickerPackUpload.fileEncSha256,
385
+ mediaKey: stickerPackUpload.mediaKey,
386
+ directPath: stickerPackUploadResult.directPath,
387
+ fileLength: stickerPackUpload.fileLength,
388
+ mediaKeyTimestamp: unixTimestampSeconds(),
389
+ trayIconFileName
390
+ };
391
+ try {
392
+ let thumbnailBuffer;
393
+ if (hasSharp) {
394
+ thumbnailBuffer = await lib.sharp.default(coverBuffer).resize(252, 252).jpeg().toBuffer();
395
+ }
396
+ else if (hasImage) {
397
+ thumbnailBuffer = await new lib.image.Transformer(coverBuffer).resize(252, 252).jpeg();
398
+ }
399
+ else if (hasJimp) {
400
+ const jimpImage = await lib.jimp.Jimp.read(coverBuffer);
401
+ thumbnailBuffer = await jimpImage.resize({ w: 252, h: 252 }).getBuffer('image/jpeg');
402
+ }
403
+ else {
404
+ throw new Error('No image processing library available for thumbnail generation');
405
+ }
406
+ if (!thumbnailBuffer || thumbnailBuffer.length === 0) {
407
+ throw new Error('Failed to generate thumbnail buffer');
408
+ }
409
+ const thumbUpload = await encryptedStream(thumbnailBuffer, 'thumbnail-sticker-pack', {
410
+ logger,
411
+ opts: options.options,
412
+ mediaKey: stickerPackUpload.mediaKey
413
+ });
414
+ let thumbUploadResult;
415
+ try {
416
+ thumbUploadResult = await options.upload(thumbUpload.encFilePath, {
417
+ fileEncSha256B64: thumbUpload.fileEncSha256.toString('base64'),
418
+ mediaType: 'thumbnail-sticker-pack',
419
+ timeoutMs: options.mediaUploadTimeoutMs
420
+ });
421
+ }
422
+ finally {
423
+ fs.unlink(thumbUpload.encFilePath).catch(() => logger?.warn('failed to remove tmp file'));
424
+ }
425
+ Object.assign(obj, {
426
+ thumbnailDirectPath: thumbUploadResult.directPath,
427
+ thumbnailSha256: thumbUpload.fileSha256,
428
+ thumbnailEncSha256: thumbUpload.fileEncSha256,
429
+ thumbnailHeight: 252,
430
+ thumbnailWidth: 252,
431
+ imageDataHash: sha256(thumbnailBuffer).toString('base64')
432
+ });
433
+ }
434
+ catch (error) {
435
+ logger?.warn(`Thumbnail generation failed: ${error}`);
436
+ }
437
+ if (cacheableKey) {
438
+ logger?.debug({ cacheableKey }, 'set cache (background)');
439
+ options.mediaCache.set(cacheableKey, WAProto.Message.StickerPackMessage.encode(obj).finish());
440
+ }
441
+ return WAProto.Message.StickerPackMessage.fromObject(obj);
442
+ };
443
+ // Lia@Changes 30-01-26 --- Add native flow button helper for interactive message
444
+ const prepareNativeFlowButtons = (message) => {
445
+ const buttons = message.nativeFlow;
446
+ const isButtonsFieldArray = Array.isArray(buttons);
447
+ const correctedField = isButtonsFieldArray ? buttons : (buttons?.buttons ?? []);
448
+ const messageParamsJson = {};
449
+ // Lia@Changes 31-01-26 --- Add offer and options inside interactive message
450
+ if (hasOptionalProperty(message, 'offerText') && !!message.offerText) {
451
+ Object.assign(messageParamsJson, {
452
+ limited_time_offer: {
453
+ text: message.offerText || LIBRARY_NAME,
454
+ url: message.offerUrl || DONATE_URL || undefined,
455
+ copy_code: message.offerCode,
456
+ expiration_time: message.offerExpiration
457
+ }
458
+ });
459
+ }
460
+ if (hasOptionalProperty(message, 'optionText') && !!message.optionText) {
461
+ Object.assign(messageParamsJson, {
462
+ bottom_sheet: {
463
+ in_thread_buttons_limit: 1,
464
+ divider_indices: Array.from({ length: correctedField.length }, (_, index) => index),
465
+ list_title: message.optionTitle || '📄 Select Options',
466
+ button_title: message.optionText
467
+ }
468
+ });
469
+ }
470
+ return {
471
+ buttons: correctedField.map(button => {
472
+ const buttonText = button.text || button.buttonText;
473
+ const buttonIcon = button.icon?.toUpperCase();
474
+ if (hasOptionalProperty(button, 'id') && !!button.id) {
475
+ return {
476
+ name: 'quick_reply',
477
+ buttonParamsJson: JSON.stringify({
478
+ display_text: buttonText || '👉🏻 Click',
479
+ id: button.id,
480
+ icon: buttonIcon
481
+ })
482
+ };
483
+ }
484
+ else if (hasOptionalProperty(button, 'copy') && !!button.copy) {
485
+ return {
486
+ name: 'cta_copy',
487
+ buttonParamsJson: JSON.stringify({
488
+ display_text: buttonText || '📋 Copy',
489
+ copy_code: button.copy,
490
+ icon: buttonIcon
491
+ })
492
+ };
493
+ }
494
+ else if (hasOptionalProperty(button, 'url') && !!button.url) {
495
+ return {
496
+ name: 'cta_url',
497
+ buttonParamsJson: JSON.stringify({
498
+ display_text: buttonText || '🌐 Visit',
499
+ url: button.url,
500
+ merchant_url: button.url,
501
+ webview_interaction: button.useWebview,
502
+ icon: buttonIcon
503
+ })
504
+ };
505
+ }
506
+ else if (hasOptionalProperty(button, 'call') && !!button.call) {
507
+ return {
508
+ name: 'cta_call',
509
+ buttonParamsJson: JSON.stringify({
510
+ display_text: buttonText || '📞 Call',
511
+ phone_number: button.call,
512
+ icon: buttonIcon
513
+ })
514
+ };
515
+ }
516
+ // Lia@Changes 12-03-26 --- Add "single_select" shortcut \⁠(⁠°⁠o⁠°⁠)⁠/
517
+ else if (hasOptionalProperty(button, 'sections') && !!button.sections) {
518
+ return {
519
+ name: 'single_select',
520
+ buttonParamsJson: JSON.stringify({
521
+ title: buttonText || '📋 Select',
522
+ sections: button.sections,
523
+ icon: buttonIcon
524
+ })
525
+ };
526
+ }
527
+ // Vanzxy@Changes --- Add "cta_reminder" shortcut
528
+ else if (hasOptionalProperty(button, 'reminder') && !!button.reminder) {
529
+ return {
530
+ name: 'cta_reminder',
531
+ buttonParamsJson: JSON.stringify({
532
+ display_text: buttonText || '⏰ Remind me',
533
+ id: button.id || button.reminder,
534
+ icon: buttonIcon
535
+ })
536
+ };
537
+ }
538
+ // Vanzxy@Changes --- Add "cta_cancel_reminder" shortcut
539
+ else if (hasOptionalProperty(button, 'cancelReminder') && !!button.cancelReminder) {
540
+ return {
541
+ name: 'cta_cancel_reminder',
542
+ buttonParamsJson: JSON.stringify({
543
+ display_text: buttonText || '🔕 Cancel reminder',
544
+ id: button.id || button.cancelReminder,
545
+ icon: buttonIcon
546
+ })
547
+ };
548
+ }
549
+ // Vanzxy@Changes --- Add "address_message" / send_location shortcut
550
+ else if (hasOptionalProperty(button, 'address') && !!button.address) {
551
+ return {
552
+ name: 'address_message',
553
+ buttonParamsJson: JSON.stringify({
554
+ display_text: buttonText || '📍 Send address',
555
+ id: button.id || 'address_message'
556
+ })
557
+ };
558
+ }
559
+ else if (hasOptionalProperty(button, 'location') && button.location === true) {
560
+ return {
561
+ name: 'send_location',
562
+ buttonParamsJson: JSON.stringify({})
563
+ };
564
+ }
565
+ // Vanzxy@Changes --- Add "view_catalog" / catalog_message / mpm shortcut
566
+ else if (hasOptionalProperty(button, 'catalog') && !!button.catalog) {
567
+ return {
568
+ name: 'catalog_message',
569
+ buttonParamsJson: JSON.stringify({
570
+ business_phone_number: button.catalog.bizJid || button.catalog,
571
+ display_text: buttonText || '🛍️ View catalog',
572
+ id: button.id || 'catalog_message'
573
+ })
574
+ };
575
+ }
576
+ else if (hasOptionalProperty(button, 'products') && !!button.products) {
577
+ return {
578
+ name: 'mpm',
579
+ buttonParamsJson: JSON.stringify({
580
+ business_phone_number: button.bizJid || button.products.bizJid,
581
+ product_ids: Array.isArray(button.products) ? button.products : button.products.ids
582
+ })
583
+ };
584
+ }
585
+ // Vanzxy@Fix (bug 12): otp_button/authentication_button removed entirely.
586
+ // These are WhatsApp Business Platform (Cloud API) authentication template
587
+ // buttons, gated behind Meta template approval — they cannot be produced
588
+ // by any MD-protocol client library, Baileys included. Not a bug to fix,
589
+ // just an unsupported surface; unrecognized `otp`/`oneTapOtp` fields now
590
+ // fall through untouched instead of building a doomed-to-fail button.
591
+
592
+ // Vanzxy@Fix (bug 11): 'call_button'/'url_button'/'reply_button' were invalid
593
+ // native-flow type names (leftover from the deprecated buttonsMessage system,
594
+ // which modern WA clients no longer render — that's why they silent-failed).
595
+ // Aliased to the real, currently-supported native-flow equivalents instead.
596
+ else if (hasOptionalProperty(button, 'phoneNumber') && !!button.phoneNumber) {
597
+ return {
598
+ name: 'cta_call',
599
+ buttonParamsJson: JSON.stringify({
600
+ display_text: buttonText || '📞 Call',
601
+ phone_number: button.phoneNumber,
602
+ icon: buttonIcon
603
+ })
604
+ };
605
+ }
606
+ else if (hasOptionalProperty(button, 'urlBtn') && !!button.urlBtn) {
607
+ return {
608
+ name: 'cta_url',
609
+ buttonParamsJson: JSON.stringify({
610
+ display_text: buttonText || '🌐 Open',
611
+ url: button.urlBtn,
612
+ merchant_url: button.urlBtn,
613
+ webview_interaction: button.useWebview,
614
+ icon: buttonIcon
615
+ })
616
+ };
617
+ }
618
+ else if (hasOptionalProperty(button, 'reply') && !!button.reply) {
619
+ return {
620
+ name: 'quick_reply',
621
+ buttonParamsJson: JSON.stringify({
622
+ display_text: buttonText || button.reply,
623
+ id: button.id || button.reply,
624
+ icon: buttonIcon
625
+ })
626
+ };
627
+ }
628
+ // Vanzxy@Changes --- Add order/payment lifecycle button shortcuts
629
+ // ⚠️ NOTE: card_message/order_details/order_status/review_and_pay/
630
+ // payment_status/payment_method are valid native-flow types, BUT WA only
631
+ // renders them when order_id/product data resolves to a real Commerce
632
+ // order tied to your catalog/business account. Fake/test IDs will always
633
+ // silently fail — this is server-side validation, not a Baileys bug.
634
+ else if (hasOptionalProperty(button, 'card') && !!button.card) {
635
+ return {
636
+ name: 'card_message',
637
+ buttonParamsJson: JSON.stringify(button.card)
638
+ };
639
+ }
640
+ else if (hasOptionalProperty(button, 'orderDetails') && !!button.orderDetails) {
641
+ return {
642
+ name: 'order_details',
643
+ buttonParamsJson: JSON.stringify(button.orderDetails)
644
+ };
645
+ }
646
+ else if (hasOptionalProperty(button, 'orderStatus') && !!button.orderStatus) {
647
+ return {
648
+ name: 'order_status',
649
+ buttonParamsJson: JSON.stringify(button.orderStatus)
650
+ };
651
+ }
652
+ else if (hasOptionalProperty(button, 'reviewAndPay') && !!button.reviewAndPay) {
653
+ return {
654
+ name: 'review_and_pay',
655
+ buttonParamsJson: JSON.stringify(button.reviewAndPay)
656
+ };
657
+ }
658
+ else if (hasOptionalProperty(button, 'paymentStatus') && !!button.paymentStatus) {
659
+ return {
660
+ name: 'payment_status',
661
+ buttonParamsJson: JSON.stringify(button.paymentStatus)
662
+ };
663
+ }
664
+ else if (hasOptionalProperty(button, 'paymentMethod') && !!button.paymentMethod) {
665
+ return {
666
+ name: 'payment_method',
667
+ buttonParamsJson: JSON.stringify(button.paymentMethod)
668
+ };
669
+ }
670
+ else if (hasOptionalProperty(button, 'trackOrder') && !!button.trackOrder) {
671
+ return {
672
+ name: 'track_order',
673
+ buttonParamsJson: JSON.stringify({
674
+ id: button.id || button.trackOrder,
675
+ display_text: buttonText || '🚚 Track order'
676
+ })
677
+ };
678
+ }
679
+ else if (hasOptionalProperty(button, 'reorder') && !!button.reorder) {
680
+ return {
681
+ name: 'reorder',
682
+ buttonParamsJson: JSON.stringify({
683
+ id: button.id || button.reorder,
684
+ display_text: buttonText || '🔁 Reorder'
685
+ })
686
+ };
687
+ }
688
+ else if (hasOptionalProperty(button, 'cancelOrder') && !!button.cancelOrder) {
689
+ return {
690
+ name: 'cancel_order',
691
+ buttonParamsJson: JSON.stringify({
692
+ id: button.id || button.cancelOrder,
693
+ display_text: buttonText || '❌ Cancel order'
694
+ })
695
+ };
696
+ }
697
+ // Vanzxy@Changes --- Add navigation / utility button shortcuts
698
+ else if (hasOptionalProperty(button, 'clearChat') && button.clearChat === true) {
699
+ return {
700
+ name: 'clear_chat',
701
+ buttonParamsJson: JSON.stringify({})
702
+ };
703
+ }
704
+ else if (hasOptionalProperty(button, 'screen') && !!button.screen) {
705
+ return {
706
+ name: 'navigateToScreen',
707
+ buttonParamsJson: JSON.stringify({
708
+ screen_name: button.screen,
709
+ data: button.data || {}
710
+ })
711
+ };
712
+ }
713
+ // Vanzxy@Changes --- Add "flow_action" shortcut (WhatsApp Flows form)
714
+ // ⚠️ NOTE: requires a flow_id actually registered & published in the
715
+ // WhatsApp Flows Manager for your business account. A fictitious ID
716
+ // (like 'flow_test_id') will always fail — server-side, not fixable here.
717
+ else if (hasOptionalProperty(button, 'flow') && !!button.flow) {
718
+ return {
719
+ name: 'flow_action',
720
+ buttonParamsJson: JSON.stringify({
721
+ flow_message_version: button.flow.version || '3',
722
+ flow_id: button.flow.id,
723
+ flow_cta: buttonText || button.flow.cta || 'Continue',
724
+ flow_action: button.flow.action || 'navigate',
725
+ flow_action_payload: button.flow.actionPayload || {
726
+ screen: button.flow.screen || 'WELCOME',
727
+ data: button.flow.data || {}
728
+ }
729
+ })
730
+ };
731
+ }
732
+ // Vanzxy@Changes --- Add "voice_call" / "video_call_button" shortcuts
733
+ else if (hasOptionalProperty(button, 'voiceCall') && !!button.voiceCall) {
734
+ return {
735
+ name: 'voice_call',
736
+ buttonParamsJson: JSON.stringify({
737
+ display_text: buttonText || '📞 Voice call',
738
+ id: button.id || button.voiceCall
739
+ })
740
+ };
741
+ }
742
+ else if (hasOptionalProperty(button, 'videoCall') && !!button.videoCall) {
743
+ return {
744
+ name: 'video_call_button',
745
+ buttonParamsJson: JSON.stringify({
746
+ display_text: buttonText || '🎥 Video call',
747
+ id: button.id || button.videoCall
748
+ })
749
+ };
750
+ }
751
+ return button;
752
+ }),
753
+ messageParamsJson: JSON.stringify(messageParamsJson)
754
+ };
755
+ };
756
+ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
757
+ ephemeralExpiration = ephemeralExpiration || 0;
758
+ const content = {
759
+ ephemeralMessage: {
760
+ message: {
761
+ protocolMessage: {
762
+ type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
763
+ ephemeralExpiration
764
+ }
765
+ }
766
+ }
767
+ };
768
+ return WAProto.Message.fromObject(content);
769
+ };
770
+ /**
771
+ * Generate forwarded message content like WA does
772
+ * @param message the message to forward
773
+ * @param options.forceForward will show the message as forwarded even if it is from you
774
+ */
775
+ export const generateForwardMessageContent = (message, forceForward) => {
776
+ let content = message.message;
777
+ if (!content) {
778
+ throw new Boom('no content in message', { statusCode: 400 });
779
+ }
780
+ // hacky copy
781
+ content = normalizeMessageContent(content);
782
+ content = proto.Message.decode(proto.Message.encode(content).finish());
783
+ let key = Object.keys(content)[0];
784
+ let innerContent = content?.[key];
785
+ if (key === 'viewOnceMessage' || key === 'ephemeralMessage') {
786
+ const innerKey = innerContent?.message ? Object.keys(innerContent.message)[0] : null;
787
+ if (innerKey) {
788
+ innerContent = innerContent.message[innerKey];
789
+ }
790
+ }
791
+ let score = innerContent?.contextInfo?.forwardingScore || 0;
792
+ score += message.key.fromMe && !forceForward ? 0 : 1;
793
+ if (key === 'conversation') {
794
+ content.extendedTextMessage = { text: content[key] };
795
+ delete content.conversation;
796
+ key = 'extendedTextMessage';
797
+ }
798
+ const key_ = content?.[key];
799
+ if (score > 0) {
800
+ key_.contextInfo = { forwardingScore: score, isForwarded: true };
801
+ }
802
+ else {
803
+ key_.contextInfo = {};
804
+ }
805
+ return content;
806
+ };
807
+ export const hasNonNullishProperty = (message, key) => {
808
+ return message != null &&
809
+ typeof message === 'object' &&
810
+ key in message &&
811
+ message[key] != null;
812
+ };
813
+ export const hasOptionalProperty = (obj, key) => {
814
+ return obj != null &&
815
+ typeof obj === 'object' &&
816
+ key in obj &&
817
+ obj[key] != null;
818
+ };
819
+ // Lia@Changes 06-02-26 --- Validate album message media to avoid bug 👀
820
+ export const hasValidAlbumMedia = (message) => {
821
+ return !!(message.imageMessage ||
822
+ message.videoMessage);
823
+ };
824
+ export const hasValidInteractiveHeader = (message) => {
825
+ return !!(message.imageMessage ||
826
+ message.videoMessage ||
827
+ message.documentMessage ||
828
+ message.productMessage ||
829
+ message.locationMessage);
830
+ };
831
+ // Lia@Changes 30-01-26 --- Validate carousel cards header to avoid bug 👀
832
+ export const hasValidCarouselHeader = (message) => {
833
+ return !!(message.imageMessage ||
834
+ message.videoMessage ||
835
+ message.productMessage);
836
+ };
837
+ export const generateWAMessageContent = async (message, options) => {
838
+ var _a, _b;
839
+ let m = {};
840
+ // Lia@Changes 30-01-26 --- Add "raw" boolean to send raw messages directly via generateWAMessage()
841
+ if (hasNonNullishProperty(message, 'raw')) {
842
+ delete message.raw;
843
+ return message;
844
+ }
845
+ // Lia@Changes 09-04-26 --- Add support for code block and table with richResponseMessage
846
+ else if (hasNonNullishProperty(message, 'code') ||
847
+ hasNonNullishProperty(message, 'links') ||
848
+ hasNonNullishProperty(message, 'table') ||
849
+ hasNonNullishProperty(message, 'richResponse') ||
850
+ hasNonNullishProperty(message, 'inlineImage') ||
851
+ hasNonNullishProperty(message, 'inlineVideo') ||
852
+ hasNonNullishProperty(message, 'headerText') ||
853
+ hasNonNullishProperty(message, 'contentText') ||
854
+ hasNonNullishProperty(message, 'footerText') ||
855
+ hasNonNullishProperty(message, 'latex') ||
856
+ hasNonNullishProperty(message, 'items') ||
857
+ hasNonNullishProperty(message, 'posts') ||
858
+ hasNonNullishProperty(message, 'products') ||
859
+ hasNonNullishProperty(message, 'suggested')) {
860
+ m = prepareRichResponseMessage(message);
861
+ }
862
+ else if (hasNonNullishProperty(message, 'text')) {
863
+ const extContent = { text: message.text };
864
+ let urlInfo = message.linkPreview;
865
+ if (typeof urlInfo === 'undefined') {
866
+ urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
867
+ }
868
+ if (urlInfo) {
869
+ extContent.matchedText = urlInfo['matched-text'];
870
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
871
+ extContent.description = urlInfo.description;
872
+ extContent.title = urlInfo.title;
873
+ extContent.previewType = urlInfo.previewType ?? 0;
874
+ extContent.linkPreviewMetadata = urlInfo.linkPreviewMetadata;
875
+ const img = urlInfo.highQualityThumbnail;
876
+ if (img) {
877
+ extContent.thumbnailDirectPath = img.directPath;
878
+ extContent.mediaKey = img.mediaKey;
879
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
880
+ extContent.thumbnailWidth = img.width;
881
+ extContent.thumbnailHeight = img.height;
882
+ extContent.thumbnailSha256 = img.fileSha256;
883
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
884
+ }
885
+ }
886
+ const faviconData = message.favicon;
887
+ if (faviconData && typeof options.upload === 'function') {
888
+ const { imageMessage } = await prepareWAMessageMedia({
889
+ image: faviconData
890
+ }, options);
891
+ extContent.faviconMMSMetadata = {
892
+ thumbnailDirectPath: imageMessage.directPath,
893
+ mediaKey: imageMessage.mediaKey,
894
+ mediaKeyTimestamp: imageMessage.mediaKeyTimestamp,
895
+ thumbnailWidth: 32,
896
+ thumbnailHeight: 32,
897
+ thumbnailSha256: imageMessage.fileSha256,
898
+ thumbnailEncSha256: imageMessage.fileEncSha256
899
+ };
900
+ }
901
+ if (options.backgroundColor) {
902
+ extContent.backgroundArgb = await assertColor(options.backgroundColor);
903
+ }
904
+ if (options.font) {
905
+ extContent.font = options.font;
906
+ }
907
+ m.extendedTextMessage = extContent;
908
+ }
909
+ else if (hasNonNullishProperty(message, 'contacts')) {
910
+ const contactLen = message.contacts.contacts.length;
911
+ if (!contactLen) {
912
+ throw new Boom('require atleast 1 contact', { statusCode: 400 });
913
+ }
914
+ if (contactLen === 1) {
915
+ m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
916
+ }
917
+ else {
918
+ m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
919
+ }
920
+ }
921
+ else if (hasNonNullishProperty(message, 'location')) {
922
+ m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
923
+ }
924
+ else if (hasNonNullishProperty(message, 'react')) {
925
+ if (!message.react.senderTimestampMs) {
926
+ message.react.senderTimestampMs = Date.now();
927
+ }
928
+ m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
929
+ }
930
+ else if (hasNonNullishProperty(message, 'delete')) {
931
+ m.protocolMessage = {
932
+ key: message.delete,
933
+ type: WAProto.Message.ProtocolMessage.Type.REVOKE
934
+ };
935
+ }
936
+ else if (hasNonNullishProperty(message, 'forward')) {
937
+ m = generateForwardMessageContent(message.forward, message.force);
938
+ }
939
+ else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
940
+ const exp = typeof message.disappearingMessagesInChat === 'boolean'
941
+ ? message.disappearingMessagesInChat
942
+ ? WA_DEFAULT_EPHEMERAL
943
+ : 0
944
+ : message.disappearingMessagesInChat;
945
+ m = prepareDisappearingMessageSettingContent(exp);
946
+ }
947
+ else if (hasNonNullishProperty(message, 'groupInvite')) {
948
+ m.groupInviteMessage = {};
949
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
950
+ m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration ?? 0;
951
+ m.groupInviteMessage.caption = message.groupInvite.text;
952
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
953
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
954
+ //TODO: use built-in interface and get disappearing mode info etc.
955
+ //TODO: cache / use store!?
956
+ if (options.getProfilePicUrl) {
957
+ const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
958
+ if (pfpUrl) {
959
+ const resp = await fetchWithTimeout(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
960
+ if (resp.ok) {
961
+ const buf = Buffer.from(await resp.arrayBuffer());
962
+ if (options.upload) {
963
+ try {
964
+ const uploaded = await prepareWAMessageMedia({ image: buf }, { upload: options.upload });
965
+ if (uploaded.imageMessage) {
966
+ m.groupInviteMessage.jpegThumbnail = buf;
967
+ m.groupInviteMessage.thumbnailDirectPath = uploaded.imageMessage.directPath;
968
+ m.groupInviteMessage.thumbnailSha256 = uploaded.imageMessage.fileSha256;
969
+ m.groupInviteMessage.thumbnailEncSha256 = uploaded.imageMessage.fileEncSha256;
970
+ m.groupInviteMessage.mediaKey = uploaded.imageMessage.mediaKey;
971
+ }
972
+ } catch {
973
+ // fallback: at least attach raw jpeg
974
+ m.groupInviteMessage.jpegThumbnail = buf;
975
+ }
976
+ } else {
977
+ m.groupInviteMessage.jpegThumbnail = buf;
978
+ }
979
+ }
980
+ }
981
+ }
982
+ }
983
+ else if (hasNonNullishProperty(message, 'stickers')) {
984
+ m.stickerPackMessage = await prepareStickerPackMessage(message, options);
985
+ }
986
+ else if (hasNonNullishProperty(message, 'pin')) {
987
+ m.pinInChatMessage = {};
988
+ m.messageContextInfo = {};
989
+ m.pinInChatMessage.key = message.pin;
990
+ m.pinInChatMessage.type = message.type;
991
+ m.pinInChatMessage.senderTimestampMs = Date.now();
992
+ m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
993
+ }
994
+ else if (hasNonNullishProperty(message, 'keep')) {
995
+ m.keepInChatMessage = {};
996
+ m.keepInChatMessage.key = message.keep;
997
+ m.keepInChatMessage.keepType = message.type;
998
+ m.keepInChatMessage.timestampMs = Date.now();
999
+ }
1000
+ else if (hasNonNullishProperty(message, 'flowReply')) {
1001
+ m.interactiveResponseMessage = {
1002
+ body: {
1003
+ format: message.flowReply.format || proto.Message.InteractiveResponseMessage.Body.Format.DEFAULT,
1004
+ text: message.flowReply.text
1005
+ },
1006
+ nativeFlowResponseMessage: {
1007
+ name: message.flowReply.name,
1008
+ paramsJson: message.flowReply.paramsJson || '{}',
1009
+ version: message.flowReply.version || 1
1010
+ }
1011
+ };
1012
+ }
1013
+ else if (hasNonNullishProperty(message, 'buttonReply')) {
1014
+ switch (message.type) {
1015
+ case 'template':
1016
+ m.templateButtonReplyMessage = {
1017
+ selectedDisplayText: message.buttonReply.displayText,
1018
+ selectedId: message.buttonReply.id,
1019
+ selectedIndex: message.buttonReply.index
1020
+ };
1021
+ break;
1022
+ case 'plain':
1023
+ m.buttonsResponseMessage = {
1024
+ selectedButtonId: message.buttonReply.id,
1025
+ selectedDisplayText: message.buttonReply.displayText,
1026
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
1027
+ };
1028
+ break;
1029
+ }
1030
+ }
1031
+ else if (hasNonNullishProperty(message, 'listReply')) {
1032
+ m.listResponseMessage = {
1033
+ description: message.listReply.description,
1034
+ listType: proto.Message.ListResponseMessage.ListType.SINGLE_SELECT,
1035
+ singleSelectReply: {
1036
+ selectedRowId: message.listReply.id
1037
+ },
1038
+ title: message.listReply.title
1039
+ };
1040
+ }
1041
+ else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
1042
+ const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
1043
+ m.ptvMessage = videoMessage;
1044
+ }
1045
+ else if (hasNonNullishProperty(message, 'product')) {
1046
+ m.productMessage = await prepareProductMessage(message, options);
1047
+ }
1048
+ else if (hasNonNullishProperty(message, 'event')) {
1049
+ m.eventMessage = {};
1050
+ const ev = message.event;
1051
+ const toSec = (unix, date) => unix != null ? Math.floor(Number(unix)) : date instanceof Date ? Math.floor(date.getTime() / 1000) : undefined;
1052
+ const startTime = toSec(ev.startTime, ev.startDate);
1053
+ if (!Number.isFinite(startTime)) {
1054
+ throw new Boom('event requires startDate (Date) or startTime (unix seconds)', { statusCode: 400 });
1055
+ }
1056
+ if (message.event.call && options.getCallLink) {
1057
+ const token = await options.getCallLink(message.event.call, { startTime });
1058
+ m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
1059
+ }
1060
+ m.messageContextInfo = {
1061
+ // encKey
1062
+ messageSecret: ev.messageSecret || randomBytes(32)
1063
+ };
1064
+ const botFbids = [].concat(ev.botFbid ?? ev.botFbids ?? []).filter(Boolean).map(String);
1065
+ if (botFbids.length) {
1066
+ m.messageContextInfo.threadId = [];
1067
+ m.messageContextInfo.botMetadata = { botGroupMetadata: { participantsMetadata: botFbids.map((botFbid) => ({ botFbid })) } };
1068
+ }
1069
+ m.eventMessage.name = ev.name;
1070
+ m.eventMessage.description = ev.description;
1071
+ m.eventMessage.startTime = startTime;
1072
+ m.eventMessage.endTime = toSec(ev.endTime, ev.endDate);
1073
+ m.eventMessage.isCanceled = ev.isCancelled ?? ev.isCanceled ?? false;
1074
+ m.eventMessage.extraGuestsAllowed = ev.extraGuestsAllowed;
1075
+ m.eventMessage.isScheduleCall = ev.isScheduleCall ?? false;
1076
+ m.eventMessage.location = ev.location;
1077
+ if (ev.reminderOffsetSec != null) {
1078
+ const off = Number(ev.reminderOffsetSec);
1079
+ if (!Number.isInteger(off) || off < 0) throw new Boom('event.reminderOffsetSec must be a non-negative integer (seconds before start)', { statusCode: 400 });
1080
+ m.eventMessage.reminderOffsetSec = off;
1081
+ }
1082
+ if (ev.hasReminder != null || m.eventMessage.reminderOffsetSec != null) {
1083
+ m.eventMessage.hasReminder = ev.hasReminder ?? true;
1084
+ }
1085
+ }
1086
+ else if (hasNonNullishProperty(message, 'poll')) {
1087
+ (_a = message.poll).selectableCount || (_a.selectableCount = 0);
1088
+ (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
1089
+ if (!Array.isArray(message.poll.values)) {
1090
+ throw new Boom('Invalid poll values', { statusCode: 400 });
1091
+ }
1092
+ if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
1093
+ throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
1094
+ statusCode: 400
1095
+ });
1096
+ }
1097
+ const pollCreationMessage = {
1098
+ name: message.poll.name,
1099
+ selectableOptionsCount: message.poll.selectableCount,
1100
+ options: message.poll.values.map(optionName => ({ optionName })),
1101
+ endTime: message.poll.endDate ? message.poll.endDate.getTime() : undefined,
1102
+ hideParticipantName: message.poll.hideVoter ?? false,
1103
+ allowAddOption: message.poll.canAddOption ?? false
1104
+ };
1105
+ if (message.poll.toAnnouncementGroup) {
1106
+ // poll v2 is for community announcement groups (single select and multiple)
1107
+ m.pollCreationMessageV2 = pollCreationMessage;
1108
+ }
1109
+ else {
1110
+ // Lia@Changes 08-02-26 --- Add quiz message support
1111
+ if (message.poll.pollType === 1) {
1112
+ if (!message.poll.correctAnswer) {
1113
+ throw new Boom('No "correctAnswer" provided for quiz', { statusCode: 400 });
1114
+ }
1115
+ m.pollCreationMessageV5 = {
1116
+ // Lia@Note 08-02-26 --- quiz for newsletter only
1117
+ ...pollCreationMessage,
1118
+ correctAnswer: {
1119
+ optionName: message.poll.correctAnswer.toString()
1120
+ },
1121
+ pollType: 1,
1122
+ selectableOptionsCount: 1
1123
+ };
1124
+ }
1125
+ else if (message.poll.selectableCount === 1) {
1126
+ //poll v3 is for single select polls
1127
+ m.pollCreationMessageV3 = pollCreationMessage;
1128
+ }
1129
+ else {
1130
+ // poll for multiple choice polls
1131
+ m.pollCreationMessage = pollCreationMessage;
1132
+ }
1133
+ }
1134
+ m.messageContextInfo = {
1135
+ // encKey
1136
+ messageSecret: message.poll.messageSecret || randomBytes(32)
1137
+ };
1138
+ }
1139
+ // Lia@Changes 08-02-26 --- Add poll result snapshot message
1140
+ else if (hasNonNullishProperty(message, 'pollResult')) {
1141
+ const pollResultSnapshotMessage = {
1142
+ name: message.pollResult.name,
1143
+ pollVotes: message.pollResult.votes.map(vote => ({
1144
+ optionName: vote.name,
1145
+ optionVoteCount: parseInt(vote.voteCount)
1146
+ }))
1147
+ };
1148
+ if (message.pollResult.pollType === 1) {
1149
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.QUIZ;
1150
+ m.pollResultSnapshotMessageV3 = pollResultSnapshotMessage;
1151
+ }
1152
+ else {
1153
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.POLL;
1154
+ m.pollResultSnapshotMessage = pollResultSnapshotMessage;
1155
+ }
1156
+ }
1157
+ // Lia@Changes 08-02-26 --- Add poll update message
1158
+ else if (hasNonNullishProperty(message, 'pollUpdate')) {
1159
+ if (!message.pollUpdate.key) {
1160
+ throw new Boom('Message key is required', { statusCode: 400 });
1161
+ }
1162
+ if (!message.pollUpdate.vote) {
1163
+ throw new Boom('Encrypted vote payload is required', { statusCode: 400 });
1164
+ }
1165
+ m.pollUpdateMessage = {
1166
+ metadata: message.pollUpdate.metadata,
1167
+ pollCreationMessageKey: message.pollUpdate.key,
1168
+ senderTimestampMs: Date.now(),
1169
+ vote: message.pollUpdate.vote
1170
+ };
1171
+ }
1172
+ else if (hasNonNullishProperty(message, 'paymentInvite')) {
1173
+ m.paymentInviteMessage = {
1174
+ serviceType: message.paymentInvite.type ?? message.paymentInvite.serviceType,
1175
+ expiryTimestamp: message.paymentInvite.expiry ?? message.paymentInvite.expiryTimestamp ?? Date.now()
1176
+ };
1177
+ }
1178
+ else if (hasNonNullishProperty(message, 'inviteAdmin')) {
1179
+ const inv = message.inviteAdmin;
1180
+ if (!inv.jid) throw new Boom('inviteAdmin requires { jid } (the newsletter jid)', { statusCode: 400 });
1181
+ m.newsletterAdminInviteMessage = {
1182
+ newsletterJid: inv.jid,
1183
+ newsletterName: inv.subject,
1184
+ caption: inv.text,
1185
+ inviteExpiration: inv.inviteExpiration ?? 0,
1186
+ ...(inv.thumbnail ? { jpegThumbnail: inv.thumbnail } : {})
1187
+ };
1188
+ }
1189
+ else if (hasNonNullishProperty(message, 'requestPayment')) {
1190
+ const rp = message.requestPayment;
1191
+ const amount1000 = Math.round(Number(rp.amount1000 ?? rp.amount));
1192
+ const currency = rp.currency ?? rp.currencyCodeIso4217;
1193
+ const requestFrom = rp.from ?? rp.requestFrom ?? options.recipientJid;
1194
+ const missing = [];
1195
+ if (!Number.isFinite(amount1000) || amount1000 <= 0) missing.push('amount (positive integer, in 1/1000 units)');
1196
+ if (!currency) missing.push('currency');
1197
+ if (!requestFrom) missing.push('from');
1198
+ if (missing.length) throw new Boom(`Invalid requestPayment: ${missing.join(', ')}`, { statusCode: 400 });
1199
+ const note = rp.noteMessage ?? (typeof rp.note === 'string' ? { extendedTextMessage: { text: rp.note } } : undefined);
1200
+ m.requestPaymentMessage = {
1201
+ amount1000,
1202
+ currencyCodeIso4217: currency,
1203
+ requestFrom,
1204
+ expiryTimestamp: rp.expiry ?? rp.expiryTimestamp ?? 0,
1205
+ ...(note ? { noteMessage: note } : {}),
1206
+ ...(rp.background != null ? { background: rp.background } : {})
1207
+ };
1208
+ }
1209
+ else if (hasNonNullishProperty(message, 'declinePaymentRequest') || hasNonNullishProperty(message, 'cancelPaymentRequest')) {
1210
+ const declining = hasNonNullishProperty(message, 'declinePaymentRequest');
1211
+ const key = declining ? message.declinePaymentRequest?.key ?? message.declinePaymentRequest : message.cancelPaymentRequest?.key ?? message.cancelPaymentRequest;
1212
+ if (!key?.id) throw new Boom(`${declining ? 'declinePaymentRequest' : 'cancelPaymentRequest'} requires the original request message key`, { statusCode: 400 });
1213
+ m[declining ? 'declinePaymentRequestMessage' : 'cancelPaymentRequestMessage'] = { key };
1214
+ }
1215
+ else if (hasNonNullishProperty(message, 'statusNotification') || hasNonNullishProperty(message, 'statusNotificationMessage')) {
1216
+ m.statusNotificationMessage = proto.Message.StatusNotificationMessage.fromObject(message.statusNotification ?? message.statusNotificationMessage);
1217
+ }
1218
+ else if (hasNonNullishProperty(message, 'statusQuestionAnswer') || hasNonNullishProperty(message, 'statusQuestionAnswerMessage')) {
1219
+ m.statusQuestionAnswerMessage = proto.Message.StatusQuestionAnswerMessage.fromObject(message.statusQuestionAnswer ?? message.statusQuestionAnswerMessage);
1220
+ }
1221
+ else if (hasNonNullishProperty(message, 'questionResponse') || hasNonNullishProperty(message, 'questionResponseMessage')) {
1222
+ m.questionResponseMessage = proto.Message.QuestionResponseMessage.fromObject(message.questionResponse ?? message.questionResponseMessage);
1223
+ }
1224
+ else if (hasNonNullishProperty(message, 'statusQuoted') || hasNonNullishProperty(message, 'statusQuotedMessage')) {
1225
+ m.statusQuotedMessage = proto.Message.StatusQuotedMessage.fromObject(message.statusQuoted ?? message.statusQuotedMessage);
1226
+ }
1227
+ else if (hasNonNullishProperty(message, 'statusStickerInteraction') || hasNonNullishProperty(message, 'statusStickerInteractionMessage')) {
1228
+ m.statusStickerInteractionMessage = proto.Message.StatusStickerInteractionMessage.fromObject(message.statusStickerInteraction ?? message.statusStickerInteractionMessage);
1229
+ }
1230
+ else if (hasNonNullishProperty(message, 'newsletterFollowerInvite') || hasNonNullishProperty(message, 'newsletterFollowerInviteMessageV2')) {
1231
+ m.newsletterFollowerInviteMessageV2 = proto.Message.NewsletterFollowerInviteMessage.fromObject(message.newsletterFollowerInvite ?? message.newsletterFollowerInviteMessageV2);
1232
+ }
1233
+ else if (hasNonNullishProperty(message, 'messageHistoryNotice')) {
1234
+ m.messageHistoryNotice = proto.Message.MessageHistoryNotice.fromObject(message.messageHistoryNotice);
1235
+ }
1236
+ // Lia@Changes 01-02-26 --- Add payment invite message
1237
+ else if (hasNonNullishProperty(message, 'paymentInviteServiceType')) {
1238
+ m.paymentInviteMessage = {
1239
+ expiryTimestamp: Date.now(),
1240
+ serviceType: message.paymentInviteServiceType
1241
+ };
1242
+ }
1243
+ // Lia@Changes 01-02-26 --- Add order message
1244
+ else if (hasNonNullishProperty(message, 'orderText')) {
1245
+ if (!Buffer.isBuffer(message.thumbnail)) {
1246
+ throw new Boom('Must provide thumbnail buffer in order message', { statusCode: 400 });
1247
+ }
1248
+ m.orderMessage = {
1249
+ itemCount: 1,
1250
+ messageVersion: 1,
1251
+ orderTitle: LIBRARY_NAME,
1252
+ status: proto.Message.OrderMessage.OrderStatus.INQUIRY,
1253
+ surface: proto.Message.OrderMessage.OrderSurface.CATALOG,
1254
+ token: generateMessageIDV2(),
1255
+ totalAmount1000: 1000,
1256
+ totalCurrencyCode: 'IDR',
1257
+ ...message,
1258
+ message: message.orderText
1259
+ };
1260
+ delete m.orderMessage.orderText;
1261
+ }
1262
+ // Lia@Changes 31-01-26 --- Add support for album messages
1263
+ else if (hasNonNullishProperty(message, 'album')) {
1264
+ if (!Array.isArray(message.album)) {
1265
+ throw new Boom('Invalid album type. Expected an array.', { statusCode: 400 });
1266
+ }
1267
+ let videoCount = 0;
1268
+ for (let i = 0; i < message.album.length; i++) {
1269
+ if (message.album[i].video)
1270
+ videoCount++;
1271
+ }
1272
+ ;
1273
+ let imageCount = 0;
1274
+ for (let i = 0; i < message.album.length; i++) {
1275
+ if (message.album[i].image)
1276
+ imageCount++;
1277
+ }
1278
+ ;
1279
+ if ((videoCount + imageCount) < 2) {
1280
+ throw new Boom('Minimum provide 2 media to upload album message', { statusCode: 400 });
1281
+ }
1282
+ m.albumMessage = {
1283
+ expectedImageCount: imageCount,
1284
+ expectedVideoCount: videoCount,
1285
+ ...(typeof message.caption === 'string' && message.caption ? { caption: message.caption } : {})
1286
+ };
1287
+ }
1288
+ else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
1289
+ m.protocolMessage = {
1290
+ type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
1291
+ };
1292
+ }
1293
+ else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
1294
+ m.requestPhoneNumberMessage = {};
1295
+ }
1296
+ else if (hasNonNullishProperty(message, 'limitSharing')) {
1297
+ m.protocolMessage = {
1298
+ type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
1299
+ limitSharing: {
1300
+ sharingLimited: message.limitSharing === true,
1301
+ trigger: 1,
1302
+ limitSharingSettingTimestamp: Date.now(),
1303
+ initiatedByMe: true
1304
+ }
1305
+ };
1306
+ }
1307
+ else {
1308
+ m = await prepareWAMessageMedia(message, options);
1309
+ }
1310
+ // Lia@Changes 30-01-26 --- Add interactive messages (buttonsMessage, listMessage, interactiveMessage, templateMessage, and carouselMessage)
1311
+ if (hasNonNullishProperty(message, 'buttons')) {
1312
+ const buttonsMessage = {
1313
+ buttons: message.buttons.map(button => {
1314
+ // Lia@Changes 12-03-26 --- Add "single_select" shortcut!
1315
+ const buttonText = button.text || button.buttonText;
1316
+ if (hasOptionalProperty(button, 'sections')) {
1317
+ return {
1318
+ nativeFlowInfo: {
1319
+ name: 'single_select',
1320
+ paramsJson: JSON.stringify({
1321
+ title: buttonText,
1322
+ sections: button.sections
1323
+ })
1324
+ },
1325
+ type: ButtonType.NATIVE_FLOW
1326
+ };
1327
+ }
1328
+ else if (hasOptionalProperty(button, 'name')) {
1329
+ return {
1330
+ nativeFlowInfo: {
1331
+ name: button.name,
1332
+ paramsJson: button.paramsJson
1333
+ },
1334
+ type: ButtonType.NATIVE_FLOW
1335
+ };
1336
+ }
1337
+ return {
1338
+ buttonId: button.id || button.buttonId,
1339
+ buttonText: typeof buttonText === 'string' ? { displayText: buttonText } : buttonText,
1340
+ type: button.type || ButtonType.RESPONSE
1341
+ };
1342
+ })
1343
+ };
1344
+ if (hasOptionalProperty(message, 'text')) {
1345
+ buttonsMessage.contentText = message.text;
1346
+ buttonsMessage.headerType = ButtonHeaderType.EMPTY;
1347
+ }
1348
+ else {
1349
+ if (hasOptionalProperty(message, 'caption')) {
1350
+ buttonsMessage.contentText = message.caption;
1351
+ }
1352
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1353
+ buttonsMessage.headerType = ButtonHeaderType[type];
1354
+ Object.assign(buttonsMessage, m);
1355
+ }
1356
+ if (hasOptionalProperty(message, 'footer')) {
1357
+ buttonsMessage.footerText = message.footer;
1358
+ }
1359
+ m = { buttonsMessage };
1360
+ }
1361
+ else if (hasNonNullishProperty(message, 'productList')) {
1362
+ const sections = message.productList;
1363
+ if (!Array.isArray(sections) || !sections.length || !Array.isArray(sections[0]?.products) || !sections[0].products.length) {
1364
+ throw new Boom('Invalid productList: needs at least one section containing at least one product', { statusCode: 400 });
1365
+ }
1366
+ if (!message.businessOwnerJid) throw new Boom('productList requires businessOwnerJid', { statusCode: 400 });
1367
+ m = {
1368
+ listMessage: {
1369
+ title: message.title,
1370
+ buttonText: message.buttonText,
1371
+ footerText: message.footer,
1372
+ description: message.text,
1373
+ productListInfo: {
1374
+ productSections: sections,
1375
+ headerImage: { productId: sections[0].products[0].productId },
1376
+ businessOwnerJid: message.businessOwnerJid
1377
+ },
1378
+ listType: proto.Message.ListMessage.ListType.PRODUCT_LIST
1379
+ }
1380
+ };
1381
+ }
1382
+ else if (hasNonNullishProperty(message, 'sections')) {
1383
+ const listMessage = {
1384
+ sections: message.sections,
1385
+ buttonText: message.buttonText,
1386
+ title: message.title,
1387
+ footerText: message.footer,
1388
+ description: message.text,
1389
+ listType: ListType.SINGLE_SELECT
1390
+ };
1391
+ m = { listMessage };
1392
+ }
1393
+ // Lia@Note 03-02-26 --- This message type is shown on WhatsApp Web/Desktop and iOS (I guess 。⁠◕⁠‿⁠◕⁠。). On Android, it only appears in newsletter (so far ಥ⁠‿⁠ಥ)
1394
+ else if (hasNonNullishProperty(message, 'templateButtons')) {
1395
+ const hydratedTemplate = {
1396
+ hydratedButtons: message.templateButtons.map((button, i) => {
1397
+ const buttonText = button.text || button.buttonText;
1398
+ if (hasOptionalProperty(button, 'id')) {
1399
+ return {
1400
+ index: i,
1401
+ quickReplyButton: {
1402
+ displayText: buttonText || '👉🏻 Click',
1403
+ id: button.id
1404
+ }
1405
+ };
1406
+ }
1407
+ else if (hasOptionalProperty(button, 'url')) {
1408
+ return {
1409
+ index: i,
1410
+ urlButton: {
1411
+ displayText: buttonText || '🌐 Visit',
1412
+ url: button.url
1413
+ }
1414
+ };
1415
+ }
1416
+ else if (hasOptionalProperty(button, 'call')) {
1417
+ return {
1418
+ index: i,
1419
+ callButton: {
1420
+ displayText: buttonText || '📞 Call',
1421
+ phoneNumber: button.call
1422
+ }
1423
+ };
1424
+ }
1425
+ button.index = button.index || i;
1426
+ return button;
1427
+ })
1428
+ };
1429
+ if (hasOptionalProperty(message, 'text')) {
1430
+ hydratedTemplate.hydratedContentText = message.text;
1431
+ }
1432
+ else {
1433
+ if (hasOptionalProperty(message, 'caption')) {
1434
+ hydratedTemplate.hydratedTitleText = message.title;
1435
+ hydratedTemplate.hydratedContentText = message.caption;
1436
+ }
1437
+ ;
1438
+ Object.assign(hydratedTemplate, m);
1439
+ }
1440
+ if (hasOptionalProperty(message, 'footer')) {
1441
+ hydratedTemplate.hydratedFooterText = message.footer;
1442
+ }
1443
+ hydratedTemplate.templateId = message.id || 'template-' + Date.now(); // Lia@Note 04-02-26 --- Minimal templateId to satisfy WhatsApp (⁠ ⁠ꈍ⁠ᴗ⁠ꈍ⁠)
1444
+ m = {
1445
+ templateMessage: {
1446
+ hydratedFourRowTemplate: hydratedTemplate,
1447
+ hydratedTemplate: hydratedTemplate
1448
+ }
1449
+ };
1450
+ }
1451
+ else if (hasNonNullishProperty(message, 'nativeFlow')) {
1452
+ const interactiveMessage = {
1453
+ nativeFlowMessage: prepareNativeFlowButtons(message)
1454
+ };
1455
+ if (hasOptionalProperty(message, 'bizJid')) {
1456
+ interactiveMessage.collectionMessage = {
1457
+ bizJid: message.bizJid,
1458
+ id: message.id,
1459
+ messageVersion: 1
1460
+ };
1461
+ }
1462
+ else if (hasOptionalProperty(message, 'shopSurface')) {
1463
+ interactiveMessage.shopStorefrontMessage = {
1464
+ surface: message.shopSurface,
1465
+ id: message.id,
1466
+ messageVersion: 1
1467
+ };
1468
+ }
1469
+ if (hasOptionalProperty(message, 'text')) {
1470
+ interactiveMessage.body = { text: message.text };
1471
+ }
1472
+ else {
1473
+ if (hasOptionalProperty(message, 'caption')) {
1474
+ const isValidHeader = hasValidInteractiveHeader(m);
1475
+ if (!isValidHeader) {
1476
+ throw new Boom('Invalid media type for interactive message header', { statusCode: 400 });
1477
+ }
1478
+ interactiveMessage.header = {
1479
+ title: message.title || '',
1480
+ subtitle: message.subtitle || '',
1481
+ hasMediaAttachment: isValidHeader
1482
+ };
1483
+ interactiveMessage.body = { text: message.caption };
1484
+ }
1485
+ if (hasOptionalProperty(message, 'thumbnail') && !!message.thumbnail) {
1486
+ interactiveMessage.jpegThumbnail = message.thumbnail;
1487
+ }
1488
+ Object.assign(interactiveMessage.header, m);
1489
+ }
1490
+ if (hasOptionalProperty(message, 'audioFooter')) {
1491
+ const { audioMessage } = await prepareWAMessageMedia({
1492
+ audio: message.audioFooter
1493
+ }, options);
1494
+ interactiveMessage.footer = {
1495
+ audioMessage,
1496
+ hasMediaAttachment: true
1497
+ };
1498
+ }
1499
+ else if (hasOptionalProperty(message, 'footer')) {
1500
+ interactiveMessage.footer = { text: message.footer };
1501
+ }
1502
+ m = { interactiveMessage };
1503
+ }
1504
+ else if (hasNonNullishProperty(message, 'cards')) {
1505
+ const interactiveMessage = {
1506
+ carouselMessage: {
1507
+ cards: await Promise.all(message.cards.map(async (card) => {
1508
+ let carouselHeader = {};
1509
+ if (hasNonNullishProperty(card, 'product')) {
1510
+ carouselHeader.productMessage = await prepareProductMessage(card, options);
1511
+ }
1512
+ else {
1513
+ carouselHeader = await prepareWAMessageMedia(card, options).catch(() => ({}));
1514
+ }
1515
+ const isValidHeader = hasValidCarouselHeader(carouselHeader);
1516
+ if (!isValidHeader) {
1517
+ throw new Boom('Invalid media type for carousel card', { statusCode: 400 });
1518
+ }
1519
+ const carouselCard = {
1520
+ nativeFlowMessage: prepareNativeFlowButtons(card.nativeFlow ? card : [])
1521
+ };
1522
+ if (hasOptionalProperty(card, 'text')) {
1523
+ carouselCard.body = { text: card.text };
1524
+ }
1525
+ else {
1526
+ if (hasOptionalProperty(card, 'caption')) {
1527
+ carouselCard.header = {
1528
+ title: card.title || '',
1529
+ subtitle: card.subtitle || '',
1530
+ hasMediaAttachment: isValidHeader
1531
+ };
1532
+ carouselCard.body = { text: card.caption };
1533
+ }
1534
+ if (hasOptionalProperty(card, 'thumbnail') && !!card.thumbnail) {
1535
+ carouselCard.jpegThumbnail = card.thumbnail;
1536
+ }
1537
+ Object.assign(carouselCard.header, carouselHeader);
1538
+ }
1539
+ if (hasOptionalProperty(card, 'audioFooter')) {
1540
+ const { audioMessage } = await prepareWAMessageMedia({
1541
+ audio: card.audioFooter
1542
+ }, options);
1543
+ carouselCard.footer = {
1544
+ audioMessage,
1545
+ hasMediaAttachment: true
1546
+ };
1547
+ }
1548
+ else if (hasOptionalProperty(card, 'footer')) {
1549
+ carouselCard.footer = { text: card.footer };
1550
+ }
1551
+ if (hasNonNullishProperty(card, 'contextInfo')) {
1552
+ carouselCard.contextInfo = card.contextInfo;
1553
+ }
1554
+ return carouselCard;
1555
+ })),
1556
+ carouselCardType: CarouselCardType.UNKNOWN,
1557
+ messageVersion: 1
1558
+ }
1559
+ };
1560
+ if (hasOptionalProperty(message, 'text')) {
1561
+ interactiveMessage.body = { text: message.text };
1562
+ }
1563
+ if (hasOptionalProperty(message, 'footer')) {
1564
+ interactiveMessage.footer = { text: message.footer };
1565
+ }
1566
+ m = { interactiveMessage };
1567
+ }
1568
+ // Lia@Changes 01-02-26 --- Add request payment message
1569
+ else if (hasNonNullishProperty(message, 'requestPaymentFrom')) {
1570
+ const requestPaymentMessage = {
1571
+ amount: {
1572
+ currencyCode: 'IDR',
1573
+ offset: 1000,
1574
+ value: 1000
1575
+ },
1576
+ amount1000: 1000,
1577
+ currencyCodeIso4217: 'IDR',
1578
+ expiryTimestamp: Date.now(),
1579
+ noteMessage: m,
1580
+ requestFrom: message.requestPaymentFrom,
1581
+ ...message
1582
+ };
1583
+ delete requestPaymentMessage.requestPaymentFrom;
1584
+ if (hasNonNullishProperty(m, 'extendedTextMessage') || hasNonNullishProperty(m, 'stickerMessage')) {
1585
+ Object.assign(requestPaymentMessage.noteMessage, m);
1586
+ }
1587
+ else {
1588
+ throw new Boom('Invalid message type for request payment note message', { statusCode: 400 });
1589
+ }
1590
+ m = { requestPaymentMessage };
1591
+ }
1592
+ // Lia@Changes 01-02-26 --- Add invoice message
1593
+ else if (hasNonNullishProperty(message, 'invoiceNote')) {
1594
+ const attachment = m.imageMessage || m.documentMessage;
1595
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1596
+ const invoiceMessage = {
1597
+ attachmentType: proto.Message.InvoiceMessage.AttachmentType[type === 'DOCUMENT' ? 'PDF' : 'IMAGE'],
1598
+ note: message.invoiceNote
1599
+ };
1600
+ if (attachment) {
1601
+ const { directPath, fileEncSha256, fileSha256, jpegThumbnail = undefined, mediaKey, mediaKeyTimestamp, mimetype } = attachment;
1602
+ Object.assign(invoiceMessage, {
1603
+ attachmentDirectPath: directPath,
1604
+ attachmentFileEncSha256: fileEncSha256,
1605
+ attachmentFileSha256: fileSha256,
1606
+ attachmentJpegThumbnail: jpegThumbnail,
1607
+ attachmentMediaKey: mediaKey,
1608
+ attachmentMediaKeyTimestamp: mediaKeyTimestamp,
1609
+ attachmentMimetype: mimetype,
1610
+ token: generateMessageIDV2()
1611
+ });
1612
+ }
1613
+ else {
1614
+ throw new Boom('Invalid media type for invoice message', { statusCode: 400 });
1615
+ }
1616
+ m = { invoiceMessage };
1617
+ }
1618
+ // Lia@Changes 31-01-26 --- Add direct externalAdReply access (no need to create contextInfo first)
1619
+ if (hasOptionalProperty(message, 'externalAdReply') && !!message.externalAdReply) {
1620
+ const messageType = Object.keys(m)[0];
1621
+ const key = m[messageType];
1622
+ const content = message.externalAdReply;
1623
+ if ('thumbnail' in content && !Buffer.isBuffer(content.thumbnail)) {
1624
+ throw new Boom('Thumbnail must in buffer type', { statusCode: 400 });
1625
+ }
1626
+ if (!content.url || typeof content.url !== 'string') {
1627
+ content.url = DONATE_URL || '';
1628
+ }
1629
+ const externalAdReply = {
1630
+ ...content,
1631
+ body: content.body,
1632
+ mediaType: content.mediaType || 1,
1633
+ mediaUrl: content.url,
1634
+ renderLargerThumbnail: content.largeThumbnail,
1635
+ sourceUrl: content.url,
1636
+ thumbnail: content.thumbnail,
1637
+ thumbnailUrl: content.url + '?update=' + Date.now(),
1638
+ title: content.title || LIBRARY_NAME
1639
+ };
1640
+ delete externalAdReply.subTitle;
1641
+ delete externalAdReply.largeThumbnail;
1642
+ delete externalAdReply.url;
1643
+ if ('contextInfo' in key && !!key.contextInfo) {
1644
+ key.contextInfo.externalAdReply = { ...key.contextInfo.externalAdReply, ...externalAdReply };
1645
+ }
1646
+ else if (key) {
1647
+ key.contextInfo = { externalAdReply };
1648
+ }
1649
+ }
1650
+ if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
1651
+ (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
1652
+ const messageType = Object.keys(m)[0];
1653
+ const key = m[messageType];
1654
+ if (key && 'contextInfo' in key) {
1655
+ key.contextInfo = key.contextInfo || {};
1656
+ if (message.mentions?.length) {
1657
+ key.contextInfo.mentionedJid = message.mentions;
1658
+ }
1659
+ if (message.mentionAll) {
1660
+ key.contextInfo.nonJidMentions = 1;
1661
+ }
1662
+ }
1663
+ else if (key) {
1664
+ key.contextInfo = {
1665
+ mentionedJid: message.mentions,
1666
+ nonJidMentions: message.mentionAll ? 1 : 0
1667
+ };
1668
+ }
1669
+ }
1670
+ if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
1671
+ const messageType = Object.keys(m)[0];
1672
+ const key = m[messageType];
1673
+ if ('contextInfo' in key && !!key.contextInfo) {
1674
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
1675
+ }
1676
+ else if (key) {
1677
+ key.contextInfo = message.contextInfo;
1678
+ }
1679
+ }
1680
+ // Vanzxy@Fix: groupStatus wrapping — audio uses groupStatusMessage (v1) for compatibility
1681
+ // with older WA versions. groupStatusMessageV2 causes black screen ("versi tidak mendukung")
1682
+ // on recipients with older WhatsApp. Only non-audio media uses V2.
1683
+ if (hasOptionalProperty(message, 'groupStatus') && !!message.groupStatus) {
1684
+ const messageType = Object.keys(m)[0];
1685
+ const key = m[messageType];
1686
+ if ('contextInfo' in key && !!key.contextInfo) {
1687
+ key.contextInfo.isGroupStatus = message.groupStatus;
1688
+ }
1689
+ else if (key) {
1690
+ key.contextInfo = {
1691
+ isGroupStatus: message.groupStatus
1692
+ };
1693
+ }
1694
+ // Vanzxy@Fix: audio must use groupStatusMessage (v1), not V2
1695
+ // V2 is not supported by older WA clients causing black screen for audio
1696
+ if (messageType === 'audioMessage') {
1697
+ m = { groupStatusMessage: { message: m } };
1698
+ } else {
1699
+ m = { groupStatusMessageV2: { message: m } };
1700
+ }
1701
+ delete message.groupStatus;
1702
+ }
1703
+ // Lia@Changes 06-05-26 --- Add "spoiler" boolean to set contextInfo.isSpoiler and wrap message into spoilerMessage
1704
+ if (hasOptionalProperty(message, 'spoiler') && !!message.spoiler) {
1705
+ const messageType = Object.keys(m)[0];
1706
+ const key = m[messageType];
1707
+ if ('contextInfo' in key && !!key.contextInfo) {
1708
+ key.contextInfo.isSpoiler = message.spoiler;
1709
+ }
1710
+ else if (key) {
1711
+ key.contextInfo = {
1712
+ isSpoiler: message.spoiler
1713
+ };
1714
+ }
1715
+ m = { spoilerMessage: { message: m } };
1716
+ delete message.spoiler;
1717
+ }
1718
+ // Lia@Changes 02-02-26 --- Add "interactiveAsTemplate" boolean to wrap interactiveMessage into templateMessage
1719
+ else if (hasOptionalProperty(message, 'interactiveAsTemplate') && !!message.interactiveAsTemplate) {
1720
+ if (!m.interactiveMessage) {
1721
+ throw new Boom('Invalid message type for template', { statusCode: 400 }); // Lia@Note 02-02-26 --- To avoid bug 👀
1722
+ }
1723
+ m = {
1724
+ templateMessage: {
1725
+ interactiveMessageTemplate: m.interactiveMessage,
1726
+ templateId: message.id || 'template-' + Date.now() // Lia@Note 04-02-26 --- Minimal templateId to satisfy WhatsApp (⁠ ⁠ꈍ⁠ᴗ⁠ꈍ⁠)
1727
+ }
1728
+ };
1729
+ delete message.interactiveAsTemplate;
1730
+ }
1731
+ // Lia@Changes 30-01-26 --- Add "ephemeral" boolean to wrap message into ephemeralMessage like "viewOnce"
1732
+ if (hasOptionalProperty(message, 'ephemeral') && !!message.ephemeral) {
1733
+ m = { ephemeralMessage: { message: m } };
1734
+ delete message.ephemeral;
1735
+ }
1736
+ // Lia@Changes 16-05-26 --- Add wrap message into lottieStickerMessage by isLottie boolean
1737
+ if (hasOptionalProperty(message, 'isLottie') && !!message.isLottie) {
1738
+ m = { lottieStickerMessage: { message: m } };
1739
+ }
1740
+ else if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
1741
+ m = { viewOnceMessage: { message: m } };
1742
+ }
1743
+ // Lia@Changes 03-02-26 --- Add "viewOnceV2" boolean to wrap message into viewOnceMessageV2 like "viewOnce"
1744
+ else if (hasOptionalProperty(message, 'viewOnceV2') && !!message.viewOnceV2) {
1745
+ m = { viewOnceMessageV2: { message: m } };
1746
+ delete message.viewOnceV2;
1747
+ }
1748
+ // Lia@Changes 03-02-26 --- Add "viewOnceV2Extension" boolean to wrap message into viewOnceMessageV2Extension like "viewOnce"
1749
+ else if (hasOptionalProperty(message, 'viewOnceV2Extension') && !!message.viewOnceV2Extension) {
1750
+ m = { viewOnceMessageV2Extension: { message: m } };
1751
+ delete message.viewOnceV2Extension;
1752
+ }
1753
+ if (hasOptionalProperty(message, 'edit')) {
1754
+ m = {
1755
+ protocolMessage: {
1756
+ key: message.edit,
1757
+ editedMessage: m,
1758
+ timestampMs: Date.now(),
1759
+ type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
1760
+ }
1761
+ };
1762
+ }
1763
+ // Whiskey rc14: `albumParentKey` links a media message to an album parent (MEDIA_ALBUM association).
1764
+ if (hasOptionalProperty(message, 'albumParentKey') && !!message.albumParentKey) {
1765
+ m.messageContextInfo = {
1766
+ ...m.messageContextInfo,
1767
+ messageAssociation: {
1768
+ associationType: WAProto.MessageAssociation.AssociationType.MEDIA_ALBUM,
1769
+ parentMessageKey: message.albumParentKey
1770
+ }
1771
+ };
1772
+ }
1773
+ if (shouldIncludeReportingToken(m)) {
1774
+ m.messageContextInfo = m.messageContextInfo || {};
1775
+ if (!m.messageContextInfo.messageSecret) {
1776
+ m.messageContextInfo.messageSecret = randomBytes(32);
1777
+ }
1778
+ }
1779
+ return WAProto.Message.create(m);
1780
+ };
1781
+ export const generateWAMessageFromContent = (jid, message, options) => {
1782
+ // set timestamp to now
1783
+ // if not specified
1784
+ if (!options.timestamp) {
1785
+ options.timestamp = new Date();
1786
+ }
1787
+ const innerMessage = normalizeMessageContent(message);
1788
+ const messageContextInfo = message.messageContextInfo;
1789
+ const key = getContentType(innerMessage);
1790
+ const timestamp = unixTimestampSeconds(options.timestamp);
1791
+ const isNewsletter = isJidNewsletter(jid);
1792
+ const { quoted, userJid, userJidLid } = options;
1793
+ const meParticipant = (targetJid) => (isLidUser(targetJid) && userJidLid) ? userJidLid : userJid;
1794
+ if (quoted) {
1795
+ const participant = quoted.key.fromMe
1796
+ ? meParticipant(quoted.key.remoteJid || jid)
1797
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
1798
+ let quotedMsg = normalizeMessageContent(quoted.message);
1799
+ const msgType = getContentType(quotedMsg);
1800
+ // strip any redundant properties
1801
+ quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
1802
+ const quotedContent = quotedMsg[msgType];
1803
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
1804
+ delete quotedContent.contextInfo;
1805
+ }
1806
+ const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
1807
+ contextInfo.participant = jidNormalizedUser(participant);
1808
+ contextInfo.stanzaId = quoted.key.id;
1809
+ contextInfo.quotedMessage = quotedMsg;
1810
+ // if a participant is quoted, then it must be a group
1811
+ // hence, remoteJid of group must also be entered
1812
+ if (!isNewsletter && jid !== quoted.key.remoteJid) {
1813
+ contextInfo.remoteJid = quoted.key.remoteJid;
1814
+ }
1815
+ if (contextInfo && innerMessage[key]) {
1816
+ /* @ts-ignore */
1817
+ innerMessage[key].contextInfo = contextInfo;
1818
+ }
1819
+ }
1820
+ if (
1821
+ // if we want to send a disappearing message
1822
+ !!options?.ephemeralExpiration &&
1823
+ // and it's not a protocol message -- delete, toggle disappear message
1824
+ key !== 'protocolMessage' &&
1825
+ // already not converted to disappearing message
1826
+ key !== 'ephemeralMessage' &&
1827
+ // newsletters don't support ephemeral messages
1828
+ !isNewsletter) {
1829
+ /* @ts-ignore */
1830
+ innerMessage[key].contextInfo = {
1831
+ ...(innerMessage[key].contextInfo || {}),
1832
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
1833
+ //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
1834
+ };
1835
+ }
1836
+ // Lia@Changes 30-01-26 --- Add deviceListMetadata inside messageContextInfo for private chat
1837
+ if (messageContextInfo?.messageSecret && (isPnUser(jid) || isLidUser(jid))) {
1838
+ messageContextInfo.deviceListMetadata = {
1839
+ recipientKeyHash: randomBytes(10),
1840
+ recipientTimestamp: unixTimestampSeconds()
1841
+ };
1842
+ messageContextInfo.deviceListMetadataVersion = 2;
1843
+ }
1844
+ message = WAProto.Message.create(message);
1845
+ const messageJSON = {
1846
+ key: {
1847
+ remoteJid: jid,
1848
+ fromMe: true,
1849
+ id: options?.messageId || generateMessageIDV2()
1850
+ },
1851
+ message: message,
1852
+ messageTimestamp: timestamp,
1853
+ messageStubParameters: [],
1854
+ participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? meParticipant(jid) : undefined,
1855
+ status: WAMessageStatus.PENDING
1856
+ };
1857
+ return WAProto.WebMessageInfo.fromObject(messageJSON);
1858
+ };
1859
+ /**
1860
+ * Vanzxy@Compat 1.4.2 --- Legacy alias for generateWAMessageFromContent.
1861
+ * Older Baileys forks exposed this exact signature (jid, message, options) => WebMessageInfo
1862
+ * as "prepareMessageFromContent". It was never replaced with a different implementation,
1863
+ * just renamed upstream — so this is a direct alias, not a stub.
1864
+ */
1865
+ export const prepareMessageFromContent = generateWAMessageFromContent;
1866
+ export const generateWAMessage = async (jid, content, options) => {
1867
+ // ensure msg ID is with every log
1868
+ options.logger = options?.logger?.child({ msgId: options.messageId });
1869
+ // Pass jid in the options to generateWAMessageContent
1870
+ if (jid) {
1871
+ options.jid = jid;
1872
+ }
1873
+ return generateWAMessageFromContent(jid, await generateWAMessageContent(content, options), options);
1874
+ };
1875
+ /** Get the key to access the true type of content */
1876
+ export const getContentType = (content) => {
1877
+ if (content) {
1878
+ const keys = Object.keys(content);
1879
+ const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
1880
+ return key;
1881
+ }
1882
+ };
1883
+ /**
1884
+ * Normalizes ephemeral, view once messages to regular message content
1885
+ * Eg. image messages in ephemeral messages, in view once messages etc.
1886
+ * @param content
1887
+ * @returns
1888
+ */
1889
+ export const normalizeMessageContent = (content) => {
1890
+ if (!content) {
1891
+ return undefined;
1892
+ }
1893
+ // set max iterations to prevent an infinite loop
1894
+ for (let i = 0; i < 5; i++) {
1895
+ const inner = getFutureProofMessage(content);
1896
+ if (!inner) {
1897
+ break;
1898
+ }
1899
+ content = inner.message;
1900
+ }
1901
+ return content;
1902
+ // Lia@Changes 03-02-26 --- Add all futureProofMessage into getFutureProofMessage()
1903
+ function getFutureProofMessage(message) {
1904
+ return (message?.associatedChildMessage ||
1905
+ message?.botForwardedMessage ||
1906
+ message?.botInvokeMessage ||
1907
+ message?.botPlatformRegistrationSuccessMessage ||
1908
+ message?.botTaskMessage ||
1909
+ message?.documentWithCaptionMessage ||
1910
+ message?.editedMessage ||
1911
+ message?.ephemeralMessage ||
1912
+ message?.eventCoverImage ||
1913
+ message?.groupMentionedMessage ||
1914
+ message?.groupStatusMentionMessage ||
1915
+ message?.groupStatusMessage ||
1916
+ message?.groupStatusMessageV2 ||
1917
+ message?.limitSharingMessage ||
1918
+ message?.lottieStickerMessage ||
1919
+ message?.newsletterAdminProfileMessage ||
1920
+ message?.newsletterAdminProfileMessageV2 ||
1921
+ message?.newsletterAdminProfileStatusMessage ||
1922
+ message?.newsletterScheduledMessage ||
1923
+ message?.pollCreationMessageV4 ||
1924
+ message?.pollCreationOptionImageMessage ||
1925
+ message?.questionMessage ||
1926
+ message?.questionReplyMessage ||
1927
+ message?.spoilerMessage ||
1928
+ message?.statusAddYours ||
1929
+ message?.statusMentionMessage ||
1930
+ message?.viewOnceMessage ||
1931
+ message?.viewOnceMessageV2 ||
1932
+ message?.viewOnceMessageV2Extension);
1933
+ }
1934
+ };
1935
+ /**
1936
+ * Extract the true message content from a message
1937
+ * Eg. extracts the inner message from a disappearing message/view once message
1938
+ */
1939
+ export const extractMessageContent = (content) => {
1940
+ const extractFromTemplateMessage = (msg) => {
1941
+ if (msg.imageMessage) {
1942
+ return { imageMessage: msg.imageMessage };
1943
+ }
1944
+ else if (msg.documentMessage) {
1945
+ return { documentMessage: msg.documentMessage };
1946
+ }
1947
+ else if (msg.videoMessage) {
1948
+ return { videoMessage: msg.videoMessage };
1949
+ }
1950
+ else if (msg.locationMessage) {
1951
+ return { locationMessage: msg.locationMessage };
1952
+ }
1953
+ else {
1954
+ return {
1955
+ conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
1956
+ };
1957
+ }
1958
+ };
1959
+ content = normalizeMessageContent(content);
1960
+ if (content?.buttonsMessage) {
1961
+ return extractFromTemplateMessage(content.buttonsMessage);
1962
+ }
1963
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
1964
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
1965
+ }
1966
+ if (content?.templateMessage?.hydratedTemplate) {
1967
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
1968
+ }
1969
+ if (content?.templateMessage?.fourRowTemplate) {
1970
+ return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
1971
+ }
1972
+ return content;
1973
+ };
1974
+ /**
1975
+ * Returns the device predicted by message ID
1976
+ */
1977
+ export const getDevice = (id) => /^3A.{18}$/.test(id)
1978
+ ? 'ios'
1979
+ : /^3E.{20}$/.test(id)
1980
+ ? 'web'
1981
+ : /^(.{21}|.{32})$/.test(id)
1982
+ ? 'android'
1983
+ : /^(3F|.{18}$)/.test(id)
1984
+ ? 'desktop'
1985
+ : 'unknown';
1986
+ /** Upserts a receipt in the message */
1987
+ export const updateMessageWithReceipt = (msg, receipt) => {
1988
+ msg.userReceipt = msg.userReceipt || [];
1989
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
1990
+ if (recp) {
1991
+ Object.assign(recp, receipt);
1992
+ }
1993
+ else {
1994
+ msg.userReceipt.push(receipt);
1995
+ }
1996
+ };
1997
+ /** Update the message with a new reaction */
1998
+ export const updateMessageWithReaction = (msg, reaction) => {
1999
+ const authorID = getKeyAuthor(reaction.key);
2000
+ const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
2001
+ reaction.text = reaction.text || '';
2002
+ reactions.push(reaction);
2003
+ msg.reactions = reactions;
2004
+ };
2005
+ /** Update the message with a new poll update */
2006
+ export const updateMessageWithPollUpdate = (msg, update) => {
2007
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
2008
+ const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
2009
+ if (update.vote?.selectedOptions?.length) {
2010
+ reactions.push(update);
2011
+ }
2012
+ msg.pollUpdates = reactions;
2013
+ };
2014
+ /** Update the message with a new event response */
2015
+ export const updateMessageWithEventResponse = (msg, update) => {
2016
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
2017
+ const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
2018
+ responses.push(update);
2019
+ msg.eventResponses = responses;
2020
+ };
2021
+ /**
2022
+ * Aggregates all poll updates in a poll.
2023
+ * @param msg the poll creation message
2024
+ * @param meId your jid
2025
+ * @returns A list of options & their voters
2026
+ */
2027
+ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
2028
+ const opts = message?.pollCreationMessage?.options ||
2029
+ message?.pollCreationMessageV2?.options ||
2030
+ message?.pollCreationMessageV3?.options ||
2031
+ [];
2032
+ const voteHashMap = opts.reduce((acc, opt) => {
2033
+ const hash = sha256(Buffer.from(opt.optionName || '')).toString();
2034
+ acc[hash] = {
2035
+ name: opt.optionName || '',
2036
+ voters: []
2037
+ };
2038
+ return acc;
2039
+ }, {});
2040
+ for (const update of pollUpdates || []) {
2041
+ const { vote } = update;
2042
+ if (!vote) {
2043
+ continue;
2044
+ }
2045
+ for (const option of vote.selectedOptions || []) {
2046
+ const hash = option.toString();
2047
+ let data = voteHashMap[hash];
2048
+ if (!data) {
2049
+ voteHashMap[hash] = {
2050
+ name: 'Unknown',
2051
+ voters: []
2052
+ };
2053
+ data = voteHashMap[hash];
2054
+ }
2055
+ voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
2056
+ }
2057
+ }
2058
+ return Object.values(voteHashMap);
2059
+ }
2060
+ /**
2061
+ * Aggregates all event responses in an event message.
2062
+ * @param msg the event creation message
2063
+ * @param meId your jid
2064
+ * @returns A list of response types & their responders
2065
+ */
2066
+ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
2067
+ const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
2068
+ const responseMap = {};
2069
+ for (const type of responseTypes) {
2070
+ responseMap[type] = {
2071
+ response: type,
2072
+ responders: []
2073
+ };
2074
+ }
2075
+ for (const update of eventResponses || []) {
2076
+ const responseType = update.eventResponse || 'UNKNOWN';
2077
+ if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
2078
+ responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
2079
+ }
2080
+ }
2081
+ return Object.values(responseMap);
2082
+ }
2083
+ /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
2084
+ export const aggregateMessageKeysNotFromMe = (keys) => {
2085
+ const keyMap = {};
2086
+ for (const { remoteJid, id, participant, fromMe } of keys) {
2087
+ if (!fromMe) {
2088
+ const uqKey = `${remoteJid}:${participant || ''}`;
2089
+ if (!keyMap[uqKey]) {
2090
+ keyMap[uqKey] = {
2091
+ jid: remoteJid,
2092
+ participant: participant,
2093
+ messageIds: []
2094
+ };
2095
+ }
2096
+ keyMap[uqKey].messageIds.push(id);
2097
+ }
2098
+ }
2099
+ return Object.values(keyMap);
2100
+ };
2101
+ const REUPLOAD_REQUIRED_STATUS = [410, 404];
2102
+ /**
2103
+ * Downloads the given message. Throws an error if it's not a media message
2104
+ */
2105
+ export const downloadMediaMessage = async (message, type, options, ctx) => {
2106
+ const result = await downloadMsg().catch(async (error) => {
2107
+ if (ctx &&
2108
+ typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
2109
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
2110
+ ctx.logger.info({ key: message.key }, 'sending reupload media request...');
2111
+ // request reupload
2112
+ message = await ctx.reuploadRequest(message);
2113
+ const result = await downloadMsg();
2114
+ return result;
2115
+ }
2116
+ throw error;
2117
+ });
2118
+ return result;
2119
+ async function downloadMsg() {
2120
+ const mContent = extractMessageContent(message.message);
2121
+ if (!mContent) {
2122
+ throw new Boom('No message present', { statusCode: 400, data: message });
2123
+ }
2124
+ const contentType = getContentType(mContent);
2125
+ let mediaType = contentType?.replace('Message', '');
2126
+ const media = mContent[contentType];
2127
+ if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
2128
+ throw new Boom(`"${contentType}" message is not a media message`);
2129
+ }
2130
+ let download;
2131
+ if ('thumbnailDirectPath' in media && !('url' in media)) {
2132
+ download = {
2133
+ directPath: media.thumbnailDirectPath,
2134
+ mediaKey: media.mediaKey
2135
+ };
2136
+ mediaType = 'thumbnail-link';
2137
+ }
2138
+ else {
2139
+ download = media;
2140
+ }
2141
+ const stream = await downloadContentFromMessage(download, mediaType, options);
2142
+ if (type === 'buffer') {
2143
+ const bufferArray = [];
2144
+ for await (const chunk of stream) {
2145
+ bufferArray.push(chunk);
2146
+ }
2147
+ return Buffer.concat(bufferArray);
2148
+ }
2149
+ return stream;
2150
+ }
2151
+ };
2152
+ /** Checks whether the given message is a media message; if it is returns the inner content */
2153
+ export const assertMediaContent = (content) => {
2154
+ content = extractMessageContent(content);
2155
+ const mediaContent = content?.documentMessage ||
2156
+ content?.imageMessage ||
2157
+ content?.videoMessage ||
2158
+ content?.audioMessage ||
2159
+ content?.stickerMessage;
2160
+ if (!mediaContent) {
2161
+ throw new Boom('given message is not a media message', { statusCode: 400, data: content });
2162
+ }
2163
+ return mediaContent;
2164
+ };
2165
+ /**
2166
+ * Checks if a WebP buffer is animated by looking for VP8X chunk with animation flag
2167
+ * or ANIM/ANMF chunks
2168
+ */
2169
+ const isAnimatedWebP = (buffer) => {
2170
+ // WebP must start with RIFF....WEBP
2171
+ if (buffer.length < 12 ||
2172
+ buffer[0] !== 0x52 ||
2173
+ buffer[1] !== 0x49 ||
2174
+ buffer[2] !== 0x46 ||
2175
+ buffer[3] !== 0x46 ||
2176
+ buffer[8] !== 0x57 ||
2177
+ buffer[9] !== 0x45 ||
2178
+ buffer[10] !== 0x42 ||
2179
+ buffer[11] !== 0x50) {
2180
+ return false;
2181
+ }
2182
+ ;
2183
+ // Parse chunks starting after RIFF header (12 bytes)
2184
+ let offset = 12;
2185
+ while (offset < buffer.length - 8) {
2186
+ const chunkFourCC = buffer.toString('ascii', offset, offset + 4);
2187
+ const chunkSize = buffer.readUInt32LE(offset + 4);
2188
+ if (chunkFourCC === 'VP8X') {
2189
+ // VP8X extended header, check animation flag (bit 1 at offset+8)
2190
+ const flagsOffset = offset + 8;
2191
+ if (flagsOffset < buffer.length) {
2192
+ const flags = buffer[flagsOffset];
2193
+ if (flags & 0x02) {
2194
+ return true;
2195
+ }
2196
+ ;
2197
+ }
2198
+ ;
2199
+ }
2200
+ else if (chunkFourCC === 'ANIM' || chunkFourCC === 'ANMF') {
2201
+ // ANIM or ANMF chunks indicate animation
2202
+ return true;
2203
+ }
2204
+ ;
2205
+ // Move to next chunk (chunk size + 8 bytes header, padded to even)
2206
+ offset += 8 + chunkSize + (chunkSize % 2);
2207
+ }
2208
+ ;
2209
+ return false;
2210
+ };
2211
+ /**
2212
+ * Checks if a buffer is a WebP file
2213
+ */
2214
+ const isWebPBuffer = (buffer) => {
2215
+ return (buffer.length >= 12 &&
2216
+ buffer[0] === 0x52 &&
2217
+ buffer[1] === 0x49 &&
2218
+ buffer[2] === 0x46 &&
2219
+ buffer[3] === 0x46 &&
2220
+ buffer[8] === 0x57 &&
2221
+ buffer[9] === 0x45 &&
2222
+ buffer[10] === 0x42 &&
2223
+ buffer[11] === 0x50);
2224
+ };
2225
+ /**
2226
+ * Lia@Changes 30-01-26
2227
+ * ---
2228
+ * Determines whether a message should include a Biz Binary Node.
2229
+ * A Biz Binary Node is added only for interactive messages
2230
+ * such as buttons or other supported interactive types.
2231
+ */
2232
+ export const shouldIncludeBizBinaryNode = (message) => !!(message.buttonsMessage ||
2233
+ message.listMessage ||
2234
+ message.templateMessage ||
2235
+ (message.interactiveMessage &&
2236
+ message.interactiveMessage.nativeFlowMessage));
2237
+
2238
+ // Vanz@Port (v2.1.6) --- from @rexxhayanasi/elaina-baileys: poll option hash that also mixes in an option image's fileSha256.
2239
+ export const getPollOptionHash = (optionName, fileSha256) => {
2240
+ const nameHash = createHash('sha256').update(String(optionName), 'utf-8').digest('hex');
2241
+ const fileHash = fileSha256 ? Buffer.from(fileSha256).toString('base64') : '';
2242
+ return createHash('sha256').update(nameHash + fileHash, 'utf-8').digest('hex');
2243
+ };
2244
+ // Vanz@Port (v2.1.6) --- from @rexxhayanasi/elaina-baileys: true when a native-flow button set breaks the client's
2245
+ // constraints (too many buttons, quick_reply mixed with other kinds, or a flow WA Web/iOS cannot render).
2246
+ export const nativeFlowButtonsViolateConstraints = (buttons = []) => {
2247
+ if (!buttons.length) return false;
2248
+ const isQuickReply = button => button?.name === 'quick_reply';
2249
+ const firstIsQuickReply = isQuickReply(buttons[0]);
2250
+ const limit = firstIsQuickReply ? NATIVE_FLOW_BUTTON_LIMIT.quickReply : NATIVE_FLOW_BUTTON_LIMIT.other;
2251
+ if (buttons.length > limit) return true;
2252
+ return !buttons.slice(1).every(button => {
2253
+ const mapped = getNativeFlowNameByButtonName(button?.name);
2254
+ const nameAllowed = mapped == null || WEB_SUPPORTED_INTERACTIVE_FLOWS.includes(mapped);
2255
+ return nameAllowed && firstIsQuickReply === isQuickReply(button);
2256
+ });
2257
+ };
2258
+ // Vanz@Port (v2.1.6) --- from @vinzsocket/baileys: additionalNodes for a hand-built interactive/native-flow message.
2259
+ export const buildInteractiveAdditionalNodes = (_jid, _message, options = {}) => [
2260
+ {
2261
+ tag: 'biz',
2262
+ attrs: {},
2263
+ content: [
2264
+ {
2265
+ tag: 'interactive',
2266
+ attrs: { type: 'native_flow', v: '1' },
2267
+ content: [{ tag: 'native_flow', attrs: { v: options.v || '9', name: options.name || 'mixed' } }]
2268
+ }
2269
+ ]
2270
+ }
2271
+ ];