@rizzxdc/baileys 8.0.10 → 8.1.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 (220) hide show
  1. package/LICENSE +4 -2
  2. package/README.md +107 -245
  3. package/WAProto/index.d.ts +15795 -0
  4. package/WAProto/index.js +25587 -4867
  5. package/lib/Defaults/index.d.ts +147 -0
  6. package/lib/Defaults/index.js +134 -104
  7. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  8. package/lib/Signal/Group/ciphertext-message.js +9 -11
  9. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  10. package/lib/Signal/Group/group-session-builder.js +5 -8
  11. package/lib/Signal/Group/group_cipher.d.ts +11 -0
  12. package/lib/Signal/Group/group_cipher.js +72 -75
  13. package/lib/Signal/Group/index.d.ts +12 -0
  14. package/lib/Signal/Group/index.js +11 -13
  15. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  16. package/lib/Signal/Group/keyhelper.js +11 -14
  17. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  18. package/lib/Signal/Group/sender-chain-key.js +23 -26
  19. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  20. package/lib/Signal/Group/sender-key-distribution-message.js +58 -61
  21. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  22. package/lib/Signal/Group/sender-key-message.js +61 -64
  23. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  24. package/lib/Signal/Group/sender-key-name.js +39 -44
  25. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  26. package/lib/Signal/Group/sender-key-record.js +35 -38
  27. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  28. package/lib/Signal/Group/sender-key-state.js +76 -79
  29. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  30. package/lib/Signal/Group/sender-message-key.js +23 -26
  31. package/lib/Signal/libsignal.d.ts +55 -0
  32. package/lib/Signal/libsignal.js +414 -308
  33. package/lib/Signal/lid-mapping.d.ts +21 -0
  34. package/lib/Signal/lid-mapping.js +270 -149
  35. package/lib/Socket/Client/index.d.ts +3 -0
  36. package/lib/Socket/Client/index.js +2 -4
  37. package/lib/Socket/Client/types.d.ts +6 -0
  38. package/lib/Socket/Client/types.js +8 -11
  39. package/lib/Socket/Client/websocket.d.ts +13 -0
  40. package/lib/Socket/Client/websocket.js +51 -50
  41. package/lib/Socket/business.d.ts +395 -0
  42. package/lib/Socket/business.js +357 -355
  43. package/lib/Socket/chats.d.ts +137 -0
  44. package/lib/Socket/chats.js +1195 -867
  45. package/lib/Socket/communities.d.ts +562 -0
  46. package/lib/Socket/communities.js +416 -398
  47. package/lib/Socket/dugong.js +8 -1
  48. package/lib/Socket/groups.d.ts +286 -0
  49. package/lib/Socket/groups.js +336 -301
  50. package/lib/Socket/index.d.ts +530 -0
  51. package/lib/Socket/index.js +8 -13
  52. package/lib/Socket/messages-recv.d.ts +334 -0
  53. package/lib/Socket/messages-recv.js +1729 -1121
  54. package/lib/Socket/messages-send.d.ts +330 -0
  55. package/lib/Socket/messages-send.js +684 -462
  56. package/lib/Socket/mex.d.ts +2 -0
  57. package/lib/Socket/mex.js +36 -40
  58. package/lib/Socket/newsletter.d.ts +284 -0
  59. package/lib/Socket/newsletter.js +247 -237
  60. package/lib/Socket/socket.d.ts +61 -0
  61. package/lib/Socket/socket.js +968 -790
  62. package/lib/Store/index.d.ts +4 -0
  63. package/lib/Store/index.js +4 -6
  64. package/lib/Store/make-cache-manager-store.js +2 -2
  65. package/lib/Store/make-in-memory-store.d.ts +63 -0
  66. package/lib/Store/make-in-memory-store.js +414 -284
  67. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  68. package/lib/Store/make-ordered-dictionary.js +75 -76
  69. package/lib/Store/object-repository.d.ts +11 -0
  70. package/lib/Store/object-repository.js +21 -23
  71. package/lib/Types/Auth.d.ts +2 -0
  72. package/lib/Types/Auth.js +0 -2
  73. package/lib/Types/Bussines.d.ts +2 -0
  74. package/lib/Types/Bussines.js +0 -2
  75. package/lib/Types/Call.d.ts +2 -0
  76. package/lib/Types/Call.js +0 -2
  77. package/lib/Types/Chat.d.ts +2 -0
  78. package/lib/Types/Chat.js +5 -7
  79. package/lib/Types/Contact.d.ts +2 -0
  80. package/lib/Types/Contact.js +0 -2
  81. package/lib/Types/Events.d.ts +2 -0
  82. package/lib/Types/Events.js +1 -3
  83. package/lib/Types/GroupMetadata.d.ts +2 -0
  84. package/lib/Types/GroupMetadata.js +0 -2
  85. package/lib/Types/Label.d.ts +3 -0
  86. package/lib/Types/Label.js +21 -22
  87. package/lib/Types/LabelAssociation.d.ts +3 -0
  88. package/lib/Types/LabelAssociation.js +3 -4
  89. package/lib/Types/Message.d.ts +12 -0
  90. package/lib/Types/Message.js +11 -6
  91. package/lib/Types/Mex.d.ts +3 -0
  92. package/lib/Types/Mex.js +38 -0
  93. package/lib/Types/Product.d.ts +2 -0
  94. package/lib/Types/Product.js +0 -2
  95. package/lib/Types/RichType.d.ts +3 -0
  96. package/lib/Types/RichType.js +22 -0
  97. package/lib/Types/Signal.d.ts +2 -0
  98. package/lib/Types/Signal.js +1 -3
  99. package/lib/Types/Socket.d.ts +2 -0
  100. package/lib/Types/Socket.js +1 -4
  101. package/lib/Types/State.d.ts +6 -0
  102. package/lib/Types/State.js +52 -8
  103. package/lib/Types/USync.d.ts +2 -0
  104. package/lib/Types/USync.js +1 -3
  105. package/lib/Types/index.d.ts +14 -0
  106. package/lib/Types/index.js +22 -25
  107. package/lib/Utils/auth-utils.d.ts +58 -0
  108. package/lib/Utils/auth-utils.js +285 -203
  109. package/lib/Utils/browser-utils.d.ts +9 -0
  110. package/lib/Utils/browser-utils.js +21 -19
  111. package/lib/Utils/business.d.ts +50 -0
  112. package/lib/Utils/business.js +206 -209
  113. package/lib/Utils/chat-utils.d.ts +409 -0
  114. package/lib/Utils/chat-utils.js +825 -706
  115. package/lib/Utils/companion-reg-client-utils.d.ts +5 -0
  116. package/lib/Utils/companion-reg-client-utils.js +39 -0
  117. package/lib/Utils/crypto.d.ts +40 -0
  118. package/lib/Utils/crypto.js +88 -101
  119. package/lib/Utils/decode-wa-message.d.ts +84 -0
  120. package/lib/Utils/decode-wa-message.js +287 -238
  121. package/lib/Utils/event-buffer.d.ts +13 -0
  122. package/lib/Utils/event-buffer.js +602 -509
  123. package/lib/Utils/generics.d.ts +64 -0
  124. package/lib/Utils/generics.js +334 -295
  125. package/lib/Utils/history.d.ts +76 -0
  126. package/lib/Utils/history.js +125 -79
  127. package/lib/Utils/identity-change-handler.d.ts +14 -0
  128. package/lib/Utils/identity-change-handler.js +49 -0
  129. package/lib/Utils/index.d.ts +25 -0
  130. package/lib/Utils/index.js +25 -21
  131. package/lib/Utils/link-preview.d.ts +13 -0
  132. package/lib/Utils/link-preview.js +73 -70
  133. package/lib/Utils/logger.d.ts +3 -0
  134. package/lib/Utils/logger.js +1 -4
  135. package/lib/Utils/lt-hash.d.ts +7 -0
  136. package/lib/Utils/lt-hash.js +7 -45
  137. package/lib/Utils/make-mutex.d.ts +7 -0
  138. package/lib/Utils/make-mutex.js +27 -31
  139. package/lib/Utils/message-retry-manager.d.ts +80 -0
  140. package/lib/Utils/message-retry-manager.js +165 -14
  141. package/lib/Utils/messages-media.d.ts +137 -0
  142. package/lib/Utils/messages-media.js +768 -572
  143. package/lib/Utils/messages.d.ts +46 -0
  144. package/lib/Utils/messages.js +1082 -130
  145. package/lib/Utils/noise-handler.d.ts +21 -0
  146. package/lib/Utils/noise-handler.js +191 -135
  147. package/lib/Utils/offline-node-processor.d.ts +10 -0
  148. package/lib/Utils/offline-node-processor.js +39 -0
  149. package/lib/Utils/pre-key-manager.d.ts +26 -0
  150. package/lib/Utils/pre-key-manager.js +96 -76
  151. package/lib/Utils/process-message.d.ts +84 -0
  152. package/lib/Utils/process-message.js +718 -311
  153. package/lib/Utils/reporting-utils.d.ts +13 -0
  154. package/lib/Utils/reporting-utils.js +257 -0
  155. package/lib/Utils/rich-message-utils.d.ts +49 -0
  156. package/lib/Utils/rich-message-utils.js +257 -0
  157. package/lib/Utils/signal.d.ts +83 -0
  158. package/lib/Utils/signal.js +174 -135
  159. package/lib/Utils/stanza-ack.d.ts +17 -0
  160. package/lib/Utils/stanza-ack.js +37 -0
  161. package/lib/Utils/sync-action-utils.d.ts +3 -0
  162. package/lib/Utils/sync-action-utils.js +48 -0
  163. package/lib/Utils/tc-token-utils.d.ts +30 -0
  164. package/lib/Utils/tc-token-utils.js +162 -0
  165. package/lib/Utils/use-multi-file-auth-state.d.ts +11 -0
  166. package/lib/Utils/use-multi-file-auth-state.js +104 -95
  167. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  168. package/lib/Utils/use-single-file-auth-state.js +108 -0
  169. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  170. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  171. package/lib/Utils/validate-connection.d.ts +44 -0
  172. package/lib/Utils/validate-connection.js +182 -180
  173. package/lib/WABinary/constants.d.ts +62 -0
  174. package/lib/WABinary/constants.js +1455 -1292
  175. package/lib/WABinary/decode.d.ts +10 -0
  176. package/lib/WABinary/decode.js +249 -228
  177. package/lib/WABinary/encode.d.ts +3 -0
  178. package/lib/WABinary/encode.js +207 -206
  179. package/lib/WABinary/generic-utils.d.ts +77 -0
  180. package/lib/WABinary/generic-utils.js +135 -99
  181. package/lib/WABinary/index.d.ts +6 -0
  182. package/lib/WABinary/index.js +5 -7
  183. package/lib/WABinary/jid-utils.d.ts +29 -0
  184. package/lib/WABinary/jid-utils.js +80 -78
  185. package/lib/WABinary/types.d.ts +2 -0
  186. package/lib/WABinary/types.js +1 -3
  187. package/lib/WAM/BinaryInfo.d.ts +8 -0
  188. package/lib/WAM/BinaryInfo.js +7 -9
  189. package/lib/WAM/constants.d.ts +34927 -0
  190. package/lib/WAM/constants.js +22847 -22848
  191. package/lib/WAM/encode.d.ts +2 -0
  192. package/lib/WAM/encode.js +129 -134
  193. package/lib/WAM/index.d.ts +4 -0
  194. package/lib/WAM/index.js +3 -5
  195. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  196. package/lib/WAUSync/Protocols/USyncContactProtocol.js +48 -27
  197. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  198. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +48 -48
  199. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  200. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +23 -26
  201. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  202. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +33 -35
  203. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  204. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  205. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  206. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +46 -49
  207. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  208. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +23 -25
  209. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  210. package/lib/WAUSync/Protocols/index.js +5 -6
  211. package/lib/WAUSync/USyncQuery.d.ts +21 -0
  212. package/lib/WAUSync/USyncQuery.js +92 -85
  213. package/lib/WAUSync/USyncUser.d.ts +17 -0
  214. package/lib/WAUSync/USyncUser.js +28 -22
  215. package/lib/WAUSync/index.d.ts +4 -0
  216. package/lib/WAUSync/index.js +3 -5
  217. package/lib/index.d.ts +12 -0
  218. package/lib/index.js +31 -19
  219. package/package.json +12 -6
  220. package/lib/Types/Newsletter.js +0 -33
