@eduh_dev021/baileys 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (504) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +495 -2
  3. package/WAProto/index.d.ts +22220 -0
  4. package/WAProto/index.js +5 -0
  5. package/cjs/WAProto/index.d.ts +22220 -0
  6. package/cjs/WAProto/index.js +60125 -0
  7. package/cjs/engine-requirements.js +12 -0
  8. package/cjs/lib/Addon/http-error.d.ts +18 -0
  9. package/cjs/lib/Addon/http-error.js +66 -0
  10. package/cjs/lib/Addon/index.d.ts +3 -0
  11. package/cjs/lib/Addon/index.js +50 -0
  12. package/cjs/lib/Addon/keyed-db.d.ts +14 -0
  13. package/cjs/lib/Addon/keyed-db.js +264 -0
  14. package/cjs/lib/Addon/link-preview.d.ts +15 -0
  15. package/cjs/lib/Addon/link-preview.js +104 -0
  16. package/cjs/lib/Defaults/index.d.ts +184 -0
  17. package/cjs/lib/Defaults/index.js +292 -0
  18. package/cjs/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  19. package/cjs/lib/Signal/Group/ciphertext-message.js +37 -0
  20. package/cjs/lib/Signal/Group/group-cipher.d.ts +10 -0
  21. package/cjs/lib/Signal/Group/group-cipher.js +105 -0
  22. package/cjs/lib/Signal/Group/group-session-builder.d.ts +7 -0
  23. package/cjs/lib/Signal/Group/group-session-builder.js +65 -0
  24. package/cjs/lib/Signal/Group/index.d.ts +11 -0
  25. package/cjs/lib/Signal/Group/index.js +67 -0
  26. package/cjs/lib/Signal/Group/keyhelper.d.ts +6 -0
  27. package/cjs/lib/Signal/Group/keyhelper.js +47 -0
  28. package/cjs/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  29. package/cjs/lib/Signal/Group/sender-chain-key.js +51 -0
  30. package/cjs/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  31. package/cjs/lib/Signal/Group/sender-key-distribution-message.js +80 -0
  32. package/cjs/lib/Signal/Group/sender-key-message.d.ts +18 -0
  33. package/cjs/lib/Signal/Group/sender-key-message.js +87 -0
  34. package/cjs/lib/Signal/Group/sender-key-name.d.ts +11 -0
  35. package/cjs/lib/Signal/Group/sender-key-name.js +73 -0
  36. package/cjs/lib/Signal/Group/sender-key-record.d.ts +12 -0
  37. package/cjs/lib/Signal/Group/sender-key-record.js +66 -0
  38. package/cjs/lib/Signal/Group/sender-key-state.d.ts +16 -0
  39. package/cjs/lib/Signal/Group/sender-key-state.js +106 -0
  40. package/cjs/lib/Signal/Group/sender-message-key.d.ts +11 -0
  41. package/cjs/lib/Signal/Group/sender-message-key.js +51 -0
  42. package/cjs/lib/Signal/libsignal.d.ts +54 -0
  43. package/cjs/lib/Signal/libsignal.js +421 -0
  44. package/cjs/lib/Signal/lid-mapping.d.ts +20 -0
  45. package/cjs/lib/Signal/lid-mapping.js +292 -0
  46. package/cjs/lib/Socket/Client/index.d.ts +2 -0
  47. package/cjs/lib/Socket/Client/index.js +23 -0
  48. package/cjs/lib/Socket/Client/types.d.ts +5 -0
  49. package/cjs/lib/Socket/Client/types.js +36 -0
  50. package/cjs/lib/Socket/Client/websocket.d.ts +12 -0
  51. package/cjs/lib/Socket/Client/websocket.js +143 -0
  52. package/cjs/lib/Socket/business.d.ts +387 -0
  53. package/cjs/lib/Socket/business.js +402 -0
  54. package/cjs/lib/Socket/chats.d.ts +144 -0
  55. package/cjs/lib/Socket/chats.js +1118 -0
  56. package/cjs/lib/Socket/communities.d.ts +554 -0
  57. package/cjs/lib/Socket/communities.js +456 -0
  58. package/cjs/lib/Socket/groups.d.ts +286 -0
  59. package/cjs/lib/Socket/groups.js +366 -0
  60. package/cjs/lib/Socket/index.d.ts +522 -0
  61. package/cjs/lib/Socket/index.js +32 -0
  62. package/cjs/lib/Socket/messages-recv.d.ts +326 -0
  63. package/cjs/lib/Socket/messages-recv.js +1670 -0
  64. package/cjs/lib/Socket/messages-send.d.ts +321 -0
  65. package/cjs/lib/Socket/messages-send.js +1252 -0
  66. package/cjs/lib/Socket/mex.d.ts +1 -0
  67. package/cjs/lib/Socket/mex.js +65 -0
  68. package/cjs/lib/Socket/newsletter.d.ts +283 -0
  69. package/cjs/lib/Socket/newsletter.js +243 -0
  70. package/cjs/lib/Socket/socket.d.ts +61 -0
  71. package/cjs/lib/Socket/socket.js +908 -0
  72. package/cjs/lib/Store/index.d.ts +3 -0
  73. package/cjs/lib/Store/index.js +25 -0
  74. package/cjs/lib/Store/make-in-memory-store.d.ts +63 -0
  75. package/cjs/lib/Store/make-in-memory-store.js +431 -0
  76. package/cjs/lib/Store/make-ordered-dictionary.d.ts +12 -0
  77. package/cjs/lib/Store/make-ordered-dictionary.js +101 -0
  78. package/cjs/lib/Store/object-repository.d.ts +10 -0
  79. package/cjs/lib/Store/object-repository.js +49 -0
  80. package/cjs/lib/Transport/crypto.d.ts +6 -0
  81. package/cjs/lib/Transport/crypto.js +107 -0
  82. package/cjs/lib/Transport/curve.d.ts +8 -0
  83. package/cjs/lib/Transport/curve.js +94 -0
  84. package/cjs/lib/Transport/index.d.ts +16 -0
  85. package/cjs/lib/Transport/index.js +67 -0
  86. package/cjs/lib/Transport/internals.d.ts +57 -0
  87. package/cjs/lib/Transport/internals.js +203 -0
  88. package/cjs/lib/Transport/session-builder.d.ts +40 -0
  89. package/cjs/lib/Transport/session-builder.js +169 -0
  90. package/cjs/lib/Transport/session-cipher.d.ts +26 -0
  91. package/cjs/lib/Transport/session-cipher.js +328 -0
  92. package/cjs/lib/Transport/session-record.d.ts +55 -0
  93. package/cjs/lib/Transport/session-record.js +289 -0
  94. package/cjs/lib/Types/Auth.d.ts +1 -0
  95. package/cjs/lib/Types/Auth.js +15 -0
  96. package/cjs/lib/Types/Bussines.d.ts +1 -0
  97. package/cjs/lib/Types/Bussines.js +15 -0
  98. package/cjs/lib/Types/Call.d.ts +1 -0
  99. package/cjs/lib/Types/Call.js +15 -0
  100. package/cjs/lib/Types/Chat.d.ts +1 -0
  101. package/cjs/lib/Types/Chat.js +33 -0
  102. package/cjs/lib/Types/Contact.d.ts +1 -0
  103. package/cjs/lib/Types/Contact.js +15 -0
  104. package/cjs/lib/Types/Events.d.ts +1 -0
  105. package/cjs/lib/Types/Events.js +1 -0
  106. package/cjs/lib/Types/GroupMetadata.d.ts +1 -0
  107. package/cjs/lib/Types/GroupMetadata.js +15 -0
  108. package/cjs/lib/Types/Label.d.ts +2 -0
  109. package/cjs/lib/Types/Label.js +49 -0
  110. package/cjs/lib/Types/LabelAssociation.d.ts +2 -0
  111. package/cjs/lib/Types/LabelAssociation.js +31 -0
  112. package/cjs/lib/Types/Message.d.ts +11 -0
  113. package/cjs/lib/Types/Message.js +58 -0
  114. package/cjs/lib/Types/Mex.d.ts +2 -0
  115. package/cjs/lib/Types/Mex.js +66 -0
  116. package/cjs/lib/Types/Product.d.ts +1 -0
  117. package/cjs/lib/Types/Product.js +15 -0
  118. package/cjs/lib/Types/RichType.d.ts +2 -0
  119. package/cjs/lib/Types/RichType.js +50 -0
  120. package/cjs/lib/Types/Signal.d.ts +1 -0
  121. package/cjs/lib/Types/Signal.js +1 -0
  122. package/cjs/lib/Types/Socket.d.ts +1 -0
  123. package/cjs/lib/Types/Socket.js +1 -0
  124. package/cjs/lib/Types/State.d.ts +5 -0
  125. package/cjs/lib/Types/State.js +83 -0
  126. package/cjs/lib/Types/USync.d.ts +1 -0
  127. package/cjs/lib/Types/USync.js +1 -0
  128. package/cjs/lib/Types/index.d.ts +13 -0
  129. package/cjs/lib/Types/index.js +64 -0
  130. package/cjs/lib/Utils/auth-utils.d.ts +58 -0
  131. package/cjs/lib/Utils/auth-utils.js +275 -0
  132. package/cjs/lib/Utils/browser-utils.d.ts +9 -0
  133. package/cjs/lib/Utils/browser-utils.js +56 -0
  134. package/cjs/lib/Utils/business.d.ts +49 -0
  135. package/cjs/lib/Utils/business.js +259 -0
  136. package/cjs/lib/Utils/chat-utils.d.ts +408 -0
  137. package/cjs/lib/Utils/chat-utils.js +821 -0
  138. package/cjs/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  139. package/cjs/lib/Utils/companion-reg-client-utils.js +71 -0
  140. package/cjs/lib/Utils/crypto.d.ts +39 -0
  141. package/cjs/lib/Utils/crypto.js +155 -0
  142. package/cjs/lib/Utils/decode-wa-message.d.ts +83 -0
  143. package/cjs/lib/Utils/decode-wa-message.js +316 -0
  144. package/cjs/lib/Utils/event-buffer.d.ts +12 -0
  145. package/cjs/lib/Utils/event-buffer.js +605 -0
  146. package/cjs/lib/Utils/generics.d.ts +63 -0
  147. package/cjs/lib/Utils/generics.js +440 -0
  148. package/cjs/lib/Utils/history.d.ts +75 -0
  149. package/cjs/lib/Utils/history.js +153 -0
  150. package/cjs/lib/Utils/identity-change-handler.d.ts +13 -0
  151. package/cjs/lib/Utils/identity-change-handler.js +73 -0
  152. package/cjs/lib/Utils/index.d.ts +24 -0
  153. package/cjs/lib/Utils/index.js +67 -0
  154. package/cjs/lib/Utils/link-preview.d.ts +13 -0
  155. package/cjs/lib/Utils/link-preview.js +87 -0
  156. package/cjs/lib/Utils/logger.d.ts +12 -0
  157. package/cjs/lib/Utils/logger.js +40 -0
  158. package/cjs/lib/Utils/lt-hash.d.ts +6 -0
  159. package/cjs/lib/Utils/lt-hash.js +28 -0
  160. package/cjs/lib/Utils/make-mutex.d.ts +6 -0
  161. package/cjs/lib/Utils/make-mutex.js +58 -0
  162. package/cjs/lib/Utils/message-retry-manager.d.ts +79 -0
  163. package/cjs/lib/Utils/message-retry-manager.js +274 -0
  164. package/cjs/lib/Utils/messages-media.d.ts +134 -0
  165. package/cjs/lib/Utils/messages-media.js +799 -0
  166. package/cjs/lib/Utils/messages.d.ts +47 -0
  167. package/cjs/lib/Utils/messages.js +1667 -0
  168. package/cjs/lib/Utils/noise-handler.d.ts +20 -0
  169. package/cjs/lib/Utils/noise-handler.js +223 -0
  170. package/cjs/lib/Utils/offline-node-processor.d.ts +10 -0
  171. package/cjs/lib/Utils/offline-node-processor.js +60 -0
  172. package/cjs/lib/Utils/pre-key-manager.d.ts +25 -0
  173. package/cjs/lib/Utils/pre-key-manager.js +116 -0
  174. package/cjs/lib/Utils/process-message.d.ts +83 -0
  175. package/cjs/lib/Utils/process-message.js +607 -0
  176. package/cjs/lib/Utils/reporting-utils.d.ts +12 -0
  177. package/cjs/lib/Utils/reporting-utils.js +282 -0
  178. package/cjs/lib/Utils/rich-message-utils.d.ts +48 -0
  179. package/cjs/lib/Utils/rich-message-utils.js +381 -0
  180. package/cjs/lib/Utils/signal.d.ts +82 -0
  181. package/cjs/lib/Utils/signal.js +232 -0
  182. package/cjs/lib/Utils/stanza-ack.d.ts +16 -0
  183. package/cjs/lib/Utils/stanza-ack.js +53 -0
  184. package/cjs/lib/Utils/sync-action-utils.d.ts +2 -0
  185. package/cjs/lib/Utils/sync-action-utils.js +68 -0
  186. package/cjs/lib/Utils/tc-token-utils.d.ts +29 -0
  187. package/cjs/lib/Utils/tc-token-utils.js +182 -0
  188. package/cjs/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
  189. package/cjs/lib/Utils/use-multi-file-auth-state.js +135 -0
  190. package/cjs/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  191. package/cjs/lib/Utils/use-single-file-auth-state.js +115 -0
  192. package/cjs/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  193. package/cjs/lib/Utils/use-sqlite-auth-state.js +140 -0
  194. package/cjs/lib/Utils/validate-connection.d.ts +44 -0
  195. package/cjs/lib/Utils/validate-connection.js +229 -0
  196. package/cjs/lib/WABinary/constants.d.ts +61 -0
  197. package/cjs/lib/WABinary/constants.js +1992 -0
  198. package/cjs/lib/WABinary/decode.d.ts +9 -0
  199. package/cjs/lib/WABinary/decode.js +292 -0
  200. package/cjs/lib/WABinary/encode.d.ts +2 -0
  201. package/cjs/lib/WABinary/encode.js +240 -0
  202. package/cjs/lib/WABinary/generic-utils.d.ts +79 -0
  203. package/cjs/lib/WABinary/generic-utils.js +252 -0
  204. package/cjs/lib/WABinary/index.d.ts +5 -0
  205. package/cjs/lib/WABinary/index.js +29 -0
  206. package/cjs/lib/WABinary/jid-utils.d.ts +28 -0
  207. package/cjs/lib/WABinary/jid-utils.js +151 -0
  208. package/cjs/lib/WABinary/types.d.ts +1 -0
  209. package/cjs/lib/WABinary/types.js +23 -0
  210. package/cjs/lib/WACrypto/appstate-keys.js +39 -0
  211. package/cjs/lib/WACrypto/curves/constants.js +37 -0
  212. package/cjs/lib/WACrypto/hkdf.js +38 -0
  213. package/cjs/lib/WACrypto/index.js +51 -0
  214. package/cjs/lib/WACrypto/lthash.js +59 -0
  215. package/cjs/lib/WACrypto/math/constants.js +53 -0
  216. package/cjs/lib/WACrypto/math/edwards.js +206 -0
  217. package/cjs/lib/WACrypto/math/fe.js +449 -0
  218. package/cjs/lib/WACrypto/math/le.js +44 -0
  219. package/cjs/lib/WACrypto/math/mod.js +36 -0
  220. package/cjs/lib/WACrypto/util/bytes.js +348 -0
  221. package/cjs/lib/WACrypto/x25519.js +157 -0
  222. package/cjs/lib/WACrypto/xeddsa.js +134 -0
  223. package/cjs/lib/WAM/BinaryInfo.d.ts +7 -0
  224. package/cjs/lib/WAM/BinaryInfo.js +35 -0
  225. package/cjs/lib/WAM/constants.d.ts +34926 -0
  226. package/cjs/lib/WAM/constants.js +22890 -0
  227. package/cjs/lib/WAM/encode.d.ts +1 -0
  228. package/cjs/lib/WAM/encode.js +162 -0
  229. package/cjs/lib/WAM/index.d.ts +3 -0
  230. package/cjs/lib/WAM/index.js +25 -0
  231. package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  232. package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.js +77 -0
  233. package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  234. package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.js +76 -0
  235. package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  236. package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +52 -0
  237. package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  238. package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.js +61 -0
  239. package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  240. package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.js +50 -0
  241. package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  242. package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +76 -0
  243. package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  244. package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.js +53 -0
  245. package/cjs/lib/WAUSync/Protocols/index.d.ts +5 -0
  246. package/cjs/lib/WAUSync/Protocols/index.js +29 -0
  247. package/cjs/lib/WAUSync/USyncQuery.d.ts +20 -0
  248. package/cjs/lib/WAUSync/USyncQuery.js +113 -0
  249. package/cjs/lib/WAUSync/USyncUser.d.ts +16 -0
  250. package/cjs/lib/WAUSync/USyncUser.js +56 -0
  251. package/cjs/lib/WAUSync/index.d.ts +3 -0
  252. package/cjs/lib/WAUSync/index.js +25 -0
  253. package/cjs/lib/index.d.ts +11 -0
  254. package/cjs/lib/index.js +56 -0
  255. package/cjs/package.json +3 -0
  256. package/engine-requirements.js +12 -0
  257. package/lib/Addon/http-error.d.ts +18 -0
  258. package/lib/Addon/http-error.js +40 -0
  259. package/lib/Addon/index.d.ts +3 -0
  260. package/lib/Addon/index.js +4 -0
  261. package/lib/Addon/keyed-db.d.ts +14 -0
  262. package/lib/Addon/keyed-db.js +241 -0
  263. package/lib/Addon/link-preview.d.ts +15 -0
  264. package/lib/Addon/link-preview.js +79 -0
  265. package/lib/Defaults/index.d.ts +184 -0
  266. package/lib/Defaults/index.js +181 -0
  267. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  268. package/lib/Signal/Group/ciphertext-message.js +11 -0
  269. package/lib/Signal/Group/group-cipher.d.ts +10 -0
  270. package/lib/Signal/Group/group-cipher.js +81 -0
  271. package/lib/Signal/Group/group-session-builder.d.ts +7 -0
  272. package/lib/Signal/Group/group-session-builder.js +29 -0
  273. package/lib/Signal/Group/index.d.ts +11 -0
  274. package/lib/Signal/Group/index.js +11 -0
  275. package/lib/Signal/Group/keyhelper.d.ts +6 -0
  276. package/lib/Signal/Group/keyhelper.js +17 -0
  277. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  278. package/lib/Signal/Group/sender-chain-key.js +25 -0
  279. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  280. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  281. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  282. package/lib/Signal/Group/sender-key-message.js +65 -0
  283. package/lib/Signal/Group/sender-key-name.d.ts +11 -0
  284. package/lib/Signal/Group/sender-key-name.js +47 -0
  285. package/lib/Signal/Group/sender-key-record.d.ts +12 -0
  286. package/lib/Signal/Group/sender-key-record.js +40 -0
  287. package/lib/Signal/Group/sender-key-state.d.ts +16 -0
  288. package/lib/Signal/Group/sender-key-state.js +83 -0
  289. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  290. package/lib/Signal/Group/sender-message-key.js +25 -0
  291. package/lib/Signal/libsignal.d.ts +54 -0
  292. package/lib/Signal/libsignal.js +426 -0
  293. package/lib/Signal/lid-mapping.d.ts +20 -0
  294. package/lib/Signal/lid-mapping.js +274 -0
  295. package/lib/Socket/Client/index.d.ts +2 -0
  296. package/lib/Socket/Client/index.js +2 -0
  297. package/lib/Socket/Client/types.d.ts +5 -0
  298. package/lib/Socket/Client/types.js +10 -0
  299. package/lib/Socket/Client/websocket.d.ts +12 -0
  300. package/lib/Socket/Client/websocket.js +119 -0
  301. package/lib/Socket/business.d.ts +387 -0
  302. package/lib/Socket/business.js +379 -0
  303. package/lib/Socket/chats.d.ts +144 -0
  304. package/lib/Socket/chats.js +1216 -0
  305. package/lib/Socket/communities.d.ts +554 -0
  306. package/lib/Socket/communities.js +431 -0
  307. package/lib/Socket/groups.d.ts +286 -0
  308. package/lib/Socket/groups.js +347 -0
  309. package/lib/Socket/index.d.ts +522 -0
  310. package/lib/Socket/index.js +11 -0
  311. package/lib/Socket/messages-recv.d.ts +326 -0
  312. package/lib/Socket/messages-recv.js +1822 -0
  313. package/lib/Socket/messages-send.d.ts +321 -0
  314. package/lib/Socket/messages-send.js +1378 -0
  315. package/lib/Socket/mex.d.ts +1 -0
  316. package/lib/Socket/mex.js +41 -0
  317. package/lib/Socket/newsletter.d.ts +283 -0
  318. package/lib/Socket/newsletter.js +225 -0
  319. package/lib/Socket/socket.d.ts +61 -0
  320. package/lib/Socket/socket.js +992 -0
  321. package/lib/Store/index.d.ts +3 -0
  322. package/lib/Store/index.js +3 -0
  323. package/lib/Store/make-in-memory-store.d.ts +63 -0
  324. package/lib/Store/make-in-memory-store.js +419 -0
  325. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  326. package/lib/Store/make-ordered-dictionary.js +78 -0
  327. package/lib/Store/object-repository.d.ts +10 -0
  328. package/lib/Store/object-repository.js +23 -0
  329. package/lib/Transport/crypto.d.ts +6 -0
  330. package/lib/Transport/crypto.js +61 -0
  331. package/lib/Transport/curve.d.ts +8 -0
  332. package/lib/Transport/curve.js +66 -0
  333. package/lib/Transport/index.d.ts +16 -0
  334. package/lib/Transport/index.js +9 -0
  335. package/lib/Transport/internals.d.ts +57 -0
  336. package/lib/Transport/internals.js +155 -0
  337. package/lib/Transport/session-builder.d.ts +40 -0
  338. package/lib/Transport/session-builder.js +143 -0
  339. package/lib/Transport/session-cipher.d.ts +26 -0
  340. package/lib/Transport/session-cipher.js +301 -0
  341. package/lib/Transport/session-record.d.ts +55 -0
  342. package/lib/Transport/session-record.js +272 -0
  343. package/lib/Types/Auth.d.ts +1 -0
  344. package/lib/Types/Auth.js +1 -0
  345. package/lib/Types/Bussines.d.ts +1 -0
  346. package/lib/Types/Bussines.js +1 -0
  347. package/lib/Types/Call.d.ts +1 -0
  348. package/lib/Types/Call.js +1 -0
  349. package/lib/Types/Chat.d.ts +1 -0
  350. package/lib/Types/Chat.js +7 -0
  351. package/lib/Types/Contact.d.ts +1 -0
  352. package/lib/Types/Contact.js +1 -0
  353. package/lib/Types/Events.d.ts +1 -0
  354. package/lib/Types/Events.js +1 -0
  355. package/lib/Types/GroupMetadata.d.ts +1 -0
  356. package/lib/Types/GroupMetadata.js +1 -0
  357. package/lib/Types/Label.d.ts +2 -0
  358. package/lib/Types/Label.js +24 -0
  359. package/lib/Types/LabelAssociation.d.ts +2 -0
  360. package/lib/Types/LabelAssociation.js +6 -0
  361. package/lib/Types/Message.d.ts +11 -0
  362. package/lib/Types/Message.js +17 -0
  363. package/lib/Types/Mex.d.ts +2 -0
  364. package/lib/Types/Mex.js +38 -0
  365. package/lib/Types/Product.d.ts +1 -0
  366. package/lib/Types/Product.js +1 -0
  367. package/lib/Types/RichType.d.ts +2 -0
  368. package/lib/Types/RichType.js +22 -0
  369. package/lib/Types/Signal.d.ts +1 -0
  370. package/lib/Types/Signal.js +1 -0
  371. package/lib/Types/Socket.d.ts +1 -0
  372. package/lib/Types/Socket.js +1 -0
  373. package/lib/Types/State.d.ts +5 -0
  374. package/lib/Types/State.js +54 -0
  375. package/lib/Types/USync.d.ts +1 -0
  376. package/lib/Types/USync.js +1 -0
  377. package/lib/Types/index.d.ts +13 -0
  378. package/lib/Types/index.js +25 -0
  379. package/lib/Utils/auth-utils.d.ts +58 -0
  380. package/lib/Utils/auth-utils.js +316 -0
  381. package/lib/Utils/browser-utils.d.ts +9 -0
  382. package/lib/Utils/browser-utils.js +28 -0
  383. package/lib/Utils/business.d.ts +49 -0
  384. package/lib/Utils/business.js +230 -0
  385. package/lib/Utils/chat-utils.d.ts +408 -0
  386. package/lib/Utils/chat-utils.js +871 -0
  387. package/lib/Utils/companion-reg-client-utils.d.ts +4 -0
  388. package/lib/Utils/companion-reg-client-utils.js +39 -0
  389. package/lib/Utils/crypto.d.ts +39 -0
  390. package/lib/Utils/crypto.js +117 -0
  391. package/lib/Utils/decode-wa-message.d.ts +83 -0
  392. package/lib/Utils/decode-wa-message.js +316 -0
  393. package/lib/Utils/event-buffer.d.ts +12 -0
  394. package/lib/Utils/event-buffer.js +621 -0
  395. package/lib/Utils/generics.d.ts +63 -0
  396. package/lib/Utils/generics.js +394 -0
  397. package/lib/Utils/history.d.ts +75 -0
  398. package/lib/Utils/history.js +133 -0
  399. package/lib/Utils/identity-change-handler.d.ts +13 -0
  400. package/lib/Utils/identity-change-handler.js +48 -0
  401. package/lib/Utils/index.d.ts +24 -0
  402. package/lib/Utils/index.js +24 -0
  403. package/lib/Utils/link-preview.d.ts +13 -0
  404. package/lib/Utils/link-preview.js +73 -0
  405. package/lib/Utils/logger.d.ts +12 -0
  406. package/lib/Utils/logger.js +12 -0
  407. package/lib/Utils/lt-hash.d.ts +6 -0
  408. package/lib/Utils/lt-hash.js +7 -0
  409. package/lib/Utils/make-mutex.d.ts +6 -0
  410. package/lib/Utils/make-mutex.js +32 -0
  411. package/lib/Utils/message-retry-manager.d.ts +79 -0
  412. package/lib/Utils/message-retry-manager.js +259 -0
  413. package/lib/Utils/messages-media.d.ts +134 -0
  414. package/lib/Utils/messages-media.js +802 -0
  415. package/lib/Utils/messages.d.ts +47 -0
  416. package/lib/Utils/messages.js +1911 -0
  417. package/lib/Utils/noise-handler.d.ts +20 -0
  418. package/lib/Utils/noise-handler.js +200 -0
  419. package/lib/Utils/offline-node-processor.d.ts +10 -0
  420. package/lib/Utils/offline-node-processor.js +40 -0
  421. package/lib/Utils/pre-key-manager.d.ts +25 -0
  422. package/lib/Utils/pre-key-manager.js +105 -0
  423. package/lib/Utils/process-message.d.ts +83 -0
  424. package/lib/Utils/process-message.js +748 -0
  425. package/lib/Utils/reporting-utils.d.ts +12 -0
  426. package/lib/Utils/reporting-utils.js +257 -0
  427. package/lib/Utils/rich-message-utils.d.ts +48 -0
  428. package/lib/Utils/rich-message-utils.js +369 -0
  429. package/lib/Utils/signal.d.ts +82 -0
  430. package/lib/Utils/signal.js +200 -0
  431. package/lib/Utils/stanza-ack.d.ts +16 -0
  432. package/lib/Utils/stanza-ack.js +37 -0
  433. package/lib/Utils/sync-action-utils.d.ts +2 -0
  434. package/lib/Utils/sync-action-utils.js +48 -0
  435. package/lib/Utils/tc-token-utils.d.ts +29 -0
  436. package/lib/Utils/tc-token-utils.js +163 -0
  437. package/lib/Utils/use-multi-file-auth-state.d.ts +10 -0
  438. package/lib/Utils/use-multi-file-auth-state.js +116 -0
  439. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  440. package/lib/Utils/use-single-file-auth-state.js +94 -0
  441. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  442. package/lib/Utils/use-sqlite-auth-state.js +109 -0
  443. package/lib/Utils/validate-connection.d.ts +44 -0
  444. package/lib/Utils/validate-connection.js +210 -0
  445. package/lib/WABinary/constants.d.ts +61 -0
  446. package/lib/WABinary/constants.js +1466 -0
  447. package/lib/WABinary/decode.d.ts +9 -0
  448. package/lib/WABinary/decode.js +261 -0
  449. package/lib/WABinary/encode.d.ts +2 -0
  450. package/lib/WABinary/encode.js +219 -0
  451. package/lib/WABinary/generic-utils.d.ts +79 -0
  452. package/lib/WABinary/generic-utils.js +228 -0
  453. package/lib/WABinary/index.d.ts +5 -0
  454. package/lib/WABinary/index.js +5 -0
  455. package/lib/WABinary/jid-utils.d.ts +28 -0
  456. package/lib/WABinary/jid-utils.js +95 -0
  457. package/lib/WABinary/types.d.ts +1 -0
  458. package/lib/WABinary/types.js +1 -0
  459. package/lib/WACrypto/appstate-keys.js +26 -0
  460. package/lib/WACrypto/curves/constants.js +12 -0
  461. package/lib/WACrypto/hkdf.js +27 -0
  462. package/lib/WACrypto/index.js +20 -0
  463. package/lib/WACrypto/lthash.js +54 -0
  464. package/lib/WACrypto/math/constants.js +24 -0
  465. package/lib/WACrypto/math/edwards.js +194 -0
  466. package/lib/WACrypto/math/fe.js +698 -0
  467. package/lib/WACrypto/math/le.js +23 -0
  468. package/lib/WACrypto/math/mod.js +15 -0
  469. package/lib/WACrypto/util/bytes.js +339 -0
  470. package/lib/WACrypto/x25519.js +145 -0
  471. package/lib/WACrypto/xeddsa.js +92 -0
  472. package/lib/WAM/BinaryInfo.d.ts +7 -0
  473. package/lib/WAM/BinaryInfo.js +9 -0
  474. package/lib/WAM/constants.d.ts +34926 -0
  475. package/lib/WAM/constants.js +22852 -0
  476. package/lib/WAM/encode.d.ts +1 -0
  477. package/lib/WAM/encode.js +149 -0
  478. package/lib/WAM/index.d.ts +3 -0
  479. package/lib/WAM/index.js +3 -0
  480. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  481. package/lib/WAUSync/Protocols/USyncContactProtocol.js +51 -0
  482. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  483. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  484. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  485. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  486. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  487. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  488. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  489. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  490. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  491. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  492. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  493. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  494. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  495. package/lib/WAUSync/Protocols/index.js +5 -0
  496. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  497. package/lib/WAUSync/USyncQuery.js +97 -0
  498. package/lib/WAUSync/USyncUser.d.ts +16 -0
  499. package/lib/WAUSync/USyncUser.js +30 -0
  500. package/lib/WAUSync/index.d.ts +3 -0
  501. package/lib/WAUSync/index.js +3 -0
  502. package/lib/index.d.ts +11 -0
  503. package/lib/index.js +11 -0
  504. package/package.json +79 -5
