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