@@ -1,14 +1,17 @@
1
1
  import { Boom } from '@hapi/boom';
2
2
  import { randomBytes } from 'crypto';
3
+ import { zip } from 'fflate';
3
4
  import { promises as fs } from 'fs';
4
- import {} from 'stream';
5
5
  import { proto } from '../../WAProto/index.js';
6
- import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
7
- import { WAMessageStatus, WAProto } from '../Types/index.js';
8
- import { isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
6
+ import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, DONATE_URL, LIBRARY_NAME, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
7
+ import { AssociationType, ButtonHeaderType, ButtonType, CarouselCardType, ListType, ProtocolType, WAMessageStatus, WAProto } from '../Types/index.js';
8
+ import { isLidUser, isPnUser, isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
9
9
  import { sha256 } from './crypto.js';
10
10
  import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
11
- import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getRawMediaUploadData } from './messages-media.js';
11
+ import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getImageProcessingLibrary, getRawMediaUploadData, getStream, toBuffer } from './messages-media.js';
12
+ import { prepareRichResponseMessage } from './rich-message-utils.js';
13
+ import { shouldIncludeReportingToken } from './reporting-utils.js';
14
+ const CONCURRENCY_LIMIT = 10;
12
15
  const MIMETYPE_MAP = {
13
16
  image: 'image/jpeg',
14
17
  video: 'video/mp4',
@@ -24,13 +27,21 @@ const MessageTypeProto = {
24
27
  sticker: WAProto.Message.StickerMessage,
25
28
  document: WAProto.Message.DocumentMessage
26
29
  };
27
- const ButtonType = proto.Message.ButtonsMessage.HeaderType;
30
+ const mediaAnnotation = [
31
+ {
32
+ polygonVertices: [
33
+ { x: 60.71664810180664, y: -36.39784622192383 },
34
+ { x: -16.710189819335938, y: 49.263675689697266 },
35
+ { x: -56.585853576660156, y: 37.85963439941406 },
36
+ { x: 20.840980529785156, y: -47.80188751220703 }
37
+ ]
38
+ }
39
+ ];
28
40
  /**
29
41
  * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
30
42
  * @param text eg. hello https://google.com
31
43
  * @returns the URL, eg. https://google.com
32
44
  */
33
-
34
45
  export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
35
46
  export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
36
47
  const url = extractUrlFromText(text);
@@ -72,40 +83,11 @@ export const prepareWAMessageMedia = async (message, options) => {
72
83
  }
73
84
  const uploadData = {
74
85
  ...message,
75
- ...(message.annotations ? {
76
- annotations: message.annotations
77
- } : {
78
- annotations: [
79
- {
80
- polygonVertices: [
81
- {
82
- x: 60.71664810180664,
83
- y: -36.39784622192383
84
- },
85
- {
86
- x: -16.710189819335938,
87
- y: 49.263675689697266
88
- },
89
- {
90
- x: -56.585853576660156,
91
- y: 37.85963439941406
92
- },
93
- {
94
- x: 20.840980529785156,
95
- y: -47.80188751220703
96
- }
97
- ],
98
- newsletter: {
99
- newsletterJid: "120363422054951473@newsletter",
100
- serverMessageId: 0,
101
- newsletterName: "skyzopedia",
102
- contentType: "UPDATE",
103
- }
104
- }
105
- ]
106
- }),
107
86
  media: message[mediaType]
108
87
  };
88
+ if (uploadData.image || uploadData.video) {
89
+ uploadData.annotations = mediaAnnotation;
90
+ }
109
91
  delete uploadData[mediaType];
110
92
  // check if cacheable + generate cache key
111
93
  const cacheableKey = typeof uploadData.media === 'object' &&
@@ -134,10 +116,11 @@ export const prepareWAMessageMedia = async (message, options) => {
134
116
  logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
135
117
  const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
136
118
  const fileSha256B64 = fileSha256.toString('base64');
137
- const { mediaUrl, directPath } = await options.upload(filePath, {
119
+ const { mediaUrl, directPath, thumbnailDirectPath, thumbnailSha256 } = await options.upload(filePath, {
138
120
  fileEncSha256B64: fileSha256B64,
139
121
  mediaType: mediaType,
140
- timeoutMs: options.mediaUploadTimeoutMs
122
+ timeoutMs: options.mediaUploadTimeoutMs,
123
+ newsletter: isNewsletter
141
124
  });
142
125
  await fs.unlink(filePath);
143
126
  const obj = WAProto.Message.fromObject({
@@ -147,6 +130,8 @@ export const prepareWAMessageMedia = async (message, options) => {
147
130
  directPath,
148
131
  fileSha256,
149
132
  fileLength,
133
+ thumbnailDirectPath,
134
+ thumbnailSha256,
150
135
  ...uploadData,
151
136
  media: undefined
152
137
  })
@@ -166,7 +151,7 @@ export const prepareWAMessageMedia = async (message, options) => {
166
151
  }
167
152
  const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
168
153
  const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
169
- const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
154
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined';
170
155
  const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
171
156
  const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
172
157
  const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
@@ -249,6 +234,313 @@ export const prepareWAMessageMedia = async (message, options) => {
249
234
  }
250
235
  return obj;
251
236
  };
237
+ // Lia@Changes 31-01-26 --- Extract product message into a standalone function so it can also be reused as the header for interactive messages
238
+ const prepareProductMessage = async (message, options) => {
239
+ if (!message.businessOwnerJid) {
240
+ throw new Boom('"businessOwnerJid" is missing from the content', { statusCode: 400 });
241
+ }
242
+ const { imageMessage } = await prepareWAMessageMedia({ image: message.image || message.product.productImage }, options);
243
+ // Lia@Changes 01-02-26 --- Add product message default value
244
+ const content = {
245
+ ...message,
246
+ product: {
247
+ currencyCode: 'IDR',
248
+ priceAmount1000: 1000,
249
+ title: LIBRARY_NAME,
250
+ ...message.product,
251
+ productImage: imageMessage
252
+ }
253
+ };
254
+ delete content.image;
255
+ return content;
256
+ };
257
+ /**
258
+ * Lia@Note 30-01-26
259
+ * ---
260
+ * Credits: Work on ensuring stickerPackMessage fields are valid by @jlucaso1 (https://github.com/jlucaso1).
261
+ * based on https://github.com/WhiskeySockets/Baileys/pull/1561
262
+ */
263
+ // Lia@Changes 21-04-26 --- Enhanced prepareStickerPackMessage
264
+ const prepareStickerPackMessage = async (message, options) => {
265
+ const { cover, stickers = [], name = '📦 Sticker Pack', publisher = 'GitHub: namamu', description = '🏷️ AlwaysRizz' } = message;
266
+ if (stickers.length > 60) {
267
+ throw new Boom('Sticker pack exceeds the maximum limit of 60 stickers', { statusCode: 400 });
268
+ }
269
+ if (stickers.length === 0) {
270
+ throw new Boom('Sticker pack must contain at least one sticker', { statusCode: 400 });
271
+ }
272
+ if (!cover) {
273
+ throw new Boom('Sticker pack must contain a cover', { statusCode: 400 });
274
+ }
275
+ const logger = options.logger;
276
+ // Lia@Changes 01-02-26 --- Add caching for sticker pack
277
+ let cacheableKey = false;
278
+ if (Array.isArray(stickers) && stickers.length && options.mediaCache) {
279
+ const urls = [];
280
+ for (let i = 0; i < stickers.length; i++) {
281
+ const data = stickers[i].data;
282
+ if (typeof data === 'object' && data?.url) {
283
+ urls.push(data.url);
284
+ }
285
+ }
286
+ if (urls.length > 0) {
287
+ cacheableKey = 'sticker:' + urls.join('@');
288
+ }
289
+ }
290
+ if (cacheableKey) {
291
+ const mediaBuff = await options.mediaCache.get(cacheableKey);
292
+ if (mediaBuff) {
293
+ logger?.debug({ cacheableKey }, 'got media cache hit');
294
+ return proto.Message.StickerPackMessage.decode(mediaBuff);
295
+ }
296
+ }
297
+ const lib = await getImageProcessingLibrary();
298
+ const hasSharp = 'sharp' in lib && !!lib.sharp?.default;
299
+ const hasImage = 'image' in lib && !!lib.image?.Transformer;
300
+ const hasJimp = 'jimp' in lib && !!lib.jimp?.Jimp;
301
+ if (!hasSharp && !hasImage) {
302
+ throw new Boom('No image processing library (sharp or @napi-rs/image) available for converting sticker to WebP.');
303
+ }
304
+ const stickerPackIdValue = generateMessageIDV2();
305
+ const stickerData = {};
306
+ const stickerMetadata = new Array(stickers.length);
307
+ for (let i = 0; i < stickers.length; i += CONCURRENCY_LIMIT) {
308
+ const promises = [];
309
+ const chunkEnd = Math.min(i + CONCURRENCY_LIMIT, stickers.length);
310
+ for (let j = i; j < chunkEnd; j++) {
311
+ promises.push((async (index) => {
312
+ const sticker = stickers[index];
313
+ const { stream } = await getStream(sticker.data);
314
+ const buffer = await toBuffer(stream);
315
+ let webpBuffer;
316
+ let isAnimated = false;
317
+ if (isWebPBuffer(buffer)) {
318
+ webpBuffer = buffer;
319
+ isAnimated = isAnimatedWebP(buffer);
320
+ }
321
+ else if (hasSharp) {
322
+ webpBuffer = await lib.sharp.default(buffer)
323
+ .resize(512, 512, { fit: 'inside' })
324
+ .webp({ quality: 80 })
325
+ .toBuffer();
326
+ }
327
+ else {
328
+ webpBuffer = await new lib.image.Transformer(buffer)
329
+ .resize(512, 512)
330
+ .webp(80);
331
+ }
332
+ if (webpBuffer.length > 1024 * 1024) {
333
+ throw new Boom(`Sticker at index ${index} exceeds the 1MB size limit`, { statusCode: 400 });
334
+ }
335
+ const hash = sha256(webpBuffer).toString('base64').replace(/\//g, '-');
336
+ const fileName = `${hash}.webp`;
337
+ stickerData[fileName] = [new Uint8Array(webpBuffer), { level: 0 }];
338
+ stickerMetadata[index] = {
339
+ fileName,
340
+ mimetype: 'image/webp',
341
+ isAnimated,
342
+ emojis: sticker.emojis || ['✨'],
343
+ accessibilityLabel: sticker.accessibilityLabel || '‎'
344
+ };
345
+ })(j));
346
+ }
347
+ await Promise.all(promises);
348
+ }
349
+ const trayIconFileName = `${stickerPackIdValue}.webp`;
350
+ const { stream: coverStream } = await getStream(cover);
351
+ const coverBuffer = await toBuffer(coverStream);
352
+ let coverWebpBuffer;
353
+ if (isWebPBuffer(coverBuffer)) {
354
+ coverWebpBuffer = coverBuffer;
355
+ }
356
+ else if (hasSharp) {
357
+ coverWebpBuffer = await lib.sharp.default(coverBuffer)
358
+ .resize(512, 512, { fit: 'inside' })
359
+ .webp({ quality: 80 })
360
+ .toBuffer();
361
+ }
362
+ else {
363
+ coverWebpBuffer = await new lib.image.Transformer(coverBuffer)
364
+ .resize(512, 512)
365
+ .webp(80);
366
+ }
367
+ stickerData[trayIconFileName] = [new Uint8Array(coverWebpBuffer), { level: 0 }];
368
+ const zipBuffer = await new Promise((resolve, reject) => {
369
+ zip(stickerData, (error, data) => error ? reject(error) : resolve(Buffer.from(data)));
370
+ });
371
+ const stickerPackUpload = await encryptedStream(zipBuffer, 'sticker-pack', {
372
+ logger,
373
+ opts: options.options
374
+ });
375
+ let stickerPackUploadResult;
376
+ try {
377
+ stickerPackUploadResult = await options.upload(stickerPackUpload.encFilePath, {
378
+ fileEncSha256B64: stickerPackUpload.fileEncSha256.toString('base64'),
379
+ mediaType: 'sticker-pack',
380
+ timeoutMs: options.mediaUploadTimeoutMs
381
+ });
382
+ }
383
+ finally {
384
+ fs.unlink(stickerPackUpload.encFilePath).catch(() => logger?.warn('failed to remove tmp file'));
385
+ }
386
+ const obj = {
387
+ name,
388
+ publisher,
389
+ stickerPackId: stickerPackIdValue,
390
+ packDescription: description,
391
+ stickerPackOrigin: proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED,
392
+ stickerPackSize: zipBuffer.length,
393
+ stickers: stickerMetadata,
394
+ fileSha256: stickerPackUpload.fileSha256,
395
+ fileEncSha256: stickerPackUpload.fileEncSha256,
396
+ mediaKey: stickerPackUpload.mediaKey,
397
+ directPath: stickerPackUploadResult.directPath,
398
+ fileLength: stickerPackUpload.fileLength,
399
+ mediaKeyTimestamp: unixTimestampSeconds(),
400
+ trayIconFileName
401
+ };
402
+ try {
403
+ let thumbnailBuffer;
404
+ if (hasSharp) {
405
+ thumbnailBuffer = await lib.sharp.default(coverBuffer).resize(252, 252).jpeg().toBuffer();
406
+ }
407
+ else if (hasImage) {
408
+ thumbnailBuffer = await new lib.image.Transformer(coverBuffer).resize(252, 252).jpeg();
409
+ }
410
+ else if (hasJimp) {
411
+ const jimpImage = await lib.jimp.Jimp.read(coverBuffer);
412
+ thumbnailBuffer = await jimpImage.resize({ w: 252, h: 252 }).getBuffer('image/jpeg');
413
+ }
414
+ else {
415
+ throw new Error('No image processing library available for thumbnail generation');
416
+ }
417
+ if (!thumbnailBuffer || thumbnailBuffer.length === 0) {
418
+ throw new Error('Failed to generate thumbnail buffer');
419
+ }
420
+ const thumbUpload = await encryptedStream(thumbnailBuffer, 'thumbnail-sticker-pack', {
421
+ logger,
422
+ opts: options.options,
423
+ mediaKey: stickerPackUpload.mediaKey
424
+ });
425
+ let thumbUploadResult;
426
+ try {
427
+ thumbUploadResult = await options.upload(thumbUpload.encFilePath, {
428
+ fileEncSha256B64: thumbUpload.fileEncSha256.toString('base64'),
429
+ mediaType: 'thumbnail-sticker-pack',
430
+ timeoutMs: options.mediaUploadTimeoutMs
431
+ });
432
+ }
433
+ finally {
434
+ fs.unlink(thumbUpload.encFilePath).catch(() => logger?.warn('failed to remove tmp file'));
435
+ }
436
+ Object.assign(obj, {
437
+ thumbnailDirectPath: thumbUploadResult.directPath,
438
+ thumbnailSha256: thumbUpload.fileSha256,
439
+ thumbnailEncSha256: thumbUpload.fileEncSha256,
440
+ thumbnailHeight: 252,
441
+ thumbnailWidth: 252,
442
+ imageDataHash: sha256(thumbnailBuffer).toString('base64')
443
+ });
444
+ }
445
+ catch (error) {
446
+ logger?.warn(`Thumbnail generation failed: ${error}`);
447
+ }
448
+ if (cacheableKey) {
449
+ logger?.debug({ cacheableKey }, 'set cache (background)');
450
+ options.mediaCache.set(cacheableKey, WAProto.Message.StickerPackMessage.encode(obj).finish());
451
+ }
452
+ return WAProto.Message.StickerPackMessage.fromObject(obj);
453
+ };
454
+ // Lia@Changes 30-01-26 --- Add native flow button helper for interactive message
455
+ const prepareNativeFlowButtons = (message) => {
456
+ const buttons = message.nativeFlow;
457
+ const isButtonsFieldArray = Array.isArray(buttons);
458
+ const correctedField = isButtonsFieldArray ? buttons : buttons.buttons;
459
+ const messageParamsJson = {};
460
+ // Lia@Changes 31-01-26 --- Add offer and options inside interactive message
461
+ if (hasOptionalProperty(message, 'offerText') && !!message.offerText) {
462
+ Object.assign(messageParamsJson, {
463
+ limited_time_offer: {
464
+ text: message.offerText || LIBRARY_NAME,
465
+ url: message.offerUrl || DONATE_URL, // Lia@Note 02-02-26 --- Apologies if this feels cheeky, just a fallback
466
+ copy_code: message.offerCode,
467
+ expiration_time: message.offerExpiration
468
+ }
469
+ });
470
+ }
471
+ if (hasOptionalProperty(message, 'optionText') && !!message.optionText) {
472
+ Object.assign(messageParamsJson, {
473
+ bottom_sheet: {
474
+ in_thread_buttons_limit: 1,
475
+ divider_indices: Array.from({ length: correctedField.length }, (_, index) => index),
476
+ list_title: message.optionTitle || '📄 Select Options',
477
+ button_title: message.optionText
478
+ }
479
+ });
480
+ }
481
+ return {
482
+ buttons: correctedField.map(button => {
483
+ const buttonText = button.text || button.buttonText;
484
+ const buttonIcon = button.icon?.toUpperCase();
485
+ if (hasOptionalProperty(button, 'id') && !!button.id) {
486
+ return {
487
+ name: 'quick_reply',
488
+ buttonParamsJson: JSON.stringify({
489
+ display_text: buttonText || '👉🏻 Click',
490
+ id: button.id,
491
+ icon: buttonIcon
492
+ })
493
+ };
494
+ }
495
+ else if (hasOptionalProperty(button, 'copy') && !!button.copy) {
496
+ return {
497
+ name: 'cta_copy',
498
+ buttonParamsJson: JSON.stringify({
499
+ display_text: buttonText || '📋 Copy',
500
+ copy_code: button.copy,
501
+ icon: buttonIcon
502
+ })
503
+ };
504
+ }
505
+ else if (hasOptionalProperty(button, 'url') && !!button.url) {
506
+ return {
507
+ name: 'cta_url',
508
+ buttonParamsJson: JSON.stringify({
509
+ display_text: buttonText || '🌐 Visit',
510
+ url: button.url,
511
+ merchant_url: button.url,
512
+ webview_interaction: button.useWebview,
513
+ icon: buttonIcon
514
+ })
515
+ };
516
+ }
517
+ else if (hasOptionalProperty(button, 'call') && !!button.call) {
518
+ return {
519
+ name: 'cta_call',
520
+ buttonParamsJson: JSON.stringify({
521
+ display_text: buttonText || '📞 Call',
522
+ phone_number: button.call,
523
+ icon: buttonIcon
524
+ })
525
+ };
526
+ }
527
+ // Lia@Changes 12-03-26 --- Add "single_select" shortcut \⁠(⁠°⁠o⁠°⁠)⁠/
528
+ else if (hasOptionalProperty(button, 'sections') && !!button.sections) {
529
+ return {
530
+ name: 'single_select',
531
+ buttonParamsJson: JSON.stringify({
532
+ title: buttonText || '📋 Select',
533
+ sections: button.sections,
534
+ icon: buttonIcon
535
+ })
536
+ };
537
+ }
538
+ return button;
539
+ }),
540
+ messageParamsJson: JSON.stringify(messageParamsJson),
541
+ messageVersion: 3
542
+ };
543
+ };
252
544
  export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
253
545
  ephemeralExpiration = ephemeralExpiration || 0;
254
546
  const content = {
@@ -268,7 +560,6 @@ export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) =>
268
560
  * @param message the message to forward
269
561
  * @param options.forceForward will show the message as forwarded even if it is from you
270
562
  */
271
-
272
563
  export const generateForwardMessageContent = (message, forceForward) => {
273
564
  let content = message.message;
274
565
  if (!content) {
@@ -294,10 +585,52 @@ export const generateForwardMessageContent = (message, forceForward) => {
294
585
  }
295
586
  return content;
296
587
  };
588
+ export const hasNonNullishProperty = (message, key) => {
589
+ return message != null &&
590
+ typeof message === 'object' &&
591
+ key in message &&
592
+ message[key] != null;
593
+ };
594
+ export const hasOptionalProperty = (obj, key) => {
595
+ return obj != null &&
596
+ typeof obj === 'object' &&
597
+ key in obj &&
598
+ obj[key] != null;
599
+ };
600
+ // Lia@Changes 06-02-26 --- Validate album message media to avoid bug 👀
601
+ export const hasValidAlbumMedia = (message) => {
602
+ return message.imageMessage ||
603
+ message.videoMessage;
604
+ };
605
+ export const hasValidInteractiveHeader = (message) => {
606
+ return message.imageMessage ||
607
+ message.videoMessage ||
608
+ message.documentMessage ||
609
+ message.productMessage ||
610
+ message.locationMessage;
611
+ };
612
+ // Lia@Changes 30-01-26 --- Validate carousel cards header to avoid bug 👀
613
+ export const hasValidCarouselHeader = (message) => {
614
+ return message.imageMessage ||
615
+ message.videoMessage ||
616
+ message.productMessage;
617
+ };
297
618
  export const generateWAMessageContent = async (message, options) => {
298
619
  var _a, _b;
299
620
  let m = {};
300
- if ('text' in message) {
621
+ // Lia@Changes 30-01-26 --- Add "raw" boolean to send raw messages directly via generateWAMessage()
622
+ if (hasNonNullishProperty(message, 'raw')) {
623
+ delete message.raw;
624
+ return message;
625
+ }
626
+ // Lia@Changes 09-04-26 --- Add support for code block and table with richResponseMessage
627
+ else if (hasNonNullishProperty(message, 'code') ||
628
+ hasNonNullishProperty(message, 'links') ||
629
+ hasNonNullishProperty(message, 'table') ||
630
+ hasNonNullishProperty(message, 'richResponse')) {
631
+ m = prepareRichResponseMessage(message);
632
+ }
633
+ else if (hasNonNullishProperty(message, 'text')) {
301
634
  const extContent = { text: message.text };
302
635
  let urlInfo = message.linkPreview;
303
636
  if (typeof urlInfo === 'undefined') {
@@ -308,7 +641,8 @@ export const generateWAMessageContent = async (message, options) => {
308
641
  extContent.jpegThumbnail = urlInfo.jpegThumbnail;
309
642
  extContent.description = urlInfo.description;
310
643
  extContent.title = urlInfo.title;
311
- extContent.previewType = 0;
644
+ extContent.previewType = urlInfo.previewType ?? 0;
645
+ extContent.linkPreviewMetadata = urlInfo.linkPreviewMetadata;
312
646
  const img = urlInfo.highQualityThumbnail;
313
647
  if (img) {
314
648
  extContent.thumbnailDirectPath = img.directPath;
@@ -320,6 +654,21 @@ export const generateWAMessageContent = async (message, options) => {
320
654
  extContent.thumbnailEncSha256 = img.fileEncSha256;
321
655
  }
322
656
  }
657
+ const faviconData = message.favicon;
658
+ if (faviconData && typeof options.upload === 'function') {
659
+ const { imageMessage } = await prepareWAMessageMedia({
660
+ image: faviconData
661
+ }, options);
662
+ extContent.faviconMMSMetadata = {
663
+ thumbnailDirectPath: imageMessage.directPath,
664
+ mediaKey: imageMessage.mediaKey,
665
+ mediaKeyTimestamp: imageMessage.mediaKeyTimestamp,
666
+ thumbnailWidth: 32,
667
+ thumbnailHeight: 32,
668
+ thumbnailSha256: imageMessage.fileSha256,
669
+ thumbnailEncSha256: imageMessage.fileEncSha256
670
+ };
671
+ }
323
672
  if (options.backgroundColor) {
324
673
  extContent.backgroundArgb = await assertColor(options.backgroundColor);
325
674
  }
@@ -328,7 +677,7 @@ export const generateWAMessageContent = async (message, options) => {
328
677
  }
329
678
  m.extendedTextMessage = extContent;
330
679
  }
331
- else if ('contacts' in message) {
680
+ else if (hasNonNullishProperty(message, 'contacts')) {
332
681
  const contactLen = message.contacts.contacts.length;
333
682
  if (!contactLen) {
334
683
  throw new Boom('require atleast 1 contact', { statusCode: 400 });
@@ -340,25 +689,25 @@ export const generateWAMessageContent = async (message, options) => {
340
689
  m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
341
690
  }
342
691
  }
343
- else if ('location' in message) {
692
+ else if (hasNonNullishProperty(message, 'location')) {
344
693
  m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
345
694
  }
346
- else if ('react' in message) {
695
+ else if (hasNonNullishProperty(message, 'react')) {
347
696
  if (!message.react.senderTimestampMs) {
348
697
  message.react.senderTimestampMs = Date.now();
349
698
  }
350
699
  m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
351
700
  }
352
- else if ('delete' in message) {
701
+ else if (hasNonNullishProperty(message, 'delete')) {
353
702
  m.protocolMessage = {
354
703
  key: message.delete,
355
704
  type: WAProto.Message.ProtocolMessage.Type.REVOKE
356
705
  };
357
706
  }
358
- else if ('forward' in message) {
707
+ else if (hasNonNullishProperty(message, 'forward')) {
359
708
  m = generateForwardMessageContent(message.forward, message.force);
360
709
  }
361
- else if ('disappearingMessagesInChat' in message) {
710
+ else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
362
711
  const exp = typeof message.disappearingMessagesInChat === 'boolean'
363
712
  ? message.disappearingMessagesInChat
364
713
  ? WA_DEFAULT_EPHEMERAL
@@ -366,7 +715,7 @@ export const generateWAMessageContent = async (message, options) => {
366
715
  : message.disappearingMessagesInChat;
367
716
  m = prepareDisappearingMessageSettingContent(exp);
368
717
  }
369
- else if ('groupInvite' in message) {
718
+ else if (hasNonNullishProperty(message, 'groupInvite')) {
370
719
  m.groupInviteMessage = {};
371
720
  m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
372
721
  m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
@@ -386,7 +735,10 @@ export const generateWAMessageContent = async (message, options) => {
386
735
  }
387
736
  }
388
737
  }
389
- else if ('pin' in message) {
738
+ else if (hasNonNullishProperty(message, 'stickers')) {
739
+ m.stickerPackMessage = await prepareStickerPackMessage(message, options);
740
+ }
741
+ else if (hasNonNullishProperty(message, 'pin')) {
390
742
  m.pinInChatMessage = {};
391
743
  m.messageContextInfo = {};
392
744
  m.pinInChatMessage.key = message.pin;
@@ -394,7 +746,26 @@ export const generateWAMessageContent = async (message, options) => {
394
746
  m.pinInChatMessage.senderTimestampMs = Date.now();
395
747
  m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
396
748
  }
397
- else if ('buttonReply' in message) {
749
+ else if (hasNonNullishProperty(message, 'keep')) {
750
+ m.keepInChatMessage = {};
751
+ m.keepInChatMessage.key = message.keep;
752
+ m.keepInChatMessage.keepType = message.type;
753
+ m.keepInChatMessage.timestampMs = Date.now();
754
+ }
755
+ else if (hasNonNullishProperty(message, 'flowReply')) {
756
+ m.interactiveResponseMessage = {
757
+ body: {
758
+ format: message.flowReply.format || proto.Message.InteractiveResponseMessage.Body.Format.DEFAULT,
759
+ text: message.flowReply.text
760
+ },
761
+ nativeFlowResponseMessage: {
762
+ name: message.flowReply.name,
763
+ paramsJson: message.flowReply.paramsJson || '{}',
764
+ version: message.flowReply.version || 1
765
+ }
766
+ };
767
+ }
768
+ else if (hasNonNullishProperty(message, 'buttonReply')) {
398
769
  switch (message.type) {
399
770
  case 'template':
400
771
  m.templateButtonReplyMessage = {
@@ -412,24 +783,24 @@ export const generateWAMessageContent = async (message, options) => {
412
783
  break;
413
784
  }
414
785
  }
415
- else if ('ptv' in message && message.ptv) {
786
+ else if (hasNonNullishProperty(message, 'listReply')) {
787
+ m.listResponseMessage = {
788
+ description: message.listReply.description,
789
+ listType: proto.Message.ListResponseMessage.ListType.SINGLE_SELECT,
790
+ singleSelectReply: {
791
+ selectedRowId: message.listReply.id
792
+ },
793
+ title: message.listReply.title
794
+ };
795
+ }
796
+ else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
416
797
  const { videoMessage } = await prepareWAMessageMedia({ video: message.video }, options);
417
798
  m.ptvMessage = videoMessage;
418
799
  }
419
- else if ('product' in message) {
420
- const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options);
421
- m.productMessage = WAProto.Message.ProductMessage.create({
422
- ...message,
423
- product: {
424
- ...message.product,
425
- productImage: imageMessage
426
- }
427
- });
800
+ else if (hasNonNullishProperty(message, 'product')) {
801
+ m.productMessage = await prepareProductMessage(message, options);
428
802
  }
429
- else if ('listReply' in message) {
430
- m.listResponseMessage = { ...message.listReply };
431
- }
432
- else if ('event' in message) {
803
+ else if (hasNonNullishProperty(message, 'event')) {
433
804
  m.eventMessage = {};
434
805
  const startTime = Math.floor(message.event.startDate.getTime() / 1000);
435
806
  if (message.event.call && options.getCallLink) {
@@ -449,7 +820,7 @@ export const generateWAMessageContent = async (message, options) => {
449
820
  m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
450
821
  m.eventMessage.location = message.event.location;
451
822
  }
452
- else if ('poll' in message) {
823
+ else if (hasNonNullishProperty(message, 'poll')) {
453
824
  (_a = message.poll).selectableCount || (_a.selectableCount = 0);
454
825
  (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
455
826
  if (!Array.isArray(message.poll.values)) {
@@ -460,21 +831,35 @@ export const generateWAMessageContent = async (message, options) => {
460
831
  statusCode: 400
461
832
  });
462
833
  }
463
- m.messageContextInfo = {
464
- // encKey
465
- messageSecret: message.poll.messageSecret || randomBytes(32)
466
- };
467
834
  const pollCreationMessage = {
468
835
  name: message.poll.name,
469
836
  selectableOptionsCount: message.poll.selectableCount,
470
- options: message.poll.values.map(optionName => ({ optionName }))
837
+ options: message.poll.values.map(optionName => ({ optionName })),
838
+ endTime: message.poll.endDate ? message.poll.endDate.getTime() : undefined,
839
+ hideParticipantName: message.poll.hideVoter ?? false,
840
+ allowAddOption: message.poll.canAddOption ?? false
471
841
  };
472
842
  if (message.poll.toAnnouncementGroup) {
473
843
  // poll v2 is for community announcement groups (single select and multiple)
474
844
  m.pollCreationMessageV2 = pollCreationMessage;
475
845
  }
476
846
  else {
477
- if (message.poll.selectableCount === 1) {
847
+ // Lia@Changes 08-02-26 --- Add quiz message support
848
+ if (message.poll.pollType === 1) {
849
+ if (!message.poll.correctAnswer) {
850
+ throw new Boom('No "correctAnswer" provided for quiz', { statusCode: 400 });
851
+ }
852
+ m.pollCreationMessageV5 = {
853
+ // Lia@Note 08-02-26 --- quiz for newsletter only
854
+ ...pollCreationMessage,
855
+ correctAnswer: {
856
+ optionName: message.poll.correctAnswer.toString()
857
+ },
858
+ pollType: 1,
859
+ selectableOptionsCount: 1
860
+ };
861
+ }
862
+ else if (message.poll.selectableCount === 1) {
478
863
  //poll v3 is for single select polls
479
864
  m.pollCreationMessageV3 = pollCreationMessage;
480
865
  }
@@ -483,16 +868,104 @@ export const generateWAMessageContent = async (message, options) => {
483
868
  m.pollCreationMessage = pollCreationMessage;
484
869
  }
485
870
  }
871
+ m.messageContextInfo = {
872
+ // encKey
873
+ messageSecret: message.poll.messageSecret || randomBytes(32)
874
+ };
875
+ }
876
+ // Lia@Changes 08-02-26 --- Add poll result snapshot message
877
+ else if (hasNonNullishProperty(message, 'pollResult')) {
878
+ const pollResultSnapshotMessage = {
879
+ name: message.pollResult.name,
880
+ pollVotes: message.pollResult.votes.map(vote => ({
881
+ optionName: vote.name,
882
+ optionVoteCount: parseInt(vote.voteCount)
883
+ }))
884
+ };
885
+ if (message.pollResult.pollType === 1) {
886
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.QUIZ;
887
+ m.pollResultSnapshotMessageV3 = pollResultSnapshotMessage;
888
+ }
889
+ else {
890
+ pollResultSnapshotMessage.pollType = proto.Message.PollType.POLL;
891
+ m.pollResultSnapshotMessage = pollResultSnapshotMessage;
892
+ }
893
+ }
894
+ // Lia@Changes 08-02-26 --- Add poll update message
895
+ else if (hasNonNullishProperty(message, 'pollUpdate')) {
896
+ if (!message.pollUpdate.key) {
897
+ throw new Boom('Message key is required', { statusCode: 400 });
898
+ }
899
+ if (!message.pollUpdate.vote) {
900
+ throw new Boom('Encrypted vote payload is required', { statusCode: 400 });
901
+ }
902
+ m.pollUpdateMessage = {
903
+ metadata: message.pollUpdate.metadata,
904
+ pollCreationMessageKey: message.pollUpdate.key,
905
+ senderTimestampMs: Date.now(),
906
+ vote: message.pollUpdate.vote
907
+ };
486
908
  }
487
- else if ('sharePhoneNumber' in message) {
909
+ // Lia@Changes 01-02-26 --- Add payment invite message
910
+ else if (hasNonNullishProperty(message, 'paymentInviteServiceType')) {
911
+ m.paymentInviteMessage = {
912
+ expiryTimestamp: Date.now(),
913
+ serviceType: message.paymentInviteServiceType
914
+ };
915
+ }
916
+ // Lia@Changes 01-02-26 --- Add order message
917
+ else if (hasNonNullishProperty(message, 'orderText')) {
918
+ if (!Buffer.isBuffer(message.thumbnail)) {
919
+ throw new Boom('Must provide thumbnail buffer in order message', { statusCode: 400 });
920
+ }
921
+ m.orderMessage = {
922
+ itemCount: 1,
923
+ messageVersion: 1,
924
+ orderTitle: LIBRARY_NAME,
925
+ status: proto.Message.OrderMessage.OrderStatus.INQUIRY,
926
+ surface: proto.Message.OrderMessage.OrderSurface.CATALOG,
927
+ token: generateMessageIDV2(),
928
+ totalAmount1000: 1000,
929
+ totalCurrencyCode: 'IDR',
930
+ ...message,
931
+ message: message.orderText
932
+ };
933
+ delete m.orderMessage.orderText;
934
+ }
935
+ // Lia@Changes 31-01-26 --- Add support for album messages
936
+ else if (hasNonNullishProperty(message, 'album')) {
937
+ if (!Array.isArray(message.album)) {
938
+ throw new Boom('Invalid album type. Expected an array.', { statusCode: 400 });
939
+ }
940
+ let videoCount = 0;
941
+ for (let i = 0; i < message.album.length; i++) {
942
+ if (message.album[i].video)
943
+ videoCount++;
944
+ }
945
+ ;
946
+ let imageCount = 0;
947
+ for (let i = 0; i < message.album.length; i++) {
948
+ if (message.album[i].image)
949
+ imageCount++;
950
+ }
951
+ ;
952
+ if ((videoCount + imageCount) < 2) {
953
+ throw new Boom('Minimum provide 2 media to upload album message', { statusCode: 400 });
954
+ }
955
+ m.albumMessage = {
956
+ expectedImageCount: imageCount,
957
+ expectedVideoCount: videoCount
958
+ };
959
+ }
960
+ else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
488
961
  m.protocolMessage = {
489
962
  type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
490
963
  };
491
964
  }
492
- else if ('requestPhoneNumber' in message) {
965
+ else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
493
966
  m.requestPhoneNumberMessage = {};
494
967
  }
495
- else if ('limitSharing' in message) {
968
+ else if (hasNonNullishProperty(message, 'limitSharing')) {
496
969
  m.protocolMessage = {
497
970
  type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
498
971
  limitSharing: {
@@ -506,77 +979,418 @@ export const generateWAMessageContent = async (message, options) => {
506
979
  else {
507
980
  m = await prepareWAMessageMedia(message, options);
508
981
  }
509
- if ('buttons' in message && !!message.buttons) {
982
+ // Lia@Changes 30-01-26 --- Add interactive messages (buttonsMessage, listMessage, interactiveMessage, templateMessage, and carouselMessage)
983
+ if (hasNonNullishProperty(message, 'buttons')) {
510
984
  const buttonsMessage = {
511
- buttons: message.buttons.map(b => ({ ...b, type: proto.Message.ButtonsMessage.Button.Type.RESPONSE }))
985
+ buttons: message.buttons.map(button => {
986
+ // Lia@Changes 12-03-26 --- Add "single_select" shortcut!
987
+ const buttonText = button.text || button.buttonText;
988
+ if (hasOptionalProperty(button, 'sections')) {
989
+ return {
990
+ nativeFlowInfo: {
991
+ name: 'single_select',
992
+ paramsJson: JSON.stringify({
993
+ title: buttonText,
994
+ sections: button.sections
995
+ })
996
+ },
997
+ type: ButtonType.NATIVE_FLOW
998
+ };
999
+ }
1000
+ else if (hasOptionalProperty(button, 'name')) {
1001
+ return {
1002
+ nativeFlowInfo: {
1003
+ name: button.name,
1004
+ paramsJson: button.paramsJson
1005
+ },
1006
+ type: ButtonType.NATIVE_FLOW
1007
+ };
1008
+ }
1009
+ return {
1010
+ buttonId: button.id || button.buttonId,
1011
+ buttonText: typeof buttonText === 'string' ? { displayText: buttonText } : buttonText,
1012
+ type: button.type || ButtonType.RESPONSE
1013
+ };
1014
+ })
512
1015
  };
513
- if ('text' in message) {
1016
+ if (hasOptionalProperty(message, 'text')) {
514
1017
  buttonsMessage.contentText = message.text;
515
- buttonsMessage.headerType = ButtonType.EMPTY;
1018
+ buttonsMessage.headerType = ButtonHeaderType.EMPTY;
516
1019
  }
517
1020
  else {
518
- if ('caption' in message) {
1021
+ if (hasOptionalProperty(message, 'caption')) {
519
1022
  buttonsMessage.contentText = message.caption;
520
1023
  }
521
1024
  const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
522
- buttonsMessage.headerType = ButtonType[type];
1025
+ buttonsMessage.headerType = ButtonHeaderType[type];
523
1026
  Object.assign(buttonsMessage, m);
524
1027
  }
525
- if ('footer' in message && !!message.footer) {
1028
+ if (hasOptionalProperty(message, 'footer')) {
526
1029
  buttonsMessage.footerText = message.footer;
527
1030
  }
528
1031
  m = { buttonsMessage };
529
1032
  }
530
- else if ('templateButtons' in message && !!message.templateButtons) {
531
- const msg = {
532
- hydratedButtons: message.templateButtons
1033
+ else if (hasNonNullishProperty(message, 'sections')) {
1034
+ const listMessage = {
1035
+ sections: message.sections,
1036
+ buttonText: message.buttonText,
1037
+ title: message.title,
1038
+ footerText: message.footer,
1039
+ description: message.text,
1040
+ listType: ListType.SINGLE_SELECT
533
1041
  };
534
- if ('text' in message) {
535
- msg.hydratedContentText = message.text;
1042
+ m = { listMessage };
1043
+ }
1044
+ // 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 ಥ⁠‿⁠ಥ)
1045
+ else if (hasNonNullishProperty(message, 'templateButtons')) {
1046
+ const hydratedTemplate = {
1047
+ hydratedButtons: message.templateButtons.map((button, i) => {
1048
+ const buttonText = button.text || button.buttonText;
1049
+ if (hasOptionalProperty(button, 'id')) {
1050
+ return {
1051
+ index: i,
1052
+ quickReplyButton: {
1053
+ displayText: buttonText || '👉🏻 Click',
1054
+ id: button.id
1055
+ }
1056
+ };
1057
+ }
1058
+ else if (hasOptionalProperty(button, 'url')) {
1059
+ return {
1060
+ index: i,
1061
+ urlButton: {
1062
+ displayText: buttonText || '🌐 Visit',
1063
+ url: button.url
1064
+ }
1065
+ };
1066
+ }
1067
+ else if (hasOptionalProperty(button, 'call')) {
1068
+ return {
1069
+ index: i,
1070
+ callButton: {
1071
+ displayText: buttonText || '📞 Call',
1072
+ phoneNumber: button.call
1073
+ }
1074
+ };
1075
+ }
1076
+ button.index = button.index || i;
1077
+ return button;
1078
+ })
1079
+ };
1080
+ if (hasOptionalProperty(message, 'text')) {
1081
+ hydratedTemplate.hydratedContentText = message.text;
536
1082
  }
537
1083
  else {
538
- if ('caption' in message) {
539
- msg.hydratedContentText = message.caption;
1084
+ if (hasOptionalProperty(message, 'caption')) {
1085
+ hydratedTemplate.hydratedTitleText = message.title;
1086
+ hydratedTemplate.hydratedContentText = message.caption;
540
1087
  }
541
- Object.assign(msg, m);
1088
+ ;
1089
+ Object.assign(hydratedTemplate, m);
542
1090
  }
543
- if ('footer' in message && !!message.footer) {
544
- msg.hydratedFooterText = message.footer;
1091
+ if (hasOptionalProperty(message, 'footer')) {
1092
+ hydratedTemplate.hydratedFooterText = message.footer;
545
1093
  }
1094
+ hydratedTemplate.templateId = message.id || 'template-' + Date.now(); // Lia@Note 04-02-26 --- Minimal templateId to satisfy WhatsApp (⁠ ⁠ꈍ⁠ᴗ⁠ꈍ⁠)
546
1095
  m = {
547
1096
  templateMessage: {
548
- fourRowTemplate: msg,
549
- hydratedTemplate: msg
1097
+ hydratedFourRowTemplate: hydratedTemplate,
1098
+ hydratedTemplate: hydratedTemplate
550
1099
  }
551
1100
  };
552
1101
  }
553
- if ('sections' in message && !!message.sections) {
554
- const listMessage = {
555
- sections: message.sections,
556
- buttonText: message.buttonText,
557
- title: message.title,
558
- footerText: message.footer,
559
- description: message.text,
560
- listType: proto.Message.ListMessage.ListType.SINGLE_SELECT
1102
+ else if (hasNonNullishProperty(message, 'nativeFlow')) {
1103
+ const interactiveMessage = {
1104
+ nativeFlowMessage: prepareNativeFlowButtons(message)
561
1105
  };
562
- m = { listMessage };
1106
+ if (hasOptionalProperty(message, 'bizJid')) {
1107
+ interactiveMessage.collectionMessage = {
1108
+ bizJid: message.bizJid,
1109
+ id: message.id,
1110
+ messageVersion: 1
1111
+ };
1112
+ }
1113
+ else if (hasOptionalProperty(message, 'shopSurface')) {
1114
+ interactiveMessage.shopStorefrontMessage = {
1115
+ surface: message.shopSurface,
1116
+ id: message.id,
1117
+ messageVersion: 1
1118
+ };
1119
+ }
1120
+ if (hasOptionalProperty(message, 'text')) {
1121
+ interactiveMessage.body = { text: message.text };
1122
+ }
1123
+ else {
1124
+ if (hasOptionalProperty(message, 'caption')) {
1125
+ const isValidHeader = hasValidInteractiveHeader(m);
1126
+ if (!isValidHeader) {
1127
+ throw new Boom('Invalid media type for interactive message header', { statusCode: 400 });
1128
+ }
1129
+ interactiveMessage.header = {
1130
+ title: message.title || '',
1131
+ subtitle: message.subtitle || '',
1132
+ hasMediaAttachment: isValidHeader
1133
+ };
1134
+ interactiveMessage.body = { text: message.caption };
1135
+ }
1136
+ if (hasOptionalProperty(message, 'thumbnail') && !!message.thumbnail) {
1137
+ interactiveMessage.jpegThumbnail = message.thumbnail;
1138
+ }
1139
+ Object.assign(interactiveMessage.header, m);
1140
+ }
1141
+ if (hasOptionalProperty(message, 'audioFooter')) {
1142
+ const { audioMessage } = await prepareWAMessageMedia({
1143
+ audio: message.audioFooter
1144
+ }, options);
1145
+ interactiveMessage.footer = {
1146
+ audioMessage,
1147
+ hasMediaAttachment: true
1148
+ };
1149
+ }
1150
+ else if (hasOptionalProperty(message, 'footer')) {
1151
+ interactiveMessage.footer = { text: message.footer };
1152
+ }
1153
+ m = { interactiveMessage };
563
1154
  }
564
- if ('viewOnce' in message && !!message.viewOnce) {
565
- m = { viewOnceMessage: { message: m } };
1155
+ else if (hasNonNullishProperty(message, 'cards')) {
1156
+ const interactiveMessage = {
1157
+ carouselMessage: {
1158
+ cards: await Promise.all(message.cards.map(async (card) => {
1159
+ let carouselHeader = {};
1160
+ if (hasNonNullishProperty(card, 'product')) {
1161
+ carouselHeader.productMessage = await prepareProductMessage(card, options);
1162
+ }
1163
+ else {
1164
+ carouselHeader = await prepareWAMessageMedia(card, options).catch(() => ({}));
1165
+ }
1166
+ const isValidHeader = hasValidCarouselHeader(carouselHeader);
1167
+ if (!isValidHeader) {
1168
+ throw new Boom('Invalid media type for carousel card', { statusCode: 400 });
1169
+ }
1170
+ const carouselCard = {
1171
+ nativeFlowMessage: prepareNativeFlowButtons(card.nativeFlow ? card : [])
1172
+ };
1173
+ if (hasOptionalProperty(card, 'text')) {
1174
+ carouselCard.body = { text: card.text };
1175
+ }
1176
+ else {
1177
+ if (hasOptionalProperty(card, 'caption')) {
1178
+ carouselCard.header = {
1179
+ title: card.title || '',
1180
+ subtitle: card.subtitle || '',
1181
+ hasMediaAttachment: isValidHeader
1182
+ };
1183
+ carouselCard.body = { text: card.caption };
1184
+ }
1185
+ if (hasOptionalProperty(card, 'thumbnail') && !!card.thumbnail) {
1186
+ carouselCard.jpegThumbnail = card.thumbnail;
1187
+ }
1188
+ Object.assign(carouselCard.header, carouselHeader);
1189
+ }
1190
+ if (hasOptionalProperty(card, 'audioFooter')) {
1191
+ const { audioMessage } = await prepareWAMessageMedia({
1192
+ audio: card.audioFooter
1193
+ }, options);
1194
+ carouselCard.footer = {
1195
+ audioMessage,
1196
+ hasMediaAttachment: true
1197
+ };
1198
+ }
1199
+ else if (hasOptionalProperty(card, 'footer')) {
1200
+ carouselCard.footer = { text: card.footer };
1201
+ }
1202
+ return carouselCard;
1203
+ })),
1204
+ carouselCardType: CarouselCardType.UNKNOWN,
1205
+ messageVersion: 1
1206
+ }
1207
+ };
1208
+ if (hasOptionalProperty(message, 'text')) {
1209
+ interactiveMessage.body = { text: message.text };
1210
+ }
1211
+ if (hasOptionalProperty(message, 'footer')) {
1212
+ interactiveMessage.footer = { text: message.footer };
1213
+ }
1214
+ m = { interactiveMessage };
566
1215
  }
567
- if ('mentions' in message && message.mentions?.length) {
1216
+ // Lia@Changes 01-02-26 --- Add request payment message
1217
+ else if (hasNonNullishProperty(message, 'requestPaymentFrom')) {
1218
+ const requestPaymentMessage = {
1219
+ amount: {
1220
+ currencyCode: 'IDR',
1221
+ offset: 1000,
1222
+ value: 1000
1223
+ },
1224
+ amount1000: 1000,
1225
+ currencyCodeIso4217: 'IDR',
1226
+ expiryTimestamp: Date.now(),
1227
+ noteMessage: m,
1228
+ requestFrom: message.requestPaymentFrom,
1229
+ ...message
1230
+ };
1231
+ delete requestPaymentMessage.requestPaymentFrom;
1232
+ if (hasNonNullishProperty(m, 'extendedTextMessage') || hasNonNullishProperty(m, 'stickerMessage')) {
1233
+ Object.assign(requestPaymentMessage.noteMessage, m);
1234
+ }
1235
+ else {
1236
+ throw new Boom('Invalid message type for request payment note message', { statusCode: 400 });
1237
+ }
1238
+ m = { requestPaymentMessage };
1239
+ }
1240
+ // Lia@Changes 01-02-26 --- Add invoice message
1241
+ else if (hasNonNullishProperty(message, 'invoiceNote')) {
1242
+ const attachment = m.imageMessage || m.documentMessage;
1243
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
1244
+ const invoiceMessage = {
1245
+ attachmentType: proto.Message.InvoiceMessage.AttachmentType[type === 'DOCUMENT' ? 'PDF' : 'IMAGE'],
1246
+ note: message.invoiceNote
1247
+ };
1248
+ if (attachment) {
1249
+ const { directPath, fileEncSha256, fileSha256, jpegThumbnail = undefined, mediaKey, mediaKeyTimestamp, mimetype } = attachment;
1250
+ Object.assign(invoiceMessage, {
1251
+ attachmentDirectPath: directPath,
1252
+ attachmentFileEncSha256: fileEncSha256,
1253
+ attachmentFileSha256: fileSha256,
1254
+ attachmentJpegThumbnail: jpegThumbnail,
1255
+ attachmentMediaKey: mediaKey,
1256
+ attachmentMediaKeyTimestamp: mediaKeyTimestamp,
1257
+ attachmentMimetype: mimetype,
1258
+ token: generateMessageIDV2()
1259
+ });
1260
+ }
1261
+ else {
1262
+ throw new Boom('Invalid media type for invoice message', { statusCode: 400 });
1263
+ }
1264
+ m = { invoiceMessage };
1265
+ }
1266
+ // Lia@Changes 31-01-26 --- Add direct externalAdReply access (no need to create contextInfo first)
1267
+ if (hasOptionalProperty(message, 'externalAdReply') && !!message.externalAdReply) {
568
1268
  const messageType = Object.keys(m)[0];
569
1269
  const key = m[messageType];
1270
+ const content = message.externalAdReply;
1271
+ if ('thumbnail' in content && !Buffer.isBuffer(content.thumbnail)) {
1272
+ throw new Boom('Thumbnail must in buffer type', { statusCode: 400 });
1273
+ }
1274
+ if (!content.url || typeof content.url !== 'string') {
1275
+ content.url = DONATE_URL; // Lia@Note 02-02-26 --- Apologies if this feels cheeky, just a fallback
1276
+ }
1277
+ const externalAdReply = {
1278
+ ...content,
1279
+ body: content.body,
1280
+ mediaType: content.mediaType || 1,
1281
+ mediaUrl: content.url,
1282
+ renderLargerThumbnail: content.largeThumbnail,
1283
+ sourceUrl: content.url,
1284
+ thumbnail: content.thumbnail,
1285
+ thumbnailUrl: content.url + '?update=' + Date.now(),
1286
+ title: content.title || LIBRARY_NAME
1287
+ };
1288
+ delete externalAdReply.subTitle;
1289
+ delete externalAdReply.largeThumbnail;
1290
+ delete externalAdReply.url;
570
1291
  if ('contextInfo' in key && !!key.contextInfo) {
571
- key.contextInfo.mentionedJid = message.mentions;
1292
+ key.contextInfo.externalAdReply = { ...key.contextInfo.externalAdReply, ...externalAdReply };
1293
+ }
1294
+ else if (key) {
1295
+ key.contextInfo = { externalAdReply };
1296
+ }
1297
+ }
1298
+ if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
1299
+ (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
1300
+ const messageType = Object.keys(m)[0];
1301
+ const key = m[messageType];
1302
+ if (key && 'contextInfo' in key) {
1303
+ key.contextInfo = key.contextInfo || {};
1304
+ if (message.mentions?.length) {
1305
+ key.contextInfo.mentionedJid = message.mentions;
1306
+ }
1307
+ if (message.mentionAll) {
1308
+ key.contextInfo.nonJidMentions = 1;
1309
+ }
572
1310
  }
573
1311
  else if (key) {
574
1312
  key.contextInfo = {
575
- mentionedJid: message.mentions
1313
+ mentionedJid: message.mentions,
1314
+ nonJidMentions: message.mentionAll ? 1 : 0
576
1315
  };
577
1316
  }
578
1317
  }
579
- if ('edit' in message) {
1318
+ if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
1319
+ const messageType = Object.keys(m)[0];
1320
+ const key = m[messageType];
1321
+ if ('contextInfo' in key && !!key.contextInfo) {
1322
+ key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
1323
+ }
1324
+ else if (key) {
1325
+ key.contextInfo = message.contextInfo;
1326
+ }
1327
+ }
1328
+ // Lia@Changes 31-01-26 --- Add "groupStatus" boolean to set contextInfo.isGroupStatus and wrap message into groupStatusMessageV2
1329
+ if (hasOptionalProperty(message, 'groupStatus') && !!message.groupStatus) {
1330
+ const messageType = Object.keys(m)[0];
1331
+ const key = m[messageType];
1332
+ if ('contextInfo' in key && !!key.contextInfo) {
1333
+ key.contextInfo.isGroupStatus = message.groupStatus;
1334
+ }
1335
+ else if (key) {
1336
+ key.contextInfo = {
1337
+ isGroupStatus: message.groupStatus
1338
+ };
1339
+ }
1340
+ m = { groupStatusMessageV2: { message: m } };
1341
+ delete message.groupStatus;
1342
+ }
1343
+ // Lia@Changes 06-05-26 --- Add "spoiler" boolean to set contextInfo.isSpoiler and wrap message into spoilerMessage
1344
+ if (hasOptionalProperty(message, 'spoiler') && !!message.spoiler) {
1345
+ const messageType = Object.keys(m)[0];
1346
+ const key = m[messageType];
1347
+ if ('contextInfo' in key && !!key.contextInfo) {
1348
+ key.contextInfo.isSpoiler = message.spoiler;
1349
+ }
1350
+ else if (key) {
1351
+ key.contextInfo = {
1352
+ isSpoiler: message.spoiler
1353
+ };
1354
+ }
1355
+ m = { spoilerMessage: { message: m } };
1356
+ delete message.spoiler;
1357
+ }
1358
+ // Lia@Changes 02-02-26 --- Add "interactiveAsTemplate" boolean to wrap interactiveMessage into templateMessage
1359
+ else if (hasOptionalProperty(message, 'interactiveAsTemplate') && !!message.interactiveAsTemplate) {
1360
+ if (!m.interactiveMessage) {
1361
+ throw new Boom('Invalid message type for template', { statusCode: 400 }); // Lia@Note 02-02-26 --- To avoid bug 👀
1362
+ }
1363
+ m = {
1364
+ templateMessage: {
1365
+ interactiveMessageTemplate: m.interactiveMessage,
1366
+ templateId: message.id || 'template-' + Date.now() // Lia@Note 04-02-26 --- Minimal templateId to satisfy WhatsApp (⁠ ⁠ꈍ⁠ᴗ⁠ꈍ⁠)
1367
+ }
1368
+ };
1369
+ delete message.interactiveAsTemplate;
1370
+ }
1371
+ // Lia@Changes 30-01-26 --- Add "ephemeral" boolean to wrap message into ephemeralMessage like "viewOnce"
1372
+ if (hasOptionalProperty(message, 'ephemeral') && !!message.ephemeral) {
1373
+ m = { ephemeralMessage: { message: m } };
1374
+ delete message.ephemeral;
1375
+ }
1376
+ // Lia@Changes 16-05-26 --- Add wrap message into lottieStickerMessage by isLottie boolean
1377
+ if (hasOptionalProperty(message, 'isLottie') && !!message.isLottie) {
1378
+ m = { lottieStickerMessage: { message: m } };
1379
+ }
1380
+ else if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
1381
+ m = { viewOnceMessage: { message: m } };
1382
+ }
1383
+ // Lia@Changes 03-02-26 --- Add "viewOnceV2" boolean to wrap message into viewOnceMessageV2 like "viewOnce"
1384
+ else if (hasOptionalProperty(message, 'viewOnceV2') && !!message.viewOnceV2) {
1385
+ m = { viewOnceMessageV2: { message: m } };
1386
+ delete message.viewOnceV2;
1387
+ }
1388
+ // Lia@Changes 03-02-26 --- Add "viewOnceV2Extension" boolean to wrap message into viewOnceMessageV2Extension like "viewOnce"
1389
+ else if (hasOptionalProperty(message, 'viewOnceV2Extension') && !!message.viewOnceV2Extension) {
1390
+ m = { viewOnceMessageV2Extension: { message: m } };
1391
+ delete message.viewOnceV2Extension;
1392
+ }
1393
+ if (hasOptionalProperty(message, 'edit')) {
580
1394
  m = {
581
1395
  protocolMessage: {
582
1396
  key: message.edit,
@@ -586,14 +1400,10 @@ export const generateWAMessageContent = async (message, options) => {
586
1400
  }
587
1401
  };
588
1402
  }
589
- if ('contextInfo' in message && !!message.contextInfo) {
590
- const messageType = Object.keys(m)[0];
591
- const key = m[messageType];
592
- if ('contextInfo' in key && !!key.contextInfo) {
593
- key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
594
- }
595
- else if (key) {
596
- key.contextInfo = message.contextInfo;
1403
+ if (shouldIncludeReportingToken(m)) {
1404
+ m.messageContextInfo = m.messageContextInfo || {};
1405
+ if (!m.messageContextInfo.messageSecret) {
1406
+ m.messageContextInfo.messageSecret = randomBytes(32);
597
1407
  }
598
1408
  }
599
1409
  return WAProto.Message.create(m);
@@ -605,10 +1415,12 @@ export const generateWAMessageFromContent = (jid, message, options) => {
605
1415
  options.timestamp = new Date();
606
1416
  }
607
1417
  const innerMessage = normalizeMessageContent(message);
1418
+ const messageContextInfo = message.messageContextInfo;
608
1419
  const key = getContentType(innerMessage);
609
1420
  const timestamp = unixTimestampSeconds(options.timestamp);
1421
+ const isNewsletter = isJidNewsletter(jid);
610
1422
  const { quoted, userJid } = options;
611
- if (quoted && !isJidNewsletter(jid)) {
1423
+ if (quoted) {
612
1424
  const participant = quoted.key.fromMe
613
1425
  ? userJid // TODO: Add support for LIDs
614
1426
  : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
@@ -626,7 +1438,7 @@ export const generateWAMessageFromContent = (jid, message, options) => {
626
1438
  contextInfo.quotedMessage = quotedMsg;
627
1439
  // if a participant is quoted, then it must be a group
628
1440
  // hence, remoteJid of group must also be entered
629
- if (jid !== quoted.key.remoteJid) {
1441
+ if (!isNewsletter && jid !== quoted.key.remoteJid) {
630
1442
  contextInfo.remoteJid = quoted.key.remoteJid;
631
1443
  }
632
1444
  if (contextInfo && innerMessage[key]) {
@@ -642,7 +1454,7 @@ export const generateWAMessageFromContent = (jid, message, options) => {
642
1454
  // already not converted to disappearing message
643
1455
  key !== 'ephemeralMessage' &&
644
1456
  // newsletters don't support ephemeral messages
645
- !isJidNewsletter(jid)) {
1457
+ !isNewsletter) {
646
1458
  /* @ts-ignore */
647
1459
  innerMessage[key].contextInfo = {
648
1460
  ...(innerMessage[key].contextInfo || {}),
@@ -650,6 +1462,14 @@ export const generateWAMessageFromContent = (jid, message, options) => {
650
1462
  //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
651
1463
  };
652
1464
  }
1465
+ // Lia@Changes 30-01-26 --- Add deviceListMetadata inside messageContextInfo for private chat
1466
+ if (messageContextInfo?.messageSecret && (isPnUser(jid) || isLidUser(jid))) {
1467
+ messageContextInfo.deviceListMetadata = {
1468
+ recipientKeyHash: randomBytes(10),
1469
+ recipientTimestamp: unixTimestampSeconds()
1470
+ };
1471
+ messageContextInfo.deviceListMetadataVersion = 2;
1472
+ }
653
1473
  message = WAProto.Message.create(message);
654
1474
  const messageJSON = {
655
1475
  key: {
@@ -669,7 +1489,10 @@ export const generateWAMessage = async (jid, content, options) => {
669
1489
  // ensure msg ID is with every log
670
1490
  options.logger = options?.logger?.child({ msgId: options.messageId });
671
1491
  // Pass jid in the options to generateWAMessageContent
672
- return generateWAMessageFromContent(jid, await generateWAMessageContent(content, { ...options, jid }), options);
1492
+ if (jid) {
1493
+ options.jid = jid;
1494
+ }
1495
+ return generateWAMessageFromContent(jid, await generateWAMessageContent(content, options), options);
673
1496
  };
674
1497
  /** Get the key to access the true type of content */
675
1498
  export const getContentType = (content) => {
@@ -698,13 +1521,35 @@ export const normalizeMessageContent = (content) => {
698
1521
  content = inner.message;
699
1522
  }
700
1523
  return content;
1524
+ // Lia@Changes 03-02-26 --- Add all futureProofMessage into getFutureProofMessage()
701
1525
  function getFutureProofMessage(message) {
702
- return (message?.ephemeralMessage ||
703
- message?.viewOnceMessage ||
1526
+ return (message?.associatedChildMessage ||
1527
+ message?.botForwardedMessage ||
1528
+ message?.botInvokeMessage ||
1529
+ message?.botTaskMessage ||
704
1530
  message?.documentWithCaptionMessage ||
1531
+ message?.editedMessage ||
1532
+ message?.ephemeralMessage ||
1533
+ message?.eventCoverImage ||
1534
+ message?.groupMentionedMessage ||
1535
+ message?.groupStatusMentionMessage ||
1536
+ message?.groupStatusMessage ||
1537
+ message?.groupStatusMessageV2 ||
1538
+ message?.limitSharingMessage ||
1539
+ message?.lottieStickerMessage ||
1540
+ message?.newsletterAdminProfileMessage ||
1541
+ message?.newsletterAdminProfileMessageV2 ||
1542
+ message?.newsletterAdminProfileStatusMessage ||
1543
+ message?.pollCreationMessageV4 ||
1544
+ message?.pollCreationOptionImageMessage ||
1545
+ message?.questionMessage ||
1546
+ message?.questionReplyMessage ||
1547
+ message?.spoilerMessage ||
1548
+ message?.statusAddYours ||
1549
+ message?.statusMentionMessage ||
1550
+ message?.viewOnceMessage ||
705
1551
  message?.viewOnceMessageV2 ||
706
- message?.viewOnceMessageV2Extension ||
707
- message?.editedMessage);
1552
+ message?.viewOnceMessageV2Extension);
708
1553
  }
709
1554
  };
710
1555
  /**
@@ -786,6 +1631,13 @@ export const updateMessageWithPollUpdate = (msg, update) => {
786
1631
  }
787
1632
  msg.pollUpdates = reactions;
788
1633
  };
1634
+ /** Update the message with a new event response */
1635
+ export const updateMessageWithEventResponse = (msg, update) => {
1636
+ const authorID = getKeyAuthor(update.eventResponseMessageKey);
1637
+ const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
1638
+ responses.push(update);
1639
+ msg.eventResponses = responses;
1640
+ };
789
1641
  /**
790
1642
  * Aggregates all poll updates in a poll.
791
1643
  * @param msg the poll creation message
@@ -825,6 +1677,29 @@ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
825
1677
  }
826
1678
  return Object.values(voteHashMap);
827
1679
  }
1680
+ /**
1681
+ * Aggregates all event responses in an event message.
1682
+ * @param msg the event creation message
1683
+ * @param meId your jid
1684
+ * @returns A list of response types & their responders
1685
+ */
1686
+ export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
1687
+ const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
1688
+ const responseMap = {};
1689
+ for (const type of responseTypes) {
1690
+ responseMap[type] = {
1691
+ response: type,
1692
+ responders: []
1693
+ };
1694
+ }
1695
+ for (const update of eventResponses || []) {
1696
+ const responseType = update.eventResponse || 'UNKNOWN';
1697
+ if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
1698
+ responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
1699
+ }
1700
+ }
1701
+ return Object.values(responseMap);
1702
+ }
828
1703
  /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
829
1704
  export const aggregateMessageKeysNotFromMe = (keys) => {
830
1705
  const keyMap = {};
@@ -894,7 +1769,7 @@ export const downloadMediaMessage = async (message, type, options, ctx) => {
894
1769
  return stream;
895
1770
  }
896
1771
  };
897
-
1772
+ /** Checks whether the given message is a media message; if it is returns the inner content */
898
1773
  export const assertMediaContent = (content) => {
899
1774
  content = extractMessageContent(content);
900
1775
  const mediaContent = content?.documentMessage ||
@@ -906,4 +1781,81 @@ export const assertMediaContent = (content) => {
906
1781
  throw new Boom('given message is not a media message', { statusCode: 400, data: content });
907
1782
  }
908
1783
  return mediaContent;
909
- };
1784
+ };
1785
+ /**
1786
+ * Checks if a WebP buffer is animated by looking for VP8X chunk with animation flag
1787
+ * or ANIM/ANMF chunks
1788
+ */
1789
+ const isAnimatedWebP = (buffer) => {
1790
+ // WebP must start with RIFF....WEBP
1791
+ if (buffer.length < 12 ||
1792
+ buffer[0] !== 0x52 ||
1793
+ buffer[1] !== 0x49 ||
1794
+ buffer[2] !== 0x46 ||
1795
+ buffer[3] !== 0x46 ||
1796
+ buffer[8] !== 0x57 ||
1797
+ buffer[9] !== 0x45 ||
1798
+ buffer[10] !== 0x42 ||
1799
+ buffer[11] !== 0x50) {
1800
+ return false;
1801
+ }
1802
+ ;
1803
+ // Parse chunks starting after RIFF header (12 bytes)
1804
+ let offset = 12;
1805
+ while (offset < buffer.length - 8) {
1806
+ const chunkFourCC = buffer.toString('ascii', offset, offset + 4);
1807
+ const chunkSize = buffer.readUInt32LE(offset + 4);
1808
+ if (chunkFourCC === 'VP8X') {
1809
+ // VP8X extended header, check animation flag (bit 1 at offset+8)
1810
+ const flagsOffset = offset + 8;
1811
+ if (flagsOffset < buffer.length) {
1812
+ const flags = buffer[flagsOffset];
1813
+ if (flags & 0x02) {
1814
+ return true;
1815
+ }
1816
+ ;
1817
+ }
1818
+ ;
1819
+ }
1820
+ else if (chunkFourCC === 'ANIM' || chunkFourCC === 'ANMF') {
1821
+ // ANIM or ANMF chunks indicate animation
1822
+ return true;
1823
+ }
1824
+ ;
1825
+ // Move to next chunk (chunk size + 8 bytes header, padded to even)
1826
+ offset += 8 + chunkSize + (chunkSize % 2);
1827
+ }
1828
+ ;
1829
+ return false;
1830
+ };
1831
+ /**
1832
+ * Checks if a buffer is a WebP file
1833
+ */
1834
+ const isWebPBuffer = (buffer) => {
1835
+ return (buffer.length >= 12 &&
1836
+ buffer[0] === 0x52 &&
1837
+ buffer[1] === 0x49 &&
1838
+ buffer[2] === 0x46 &&
1839
+ buffer[3] === 0x46 &&
1840
+ buffer[8] === 0x57 &&
1841
+ buffer[9] === 0x45 &&
1842
+ buffer[10] === 0x42 &&
1843
+ buffer[11] === 0x50);
1844
+ };
1845
+ /**
1846
+ * Lia@Changes 30-01-26
1847
+ * ---
1848
+ * Determines whether a message should include a Biz Binary Node.
1849
+ * A Biz Binary Node is added only for interactive messages
1850
+ * such as buttons or other supported interactive types.
1851
+ */
1852
+ export const shouldIncludeBizBinaryNode = (message) => {
1853
+ const hasValidInteractive = message.interactiveMessage &&
1854
+ !message.interactiveMessage.carouselMessage &&
1855
+ !message.interactiveMessage.collectionMessage &&
1856
+ !message.interactiveMessage.shopStorefrontMessage;
1857
+ return (message.buttonsMessage ||
1858
+ message.interactiveMessage ||
1859
+ message.listMessage ||
1860
+ hasValidInteractive);
1861
+ };