@@ -0,0 +1,1911 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { promises as fs } from 'node:fs';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { HttpError, createZip, detectFileType } from '../Addon/index.js';
5
+ import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, DONATE_URL, LIBRARY_NAME, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
+ import { AssociationType, ButtonHeaderType, ButtonType, CarouselCardType, ListType, ProtocolType, WAMessageStatus, WAProto } from '../Types/index.js';
7
+ import { isLidUser, isPnUser, isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
8
+ import { sha256 } from './crypto.js';
9
+ import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
10
+ import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioData, getImageProcessingLibrary, getRawMediaUploadData, getStream, toBuffer } from './messages-media.js';
11
+ import { prepareRichResponseMessage } from './rich-message-utils.js';
12
+ import { shouldIncludeReportingToken } from './reporting-utils.js';
13
+ const MIMETYPE_MAP = {
14
+ image: 'image/jpeg',
15
+ video: 'video/mp4',
16
+ document: 'application/pdf',
17
+ audio: 'audio/ogg; codecs=opus',
18
+ sticker: 'image/webp',
19
+ 'product-catalog-image': 'image/jpeg'
20
+ };
21
+ /**
22
+ * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
23
+ * @param text eg. hello https://google.com
24
+ * @returns the URL, eg. https://google.com
25
+ */
26
+ export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
27
+ export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
28
+ const url = extractUrlFromText(text);
29
+ if (!!getUrlInfo && url) {
30
+ try {
31
+ const urlInfo = await getUrlInfo(url);
32
+ return urlInfo;
33
+ }
34
+ catch (error) {
35
+ // ignore if fails
36
+ logger?.warn({ trace: error.stack }, 'url generation failed');
37
+ }
38
+ }
39
+ };
40
+ const ensureMessageProto = (m) => {
41
+ if (m instanceof WAProto.Message)
42
+ return m;
43
+ return WAProto.Message.fromObject(m);
44
+ };
45
+ const assertColor = (color) => {
46
+ if (typeof color === 'number') {
47
+ return color < 0
48
+ ? 0xffffffff + color + 1
49
+ : color;
50
+ }
51
+ let hex = color.trim();
52
+ if (hex.charCodeAt(0) === 35) {
53
+ hex = hex.slice(1);
54
+ }
55
+ if (hex.length <= 6) {
56
+ hex = hex.padStart(6, '0');
57
+ hex = 'FF' + hex;
58
+ }
59
+ return parseInt(hex, 16);
60
+ };
61
+ export const prepareWAMessageMedia = async (message, options) => {
62
+ const logger = options.logger;
63
+ let mediaType;
64
+ for (const key of MEDIA_KEYS) {
65
+ if (key in message) {
66
+ mediaType = key;
67
+ break;
68
+ }
69
+ }
70
+ if (!mediaType) {
71
+ throw new HttpError('Invalid media type', { statusCode: 400 });
72
+ }
73
+ const uploadData = {
74
+ ...message,
75
+ media: message[mediaType]
76
+ };
77
+ delete uploadData[mediaType];
78
+ // check if cacheable + generate cache key
79
+ const cacheableKey = typeof uploadData.media === 'object' &&
80
+ 'url' in uploadData.media &&
81
+ !!uploadData.media.url &&
82
+ !!options.mediaCache &&
83
+ mediaType + ':' + uploadData.media.url.toString();
84
+ if (mediaType === 'document' && !uploadData.fileName) {
85
+ uploadData.fileName = LIBRARY_NAME;
86
+ }
87
+ if (cacheableKey) {
88
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
89
+ if (mediaBuff) {
90
+ logger?.debug({ cacheableKey }, 'got media cache hit');
91
+ const obj = proto.Message.decode(mediaBuff);
92
+ const key = `${mediaType}Message`;
93
+ Object.assign(obj[key], { ...uploadData, media: undefined });
94
+ return obj;
95
+ }
96
+ }
97
+ const isNewsletter = isJidNewsletter(options.jid);
98
+ const requiresMimetypeDetection = uploadData.mimetype == null;
99
+ const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && uploadData.jpegThumbnail == null;
100
+ const requiresDurationComputation = mediaType === 'audio' && uploadData.seconds == null;
101
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && uploadData.waveform == null;
102
+ const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
103
+ if (isNewsletter) {
104
+ logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
105
+ const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
106
+ const fileSha256B64 = fileSha256.toString('base64');
107
+ const [{ mediaUrl, directPath, thumbnailDirectPath, thumbnailSha256 }] = await Promise.all([
108
+ (async () => {
109
+ const result = await options.upload(filePath, {
110
+ fileEncSha256B64: fileSha256B64,
111
+ mediaType: mediaType,
112
+ timeoutMs: options.mediaUploadTimeoutMs,
113
+ newsletter: isNewsletter
114
+ });
115
+ logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
116
+ return result;
117
+ })(),
118
+ (async () => {
119
+ try {
120
+ if (requiresMimetypeDetection) {
121
+ const { mime } = uploadData.ptt === true ? { mime: MIMETYPE_MAP['audio'] } : (await detectFileType(filePath));
122
+ uploadData.mimetype = mime || MIMETYPE_MAP[mediaType];
123
+ logger?.debug('detected media mime');
124
+ }
125
+ if (requiresDurationComputation || requiresWaveformProcessing) {
126
+ const computedData = await getAudioData(filePath, logger);
127
+ uploadData.seconds = computedData.durationSeconds;
128
+ uploadData.waveform = computedData.waveform;
129
+ logger?.debug('computed audio data');
130
+ }
131
+ if (requiresAudioBackground) {
132
+ uploadData.backgroundArgb = assertColor(options.backgroundColor);
133
+ logger?.debug('computed backgroundColor audio');
134
+ }
135
+ }
136
+ catch (error) {
137
+ logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
138
+ }
139
+ })()
140
+ ]).finally(async () => {
141
+ try {
142
+ await fs.unlink(filePath);
143
+ logger?.debug('removed tmp files');
144
+ }
145
+ catch (error) {
146
+ logger?.warn('failed to remove tmp file');
147
+ }
148
+ });
149
+ const obj = ensureMessageProto({
150
+ // todo: add more support here
151
+ [`${mediaType}Message`]: {
152
+ url: mediaUrl,
153
+ directPath,
154
+ fileSha256,
155
+ fileLength,
156
+ thumbnailDirectPath,
157
+ thumbnailSha256,
158
+ ...uploadData,
159
+ media: undefined
160
+ }
161
+ });
162
+ if (uploadData.ptv) {
163
+ obj.ptvMessage = obj.videoMessage;
164
+ delete obj.videoMessage;
165
+ }
166
+ if (obj.stickerMessage) {
167
+ obj.stickerMessage.stickerSentTs = Date.now();
168
+ }
169
+ if (cacheableKey) {
170
+ logger?.debug({ cacheableKey }, 'set cache');
171
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
172
+ }
173
+ return obj;
174
+ }
175
+ const requiresOriginalForSomeProcessing = requiresMimetypeDetection || requiresDurationComputation || requiresWaveformProcessing || requiresThumbnailComputation;
176
+ const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
177
+ logger,
178
+ saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
179
+ opts: options.options
180
+ });
181
+ const fileEncSha256B64 = fileEncSha256.toString('base64');
182
+ const [{ mediaUrl, directPath }] = await Promise.all([
183
+ (async () => {
184
+ const result = await options.upload(encFilePath, {
185
+ fileEncSha256B64,
186
+ mediaType,
187
+ timeoutMs: options.mediaUploadTimeoutMs
188
+ });
189
+ logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
190
+ return result;
191
+ })(),
192
+ (async () => {
193
+ try {
194
+ if (requiresThumbnailComputation) {
195
+ const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options);
196
+ uploadData.jpegThumbnail = thumbnail;
197
+ if (!uploadData.width && originalImageDimensions) {
198
+ uploadData.width = originalImageDimensions.width;
199
+ uploadData.height = originalImageDimensions.height;
200
+ logger?.debug('set dimensions');
201
+ }
202
+ logger?.debug('generated thumbnail');
203
+ }
204
+ if (requiresMimetypeDetection) {
205
+ const { mime } = uploadData.ptt === true ? { mime: MIMETYPE_MAP['audio'] } : (await detectFileType(originalFilePath));
206
+ uploadData.mimetype = mime || MIMETYPE_MAP[mediaType];
207
+ logger?.debug('detected media mime');
208
+ }
209
+ if (requiresDurationComputation || requiresWaveformProcessing) {
210
+ const computedData = await getAudioData(originalFilePath, logger);
211
+ uploadData.seconds = computedData.durationSeconds;
212
+ uploadData.waveform = computedData.waveform;
213
+ logger?.debug('computed audio data');
214
+ }
215
+ if (requiresAudioBackground) {
216
+ uploadData.backgroundArgb = assertColor(options.backgroundColor);
217
+ logger?.debug('computed backgroundColor audio');
218
+ }
219
+ }
220
+ catch (error) {
221
+ logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
222
+ }
223
+ })()
224
+ ]).finally(async () => {
225
+ try {
226
+ await fs.unlink(encFilePath);
227
+ if (originalFilePath) {
228
+ await fs.unlink(originalFilePath);
229
+ }
230
+ logger?.debug('removed tmp files');
231
+ }
232
+ catch (error) {
233
+ logger?.warn('failed to remove tmp file');
234
+ }
235
+ });
236
+ const obj = ensureMessageProto({
237
+ [`${mediaType}Message`]: {
238
+ url: mediaUrl,
239
+ directPath,
240
+ mediaKey,
241
+ fileEncSha256,
242
+ fileSha256,
243
+ fileLength,
244
+ mediaKeyTimestamp: unixTimestampSeconds(),
245
+ ...uploadData,
246
+ media: undefined
247
+ }
248
+ });
249
+ if (uploadData.ptv) {
250
+ obj.ptvMessage = obj.videoMessage;
251
+ delete obj.videoMessage;
252
+ }
253
+ if (cacheableKey) {
254
+ logger?.debug({ cacheableKey }, 'set cache');
255
+ await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
256
+ }
257
+ return obj;
258
+ };
259
+ // Lia@Changes 31-01-26 --- Extract product message into a standalone function so it can also be reused as the header for interactive messages
260
+ const prepareProductMessage = async (message, options) => {
261
+ if (!message.businessOwnerJid) {
262
+ throw new HttpError('"businessOwnerJid" is missing from the content', { statusCode: 400 });
263
+ }
264
+ const { imageMessage } = await prepareWAMessageMedia({ image: message.image || message.product.productImage }, options);
265
+ // Lia@Changes 01-02-26 --- Add product message default value
266
+ const { image, ...content } = message;
267
+ content.product = {
268
+ currencyCode: 'IDR',
269
+ priceAmount1000: 1000,
270
+ title: LIBRARY_NAME,
271
+ ...message.product,
272
+ productImage: imageMessage
273
+ };
274
+ return content;
275
+ };
276
+ /**
277
+ * Lia@Note 30-01-26
278
+ * ---
279
+ * Credits: Work on ensuring stickerPackMessage fields are valid by @jlucaso1 (https://github.com/jlucaso1).
280
+ * based on https://github.com/WhiskeySockets/Baileys/pull/1561
281
+ */
282
+ // Lia@Changes 21-04-26 --- Enhanced prepareStickerPackMessage
283
+ const prepareStickerPackMessage = async (message, options) => {
284
+ const { cover, stickers = [], name = '📦 Sticker Pack', publisher = 'GitHub: itsliaaa', description = '🏷️ itsliaaa/baileys' } = message;
285
+ if (stickers.length > 60) {
286
+ throw new HttpError('Sticker pack exceeds the maximum limit of 60 stickers', { statusCode: 400 });
287
+ }
288
+ if (stickers.length === 0) {
289
+ throw new HttpError('Sticker pack must contain at least one sticker', { statusCode: 400 });
290
+ }
291
+ if (!cover) {
292
+ throw new HttpError('Sticker pack must contain a cover', { statusCode: 400 });
293
+ }
294
+ const logger = options.logger;
295
+ // Lia@Changes 01-02-26 --- Add caching for sticker pack
296
+ let cacheableKey = false;
297
+ if (Array.isArray(stickers) && stickers.length && options.mediaCache) {
298
+ const urls = [];
299
+ for (let i = 0; i < stickers.length; i++) {
300
+ const data = stickers[i].data;
301
+ if (typeof data === 'object' && data?.url) {
302
+ urls.push(data.url);
303
+ }
304
+ }
305
+ if (urls.length > 0) {
306
+ cacheableKey = 'sticker:' + urls.join('@');
307
+ }
308
+ }
309
+ if (cacheableKey) {
310
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
311
+ if (mediaBuff) {
312
+ logger?.debug({ cacheableKey }, 'got media cache hit');
313
+ return proto.Message.decode(mediaBuff);
314
+ }
315
+ }
316
+ const lib = await getImageProcessingLibrary();
317
+ const hasSharp = 'sharp' in lib && !!lib.sharp?.default;
318
+ const hasImage = 'image' in lib && !!lib.image?.Transformer;
319
+ const hasJimp = 'jimp' in lib && !!lib.jimp?.Jimp;
320
+ if (!hasSharp && !hasImage) {
321
+ throw new HttpError('No image processing library (sharp or @napi-rs/image) available for converting sticker to WebP.');
322
+ }
323
+ const isNewsletter = isJidNewsletter(options.jid);
324
+ const stickerPackIdValue = generateMessageIDV2();
325
+ const stickerData = new Array(stickers.length);
326
+ const stickerMetadata = new Array(stickers.length);
327
+ await Promise.all(stickers.map(async (sticker, index) => {
328
+ const { stream } = await getStream(sticker.data);
329
+ const buffer = await toBuffer(stream);
330
+ let webpBuffer;
331
+ let isAnimated = false;
332
+ if (isWebPBuffer(buffer)) {
333
+ webpBuffer = buffer;
334
+ isAnimated = isAnimatedWebP(buffer);
335
+ }
336
+ else if (hasSharp) {
337
+ webpBuffer = await lib.sharp.default(buffer)
338
+ .resize(512, 512, { fit: 'inside' })
339
+ .webp({ quality: 80 })
340
+ .toBuffer();
341
+ }
342
+ else {
343
+ webpBuffer = await new lib.image.Transformer(buffer)
344
+ .resize(512, 512)
345
+ .webp(80);
346
+ }
347
+ if (webpBuffer.length > 1024 * 1024) {
348
+ throw new HttpError(`Sticker at index ${index} exceeds the 1MB size limit`, { statusCode: 400 });
349
+ }
350
+ const hash = sha256(webpBuffer)
351
+ .toString('base64')
352
+ .replace(/\//g, '-');
353
+ const fileName = `${hash}.webp`;
354
+ stickerData[index] = {
355
+ name: fileName,
356
+ data: webpBuffer
357
+ };
358
+ stickerMetadata[index] = {
359
+ fileName,
360
+ mimetype: 'image/webp',
361
+ isAnimated,
362
+ isLottie: sticker.isLottie || false,
363
+ emojis: sticker.emojis || ['✨'],
364
+ accessibilityLabel: sticker.accessibilityLabel || '‎'
365
+ };
366
+ }));
367
+ const trayIconFileName = `${stickerPackIdValue}.webp`;
368
+ const { stream: coverStream } = await getStream(cover);
369
+ const coverBuffer = await toBuffer(coverStream);
370
+ let coverWebpBuffer;
371
+ if (isWebPBuffer(coverBuffer)) {
372
+ coverWebpBuffer = coverBuffer;
373
+ }
374
+ else if (hasSharp) {
375
+ coverWebpBuffer = await lib.sharp.default(coverBuffer)
376
+ .resize(512, 512, { fit: 'inside' })
377
+ .webp({ quality: 80 })
378
+ .toBuffer();
379
+ }
380
+ else {
381
+ coverWebpBuffer = await new lib.image.Transformer(coverBuffer)
382
+ .resize(512, 512)
383
+ .webp(80);
384
+ }
385
+ stickerData[stickers.length] = {
386
+ name: trayIconFileName,
387
+ data: coverWebpBuffer
388
+ };
389
+ const zipBuffer = await createZip(stickerData);
390
+ const { encFilePath, filePath, fileEncSha256, fileSha256, mediaKey, fileLength } = isNewsletter
391
+ ? (await getRawMediaUploadData(zipBuffer, 'sticker-pack', logger))
392
+ : (await encryptedStream(zipBuffer, 'sticker-pack', {
393
+ logger,
394
+ opts: options.options
395
+ }));
396
+ let stickerPackUploadResult;
397
+ try {
398
+ stickerPackUploadResult = await options.upload(encFilePath || filePath, {
399
+ fileEncSha256B64: (fileEncSha256 || fileSha256).toString('base64'),
400
+ mediaType: 'sticker-pack',
401
+ timeoutMs: options.mediaUploadTimeoutMs,
402
+ newsletter: isNewsletter
403
+ });
404
+ }
405
+ finally {
406
+ await fs.unlink(encFilePath || filePath).catch(() => logger?.warn('failed to remove tmp file'));
407
+ }
408
+ const obj = {
409
+ name,
410
+ publisher,
411
+ stickerPackId: stickerPackIdValue,
412
+ packDescription: description,
413
+ stickerPackOrigin: proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED,
414
+ stickerPackSize: zipBuffer.length,
415
+ stickers: stickerMetadata,
416
+ fileSha256,
417
+ fileEncSha256,
418
+ mediaKey,
419
+ directPath: stickerPackUploadResult.directPath,
420
+ fileLength,
421
+ mediaKeyTimestamp: unixTimestampSeconds(),
422
+ trayIconFileName
423
+ };
424
+ try {
425
+ let thumbnailBuffer;
426
+ if (hasSharp) {
427
+ thumbnailBuffer = await lib.sharp.default(coverBuffer).resize(252, 252).jpeg().toBuffer();
428
+ }
429
+ else if (hasImage) {
430
+ thumbnailBuffer = await new lib.image.Transformer(coverBuffer).resize(252, 252).jpeg();
431
+ }
432
+ else if (hasJimp) {
433
+ const jimpImage = await lib.jimp.Jimp.read(coverBuffer);
434
+ thumbnailBuffer = await jimpImage.resize({ w: 252, h: 252 }).getBuffer('image/jpeg');
435
+ }
436
+ else {
437
+ throw new Error('No image processing library available for thumbnail generation');
438
+ }
439
+ if (!thumbnailBuffer || thumbnailBuffer.length === 0) {
440
+ throw new Error('Failed to generate thumbnail buffer');
441
+ }
442
+ const thumbUpload = isNewsletter
443
+ ? (await await getRawMediaUploadData(thumbnailBuffer, 'thumbnail-sticker-pack', logger))
444
+ : (await encryptedStream(thumbnailBuffer, 'thumbnail-sticker-pack', {
445
+ logger,
446
+ opts: options.options,
447
+ mediaKey
448
+ }));
449
+ let thumbUploadResult;
450
+ try {
451
+ thumbUploadResult = await options.upload(thumbUpload.encFilePath || thumbUpload.filePath, {
452
+ fileEncSha256B64: (thumbUpload.fileEncSha256 || thumbUpload.fileSha256).toString('base64'),
453
+ mediaType: 'thumbnail-sticker-pack',
454
+ timeoutMs: options.mediaUploadTimeoutMs,
455
+ newsletter: isNewsletter
456
+ });
457
+ }
458
+ finally {
459
+ await fs.unlink(thumbUpload.encFilePath || thumbUpload.filePath).catch(() => logger?.warn('failed to remove tmp file'));
460
+ }
461
+ Object.assign(obj, {
462
+ thumbnailDirectPath: thumbUploadResult.directPath,
463
+ thumbnailSha256: thumbUpload.fileSha256,
464
+ thumbnailEncSha256: thumbUpload.fileEncSha256,
465
+ thumbnailHeight: 252,
466
+ thumbnailWidth: 252,
467
+ imageDataHash: sha256(thumbnailBuffer).toString('base64')
468
+ });
469
+ }
470
+ catch (error) {
471
+ logger?.warn(`Thumbnail generation failed: ${error}`);
472
+ }
473
+ const payload = ensureMessageProto({ stickerPackMessage: obj });
474
+ if (cacheableKey) {
475
+ logger?.debug({ cacheableKey }, 'set cache (background)');
476
+ options.mediaCache.set(cacheableKey, WAProto.Message.encode(payload).finish());
477
+ }
478
+ return payload;
479
+ };
480
+ // Lia@Changes 30-01-26 --- Add native flow button helper for interactive message
481
+ const prepareNativeFlowButtons = (message) => {
482
+ const buttons = message.nativeFlow;
483
+ const isButtonsFieldArray = Array.isArray(buttons);
484
+ const correctedField = isButtonsFieldArray ? buttons : buttons.buttons;
485
+ const messageParamsJson = {};
486
+ // Lia@Changes 31-01-26 --- Add offer and options inside interactive message
487
+ if (hasOptionalProperty(message, 'offerText') && !!message.offerText) {
488
+ Object.assign(messageParamsJson, {
489
+ limited_time_offer: {
490
+ text: message.offerText || LIBRARY_NAME,
491
+ url: message.offerUrl || DONATE_URL, // Lia@Note 02-02-26 --- Apologies if this feels cheeky, just a fallback
492
+ copy_code: message.offerCode,
493
+ expiration_time: message.offerExpiration
494
+ }
495
+ });
496
+ }
497
+ if (hasOptionalProperty(message, 'optionText') && !!message.optionText) {
498
+ Object.assign(messageParamsJson, {
499
+ bottom_sheet: {
500
+ in_thread_buttons_limit: 1,
501
+ divider_indices: Array.from({ length: correctedField.length }, (_, index) => index),
502
+ list_title: message.optionTitle || '📄 Select Options',
503
+ button_title: message.optionText
504
+ }
505
+ });
506
+ }
507
+ return {
508
+ buttons: correctedField.map(button => {
509
+ const buttonText = button.text || button.buttonText;
510
+ const buttonIcon = button.icon?.toUpperCase();
511
+ if (hasOptionalProperty(button, 'id') && !!button.id) {
512
+ return {
513
+ name: 'quick_reply',
514
+ buttonParamsJson: JSON.stringify({
515
+ display_text: buttonText || '👉🏻 Click',
516
+ id: button.id,
517
+ icon: buttonIcon
518
+ })
519
+ };
520
+ }
521
+ else if (hasOptionalProperty(button, 'copy') && !!button.copy) {
522
+ return {
523
+ name: 'cta_copy',
524
+ buttonParamsJson: JSON.stringify({
525
+ display_text: buttonText || '📋 Copy',
526
+ copy_code: button.copy,
527
+ icon: buttonIcon
528
+ })
529
+ };
530
+ }
531
+ else if (hasOptionalProperty(button, 'url') && !!button.url) {
532
+ return {
533
+ name: 'cta_url',
534
+ buttonParamsJson: JSON.stringify({
535
+ display_text: buttonText || '🌐 Visit',
536
+ url: button.url,
537
+ merchant_url: button.url,
538
+ webview_interaction: button.useWebview,
539
+ icon: buttonIcon
540
+ })
541
+ };
542
+ }
543
+ else if (hasOptionalProperty(button, 'call') && !!button.call) {
544
+ return {
545
+ name: 'cta_call',
546
+ buttonParamsJson: JSON.stringify({
547
+ display_text: buttonText || '📞 Call',
548
+ phone_number: button.call,
549
+ icon: buttonIcon
550
+ })
551
+ };
552
+ }
553
+ // Lia@Changes 12-03-26 --- Add "single_select" shortcut \⁠(⁠°⁠o⁠°⁠)⁠/
554
+ else if (hasOptionalProperty(button, 'sections') && !!button.sections) {
555
+ return {
556
+ name: 'single_select',
557
+ buttonParamsJson: JSON.stringify({
558
+ title: buttonText || '📋 Select',
559
+ sections: button.sections,
560
+ icon: buttonIcon
561
+ })
562
+ };
563
+ }
564
+ return button;
565
+ }),
566
+ messageParamsJson: JSON.stringify(messageParamsJson)
567
+ };
568
+ };
569
+ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
570
+ ephemeralExpiration = ephemeralExpiration || 0;
571
+ const content = {
572
+ ephemeralMessage: {
573
+ message: {
574
+ protocolMessage: {
575
+ type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
576
+ ephemeralExpiration
577
+ }
578
+ }
579
+ }
580
+ };
581
+ return ensureMessageProto(content);
582
+ };
583
+ /**
584
+ * Generate forwarded message content like WA does
585
+ * @param message the message to forward
586
+ * @param options.forceForward will show the message as forwarded even if it is from you
587
+ */
588
+ export const generateForwardMessageContent = (message, forceForward) => {
589
+ let content = message.message;
590
+ if (!content) {
591
+ throw new HttpError('no content in message', { statusCode: 400 });
592
+ }
593
+ // hacky copy
594
+ content = normalizeMessageContent(content);
595
+ content = proto.Message.decode(proto.Message.encode(content).finish());
596
+ let key = Object.keys(content)[0];
597
+ let score = content?.[key]?.contextInfo?.forwardingScore || 0;
598
+ score += message.key.fromMe && !forceForward ? 0 : 1;
599
+ if (key === 'conversation') {
600
+ content.extendedTextMessage = { text: content[key] };
601
+ delete content.conversation;
602
+ key = 'extendedTextMessage';
603
+ }
604
+ const key_ = content?.[key];
605
+ if (score > 0) {
606
+ key_.contextInfo = { forwardingScore: score, isForwarded: true };
607
+ }
608
+ else {
609
+ key_.contextInfo = {};
610
+ }
611
+ return content;
612
+ };
613
+ export const hasNonNullishProperty = (message, key) => {
614
+ return message != null &&
615
+ typeof message === 'object' &&
616
+ key in message &&
617
+ message[key] != null;
618
+ };
619
+ export const hasOptionalProperty = (obj, key) => {
620
+ return obj != null &&
621
+ typeof obj === 'object' &&
622
+ key in obj &&
623
+ obj[key] != null;
624
+ };
625
+ // Lia@Changes 06-02-26 --- Validate album message media to avoid bug 👀
626
+ export const hasValidAlbumMedia = (message) => {
627
+ return !!(message.imageMessage ||
628
+ message.videoMessage);
629
+ };
630
+ export const hasValidInteractiveHeader = (message) => {
631
+ return !!(message.imageMessage ||
632
+ message.videoMessage ||
633
+ message.documentMessage ||
634
+ message.productMessage ||
635
+ message.locationMessage);
636
+ };
637
+ // Lia@Changes 30-01-26 --- Validate carousel cards header to avoid bug 👀
638
+ export const hasValidCarouselHeader = (message) => {
639
+ return !!(message.imageMessage ||
640
+ message.videoMessage ||
641
+ message.productMessage);
642
+ };
643
+ export const markViewOnce = (m) => {
644
+ const type = getContentType(m);
645
+ if (!type)
646
+ return;
647
+ const content = m[type];
648
+ if (!content || typeof content !== 'object')
649
+ return;
650
+ const MessageType = WAProto.Message[type.charAt(0).toUpperCase() + type.slice(1)];
651
+ if (!MessageType?.prototype || !('viewOnce' in MessageType.prototype))
652
+ return;
653
+ content.viewOnce = true;
654
+ };
655
+ export const generateWAMessageContent = async (message, options) => {
656
+ var _a, _b;
657
+ let m = {};
658
+ // Lia@Changes 30-01-26 --- Add "raw" boolean to send raw messages directly via generateWAMessage()
659
+ if (hasNonNullishProperty(message, 'raw')) {
660
+ delete message.raw;
661
+ return message;
662
+ }
663
+ // Lia@Changes 09-04-26 --- Add support for code block and table with richResponseMessage
664
+ else if (hasNonNullishProperty(message, 'code') ||
665
+ hasNonNullishProperty(message, 'links') ||
666
+ hasNonNullishProperty(message, 'table') ||
667
+ hasNonNullishProperty(message, 'richResponse')) {
668
+ m = prepareRichResponseMessage(message);
669
+ }
670
+ else if (hasNonNullishProperty(message, 'text')) {
671
+ const extContent = { text: message.text };
672
+ let urlInfo = message.linkPreview;
673
+ if (urlInfo == null) {
674
+ urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
675
+ }
676
+ if (urlInfo) {
677
+ extContent.matchedText = urlInfo['matched-text'];
678
+ extContent.jpegThumbnail = urlInfo.jpegThumbnail;
679
+ extContent.description = urlInfo.description;
680
+ extContent.title = urlInfo.title;
681
+ extContent.previewType = urlInfo.previewType ?? urlInfo['preview-type'] ?? 0;
682
+ extContent.linkPreviewMetadata = urlInfo.linkPreviewMetadata;
683
+ const img = urlInfo.highQualityThumbnail;
684
+ if (img) {
685
+ extContent.thumbnailDirectPath = img.directPath;
686
+ extContent.mediaKey = img.mediaKey;
687
+ extContent.mediaKeyTimestamp = img.mediaKeyTimestamp;
688
+ extContent.thumbnailWidth = img.width;
689
+ extContent.thumbnailHeight = img.height;
690
+ extContent.thumbnailSha256 = img.fileSha256;
691
+ extContent.thumbnailEncSha256 = img.fileEncSha256;
692
+ }
693
+ }
694
+ const customFavicon = message.favicon;
695
+ const favicon = customFavicon && typeof options.upload === 'function'
696
+ ? (await prepareWAMessageMedia({ image: customFavicon }, options)).imageMessage
697
+ : urlInfo?.favicon;
698
+ if (favicon) {
699
+ extContent.faviconMmsMetadata = {
700
+ thumbnailDirectPath: favicon.directPath,
701
+ mediaKey: favicon.mediaKey,
702
+ mediaKeyTimestamp: favicon.mediaKeyTimestamp,
703
+ thumbnailWidth: 32,
704
+ thumbnailHeight: 32,
705
+ thumbnailSha256: favicon.fileSha256,
706
+ thumbnailEncSha256: favicon.fileEncSha256
707
+ };
708
+ }
709
+ if (options.backgroundColor) {
710
+ extContent.backgroundArgb = assertColor(options.backgroundColor);
711
+ }
712
+ if (options.font) {
713
+ extContent.font = options.font;
714
+ }
715
+ m.extendedTextMessage = extContent;
716
+ }
717
+ else if (hasNonNullishProperty(message, 'contacts')) {
718
+ const contactLen = message.contacts.contacts.length;
719
+ if (!contactLen) {
720
+ throw new HttpError('require atleast 1 contact', { statusCode: 400 });
721
+ }
722
+ if (contactLen === 1) {
723
+ m.contactMessage = message.contacts.contacts[0];
724
+ }
725
+ else {
726
+ m.contactsArrayMessage = message.contacts;
727
+ }
728
+ }
729
+ else if (hasNonNullishProperty(message, 'location')) {
730
+ m.locationMessage = message.location;
731
+ }
732
+ else if (hasNonNullishProperty(message, 'react')) {
733
+ if (!message.react.senderTimestampMs) {
734
+ message.react.senderTimestampMs = Date.now();
735
+ }
736
+ m.reactionMessage = message.react;
737
+ }
738
+ else if (hasNonNullishProperty(message, 'delete')) {
739
+ m.protocolMessage = {
740
+ key: message.delete,
741
+ type: WAProto.Message.ProtocolMessage.Type.REVOKE
742
+ };
743
+ }
744
+ else if (hasNonNullishProperty(message, 'forward')) {
745
+ m = generateForwardMessageContent(message.forward, message.force);
746
+ }
747
+ else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
748
+ const exp = typeof message.disappearingMessagesInChat === 'boolean'
749
+ ? message.disappearingMessagesInChat
750
+ ? WA_DEFAULT_EPHEMERAL
751
+ : 0
752
+ : message.disappearingMessagesInChat;
753
+ m = prepareDisappearingMessageSettingContent(exp);
754
+ }
755
+ else if (hasNonNullishProperty(message, 'groupInvite')) {
756
+ m.groupInviteMessage = {};
757
+ m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
758
+ m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
759
+ m.groupInviteMessage.caption = message.groupInvite.text;
760
+ m.groupInviteMessage.groupJid = message.groupInvite.jid;
761
+ m.groupInviteMessage.groupName = message.groupInvite.subject;
762
+ //TODO: use built-in interface and get disappearing mode info etc.
763
+ //TODO: cache / use store!?
764
+ if (options.getProfilePicUrl) {
765
+ const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
766
+ if (pfpUrl) {
767
+ const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
768
+ if (resp.ok) {
769
+ const buf = Buffer.from(await resp.arrayBuffer());
770
+ m.groupInviteMessage.jpegThumbnail = buf;
771
+ }
772
+ }
773
+ }
774
+ }
775
+ else if (hasNonNullishProperty(message, 'pin')) {
776
+ m.pinInChatMessage = {};
777
+ m.messageContextInfo = {};
778
+ m.pinInChatMessage.key = message.pin;
779
+ m.pinInChatMessage.type = message.type;
780
+ m.pinInChatMessage.senderTimestampMs = Date.now();
781
+ m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
782
+ }
783
+ else if (hasNonNullishProperty(message, 'keep')) {
784
+ m.keepInChatMessage = {};
785
+ m.keepInChatMessage.key = message.keep;
786
+ m.keepInChatMessage.keepType = message.type;
787
+ m.keepInChatMessage.timestampMs = Date.now();
788
+ }
789
+ else if (hasNonNullishProperty(message, 'flowReply')) {
790
+ m.interactiveResponseMessage = {
791
+ body: {
792
+ format: message.flowReply.format || proto.Message.InteractiveResponseMessage.Body.Format.DEFAULT,
793
+ text: message.flowReply.text
794
+ },
795
+ nativeFlowResponseMessage: {
796
+ name: message.flowReply.name,
797
+ paramsJson: message.flowReply.paramsJson || '{}',
798
+ version: message.flowReply.version || 1
799
+ }
800
+ };
801
+ }
802
+ else if (hasNonNullishProperty(message, 'buttonReply')) {
803
+ switch (message.type) {
804
+ case 'template':
805
+ m.templateButtonReplyMessage = {
806
+ selectedDisplayText: message.buttonReply.displayText,
807
+ selectedId: message.buttonReply.id,
808
+ selectedIndex: message.buttonReply.index
809
+ };
810
+ break;
811
+ case 'plain':
812
+ m.buttonsResponseMessage = {
813
+ selectedButtonId: message.buttonReply.id,
814
+ selectedDisplayText: message.buttonReply.displayText,
815
+ type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
816
+ };
817
+ break;
818
+ }
819
+ }
820
+ else if (hasNonNullishProperty(message, 'listReply')) {
821
+ m.listResponseMessage = {
822
+ description: message.listReply.description,
823
+ listType: proto.Message.ListResponseMessage.ListType.SINGLE_SELECT,
824
+ singleSelectReply: {
825
+ selectedRowId: message.listReply.id
826
+ },
827
+ title: message.listReply.title
828
+ };
829
+ }
830
+ else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
831
+ const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
832
+ m.ptvMessage = videoMessage;
833
+ }
834
+ else if (hasNonNullishProperty(message, 'product')) {
835
+ m.productMessage = await prepareProductMessage(message, options);
836
+ }
837
+ else if (hasNonNullishProperty(message, 'event')) {
838
+ m.eventMessage = {};
839
+ const startTime = Math.floor(message.event.startDate.getTime() / 1000);
840
+ if (message.event.call && options.getCallLink) {
841
+ const token = await options.getCallLink(message.event.call, { startTime });
842
+ m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
843
+ }
844
+ m.messageContextInfo = {
845
+ // encKey
846
+ messageSecret: message.event.messageSecret || randomBytes(32)
847
+ };
848
+ m.eventMessage.name = message.event.name;
849
+ m.eventMessage.description = message.event.description;
850
+ m.eventMessage.startTime = startTime;
851
+ m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined;
852
+ m.eventMessage.isCanceled = message.event.isCancelled ?? false;
853
+ m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
854
+ m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
855
+ m.eventMessage.location = message.event.location;
856
+ }
857
+ else if (hasNonNullishProperty(message, 'poll')) {
858
+ (_a = message.poll).selectableCount || (_a.selectableCount = 0);
859
+ (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
860
+ if (!Array.isArray(message.poll.values)) {
861
+ throw new HttpError('Invalid poll values', { statusCode: 400 });
862
+ }
863
+ if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
864
+ throw new HttpError(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
865
+ statusCode: 400
866
+ });
867
+ }
868
+ const pollCreationMessage = {
869
+ name: message.poll.name,
870
+ selectableOptionsCount: message.poll.selectableCount,
871
+ options: message.poll.values.map(optionName => ({ optionName })),
872
+ endTime: message.poll.endDate ? message.poll.endDate.getTime() : undefined,
873
+ hideParticipantName: message.poll.hideVoter ?? false,
874
+ allowAddOption: message.poll.canAddOption ?? false
875
+ };
876
+ if (message.poll.toAnnouncementGroup) {
877
+ // poll v2 is for community announcement groups (single select and multiple)
878
+ m.pollCreationMessageV2 = pollCreationMessage;
879
+ }
880
+ else {
881
+ // Lia@Changes 08-02-26 --- Add quiz message support
882
+ if (message.poll.pollType === 1) {
883
+ if (!message.poll.correctAnswer) {
884
+ throw new HttpError('No "correctAnswer" provided for quiz', { statusCode: 400 });
885
+ }
886
+ m.pollCreationMessageV5 = {
887
+ // Lia@Note 08-02-26 --- quiz for newsletter only
888
+ ...pollCreationMessage,
889
+ correctAnswer: {
890
+ optionName: message.poll.correctAnswer.toString()
891
+ },
892
+ pollType: 1,
893
+ selectableOptionsCount: 1
894
+ };
895
+ }
896
+ else if (message.poll.selectableCount === 1) {
897
+ //poll v3 is for single select polls
898
+ m.pollCreationMessageV3 = pollCreationMessage;
899
+ }
900
+ else {
901
+ // poll for multiple choice polls
902
+ m.pollCreationMessage = pollCreationMessage;
903
+ }
904
+ }
905
+ m.messageContextInfo = {
906
+ // encKey
907
+ messageSecret: message.poll.messageSecret || randomBytes(32)
908
+ };
909
+ }
910
+ // Lia@Changes 08-02-26 --- Add poll result snapshot message
911
+ else if (hasNonNullishProperty(message, 'pollResult')) {
912
+ const pollResultSnapshotMessage = {
913
+ name: message.pollResult.name,
914
+ pollVotes: message.pollResult.votes.map(vote => ({
915
+ optionName: vote.name,
916
+ optionVoteCount: parseInt(vote.voteCount)
917
+ }))
918
+ };
919
+ if (message.pollResult.pollType === 1) {
920
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.QUIZ;
921
+ m.pollResultSnapshotMessageV3 = pollResultSnapshotMessage;
922
+ }
923
+ else {
924
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.POLL;
925
+ m.pollResultSnapshotMessage = pollResultSnapshotMessage;
926
+ }
927
+ }
928
+ // Lia@Changes 08-02-26 --- Add poll update message
929
+ else if (hasNonNullishProperty(message, 'pollUpdate')) {
930
+ if (!message.pollUpdate.key) {
931
+ throw new HttpError('Message key is required', { statusCode: 400 });
932
+ }
933
+ if (!message.pollUpdate.vote) {
934
+ throw new HttpError('Encrypted vote payload is required', { statusCode: 400 });
935
+ }
936
+ m.pollUpdateMessage = {
937
+ metadata: message.pollUpdate.metadata,
938
+ pollCreationMessageKey: message.pollUpdate.key,
939
+ senderTimestampMs: Date.now(),
940
+ vote: message.pollUpdate.vote
941
+ };
942
+ }
943
+ // Lia@Changes 01-02-26 --- Add payment invite message
944
+ else if (hasNonNullishProperty(message, 'paymentInviteServiceType')) {
945
+ m.paymentInviteMessage = {
946
+ expiryTimestamp: Date.now(),
947
+ serviceType: message.paymentInviteServiceType
948
+ };
949
+ }
950
+ // Lia@Changes 01-02-26 --- Add order message
951
+ else if (hasNonNullishProperty(message, 'orderText')) {
952
+ if (!Buffer.isBuffer(message.thumbnail)) {
953
+ throw new HttpError('Must provide thumbnail buffer in order message', { statusCode: 400 });
954
+ }
955
+ m.orderMessage = {
956
+ itemCount: 1,
957
+ messageVersion: 1,
958
+ orderTitle: LIBRARY_NAME,
959
+ status: proto.Message.OrderMessage.OrderStatus.INQUIRY,
960
+ surface: proto.Message.OrderMessage.OrderSurface.CATALOG,
961
+ token: generateMessageIDV2(),
962
+ totalAmount1000: 1000,
963
+ totalCurrencyCode: 'IDR',
964
+ ...message,
965
+ message: message.orderText
966
+ };
967
+ delete m.orderMessage.orderText;
968
+ }
969
+ // Lia@Changes 31-01-26 --- Add support for album messages
970
+ else if (hasNonNullishProperty(message, 'album')) {
971
+ if (!Array.isArray(message.album)) {
972
+ throw new HttpError('Invalid album type. Expected an array.', { statusCode: 400 });
973
+ }
974
+ let videoCount = 0;
975
+ for (let i = 0; i < message.album.length; i++) {
976
+ if (message.album[i].video)
977
+ videoCount++;
978
+ }
979
+ ;
980
+ let imageCount = 0;
981
+ for (let i = 0; i < message.album.length; i++) {
982
+ if (message.album[i].image)
983
+ imageCount++;
984
+ }
985
+ ;
986
+ if ((videoCount + imageCount) < 2) {
987
+ throw new HttpError('Minimum provide 2 media to upload album message', { statusCode: 400 });
988
+ }
989
+ m.albumMessage = {
990
+ expectedImageCount: imageCount,
991
+ expectedVideoCount: videoCount
992
+ };
993
+ }
994
+ else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
995
+ m.protocolMessage = {
996
+ type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
997
+ };
998
+ }
999
+ else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
1000
+ m.requestPhoneNumberMessage = {};
1001
+ }
1002
+ else if (hasNonNullishProperty(message, 'limitSharing')) {
1003
+ m.protocolMessage = {
1004
+ type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
1005
+ limitSharing: {
1006
+ sharingLimited: message.limitSharing === true,
1007
+ trigger: 1,
1008
+ limitSharingSettingTimestamp: Date.now(),
1009
+ initiatedByMe: true
1010
+ }
1011
+ };
1012
+ }
1013
+ else if (hasNonNullishProperty(message, 'stickers')) {
1014
+ m = await prepareStickerPackMessage(message, options);
1015
+ }
1016
+ else {
1017
+ m = await prepareWAMessageMedia(message, options);
1018
+ }
1019
+ // Lia@Changes 30-01-26 --- Add interactive messages (buttonsMessage, listMessage, interactiveMessage, templateMessage, and carouselMessage)
1020
+ if (hasNonNullishProperty(message, 'buttons')) {
1021
+ const buttonsMessage = {
1022
+ buttons: message.buttons.map(button => {
1023
+ // Lia@Changes 12-03-26 --- Add "single_select" shortcut!
1024
+ const buttonText = button.text || button.buttonText;
1025
+ if (hasOptionalProperty(button, 'sections')) {
1026
+ return {
1027
+ nativeFlowInfo: {
1028
+ name: 'single_select',
1029
+ paramsJson: JSON.stringify({
1030
+ title: buttonText,
1031
+ sections: button.sections
1032
+ })
1033
+ },
1034
+ type: ButtonType.NATIVE_FLOW
1035
+ };
1036
+ }
1037
+ else if (hasOptionalProperty(button, 'name')) {
1038
+ return {
1039
+ nativeFlowInfo: {
1040
+ name: button.name,
1041
+ paramsJson: button.paramsJson
1042
+ },
1043
+ type: ButtonType.NATIVE_FLOW
1044
+ };
1045
+ }
1046
+ return {
1047
+ buttonId: button.id || button.buttonId,
1048
+ buttonText: typeof buttonText === 'string' ? { displayText: buttonText } : buttonText,
1049
+ type: button.type || ButtonType.RESPONSE
1050
+ };
1051
+ })
1052
+ };
1053
+ if (hasOptionalProperty(message, 'text')) {
1054
+ buttonsMessage.contentText = message.text;
1055
+ buttonsMessage.headerType = ButtonHeaderType.EMPTY;
1056
+ }
1057
+ else {
1058
+ if (hasOptionalProperty(message, 'caption')) {
1059
+ buttonsMessage.contentText = message.caption;
1060
+ }
1061
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1062
+ buttonsMessage.headerType = ButtonHeaderType[type];
1063
+ Object.assign(buttonsMessage, m);
1064
+ }
1065
+ if (hasOptionalProperty(message, 'footer')) {
1066
+ buttonsMessage.footerText = message.footer;
1067
+ }
1068
+ m = { buttonsMessage };
1069
+ }
1070
+ else if (hasNonNullishProperty(message, 'sections')) {
1071
+ const listMessage = {
1072
+ sections: message.sections,
1073
+ buttonText: message.buttonText,
1074
+ title: message.title,
1075
+ footerText: message.footer,
1076
+ description: message.text,
1077
+ listType: ListType.SINGLE_SELECT
1078
+ };
1079
+ m = { listMessage };
1080
+ }
1081
+ // 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 ಥ⁠‿⁠ಥ)
1082
+ else if (hasNonNullishProperty(message, 'templateButtons')) {
1083
+ const hydratedTemplate = {
1084
+ hydratedButtons: message.templateButtons.map((button, i) => {
1085
+ const buttonText = button.text || button.buttonText;
1086
+ if (hasOptionalProperty(button, 'id')) {
1087
+ return {
1088
+ index: i,
1089
+ quickReplyButton: {
1090
+ displayText: buttonText || '👉🏻 Click',
1091
+ id: button.id
1092
+ }
1093
+ };
1094
+ }
1095
+ else if (hasOptionalProperty(button, 'url')) {
1096
+ return {
1097
+ index: i,
1098
+ urlButton: {
1099
+ displayText: buttonText || '🌐 Visit',
1100
+ url: button.url
1101
+ }
1102
+ };
1103
+ }
1104
+ else if (hasOptionalProperty(button, 'call')) {
1105
+ return {
1106
+ index: i,
1107
+ callButton: {
1108
+ displayText: buttonText || '📞 Call',
1109
+ phoneNumber: button.call
1110
+ }
1111
+ };
1112
+ }
1113
+ button.index = button.index || i;
1114
+ return button;
1115
+ })
1116
+ };
1117
+ if (hasOptionalProperty(message, 'text')) {
1118
+ hydratedTemplate.hydratedContentText = message.text;
1119
+ }
1120
+ else {
1121
+ if (hasOptionalProperty(message, 'caption')) {
1122
+ hydratedTemplate.hydratedTitleText = message.title;
1123
+ hydratedTemplate.hydratedContentText = message.caption;
1124
+ }
1125
+ ;
1126
+ Object.assign(hydratedTemplate, m);
1127
+ }
1128
+ if (hasOptionalProperty(message, 'footer')) {
1129
+ hydratedTemplate.hydratedFooterText = message.footer;
1130
+ }
1131
+ hydratedTemplate.templateId = message.id || 'template-' + Date.now(); // Lia@Note 04-02-26 --- Minimal templateId to satisfy WhatsApp (⁠ ⁠ꈍ⁠ᴗ⁠ꈍ⁠)
1132
+ m = {
1133
+ templateMessage: {
1134
+ hydratedFourRowTemplate: hydratedTemplate,
1135
+ hydratedTemplate: hydratedTemplate
1136
+ }
1137
+ };
1138
+ }
1139
+ else if (hasNonNullishProperty(message, 'nativeFlow')) {
1140
+ const interactiveMessage = {
1141
+ nativeFlowMessage: prepareNativeFlowButtons(message)
1142
+ };
1143
+ if (hasOptionalProperty(message, 'bizJid')) {
1144
+ interactiveMessage.collectionMessage = {
1145
+ bizJid: message.bizJid,
1146
+ id: message.id,
1147
+ messageVersion: 1
1148
+ };
1149
+ }
1150
+ else if (hasOptionalProperty(message, 'shopSurface')) {
1151
+ interactiveMessage.shopStorefrontMessage = {
1152
+ surface: message.shopSurface,
1153
+ id: message.id,
1154
+ messageVersion: 1
1155
+ };
1156
+ }
1157
+ if (hasOptionalProperty(message, 'text')) {
1158
+ interactiveMessage.body = { text: message.text };
1159
+ }
1160
+ else {
1161
+ if (hasOptionalProperty(message, 'caption')) {
1162
+ const isValidHeader = hasValidInteractiveHeader(m);
1163
+ if (!isValidHeader) {
1164
+ throw new HttpError('Invalid media type for interactive message header', { statusCode: 400 });
1165
+ }
1166
+ interactiveMessage.header = {
1167
+ title: message.title || '',
1168
+ subtitle: message.subtitle || '',
1169
+ hasMediaAttachment: isValidHeader
1170
+ };
1171
+ interactiveMessage.body = { text: message.caption };
1172
+ }
1173
+ if (hasOptionalProperty(message, 'thumbnail') && !!message.thumbnail) {
1174
+ interactiveMessage.jpegThumbnail = message.thumbnail;
1175
+ }
1176
+ Object.assign(interactiveMessage.header, m);
1177
+ }
1178
+ if (hasOptionalProperty(message, 'audioFooter')) {
1179
+ const { audioMessage } = await prepareWAMessageMedia({
1180
+ audio: message.audioFooter
1181
+ }, options);
1182
+ interactiveMessage.footer = {
1183
+ audioMessage,
1184
+ hasMediaAttachment: true
1185
+ };
1186
+ }
1187
+ else if (hasOptionalProperty(message, 'footer')) {
1188
+ interactiveMessage.footer = { text: message.footer };
1189
+ }
1190
+ m = { interactiveMessage };
1191
+ }
1192
+ else if (hasNonNullishProperty(message, 'cards')) {
1193
+ const interactiveMessage = {
1194
+ carouselMessage: {
1195
+ cards: await Promise.all(message.cards.map(async (card) => {
1196
+ let carouselHeader = {};
1197
+ if (hasNonNullishProperty(card, 'product')) {
1198
+ carouselHeader.productMessage = await prepareProductMessage(card, options);
1199
+ }
1200
+ else {
1201
+ carouselHeader = await prepareWAMessageMedia(card, options).catch(() => ({}));
1202
+ }
1203
+ const isValidHeader = hasValidCarouselHeader(carouselHeader);
1204
+ if (!isValidHeader) {
1205
+ throw new HttpError('Invalid media type for carousel card', { statusCode: 400 });
1206
+ }
1207
+ const carouselCard = {
1208
+ nativeFlowMessage: prepareNativeFlowButtons(card.nativeFlow ? card : [])
1209
+ };
1210
+ if (hasOptionalProperty(card, 'text')) {
1211
+ carouselCard.body = { text: card.text };
1212
+ }
1213
+ else {
1214
+ if (hasOptionalProperty(card, 'caption')) {
1215
+ carouselCard.header = {
1216
+ title: card.title || '',
1217
+ subtitle: card.subtitle || '',
1218
+ hasMediaAttachment: isValidHeader
1219
+ };
1220
+ carouselCard.body = { text: card.caption };
1221
+ }
1222
+ if (hasOptionalProperty(card, 'thumbnail') && !!card.thumbnail) {
1223
+ carouselCard.jpegThumbnail = card.thumbnail;
1224
+ }
1225
+ Object.assign(carouselCard.header, carouselHeader);
1226
+ }
1227
+ if (hasOptionalProperty(card, 'audioFooter')) {
1228
+ const { audioMessage } = await prepareWAMessageMedia({
1229
+ audio: card.audioFooter
1230
+ }, options);
1231
+ carouselCard.footer = {
1232
+ audioMessage,
1233
+ hasMediaAttachment: true
1234
+ };
1235
+ }
1236
+ else if (hasOptionalProperty(card, 'footer')) {
1237
+ carouselCard.footer = { text: card.footer };
1238
+ }
1239
+ return carouselCard;
1240
+ })),
1241
+ carouselCardType: CarouselCardType.UNKNOWN,
1242
+ messageVersion: 1
1243
+ }
1244
+ };
1245
+ if (hasOptionalProperty(message, 'text')) {
1246
+ interactiveMessage.body = { text: message.text };
1247
+ }
1248
+ if (hasOptionalProperty(message, 'footer')) {
1249
+ interactiveMessage.footer = { text: message.footer };
1250
+ }
1251
+ m = { interactiveMessage };
1252
+ }
1253
+ // Lia@Changes 01-02-26 --- Add request payment message
1254
+ else if (hasNonNullishProperty(message, 'requestPaymentFrom')) {
1255
+ const requestPaymentMessage = {
1256
+ amount: {
1257
+ currencyCode: 'IDR',
1258
+ offset: 1000,
1259
+ value: 1000
1260
+ },
1261
+ amount1000: 1000,
1262
+ currencyCodeIso4217: 'IDR',
1263
+ expiryTimestamp: Date.now(),
1264
+ noteMessage: m,
1265
+ requestFrom: message.requestPaymentFrom,
1266
+ ...message
1267
+ };
1268
+ delete requestPaymentMessage.requestPaymentFrom;
1269
+ if (hasNonNullishProperty(m, 'extendedTextMessage') || hasNonNullishProperty(m, 'stickerMessage')) {
1270
+ Object.assign(requestPaymentMessage.noteMessage, m);
1271
+ }
1272
+ else {
1273
+ throw new HttpError('Invalid message type for request payment note message', { statusCode: 400 });
1274
+ }
1275
+ m = { requestPaymentMessage };
1276
+ }
1277
+ // Lia@Changes 01-02-26 --- Add invoice message
1278
+ else if (hasNonNullishProperty(message, 'invoiceNote')) {
1279
+ const attachment = m.imageMessage || m.documentMessage;
1280
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1281
+ const invoiceMessage = {
1282
+ attachmentType: proto.Message.InvoiceMessage.AttachmentType[type === 'DOCUMENT' ? 'PDF' : 'IMAGE'],
1283
+ note: message.invoiceNote
1284
+ };
1285
+ if (attachment) {
1286
+ const { directPath, fileEncSha256, fileSha256, jpegThumbnail = undefined, mediaKey, mediaKeyTimestamp, mimetype } = attachment;
1287
+ Object.assign(invoiceMessage, {
1288
+ attachmentDirectPath: directPath,
1289
+ attachmentFileEncSha256: fileEncSha256,
1290
+ attachmentFileSha256: fileSha256,
1291
+ attachmentJpegThumbnail: jpegThumbnail,
1292
+ attachmentMediaKey: mediaKey,
1293
+ attachmentMediaKeyTimestamp: mediaKeyTimestamp,
1294
+ attachmentMimetype: mimetype,
1295
+ token: generateMessageIDV2()
1296
+ });
1297
+ }
1298
+ else {
1299
+ throw new HttpError('Invalid media type for invoice message', { statusCode: 400 });
1300
+ }
1301
+ m = { invoiceMessage };
1302
+ }
1303
+ // Lia@Changes 31-01-26 --- Add direct externalAdReply access (no need to create contextInfo first)
1304
+ if (hasOptionalProperty(message, 'externalAdReply') && !!message.externalAdReply) {
1305
+ const messageType = Object.keys(m)[0];
1306
+ const key = m[messageType];
1307
+ const content = message.externalAdReply;
1308
+ if ('thumbnail' in content && !Buffer.isBuffer(content.thumbnail)) {
1309
+ throw new HttpError('Thumbnail must in buffer type', { statusCode: 400 });
1310
+ }
1311
+ if (!content.url || typeof content.url !== 'string') {
1312
+ content.url = DONATE_URL; // Lia@Note 02-02-26 --- Apologies if this feels cheeky, just a fallback
1313
+ }
1314
+ const externalAdReply = {
1315
+ ...content,
1316
+ body: content.body,
1317
+ mediaType: content.mediaType || 1,
1318
+ mediaUrl: content.url,
1319
+ renderLargerThumbnail: content.largeThumbnail,
1320
+ sourceUrl: content.url,
1321
+ thumbnail: content.thumbnail,
1322
+ thumbnailUrl: content.url + '?update=' + Date.now(),
1323
+ title: content.title || LIBRARY_NAME
1324
+ };
1325
+ delete externalAdReply.subTitle;
1326
+ delete externalAdReply.largeThumbnail;
1327
+ delete externalAdReply.url;
1328
+ if ('contextInfo' in key && !!key.contextInfo) {
1329
+ key.contextInfo.externalAdReply = { ...key.contextInfo.externalAdReply, ...externalAdReply };
1330
+ }
1331
+ else if (key) {
1332
+ key.contextInfo = { externalAdReply };
1333
+ }
1334
+ }
1335
+ if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
1336
+ (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
1337
+ const messageType = Object.keys(m)[0];
1338
+ const key = m[messageType];
1339
+ if (key && 'contextInfo' in key) {
1340
+ key.contextInfo = key.contextInfo || {};
1341
+ if (message.mentions?.length) {
1342
+ key.contextInfo.mentionedJid = message.mentions;
1343
+ }
1344
+ if (message.mentionAll) {
1345
+ key.contextInfo.nonJidMentions = 1;
1346
+ }
1347
+ }
1348
+ else if (key) {
1349
+ key.contextInfo = {
1350
+ mentionedJid: message.mentions,
1351
+ nonJidMentions: message.mentionAll ? 1 : 0
1352
+ };
1353
+ }
1354
+ }
1355
+ if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
1356
+ const messageType = Object.keys(m)[0];
1357
+ const key = m[messageType];
1358
+ if ('contextInfo' in key && !!key.contextInfo) {
1359
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
1360
+ }
1361
+ else if (key) {
1362
+ key.contextInfo = message.contextInfo;
1363
+ }
1364
+ }
1365
+ // Lia@Changes 31-01-26 --- Add "groupStatus" boolean to set contextInfo.isGroupStatus and wrap message into groupStatusMessageV2
1366
+ if (hasOptionalProperty(message, 'groupStatus') && !!message.groupStatus) {
1367
+ const messageType = Object.keys(m)[0];
1368
+ const key = m[messageType];
1369
+ if ('contextInfo' in key && !!key.contextInfo) {
1370
+ key.contextInfo.isGroupStatus = message.groupStatus;
1371
+ }
1372
+ else if (key) {
1373
+ key.contextInfo = {
1374
+ isGroupStatus: message.groupStatus
1375
+ };
1376
+ }
1377
+ m = { groupStatusMessageV2: { message: m } };
1378
+ delete message.groupStatus;
1379
+ }
1380
+ // Lia@Changes 06-05-26 --- Add "spoiler" boolean to set contextInfo.isSpoiler and wrap message into spoilerMessage
1381
+ if (hasOptionalProperty(message, 'spoiler') && !!message.spoiler) {
1382
+ const messageType = Object.keys(m)[0];
1383
+ const key = m[messageType];
1384
+ if ('contextInfo' in key && !!key.contextInfo) {
1385
+ key.contextInfo.isSpoiler = message.spoiler;
1386
+ }
1387
+ else if (key) {
1388
+ key.contextInfo = {
1389
+ isSpoiler: message.spoiler
1390
+ };
1391
+ }
1392
+ m = { spoilerMessage: { message: m } };
1393
+ delete message.spoiler;
1394
+ }
1395
+ // Lia@Changes 02-02-26 --- Add "interactiveAsTemplate" boolean to wrap interactiveMessage into templateMessage
1396
+ else if (hasOptionalProperty(message, 'interactiveAsTemplate') && !!message.interactiveAsTemplate) {
1397
+ if (!m.interactiveMessage) {
1398
+ throw new HttpError('Invalid message type for template', { statusCode: 400 }); // Lia@Note 02-02-26 --- To avoid bug 👀
1399
+ }
1400
+ m = {
1401
+ templateMessage: {
1402
+ interactiveMessageTemplate: m.interactiveMessage,
1403
+ templateId: message.id || 'template-' + Date.now() // Lia@Note 04-02-26 --- Minimal templateId to satisfy WhatsApp (⁠ ⁠ꈍ⁠ᴗ⁠ꈍ⁠)
1404
+ }
1405
+ };
1406
+ delete message.interactiveAsTemplate;
1407
+ }
1408
+ // Lia@Changes 30-01-26 --- Add "ephemeral" boolean to wrap message into ephemeralMessage like "viewOnce"
1409
+ if (hasOptionalProperty(message, 'ephemeral') && !!message.ephemeral) {
1410
+ m = { ephemeralMessage: { message: m } };
1411
+ delete message.ephemeral;
1412
+ }
1413
+ // Lia@Changes 16-05-26 --- Add wrap message into lottieStickerMessage by isLottie boolean
1414
+ if (hasOptionalProperty(message, 'isLottie') && !!message.isLottie) {
1415
+ m = { lottieStickerMessage: { message: m } };
1416
+ }
1417
+ else if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
1418
+ markViewOnce(m);
1419
+ m = { viewOnceMessage: { message: m } };
1420
+ }
1421
+ // Lia@Changes 03-02-26 --- Add "viewOnceV2" boolean to wrap message into viewOnceMessageV2 like "viewOnce"
1422
+ else if (hasOptionalProperty(message, 'viewOnceV2') && !!message.viewOnceV2) {
1423
+ markViewOnce(m);
1424
+ m = { viewOnceMessageV2: { message: m } };
1425
+ delete message.viewOnceV2;
1426
+ }
1427
+ // Lia@Changes 03-02-26 --- Add "viewOnceV2Extension" boolean to wrap message into viewOnceMessageV2Extension like "viewOnce"
1428
+ else if (hasOptionalProperty(message, 'viewOnceV2Extension') && !!message.viewOnceV2Extension) {
1429
+ markViewOnce(m);
1430
+ m = { viewOnceMessageV2Extension: { message: m } };
1431
+ delete message.viewOnceV2Extension;
1432
+ }
1433
+ if (hasOptionalProperty(message, 'edit')) {
1434
+ m = {
1435
+ protocolMessage: {
1436
+ key: message.edit,
1437
+ editedMessage: m,
1438
+ timestampMs: Date.now(),
1439
+ type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
1440
+ }
1441
+ };
1442
+ }
1443
+ if (shouldIncludeReportingToken(m)) {
1444
+ m.messageContextInfo = m.messageContextInfo || {};
1445
+ if (!m.messageContextInfo.messageSecret) {
1446
+ m.messageContextInfo.messageSecret = randomBytes(32);
1447
+ }
1448
+ }
1449
+ return ensureMessageProto(m);
1450
+ };
1451
+ export const generateWAMessageFromContent = (jid, message, options) => {
1452
+ // set timestamp to now
1453
+ // if not specified
1454
+ if (!options.timestamp) {
1455
+ options.timestamp = new Date();
1456
+ }
1457
+ const innerMessage = normalizeMessageContent(message);
1458
+ const messageContextInfo = message.messageContextInfo;
1459
+ const key = getContentType(innerMessage);
1460
+ const timestamp = unixTimestampSeconds(options.timestamp);
1461
+ const isNewsletter = isJidNewsletter(jid);
1462
+ const { quoted, userJid } = options;
1463
+ if (quoted) {
1464
+ const participant = quoted.key.fromMe
1465
+ ? userJid // TODO: Add support for LIDs
1466
+ : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
1467
+ let quotedMsg = normalizeMessageContent(quoted.message);
1468
+ const msgType = getContentType(quotedMsg);
1469
+ // strip any redundant properties
1470
+ quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
1471
+ const quotedContent = quotedMsg[msgType];
1472
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
1473
+ delete quotedContent.contextInfo;
1474
+ }
1475
+ const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
1476
+ contextInfo.participant = jidNormalizedUser(participant);
1477
+ contextInfo.stanzaId = quoted.key.id;
1478
+ contextInfo.quotedMessage = quotedMsg;
1479
+ // if a participant is quoted, then it must be a group
1480
+ // hence, remoteJid of group must also be entered
1481
+ if (!isNewsletter && jid !== quoted.key.remoteJid) {
1482
+ contextInfo.remoteJid = quoted.key.remoteJid;
1483
+ }
1484
+ if (contextInfo && innerMessage[key]) {
1485
+ /* @ts-ignore */
1486
+ innerMessage[key].contextInfo = contextInfo;
1487
+ }
1488
+ }
1489
+ if (
1490
+ // if we want to send a disappearing message
1491
+ !!options?.ephemeralExpiration &&
1492
+ // and it's not a protocol message -- delete, toggle disappear message
1493
+ key !== 'protocolMessage' &&
1494
+ // already not converted to disappearing message
1495
+ key !== 'ephemeralMessage' &&
1496
+ // newsletters don't support ephemeral messages
1497
+ !isNewsletter) {
1498
+ /* @ts-ignore */
1499
+ innerMessage[key].contextInfo = {
1500
+ ...(innerMessage[key].contextInfo || {}),
1501
+ expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
1502
+ //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
1503
+ };
1504
+ }
1505
+ // Lia@Changes 30-01-26 --- Add deviceListMetadata inside messageContextInfo for private chat
1506
+ if (messageContextInfo?.messageSecret && (isPnUser(jid) || isLidUser(jid))) {
1507
+ messageContextInfo.deviceListMetadata = {
1508
+ recipientKeyHash: randomBytes(10),
1509
+ recipientTimestamp: unixTimestampSeconds()
1510
+ };
1511
+ messageContextInfo.deviceListMetadataVersion = 2;
1512
+ }
1513
+ return WAProto.WebMessageInfo.create({
1514
+ key: {
1515
+ remoteJid: jid,
1516
+ fromMe: true,
1517
+ id: options?.messageId || generateMessageIDV2()
1518
+ },
1519
+ message: ensureMessageProto(message),
1520
+ messageTimestamp: timestamp,
1521
+ messageStubParameters: [],
1522
+ participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
1523
+ status: WAMessageStatus.PENDING
1524
+ });
1525
+ };
1526
+ export const generateWAMessage = async (jid, content, options) => {
1527
+ // ensure msg ID is with every log
1528
+ options.logger = options?.logger?.child({ msgId: options.messageId });
1529
+ // Pass jid in the options to generateWAMessageContent
1530
+ if (jid) {
1531
+ options.jid = jid;
1532
+ }
1533
+ return generateWAMessageFromContent(jid, await generateWAMessageContent(content, options), options);
1534
+ };
1535
+ /** Get the key to access the true type of content */
1536
+ export const getContentType = (content) => {
1537
+ if (content) {
1538
+ const keys = Object.keys(content);
1539
+ const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
1540
+ return key;
1541
+ }
1542
+ };
1543
+ /**
1544
+ * Normalizes ephemeral, view once messages to regular message content
1545
+ * Eg. image messages in ephemeral messages, in view once messages etc.
1546
+ * @param content
1547
+ * @returns
1548
+ */
1549
+ export const normalizeMessageContent = (content) => {
1550
+ if (!content) {
1551
+ return undefined;
1552
+ }
1553
+ // set max iterations to prevent an infinite loop
1554
+ for (let i = 0; i < 5; i++) {
1555
+ const inner = getFutureProofMessage(content);
1556
+ if (!inner) {
1557
+ break;
1558
+ }
1559
+ content = inner.message;
1560
+ }
1561
+ return content;
1562
+ // Lia@Changes 03-02-26 --- Add all futureProofMessage into getFutureProofMessage()
1563
+ function getFutureProofMessage(message) {
1564
+ return (message?.acp2SettingMessage ||
1565
+ message?.associatedChildMessage ||
1566
+ message?.audioStickerMessage ||
1567
+ message?.botForwardedMessage ||
1568
+ message?.botGroupParticipantMessage ||
1569
+ message?.botInvokeMessage ||
1570
+ message?.botPlatformRegistrationSuccessMessage ||
1571
+ message?.botTaskMessage ||
1572
+ message?.documentWithCaptionMessage ||
1573
+ message?.editedMessage ||
1574
+ message?.ephemeralMessage ||
1575
+ message?.eventCoverImage ||
1576
+ message?.groupMentionedMessage ||
1577
+ message?.groupStatusMentionMessage ||
1578
+ message?.groupStatusMessage ||
1579
+ message?.groupStatusMessageV2 ||
1580
+ message?.limitSharingMessage ||
1581
+ message?.lottieStickerMessage ||
1582
+ message?.newsletterAdminProfileMessage ||
1583
+ message?.newsletterAdminProfileMessageV2 ||
1584
+ message?.newsletterAdminProfileStatusMessage ||
1585
+ message?.newsletterScheduledMessage ||
1586
+ message?.pollCreationMessageV4 ||
1587
+ message?.pollCreationOptionImageMessage ||
1588
+ message?.questionMessage ||
1589
+ message?.questionReplyMessage ||
1590
+ message?.spoilerMessage ||
1591
+ message?.statusAddYours ||
1592
+ message?.statusMentionMessage ||
1593
+ message?.viewOnceMessage ||
1594
+ message?.viewOnceMessageV2 ||
1595
+ message?.viewOnceMessageV2Extension);
1596
+ }
1597
+ };
1598
+ /**
1599
+ * Extract the true message content from a message
1600
+ * Eg. extracts the inner message from a disappearing message/view once message
1601
+ */
1602
+ export const extractMessageContent = (content) => {
1603
+ const extractFromTemplateMessage = (msg) => {
1604
+ if (msg.imageMessage) {
1605
+ return { imageMessage: msg.imageMessage };
1606
+ }
1607
+ else if (msg.documentMessage) {
1608
+ return { documentMessage: msg.documentMessage };
1609
+ }
1610
+ else if (msg.videoMessage) {
1611
+ return { videoMessage: msg.videoMessage };
1612
+ }
1613
+ else if (msg.locationMessage) {
1614
+ return { locationMessage: msg.locationMessage };
1615
+ }
1616
+ else {
1617
+ return {
1618
+ conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
1619
+ };
1620
+ }
1621
+ };
1622
+ content = normalizeMessageContent(content);
1623
+ if (content?.buttonsMessage) {
1624
+ return extractFromTemplateMessage(content.buttonsMessage);
1625
+ }
1626
+ if (content?.templateMessage?.hydratedFourRowTemplate) {
1627
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
1628
+ }
1629
+ if (content?.templateMessage?.hydratedTemplate) {
1630
+ return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
1631
+ }
1632
+ if (content?.templateMessage?.fourRowTemplate) {
1633
+ return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
1634
+ }
1635
+ return content;
1636
+ };
1637
+ /**
1638
+ * Returns the device predicted by message ID
1639
+ */
1640
+ export const getDevice = (id) => /^3A.{18}$/.test(id)
1641
+ ? 'ios'
1642
+ : /^3E.{20}$/.test(id)
1643
+ ? 'web'
1644
+ : /^(.{21}|.{32})$/.test(id)
1645
+ ? 'android'
1646
+ : /^(3F|.{18}$)/.test(id)
1647
+ ? 'desktop'
1648
+ : 'unknown';
1649
+ /** Upserts a receipt in the message */
1650
+ export const updateMessageWithReceipt = (msg, receipt) => {
1651
+ msg.userReceipt = msg.userReceipt || [];
1652
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
1653
+ if (recp) {
1654
+ Object.assign(recp, receipt);
1655
+ }
1656
+ else {
1657
+ msg.userReceipt.push(receipt);
1658
+ }
1659
+ };
1660
+ /** Update the message with a new reaction */
1661
+ export const updateMessageWithReaction = (msg, reaction) => {
1662
+ const authorID = getKeyAuthor(reaction.key);
1663
+ const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
1664
+ reaction.text = reaction.text || '';
1665
+ reactions.push(reaction);
1666
+ msg.reactions = reactions;
1667
+ };
1668
+ /** Update the message with a new poll update */
1669
+ export const updateMessageWithPollUpdate = (msg, update) => {
1670
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey);
1671
+ const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
1672
+ if (update.vote?.selectedOptions?.length) {
1673
+ reactions.push(update);
1674
+ }
1675
+ msg.pollUpdates = reactions;
1676
+ };
1677
+ /** Update the message with a new event response */
1678
+ export const updateMessageWithEventResponse = (msg, update) => {
1679
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
1680
+ const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
1681
+ responses.push(update);
1682
+ msg.eventResponses = responses;
1683
+ };
1684
+ /**
1685
+ * Aggregates all poll updates in a poll.
1686
+ * @param msg the poll creation message
1687
+ * @param meId your jid
1688
+ * @returns A list of options & their voters
1689
+ */
1690
+ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
1691
+ const opts = message?.pollCreationMessage?.options ||
1692
+ message?.pollCreationMessageV2?.options ||
1693
+ message?.pollCreationMessageV3?.options ||
1694
+ [];
1695
+ const voteHashMap = opts.reduce((acc, opt) => {
1696
+ const hash = sha256(Buffer.from(opt.optionName || '')).toString();
1697
+ acc[hash] = {
1698
+ name: opt.optionName || '',
1699
+ voters: []
1700
+ };
1701
+ return acc;
1702
+ }, {});
1703
+ for (const update of pollUpdates || []) {
1704
+ const { vote } = update;
1705
+ if (!vote) {
1706
+ continue;
1707
+ }
1708
+ for (const option of vote.selectedOptions || []) {
1709
+ const hash = option.toString();
1710
+ let data = voteHashMap[hash];
1711
+ if (!data) {
1712
+ voteHashMap[hash] = {
1713
+ name: 'Unknown',
1714
+ voters: []
1715
+ };
1716
+ data = voteHashMap[hash];
1717
+ }
1718
+ voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
1719
+ }
1720
+ }
1721
+ return Object.values(voteHashMap);
1722
+ }
1723
+ /**
1724
+ * Aggregates all event responses in an event message.
1725
+ * @param msg the event creation message
1726
+ * @param meId your jid
1727
+ * @returns A list of response types & their responders
1728
+ */
1729
+ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
1730
+ const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
1731
+ const responseMap = {};
1732
+ for (const type of responseTypes) {
1733
+ responseMap[type] = {
1734
+ response: type,
1735
+ responders: []
1736
+ };
1737
+ }
1738
+ for (const update of eventResponses || []) {
1739
+ const responseType = update.eventResponse || 'UNKNOWN';
1740
+ if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
1741
+ responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
1742
+ }
1743
+ }
1744
+ return Object.values(responseMap);
1745
+ }
1746
+ /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
1747
+ export const aggregateMessageKeysNotFromMe = (keys) => {
1748
+ const keyMap = {};
1749
+ for (const { remoteJid, id, participant, fromMe } of keys) {
1750
+ if (!fromMe) {
1751
+ const uqKey = `${remoteJid}:${participant || ''}`;
1752
+ if (!keyMap[uqKey]) {
1753
+ keyMap[uqKey] = {
1754
+ jid: remoteJid,
1755
+ participant: participant,
1756
+ messageIds: []
1757
+ };
1758
+ }
1759
+ keyMap[uqKey].messageIds.push(id);
1760
+ }
1761
+ }
1762
+ return Object.values(keyMap);
1763
+ };
1764
+ const REUPLOAD_REQUIRED_STATUS = [410, 404];
1765
+ /**
1766
+ * Downloads the given message. Throws an error if it's not a media message
1767
+ */
1768
+ export const downloadMediaMessage = async (message, type, options, ctx) => {
1769
+ const result = await downloadMsg().catch(async (error) => {
1770
+ if (ctx &&
1771
+ typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
1772
+ REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
1773
+ ctx.logger.info({ key: message.key }, 'sending reupload media request...');
1774
+ // request reupload
1775
+ message = await ctx.reuploadRequest(message);
1776
+ const result = await downloadMsg();
1777
+ return result;
1778
+ }
1779
+ throw error;
1780
+ });
1781
+ return result;
1782
+ async function downloadMsg() {
1783
+ const mContent = extractMessageContent(message.message);
1784
+ if (!mContent) {
1785
+ throw new HttpError('No message present', { statusCode: 400, data: message });
1786
+ }
1787
+ const contentType = getContentType(mContent);
1788
+ let mediaType = contentType?.replace('Message', '');
1789
+ const media = mContent[contentType];
1790
+ if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
1791
+ throw new HttpError(`"${contentType}" message is not a media message`);
1792
+ }
1793
+ let download;
1794
+ if ('thumbnailDirectPath' in media && !('url' in media)) {
1795
+ download = {
1796
+ directPath: media.thumbnailDirectPath,
1797
+ mediaKey: media.mediaKey
1798
+ };
1799
+ mediaType = 'thumbnail-link';
1800
+ }
1801
+ else {
1802
+ download = media;
1803
+ }
1804
+ const stream = await downloadContentFromMessage(download, mediaType, options);
1805
+ if (type === 'buffer') {
1806
+ const bufferArray = [];
1807
+ for await (const chunk of stream) {
1808
+ bufferArray.push(chunk);
1809
+ }
1810
+ return Buffer.concat(bufferArray);
1811
+ }
1812
+ return stream;
1813
+ }
1814
+ };
1815
+ /** Checks whether the given message is a media message; if it is returns the inner content */
1816
+ export const assertMediaContent = (content) => {
1817
+ content = extractMessageContent(content);
1818
+ const mediaContent = content?.documentMessage ||
1819
+ content?.imageMessage ||
1820
+ content?.videoMessage ||
1821
+ content?.audioMessage ||
1822
+ content?.stickerMessage;
1823
+ if (!mediaContent) {
1824
+ throw new HttpError('given message is not a media message', { statusCode: 400, data: content });
1825
+ }
1826
+ return mediaContent;
1827
+ };
1828
+ /**
1829
+ * Checks if a WebP buffer is animated by looking for VP8X chunk with animation flag
1830
+ * or ANIM/ANMF chunks
1831
+ */
1832
+ const isAnimatedWebP = (buffer) => {
1833
+ // WebP must start with RIFF....WEBP
1834
+ if (buffer.length < 12 ||
1835
+ buffer[0] !== 0x52 ||
1836
+ buffer[1] !== 0x49 ||
1837
+ buffer[2] !== 0x46 ||
1838
+ buffer[3] !== 0x46 ||
1839
+ buffer[8] !== 0x57 ||
1840
+ buffer[9] !== 0x45 ||
1841
+ buffer[10] !== 0x42 ||
1842
+ buffer[11] !== 0x50) {
1843
+ return false;
1844
+ }
1845
+ ;
1846
+ // Parse chunks starting after RIFF header (12 bytes)
1847
+ let offset = 12;
1848
+ while (offset < buffer.length - 8) {
1849
+ const chunkFourCC = buffer.toString('ascii', offset, offset + 4);
1850
+ const chunkSize = buffer.readUInt32LE(offset + 4);
1851
+ if (chunkFourCC === 'VP8X') {
1852
+ // VP8X extended header, check animation flag (bit 1 at offset+8)
1853
+ const flagsOffset = offset + 8;
1854
+ if (flagsOffset < buffer.length) {
1855
+ const flags = buffer[flagsOffset];
1856
+ if (flags & 0x02) {
1857
+ return true;
1858
+ }
1859
+ ;
1860
+ }
1861
+ ;
1862
+ }
1863
+ else if (chunkFourCC === 'ANIM' || chunkFourCC === 'ANMF') {
1864
+ // ANIM or ANMF chunks indicate animation
1865
+ return true;
1866
+ }
1867
+ ;
1868
+ // Move to next chunk (chunk size + 8 bytes header, padded to even)
1869
+ offset += 8 + chunkSize + (chunkSize % 2);
1870
+ }
1871
+ ;
1872
+ return false;
1873
+ };
1874
+ /**
1875
+ * Checks if a buffer is a WebP file
1876
+ */
1877
+ const isWebPBuffer = (buffer) => {
1878
+ return (buffer.length >= 12 &&
1879
+ buffer[0] === 0x52 &&
1880
+ buffer[1] === 0x49 &&
1881
+ buffer[2] === 0x46 &&
1882
+ buffer[3] === 0x46 &&
1883
+ buffer[8] === 0x57 &&
1884
+ buffer[9] === 0x45 &&
1885
+ buffer[10] === 0x42 &&
1886
+ buffer[11] === 0x50);
1887
+ };
1888
+ /**
1889
+ * Lia@Changes 30-01-26
1890
+ * ---
1891
+ * Determines whether a message should include a Biz Binary Node.
1892
+ * A Biz Binary Node is added only for interactive messages
1893
+ * such as buttons or other supported interactive types.
1894
+ */
1895
+ export const shouldIncludeBizBinaryNode = (message) => !!(message.buttonsMessage ||
1896
+ message.listMessage ||
1897
+ message.templateMessage ||
1898
+ (message.interactiveMessage &&
1899
+ message.interactiveMessage.nativeFlowMessage));
1900
+ export const isViewOnceMessage = (message) => {
1901
+ // Fast path, check viewOnce flags directly
1902
+ if (message?.viewOnce === true ||
1903
+ message?.viewOnceMessage ||
1904
+ message?.viewOnceMessageV2 ||
1905
+ message?.viewOnceMessageV2Extension)
1906
+ return true;
1907
+ const innerMsg = normalizeMessageContent(message);
1908
+ const msgType = getContentType(innerMsg);
1909
+ const msgCtn = innerMsg?.[msgType];
1910
+ return msgCtn?.viewOnce === true;
1911
+ };