@vanzxy/baileys 1.4.0 → 1.4.2

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