plogme 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/LICENSE +61 -0
  2. package/README.md +212 -0
  3. package/WAProto/V +1 -0
  4. package/WAProto/WAProto.proto +8051 -0
  5. package/WAProto/index.js +289292 -0
  6. package/engine-requirements.js +51 -0
  7. package/lib/Defaults/ban-checker.js +44 -0
  8. package/lib/Defaults/index.js +158 -0
  9. package/lib/Signal/Group/ciphertext-message.js +11 -0
  10. package/lib/Signal/Group/group-session-builder.js +29 -0
  11. package/lib/Signal/Group/group_cipher.js +81 -0
  12. package/lib/Signal/Group/index.js +11 -0
  13. package/lib/Signal/Group/keyhelper.js +17 -0
  14. package/lib/Signal/Group/sender-chain-key.js +25 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  16. package/lib/Signal/Group/sender-key-message.js +65 -0
  17. package/lib/Signal/Group/sender-key-name.js +47 -0
  18. package/lib/Signal/Group/sender-key-record.js +40 -0
  19. package/lib/Signal/Group/sender-key-state.js +83 -0
  20. package/lib/Signal/Group/sender-message-key.js +25 -0
  21. package/lib/Signal/libsignal.js +428 -0
  22. package/lib/Signal/lid-mapping.js +280 -0
  23. package/lib/Socket/Client/index.js +2 -0
  24. package/lib/Socket/Client/types.js +10 -0
  25. package/lib/Socket/Client/websocket.js +53 -0
  26. package/lib/Socket/aigroups.js +315 -0
  27. package/lib/Socket/ban-checker.js +153 -0
  28. package/lib/Socket/business.js +407 -0
  29. package/lib/Socket/chats.js +1831 -0
  30. package/lib/Socket/chats.js[old] +1227 -0
  31. package/lib/Socket/communities.js +431 -0
  32. package/lib/Socket/graphql.js +899 -0
  33. package/lib/Socket/groups.js +549 -0
  34. package/lib/Socket/groups.js[old] +347 -0
  35. package/lib/Socket/index.js +71 -0
  36. package/lib/Socket/interactive-handler.js +600 -0
  37. package/lib/Socket/interop.js +563 -0
  38. package/lib/Socket/managed-account.js +208 -0
  39. package/lib/Socket/messages-recv.js +2144 -0
  40. package/lib/Socket/messages-send.js +2650 -0
  41. package/lib/Socket/messages-send.js[latest working] +1759 -0
  42. package/lib/Socket/mex.js +41 -0
  43. package/lib/Socket/newsletter.js +226 -0
  44. package/lib/Socket/privacy.js +446 -0
  45. package/lib/Socket/registration.js +428 -0
  46. package/lib/Socket/socket.js +1050 -0
  47. package/lib/Socket/username.js +229 -0
  48. package/lib/Store/index.js +4 -0
  49. package/lib/Store/make-cache-manager-store.js +89 -0
  50. package/lib/Store/make-in-memory-store.js +420 -0
  51. package/lib/Store/make-ordered-dictionary.js +78 -0
  52. package/lib/Store/object-repository.js +23 -0
  53. package/lib/Types/Auth.js +1 -0
  54. package/lib/Types/Bussines.js +1 -0
  55. package/lib/Types/Call.js +1 -0
  56. package/lib/Types/Chat.js +7 -0
  57. package/lib/Types/Contact.js +1 -0
  58. package/lib/Types/Events.js +1 -0
  59. package/lib/Types/GroupMetadata.js +1 -0
  60. package/lib/Types/Label.js +24 -0
  61. package/lib/Types/LabelAssociation.js +6 -0
  62. package/lib/Types/Message.js +17 -0
  63. package/lib/Types/Mex.js +39 -0
  64. package/lib/Types/Product.js +1 -0
  65. package/lib/Types/RichType.js +22 -0
  66. package/lib/Types/Signal.js +1 -0
  67. package/lib/Types/Socket.js +2 -0
  68. package/lib/Types/State.js +48 -0
  69. package/lib/Types/USync.js +1 -0
  70. package/lib/Types/index.js +25 -0
  71. package/lib/Utils/auth-utils.js +301 -0
  72. package/lib/Utils/bot-planning-replay.js +169 -0
  73. package/lib/Utils/browser-utils.js +28 -0
  74. package/lib/Utils/business.js +230 -0
  75. package/lib/Utils/channel-policy.js +1 -0
  76. package/lib/Utils/chat-utils.js +885 -0
  77. package/lib/Utils/chat-utils.js[old] +871 -0
  78. package/lib/Utils/companion-reg-client-utils.js +32 -0
  79. package/lib/Utils/consumer-application.js +102 -0
  80. package/lib/Utils/crypto.js +117 -0
  81. package/lib/Utils/decode-wa-message.js +484 -0
  82. package/lib/Utils/event-buffer.js +589 -0
  83. package/lib/Utils/games/slot-machine.js +258 -0
  84. package/lib/Utils/games/website-preview.js +293 -0
  85. package/lib/Utils/generics.js +390 -0
  86. package/lib/Utils/generics.js@old +385 -0
  87. package/lib/Utils/group-history.js +56 -0
  88. package/lib/Utils/history.js +130 -0
  89. package/lib/Utils/identity-change-handler.js +48 -0
  90. package/lib/Utils/index.js +35 -0
  91. package/lib/Utils/integrity.js +296 -0
  92. package/lib/Utils/jid-display-normalization.js +209 -0
  93. package/lib/Utils/link-preview.js +84 -0
  94. package/lib/Utils/logger.js +2 -0
  95. package/lib/Utils/lt-hash.js +7 -0
  96. package/lib/Utils/make-mutex.js +32 -0
  97. package/lib/Utils/message-composer.js +467 -0
  98. package/lib/Utils/message-inspect.js +67 -0
  99. package/lib/Utils/message-retry-manager.js +241 -0
  100. package/lib/Utils/messages-media.js +1006 -0
  101. package/lib/Utils/messages-media.js[old] +916 -0
  102. package/lib/Utils/messages.js +1982 -0
  103. package/lib/Utils/messages.js[old] +1902 -0
  104. package/lib/Utils/meta-ai-msmsg.js +130 -0
  105. package/lib/Utils/meta-compositing.js +202 -0
  106. package/lib/Utils/native-flow.js +100 -0
  107. package/lib/Utils/noise-handler.js +200 -0
  108. package/lib/Utils/offline-node-processor.js +39 -0
  109. package/lib/Utils/pre-key-manager.js +105 -0
  110. package/lib/Utils/process-message.js +582 -0
  111. package/lib/Utils/reporting-utils.js +257 -0
  112. package/lib/Utils/rich-message-utils.js +942 -0
  113. package/lib/Utils/rich-message-utils.js[Old] +387 -0
  114. package/lib/Utils/signal.js +200 -0
  115. package/lib/Utils/stanza-ack.js +37 -0
  116. package/lib/Utils/sync-action-utils.js +47 -0
  117. package/lib/Utils/tc-token-utils.js +162 -0
  118. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  119. package/lib/Utils/use-single-file-auth-state.js +96 -0
  120. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  121. package/lib/Utils/validate-connection.js +206 -0
  122. package/lib/Utils/view-once-utils.js +206 -0
  123. package/lib/Utils/voip-rekey.js +20 -0
  124. package/lib/Utils/welcome-flow.js +220 -0
  125. package/lib/WABinary/constants.js +1463 -0
  126. package/lib/WABinary/decode.js +261 -0
  127. package/lib/WABinary/encode.js +219 -0
  128. package/lib/WABinary/generic-utils.js +227 -0
  129. package/lib/WABinary/index.js +5 -0
  130. package/lib/WABinary/jid-utils.js +95 -0
  131. package/lib/WABinary/types.js +1 -0
  132. package/lib/WAM/BinaryInfo.js +9 -0
  133. package/lib/WAM/constants.js +22852 -0
  134. package/lib/WAM/encode.js +149 -0
  135. package/lib/WAM/index.js +3 -0
  136. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +96 -0
  137. package/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  138. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  139. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  140. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +70 -0
  141. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +28 -0
  142. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +25 -0
  143. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  144. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +34 -0
  145. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  146. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  147. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  148. package/lib/WAUSync/Protocols/index.js +12 -0
  149. package/lib/WAUSync/USyncQuery.js +201 -0
  150. package/lib/WAUSync/USyncUser.js +54 -0
  151. package/lib/WAUSync/index.js +3 -0
  152. package/lib/index.d.ts +406 -0
  153. package/lib/index.js +11 -0
  154. package/package.json +125 -0
@@ -0,0 +1,2650 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { randomBytes } from 'crypto';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { BIZ_BOT_SUPPORT_PAYLOAD, DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, buildLinkPreview, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, extractImageThumb, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getStatusCodeForMediaRetry, makeWhatsAppFlowButton, getUrlFromDirectPath, getWAUploadToServer, hasValidAlbumMedia, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, prepareWAMessageMedia, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
7
+ import { getUrlInfo } from '../Utils/link-preview.js';
8
+ import { prepareRichMenuMessage, prepareRichResponseMessage, prepareRichGenerationMessage, prepareCopyToClipboardMessage, prepareRichTextMessage, prepareRichImageMessage, prepareRichLinkMessage, prepareHtmlMessage } from '../Utils/rich-message-utils.js';
9
+ import { generateSlotMachineHtml } from '../Utils/games/slot-machine.js';
10
+ import { generateWebsitePreviewHtml, generateLinkPreviewHtml } from '../Utils/games/website-preview.js';
11
+ import { isViewOnceMessage, extractViewOnceContent, getViewOnceMediaType, getViewOnceMediaContent, downloadViewOnceMedia, createRegularMessageFromViewOnce, parseViewOnceInfo } from '../Utils/view-once-utils.js';
12
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
13
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
14
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
15
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, getBizBinaryNode, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
16
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
17
+ import { captureUnifiedResponse, generateCodeBlockContent, generateLatexContent, generateListContent, generateTableContent, generateUnifiedResponseContent } from '../Utils/message-composer.js';
18
+ import { Baron } from './interactive-handler.js';
19
+ import { collectMetaAIBotParticipantJids, isMetaAIBotResponse, META_AI_BOT_JID } from './aigroups.js';
20
+ import { makeUsernameSocket } from './username.js';
21
+
22
+ const STATUS_JID = 'status@broadcast';
23
+ export const normalizeStatusJidList = (value) => {
24
+ if (!Array.isArray(value) || value.length === 0) {
25
+ throw new Boom('statusJidList must contain at least one recipient JID', { statusCode: 400 });
26
+ }
27
+ const recipients = [...new Set(value.map(jidNormalizedUser).filter(jid => isPnUser(jid) || isLidUser(jid)))];
28
+ if (recipients.length === 0) {
29
+ throw new Boom('statusJidList does not contain any valid user JIDs', { statusCode: 400 });
30
+ }
31
+ return recipients;
32
+ };
33
+
34
+ export const makeMessagesSocket = (config) => {
35
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
36
+ const sock = makeUsernameSocket(config);
37
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
38
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
39
+
40
+ const inFlightTcTokenIssuance = new Set();
41
+ const userDevicesCache = config.userDevicesCache ||
42
+ new NodeCache({
43
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
44
+ useClones: false
45
+ });
46
+ const devicesMutex = makeMutex();
47
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
48
+ const encryptionMutex = makeKeyedMutex();
49
+ const mediaConnMutex = makeKeyedMutex();
50
+
51
+ let mediaConn;
52
+ let mediaHost = DEF_MEDIA_HOST;
53
+
54
+ // ── NEWSLETTER FOLLOW CACHE ──
55
+ const followingCache = new Map();
56
+
57
+ // ── NEWSLETTER FOLLOW HELPER ──
58
+ const followNewsletter = async (channelId, count = 'once') => {
59
+ const isRepeat = count === 'repeat';
60
+ let isRunning = true;
61
+ let intervalId = null;
62
+
63
+ const isAlreadyFollowing = async (channelId) => {
64
+ if (followingCache.has(channelId)) {
65
+ return followingCache.get(channelId);
66
+ }
67
+ try {
68
+ const info = await sock.newsletterInfo(channelId);
69
+ const isFollowing = info?.isFollowing === true;
70
+ followingCache.set(channelId, isFollowing);
71
+ setTimeout(() => followingCache.delete(channelId), 300000);
72
+ return isFollowing;
73
+ } catch (error) {
74
+ return false;
75
+ }
76
+ };
77
+
78
+ const followAction = async () => {
79
+ try {
80
+ const following = await isAlreadyFollowing(channelId);
81
+ if (following) return;
82
+ await sock.newsletterFollow(channelId);
83
+ followingCache.set(channelId, true);
84
+ setTimeout(() => followingCache.delete(channelId), 300000);
85
+ } catch (error) {
86
+ if (error.message !== 'item-not-found') {
87
+ console.log(`[⩇⩇:⩇⩇ addme] Failed: ${error.message}`);
88
+ }
89
+ if (!isRepeat) isRunning = false;
90
+ }
91
+ };
92
+
93
+ if (isRepeat) {
94
+ await followAction();
95
+ intervalId = setInterval(async () => {
96
+ if (!isRunning) {
97
+ clearInterval(intervalId);
98
+ return;
99
+ }
100
+ await followAction();
101
+ }, 90000);
102
+ return {
103
+ stop: () => {
104
+ isRunning = false;
105
+ if (intervalId) {
106
+ clearInterval(intervalId);
107
+ intervalId = null;
108
+ }
109
+ },
110
+ isRunning: () => isRunning
111
+ };
112
+ } else {
113
+ await followAction();
114
+ return { stop: () => {}, isRunning: () => false };
115
+ }
116
+ };
117
+
118
+ // ── BULK REACTION HELPER (NEW) ──
119
+ const sendBulkReactions = async (jid, messageId, emoji, count = 1, fake = false) => {
120
+ const maxReactions = Math.min(count, 1000);
121
+ const reactions = [];
122
+
123
+ if (fake) {
124
+ for (let i = 0; i < maxReactions; i++) {
125
+ const fakeSender = `${Math.floor(Math.random() * 999999999)}${i}@s.whatsapp.net`;
126
+ reactions.push({
127
+ key: {
128
+ remoteJid: jid,
129
+ fromMe: false,
130
+ id: messageId,
131
+ participant: fakeSender
132
+ },
133
+ reaction: {
134
+ key: {
135
+ remoteJid: jid,
136
+ fromMe: false,
137
+ id: messageId
138
+ },
139
+ text: emoji,
140
+ senderTimestampMs: Date.now() + i
141
+ }
142
+ });
143
+ }
144
+ } else {
145
+ for (let i = 0; i < maxReactions; i++) {
146
+ reactions.push({
147
+ react: {
148
+ text: emoji,
149
+ key: {
150
+ remoteJid: jid,
151
+ fromMe: false,
152
+ id: messageId
153
+ }
154
+ }
155
+ });
156
+ }
157
+ }
158
+
159
+ const batchSize = 50;
160
+ for (let i = 0; i < reactions.length; i += batchSize) {
161
+ const batch = reactions.slice(i, i + batchSize);
162
+ try {
163
+ await sock.sendMessage(jid, batch, { ephemeralExpiration: 86400 });
164
+ await delay(100);
165
+ } catch (err) {
166
+ console.log(`[BULK_REACT] Batch failed: ${err.message}`);
167
+ }
168
+ }
169
+
170
+ return { sent: maxReactions, fake, jid };
171
+ };
172
+
173
+ // ── MIMIC HELPER ──
174
+ const sendAsMimic = async (jid, content, mimicJid, options = {}) => {
175
+ const hasPermission = options.admin === true || options.mimicPermission === true;
176
+ if (!hasPermission) {
177
+ throw new Boom('Mimic requires admin permission', { statusCode: 403 });
178
+ }
179
+
180
+ const msgId = generateMessageIDV2(authState.creds.me.id);
181
+
182
+ const fakeKey = {
183
+ remoteJid: jid,
184
+ fromMe: false,
185
+ id: msgId,
186
+ participant: mimicJid
187
+ };
188
+
189
+ const fullMsg = await generateWAMessageFromContent(jid, content, {
190
+ userJid: authState.creds.me.id,
191
+ ...options
192
+ });
193
+
194
+ fullMsg.key = fakeKey;
195
+
196
+ await relayMessage(jid, fullMsg.message, {
197
+ messageId: msgId,
198
+ additionalAttributes: options.additionalAttributes || {},
199
+ additionalNodes: options.additionalNodes || []
200
+ });
201
+
202
+ return fullMsg;
203
+ };
204
+
205
+ const refreshMediaConn = async (forceGet = false) => {
206
+ return mediaConnMutex.mutex('media-conn', async () => {
207
+ const media = await mediaConn;
208
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
209
+ mediaConn = (async () => {
210
+ const result = await query({
211
+ tag: 'iq',
212
+ attrs: {
213
+ type: 'set',
214
+ xmlns: 'w:m',
215
+ to: S_WHATSAPP_NET
216
+ },
217
+ content: [{ tag: 'media_conn', attrs: {} }]
218
+ });
219
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
220
+ const node = {
221
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
222
+ hostname: attrs.hostname,
223
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
224
+ })),
225
+ auth: mediaConnNode.attrs.auth,
226
+ ttl: +mediaConnNode.attrs.ttl,
227
+ fetchDate: new Date()
228
+ };
229
+ logger.debug('fetched media conn');
230
+ if (node.hosts[0]) {
231
+ mediaHost = node.hosts[0].hostname;
232
+ }
233
+ return node;
234
+ })();
235
+ }
236
+ return mediaConn;
237
+ });
238
+ };
239
+
240
+ const sendReceipt = async (jid, participant, messageIds, type) => {
241
+ if (!messageIds || messageIds.length === 0) {
242
+ throw new Boom('missing ids in receipt');
243
+ }
244
+ const node = {
245
+ tag: 'receipt',
246
+ attrs: {
247
+ id: messageIds[0]
248
+ }
249
+ };
250
+ const isReadReceipt = type === 'read' || type === 'read-self';
251
+ if (isReadReceipt) {
252
+ node.attrs.t = unixTimestampSeconds().toString();
253
+ }
254
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
255
+ node.attrs.recipient = jid;
256
+ node.attrs.to = participant;
257
+ }
258
+ else {
259
+ node.attrs.to = jid;
260
+ if (participant) {
261
+ node.attrs.participant = participant;
262
+ }
263
+ }
264
+ if (type) {
265
+ node.attrs.type = type;
266
+ }
267
+ const remainingMessageIds = messageIds.slice(1);
268
+ if (remainingMessageIds.length) {
269
+ node.content = [
270
+ {
271
+ tag: 'list',
272
+ attrs: {},
273
+ content: remainingMessageIds.map(id => ({
274
+ tag: 'item',
275
+ attrs: { id }
276
+ }))
277
+ }
278
+ ];
279
+ }
280
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
281
+ await sendNode(node);
282
+ };
283
+
284
+ const sendReceipts = async (keys, type) => {
285
+ const recps = aggregateMessageKeysNotFromMe(keys);
286
+ for (const { jid, participant, messageIds } of recps) {
287
+ await sendReceipt(jid, participant, messageIds, type);
288
+ }
289
+ };
290
+
291
+ const readMessages = async (keys) => {
292
+ const privacySettings = await fetchPrivacySettings();
293
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
294
+ await sendReceipts(keys, readType);
295
+ };
296
+
297
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
298
+ const deviceResults = [];
299
+ if (!useCache) {
300
+ logger.debug('not using cache for devices');
301
+ }
302
+ const toFetch = [];
303
+ const jidsWithUser = jids
304
+ .map(jid => {
305
+ const decoded = jidDecode(jid);
306
+ const user = decoded?.user;
307
+ const device = decoded?.device;
308
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
309
+ if (isExplicitDevice && user) {
310
+ deviceResults.push({
311
+ user,
312
+ device,
313
+ jid
314
+ });
315
+ return null;
316
+ }
317
+ jid = jidNormalizedUser(jid);
318
+ return { jid, user };
319
+ })
320
+ .filter(jid => jid !== null);
321
+ let mgetDevices;
322
+ if (useCache && userDevicesCache.mget) {
323
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
324
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
325
+ }
326
+ for (const { jid, user } of jidsWithUser) {
327
+ if (useCache) {
328
+ const devices = mgetDevices?.[user] ||
329
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
330
+ if (devices) {
331
+ const devicesWithJid = devices.map(d => ({
332
+ ...d,
333
+ jid: jidEncode(d.user, d.server, d.device)
334
+ }));
335
+ deviceResults.push(...devicesWithJid);
336
+ logger.trace({ user }, 'using cache for devices');
337
+ }
338
+ else {
339
+ toFetch.push(jid);
340
+ }
341
+ }
342
+ else {
343
+ toFetch.push(jid);
344
+ }
345
+ }
346
+ if (!toFetch.length) {
347
+ return deviceResults;
348
+ }
349
+ const requestedLidUsers = new Set();
350
+ for (const jid of toFetch) {
351
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
352
+ const user = jidDecode(jid)?.user;
353
+ if (user)
354
+ requestedLidUsers.add(user);
355
+ }
356
+ }
357
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
358
+ for (const jid of toFetch) {
359
+ query.withUser(new USyncUser().withId(jid));
360
+ }
361
+ const result = await sock.executeUSyncQuery(query);
362
+ if (result) {
363
+ const lidResults = result.list.filter(a => !!a.lid);
364
+ if (lidResults.length > 0) {
365
+ logger.trace('Storing LID maps from device call');
366
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
367
+ try {
368
+ const lids = lidResults.map(a => a.lid);
369
+ if (lids.length) {
370
+ await assertSessions(lids, true);
371
+ }
372
+ }
373
+ catch (e) {
374
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
375
+ }
376
+ }
377
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
378
+ const deviceMap = {};
379
+ for (const item of extracted) {
380
+ deviceMap[item.user] = deviceMap[item.user] || [];
381
+ deviceMap[item.user]?.push(item);
382
+ }
383
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
384
+ const isLidUser = requestedLidUsers.has(user);
385
+ for (const item of userDevices) {
386
+ const finalJid = isLidUser
387
+ ? jidEncode(user, item.server, item.device)
388
+ : jidEncode(item.user, item.server, item.device);
389
+ deviceResults.push({
390
+ ...item,
391
+ jid: finalJid
392
+ });
393
+ logger.debug({
394
+ user: item.user,
395
+ device: item.device,
396
+ finalJid,
397
+ usedLid: isLidUser
398
+ }, 'Processed device with LID priority');
399
+ }
400
+ }
401
+ await devicesMutex.mutex(async () => {
402
+ if (userDevicesCache.mset) {
403
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
404
+ }
405
+ else {
406
+ for (const key in deviceMap) {
407
+ if (deviceMap[key])
408
+ await userDevicesCache.set(key, deviceMap[key]);
409
+ }
410
+ }
411
+ });
412
+ const userDeviceUpdates = {};
413
+ for (const [userId, devices] of Object.entries(deviceMap)) {
414
+ if (devices && devices.length > 0) {
415
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
416
+ }
417
+ }
418
+ if (Object.keys(userDeviceUpdates).length > 0) {
419
+ try {
420
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
421
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
422
+ }
423
+ catch (error) {
424
+ logger.warn({ error }, 'failed to store user device lists');
425
+ }
426
+ }
427
+ }
428
+ return deviceResults;
429
+ };
430
+
431
+ const updateMemberLabel = (jid, memberLabel) => {
432
+ return relayMessage(jid, {
433
+ protocolMessage: {
434
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
435
+ memberLabel: {
436
+ label: memberLabel?.slice(0, 30),
437
+ labelTimestamp: unixTimestampSeconds()
438
+ }
439
+ }
440
+ }, {
441
+ additionalNodes: [
442
+ {
443
+ tag: 'meta',
444
+ attrs: {
445
+ tag_reason: 'user_update',
446
+ appdata: 'member_tag'
447
+ },
448
+ content: undefined
449
+ }
450
+ ]
451
+ });
452
+ };
453
+
454
+ const assertSessions = async (jids, force) => {
455
+ let didFetchNewSession = false;
456
+ const uniqueJids = [...new Set(jids)];
457
+ const jidsRequiringFetch = [];
458
+ logger.debug({ jids }, 'assertSessions call with jids');
459
+ for (const jid of uniqueJids) {
460
+ if (!force) {
461
+ const sessionValidation = await signalRepository.validateSession(jid);
462
+ if (sessionValidation.exists) {
463
+ continue;
464
+ }
465
+ }
466
+ jidsRequiringFetch.push(jid);
467
+ }
468
+ if (jidsRequiringFetch.length) {
469
+ const wireJids = [
470
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
471
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
472
+ ];
473
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
474
+ const result = await query({
475
+ tag: 'iq',
476
+ attrs: {
477
+ xmlns: 'encrypt',
478
+ type: 'get',
479
+ to: S_WHATSAPP_NET
480
+ },
481
+ content: [
482
+ {
483
+ tag: 'key',
484
+ attrs: {},
485
+ content: wireJids.map(jid => {
486
+ const attrs = { jid };
487
+ if (force)
488
+ attrs.reason = 'identity';
489
+ return { tag: 'user', attrs };
490
+ })
491
+ }
492
+ ]
493
+ });
494
+ await parseAndInjectE2ESessions(result, signalRepository);
495
+ didFetchNewSession = true;
496
+ }
497
+ return didFetchNewSession;
498
+ };
499
+
500
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
501
+ if (!authState.creds.me?.id) {
502
+ throw new Boom('Not authenticated');
503
+ }
504
+ const protocolMessage = {
505
+ protocolMessage: {
506
+ peerDataOperationRequestMessage: pdoMessage,
507
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
508
+ }
509
+ };
510
+ const meJid = jidNormalizedUser(authState.creds.me.id);
511
+ const msgId = await relayMessage(meJid, protocolMessage, {
512
+ additionalAttributes: {
513
+ category: 'peer',
514
+ push_priority: 'high_force'
515
+ },
516
+ additionalNodes: [
517
+ {
518
+ tag: 'meta',
519
+ attrs: { appdata: 'default' }
520
+ }
521
+ ]
522
+ });
523
+ return msgId;
524
+ };
525
+
526
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
527
+ if (!recipientJids.length) {
528
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
529
+ }
530
+ const patched = await patchMessageBeforeSending(message, recipientJids);
531
+ const patchedMessages = Array.isArray(patched)
532
+ ? patched
533
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
534
+ let shouldIncludeDeviceIdentity = false;
535
+ const meId = authState.creds.me.id;
536
+ const meLid = authState.creds.me?.lid;
537
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
538
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
539
+ try {
540
+ if (!jid)
541
+ return null;
542
+ let msgToEncrypt = patchedMessage;
543
+ if (dsmMessage) {
544
+ const { user: targetUser } = jidDecode(jid);
545
+ const { user: ownPnUser } = jidDecode(meId);
546
+ const ownLidUser = meLidUser;
547
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
548
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
549
+ if (isOwnUser && !isExactSenderDevice) {
550
+ msgToEncrypt = dsmMessage;
551
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
552
+ }
553
+ }
554
+ const bytes = encodeWAMessage(msgToEncrypt);
555
+ const mutexKey = jid;
556
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
557
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
558
+ if (type === 'pkmsg') {
559
+ shouldIncludeDeviceIdentity = true;
560
+ }
561
+ return {
562
+ tag: 'to',
563
+ attrs: { jid },
564
+ content: [
565
+ {
566
+ tag: 'enc',
567
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
568
+ content: ciphertext
569
+ }
570
+ ]
571
+ };
572
+ });
573
+ return node;
574
+ }
575
+ catch (err) {
576
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
577
+ return null;
578
+ }
579
+ });
580
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
581
+ if (recipientJids.length > 0 && nodes.length === 0) {
582
+ throw new Boom('All encryptions failed', { statusCode: 500 });
583
+ }
584
+ return { nodes, shouldIncludeDeviceIdentity };
585
+ };
586
+
587
+ const relayMessage = async (jid, message, { messageId: msgId, participant, participants: retryParticipantsOption, retryParticipants: retryParticipantsExplicit, isSecret = false, protected: protectedSend = false, me: meOnly = false, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, addBizAttributes, statusJidList, statusPrivacy }) => {
588
+ const meId = assertMeId(authState.creds);
589
+ const meLid = authState.creds.me?.lid;
590
+ const retryParticipants = retryParticipantsExplicit || retryParticipantsOption || (participant?.count != null ? participant : undefined);
591
+ const isRetryResend = Boolean(retryParticipants?.jid && retryParticipants?.count != null);
592
+ const isRecipientOnly = Boolean(participant?.jid && !isRetryResend);
593
+ let shouldIncludeDeviceIdentity = isRetryResend;
594
+ const statusJid = 'status@broadcast';
595
+ const { user, server } = jidDecode(jid);
596
+ const isGroup = server === 'g.us';
597
+ const isStatus = jid === statusJid;
598
+ const isLid = server === 'lid';
599
+ const isNewsletter = server === 'newsletter';
600
+ const isGroupOrStatus = isGroup || isStatus;
601
+ const finalJid = jid;
602
+ msgId = msgId || generateMessageIDV2(meId);
603
+ useUserDevicesCache = useUserDevicesCache !== false;
604
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
605
+ const participants = [];
606
+ const destinationJid = !isStatus ? finalJid : statusJid;
607
+ const binaryNodeContent = [];
608
+ const devices = [];
609
+ let reportingMessage;
610
+ const requiresViewOnce = !!(message.buttonsMessage || message.templateMessage || message.listMessage || message.interactiveMessage);
611
+ if (requiresViewOnce) {
612
+ message = {
613
+ viewOnceMessage: {
614
+ message: { ...message }
615
+ }
616
+ };
617
+ }
618
+ const applyForwarded = m => {
619
+ const rich = m?.botForwardedMessage?.message?.richResponseMessage || m?.richResponseMessage;
620
+ if (!rich) return m;
621
+ rich.contextInfo = { ...rich.contextInfo, isForwarded: true, forwardOrigin: 4 };
622
+ return m.botForwardedMessage ? m : { botForwardedMessage: { message: m } };
623
+ };
624
+ if (message?.deviceSentMessage?.message) {
625
+ message.deviceSentMessage.message = applyForwarded(message.deviceSentMessage.message);
626
+ }
627
+ else {
628
+ message = applyForwarded(message);
629
+ }
630
+ const meMsg = {
631
+ deviceSentMessage: {
632
+ destinationJid,
633
+ message
634
+ },
635
+ messageContextInfo: message.messageContextInfo
636
+ };
637
+ const extraAttrs = {};
638
+ if (isRetryResend) {
639
+ if (!isGroup && !isStatus) {
640
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
641
+ }
642
+ const { user, device } = jidDecode(retryParticipants.jid);
643
+ devices.push({ user, device, jid: retryParticipants.jid });
644
+ }
645
+ if ((isRecipientOnly || isSecret || protectedSend || meOnly) && !isGroup && !isStatus) {
646
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
647
+ }
648
+ await authState.keys.transaction(async () => {
649
+ const innerMessage = normalizeMessageContent(message);
650
+ const mediaType = getMediaType(innerMessage);
651
+ if (mediaType) {
652
+ extraAttrs['mediatype'] = mediaType;
653
+ }
654
+ if (isNewsletter) {
655
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
656
+ const bytes = encodeNewsletterMessage(patched);
657
+ if (additionalNodes && additionalNodes.length > 0) {
658
+ binaryNodeContent.push(...additionalNodes);
659
+ }
660
+ binaryNodeContent.push({
661
+ tag: 'plaintext',
662
+ attrs: extraAttrs,
663
+ content: bytes
664
+ });
665
+ const stanza = {
666
+ tag: 'message',
667
+ attrs: {
668
+ to: jid,
669
+ id: msgId,
670
+ type: getMessageType(innerMessage),
671
+ ...(additionalAttributes || {})
672
+ },
673
+ content: binaryNodeContent
674
+ };
675
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
676
+ await sendNode(stanza);
677
+ return;
678
+ }
679
+ const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
680
+ const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
681
+ const isPollUpdate = innerMessage?.pollUpdateMessage;
682
+ if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
683
+ const metaAttrs = {};
684
+ if (isNeedMetaAttrs) {
685
+ metaAttrs.content_type = 'add_on';
686
+ }
687
+ if (isPollUpdate && !isGroupStatus) {
688
+ metaAttrs.polltype = 'vote';
689
+ }
690
+ if (isGroupStatus) {
691
+ metaAttrs.is_group_status = 'true';
692
+ }
693
+ binaryNodeContent.push({
694
+ tag: 'meta',
695
+ attrs: metaAttrs,
696
+ content: undefined
697
+ });
698
+ }
699
+ if (isStatus && statusPrivacy && !additionalAttributes?.edit) {
700
+ binaryNodeContent.push({
701
+ tag: 'meta',
702
+ attrs: { status_setting: statusPrivacy, session_scope: 'status' }
703
+ });
704
+ }
705
+ if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
706
+ extraAttrs['decrypt-fail'] = 'hide';
707
+ }
708
+ if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
709
+ extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
710
+ }
711
+ if (isGroupOrStatus && !isRetryResend) {
712
+ const [groupData, senderKeyMap] = await Promise.all([
713
+ (async () => {
714
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
715
+ if (groupData && Array.isArray(groupData?.participants)) {
716
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
717
+ }
718
+ else if (!isStatus) {
719
+ groupData = await groupMetadata(jid);
720
+ }
721
+ return groupData;
722
+ })(),
723
+ (async () => {
724
+ if (!participant && !isStatus) {
725
+ const result = await authState.keys.get('sender-key-memory', [jid]);
726
+ return result[jid] || {};
727
+ }
728
+ return {};
729
+ })()
730
+ ]);
731
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
732
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
733
+ additionalAttributes = {
734
+ ...additionalAttributes,
735
+ expiration: groupData.ephemeralDuration.toString()
736
+ };
737
+ }
738
+ if (isStatus && statusJidList) {
739
+ participantsList.push(...statusJidList);
740
+ }
741
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
742
+ devices.push(...additionalDevices);
743
+ if (isGroup) {
744
+ additionalAttributes = {
745
+ ...additionalAttributes,
746
+ addressing_mode: groupData?.addressingMode || 'lid'
747
+ };
748
+ }
749
+ const patched = await patchMessageBeforeSending(message);
750
+ if (Array.isArray(patched)) {
751
+ throw new Boom('Per-jid patching is not supported in groups');
752
+ }
753
+ const bytes = encodeWAMessage(patched);
754
+ reportingMessage = patched;
755
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
756
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
757
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
758
+ group: destinationJid,
759
+ data: bytes,
760
+ meId: groupSenderIdentity
761
+ });
762
+ const senderKeyRecipients = [];
763
+ for (const device of devices) {
764
+ const deviceJid = device.jid;
765
+ const hasKey = !!senderKeyMap[deviceJid];
766
+ if ((!hasKey || !!participant) &&
767
+ !isHostedLidUser(deviceJid) &&
768
+ !isHostedPnUser(deviceJid) &&
769
+ device.device !== 99) {
770
+ senderKeyRecipients.push(deviceJid);
771
+ senderKeyMap[deviceJid] = true;
772
+ }
773
+ }
774
+ if (senderKeyRecipients.length) {
775
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
776
+ const senderKeyMsg = {
777
+ senderKeyDistributionMessage: {
778
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
779
+ groupId: destinationJid
780
+ }
781
+ };
782
+ const senderKeySessionTargets = senderKeyRecipients;
783
+ await assertSessions(senderKeySessionTargets);
784
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
785
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
786
+ participants.push(...result.nodes);
787
+ }
788
+ binaryNodeContent.push({
789
+ tag: 'enc',
790
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
791
+ content: ciphertext
792
+ });
793
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
794
+ }
795
+ else {
796
+ let ownId = meId;
797
+ if (isLid && meLid) {
798
+ ownId = meLid;
799
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
800
+ }
801
+ else {
802
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
803
+ }
804
+ const { user: ownUser } = jidDecode(ownId);
805
+ if (!participant) {
806
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
807
+ reportingMessage = Array.isArray(patchedForReporting)
808
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
809
+ : patchedForReporting;
810
+ }
811
+ if (!isRetryResend) {
812
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
813
+ devices.push({
814
+ user,
815
+ device: 0,
816
+ jid: jidEncode(user, targetUserServer, 0)
817
+ });
818
+ if (user !== ownUser) {
819
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
820
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
821
+ devices.push({
822
+ user: ownUserForAddressing,
823
+ device: 0,
824
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
825
+ });
826
+ }
827
+ if (additionalAttributes?.['category'] !== 'peer') {
828
+ devices.length = 0;
829
+ const senderIdentity = isLid && meLid
830
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
831
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
832
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
833
+ devices.push(...sessionDevices);
834
+ logger.debug({
835
+ deviceCount: devices.length,
836
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
837
+ }, 'Device enumeration complete with unified addressing');
838
+ }
839
+ }
840
+ const allRecipients = [];
841
+ const meRecipients = [];
842
+ const otherRecipients = [];
843
+ const { user: mePnUser } = jidDecode(meId);
844
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
845
+ for (const { user, jid } of devices) {
846
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
847
+ if (isExactSenderDevice) {
848
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
849
+ continue;
850
+ }
851
+ const isMe = user === mePnUser || user === meLidUser;
852
+ const hasDevice = jid.includes(':');
853
+ if (isRecipientOnly && isMe) continue;
854
+ if (isSecret && !(!isMe && !hasDevice)) continue;
855
+ if (protectedSend && !isMe && hasDevice) continue;
856
+ if (meOnly && !isMe) continue;
857
+ if (isMe) {
858
+ meRecipients.push(jid);
859
+ }
860
+ else {
861
+ otherRecipients.push(jid);
862
+ }
863
+ allRecipients.push(jid);
864
+ }
865
+ await assertSessions(allRecipients);
866
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
867
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
868
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
869
+ ]);
870
+ participants.push(...meNodes);
871
+ participants.push(...otherNodes);
872
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
873
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
874
+ }
875
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
876
+ }
877
+ if (isRetryResend) {
878
+ const isParticipantLid = isLidUser(retryParticipants.jid);
879
+ const isMe = areJidsSameUser(retryParticipants.jid, isParticipantLid ? meLid : meId);
880
+ let messageToSend = message;
881
+ if (isGroupOrStatus) {
882
+ let groupSenderIdentity;
883
+ if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
884
+ groupSenderIdentity = meLid;
885
+ }
886
+ else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
887
+ groupSenderIdentity = meId;
888
+ }
889
+ if (groupSenderIdentity) {
890
+ try {
891
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
892
+ group: destinationJid,
893
+ meId: groupSenderIdentity
894
+ });
895
+ messageToSend = {
896
+ ...message,
897
+ senderKeyDistributionMessage: {
898
+ groupId: destinationJid,
899
+ axolotlSenderKeyDistributionMessage: skdm
900
+ }
901
+ };
902
+ }
903
+ catch (err) {
904
+ logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
905
+ }
906
+ }
907
+ }
908
+ const encodedMessageToSend = isMe
909
+ ? encodeWAMessage({
910
+ deviceSentMessage: {
911
+ destinationJid,
912
+ message: messageToSend
913
+ }
914
+ })
915
+ : encodeWAMessage(messageToSend);
916
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
917
+ data: encodedMessageToSend,
918
+ jid: retryParticipants.jid
919
+ });
920
+ binaryNodeContent.push({
921
+ tag: 'enc',
922
+ attrs: {
923
+ v: '2',
924
+ type,
925
+ count: retryParticipants.count.toString()
926
+ },
927
+ content: encryptedContent
928
+ });
929
+ }
930
+ if (participants.length) {
931
+ if (additionalAttributes?.['category'] === 'peer') {
932
+ const peerNode = participants[0]?.content?.[0];
933
+ if (peerNode) {
934
+ binaryNodeContent.push(peerNode);
935
+ }
936
+ }
937
+ else {
938
+ binaryNodeContent.push({
939
+ tag: 'participants',
940
+ attrs: {},
941
+ content: participants
942
+ });
943
+ }
944
+ }
945
+ const stanza = {
946
+ tag: 'message',
947
+ attrs: {
948
+ id: msgId,
949
+ to: destinationJid,
950
+ type: getMessageType(innerMessage),
951
+ ...(additionalAttributes || {})
952
+ },
953
+ content: binaryNodeContent
954
+ };
955
+ if (isRetryResend) {
956
+ if (isJidGroup(destinationJid)) {
957
+ stanza.attrs.to = destinationJid;
958
+ stanza.attrs.participant = retryParticipants.jid;
959
+ }
960
+ else if (areJidsSameUser(retryParticipants.jid, meId)) {
961
+ stanza.attrs.to = retryParticipants.jid;
962
+ stanza.attrs.recipient = destinationJid;
963
+ }
964
+ else {
965
+ stanza.attrs.to = retryParticipants.jid;
966
+ }
967
+ }
968
+ else {
969
+ stanza.attrs.to = destinationJid;
970
+ }
971
+ if (shouldIncludeDeviceIdentity) {
972
+ stanza.content.push({
973
+ tag: 'device-identity',
974
+ attrs: {},
975
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
976
+ });
977
+ logger.debug({ jid }, 'adding device identity');
978
+ }
979
+ if (!isNewsletter &&
980
+ !isRetryResend &&
981
+ reportingMessage?.messageContextInfo?.messageSecret &&
982
+ shouldIncludeReportingToken(reportingMessage)) {
983
+ try {
984
+ const encoded = encodeWAMessage(reportingMessage);
985
+ const reportingKey = {
986
+ id: msgId,
987
+ fromMe: true,
988
+ remoteJid: destinationJid,
989
+ participant: retryParticipants?.jid
990
+ };
991
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
992
+ if (reportingNode) {
993
+ stanza.content.push(reportingNode);
994
+ logger.trace({ jid }, 'added reporting token to message');
995
+ }
996
+ }
997
+ catch (error) {
998
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
999
+ }
1000
+ }
1001
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
1002
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
1003
+ const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
1004
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
1005
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
1006
+ let tcTokenBuffer = existingTokenEntry?.token;
1007
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
1008
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
1009
+ tcTokenBuffer = undefined;
1010
+ const cleared = existingTokenEntry?.senderTimestamp !== undefined
1011
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
1012
+ : null;
1013
+ try {
1014
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
1015
+ }
1016
+ catch (err) {
1017
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
1018
+ }
1019
+ }
1020
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
1021
+ stanza.content.push({
1022
+ tag: 'tctoken',
1023
+ attrs: {},
1024
+ content: tcTokenBuffer
1025
+ });
1026
+ }
1027
+ let alreadyHasBizNode = false;
1028
+ if (additionalNodes && additionalNodes.length > 0) {
1029
+ stanza.content.push(...additionalNodes);
1030
+ alreadyHasBizNode = !addBizAttributes &&
1031
+ additionalNodes.some(node => node.tag === 'biz');
1032
+ }
1033
+ if ((!alreadyHasBizNode && shouldIncludeBizBinaryNode(innerMessage)) || addBizAttributes) {
1034
+ const bizNode = getBizBinaryNode(innerMessage, addBizAttributes);
1035
+ stanza.content.push(bizNode);
1036
+ }
1037
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
1038
+ await sendNode(stanza);
1039
+ const isProtocolMsg = !!innerMessage?.protocolMessage;
1040
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
1041
+ if (is1on1Send &&
1042
+ !isProtocolMsg &&
1043
+ !isBotOrPSA &&
1044
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
1045
+ !inFlightTcTokenIssuance.has(tcTokenJid)) {
1046
+ inFlightTcTokenIssuance.add(tcTokenJid);
1047
+ const issueTimestamp = unixTimestampSeconds();
1048
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
1049
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
1050
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
1051
+ .then(async (result) => {
1052
+ await storeTcTokensFromIqResult({
1053
+ result,
1054
+ fallbackJid: tcTokenJid,
1055
+ keys: authState.keys,
1056
+ getLIDForPN
1057
+ });
1058
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
1059
+ const currentEntry = currentData[tcTokenJid];
1060
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
1061
+ await authState.keys.set({
1062
+ tctoken: {
1063
+ [tcTokenJid]: {
1064
+ token: Buffer.alloc(0),
1065
+ ...currentEntry,
1066
+ senderTimestamp: issueTimestamp
1067
+ },
1068
+ ...indexWrite
1069
+ }
1070
+ });
1071
+ })
1072
+ .catch(err => {
1073
+ logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
1074
+ })
1075
+ .finally(() => {
1076
+ inFlightTcTokenIssuance.delete(tcTokenJid);
1077
+ });
1078
+ }
1079
+ if (messageRetryManager && !retryParticipants) {
1080
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1081
+ }
1082
+ }, meId);
1083
+ return msgId;
1084
+ };
1085
+
1086
+ const getMessageType = (message) => {
1087
+ if (!message)
1088
+ return 'text';
1089
+ if (message.reactionMessage || message.encReactionMessage) {
1090
+ return 'reaction';
1091
+ }
1092
+ if (message.pollCreationMessage ||
1093
+ message.pollCreationMessageV2 ||
1094
+ message.pollCreationMessageV3 ||
1095
+ message.pollCreationMessageV5 ||
1096
+ message.pollCreationMessageV6 ||
1097
+ message.pollUpdateMessage) {
1098
+ return 'poll';
1099
+ }
1100
+ if (message.eventMessage) {
1101
+ return 'event';
1102
+ }
1103
+ if (getMediaType(message) !== '') {
1104
+ return 'media';
1105
+ }
1106
+ return 'text';
1107
+ };
1108
+
1109
+ const getMediaType = (message) => {
1110
+ if (message.imageMessage) {
1111
+ return 'image';
1112
+ }
1113
+ else if (message.videoMessage) {
1114
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
1115
+ }
1116
+ else if (message.stickerMessage) {
1117
+ return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker';
1118
+ }
1119
+ else if (message.audioMessage) {
1120
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
1121
+ }
1122
+ else if (message.albumMessage) {
1123
+ return 'collection';
1124
+ }
1125
+ else if (message.contactMessage) {
1126
+ return 'vcard';
1127
+ }
1128
+ else if (message.documentMessage) {
1129
+ return 'document';
1130
+ }
1131
+ else if (message.contactsArrayMessage) {
1132
+ return 'contact_array';
1133
+ }
1134
+ else if (message.liveLocationMessage) {
1135
+ return 'livelocation';
1136
+ }
1137
+ else if (message.stickerPackMessage) {
1138
+ return 'sticker_pack';
1139
+ }
1140
+ else if (message.listMessage) {
1141
+ return 'list';
1142
+ }
1143
+ else if (message.listResponseMessage) {
1144
+ return 'list_response';
1145
+ }
1146
+ else if (message.buttonsResponseMessage) {
1147
+ return 'buttons_response';
1148
+ }
1149
+ else if (message.orderMessage) {
1150
+ return 'order';
1151
+ }
1152
+ else if (message.productMessage) {
1153
+ return 'product';
1154
+ }
1155
+ else if (message.interactiveResponseMessage) {
1156
+ return 'native_flow_response';
1157
+ }
1158
+ else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
1159
+ return 'url';
1160
+ }
1161
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/c/')) {
1162
+ return 'cataloglink';
1163
+ }
1164
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/p/')) {
1165
+ return 'productlink';
1166
+ }
1167
+ return '';
1168
+ };
1169
+
1170
+ const issuePrivacyTokens = async (jids, timestamp) => {
1171
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
1172
+ const result = await query({
1173
+ tag: 'iq',
1174
+ attrs: {
1175
+ to: S_WHATSAPP_NET,
1176
+ type: 'set',
1177
+ xmlns: 'privacy'
1178
+ },
1179
+ content: [
1180
+ {
1181
+ tag: 'tokens',
1182
+ attrs: {},
1183
+ content: jids.map(jid => ({
1184
+ tag: 'token',
1185
+ attrs: {
1186
+ jid: jidNormalizedUser(jid),
1187
+ t,
1188
+ type: 'trusted_contact'
1189
+ }
1190
+ }))
1191
+ }
1192
+ ]
1193
+ });
1194
+ return result;
1195
+ };
1196
+
1197
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1198
+ const baron2 = new Baron(waUploadToServer, relayMessage, config, sock);
1199
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1200
+
1201
+ const resolveStatusRecipients = async (provided) => {
1202
+ let recipients = provided || config.statusJidList;
1203
+ if (!recipients && typeof config.getStatusJidList === 'function') {
1204
+ recipients = await config.getStatusJidList(sock);
1205
+ }
1206
+ if (!recipients) {
1207
+ const contactSource = config.store?.contacts || config.contactStore?.contacts || config.contacts;
1208
+ if (Array.isArray(contactSource)) {
1209
+ recipients = contactSource;
1210
+ }
1211
+ else if (contactSource && typeof contactSource === 'object') {
1212
+ recipients = Object.keys(contactSource);
1213
+ }
1214
+ }
1215
+ const ownJid = authState.creds.me?.id;
1216
+ try {
1217
+ return normalizeStatusJidList([...(recipients || []), ownJid].filter(Boolean));
1218
+ }
1219
+ catch (error) {
1220
+ throw new Boom('sendStatus requires a non-empty statusJidList or a configured contact source/provider', {
1221
+ statusCode: 400,
1222
+ data: { hint: 'Pass statusJidList, config.statusJidList, config.getStatusJidList, or config.store.contacts' },
1223
+ cause: error
1224
+ });
1225
+ }
1226
+ };
1227
+
1228
+ registerSocketEndHandler(() => {
1229
+ if (!config.userDevicesCache && userDevicesCache.close) {
1230
+ userDevicesCache.close();
1231
+ }
1232
+ mediaConn = undefined;
1233
+ if (messageRetryManager) {
1234
+ messageRetryManager.clear();
1235
+ }
1236
+ followingCache.clear();
1237
+ });
1238
+
1239
+ const socket = {
1240
+ ...sock,
1241
+ userDevicesCache,
1242
+ devicesMutex,
1243
+ issuePrivacyTokens,
1244
+ assertSessions,
1245
+ relayMessage,
1246
+ sendReceipt,
1247
+ sendReceipts,
1248
+ readMessages,
1249
+ refreshMediaConn,
1250
+ getMediaHost: () => mediaHost,
1251
+ waUploadToServer,
1252
+ fetchPrivacySettings,
1253
+ sendPeerDataOperationMessage,
1254
+ createParticipantNodes,
1255
+ getUSyncDevices,
1256
+ messageRetryManager,
1257
+ updateMemberLabel,
1258
+ followNewsletter,
1259
+ sendBulkReactions, // ← NEW: Bulk reaction helper
1260
+ sendAsMimic,
1261
+ // Native status mention path. The array-jid sendMessage branch expands
1262
+ // group recipients, emits mentioned_users metadata, and sends the
1263
+ // follow-up statusMentionMessage/groupStatusMentionMessage reference.
1264
+ sendStatusMention: async (content, jids = [], options = {}) => {
1265
+ if (!Array.isArray(jids) || jids.length === 0) {
1266
+ throw new Boom('sendStatusMention requires at least one user or group JID', { statusCode: 400 });
1267
+ }
1268
+ return socket.sendMessage(jids, {
1269
+ ...content,
1270
+ status: true
1271
+ }, options);
1272
+ },
1273
+ sendStatusMentions: async (content, jids = [], options = {}) => {
1274
+ if (!Array.isArray(jids) || jids.length === 0) {
1275
+ throw new Boom('sendStatusMentions requires at least one user or group JID', { statusCode: 400 });
1276
+ }
1277
+ return socket.sendMessage(jids, {
1278
+ ...content,
1279
+ status: true
1280
+ }, options);
1281
+ },
1282
+ sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1283
+ const { message, messageId } = generateTableContent(title, headers, rows, quoted, options);
1284
+ await relayMessage(jid, message, { messageId });
1285
+ return { message, messageId };
1286
+ },
1287
+ sendList: async (jid, title, items, quoted, options = {}) => {
1288
+ const { message, messageId } = generateListContent(title, items, quoted, options);
1289
+ await relayMessage(jid, message, { messageId });
1290
+ return { message, messageId };
1291
+ },
1292
+ sendCodeBlock: async (jid, code, quoted, options = {}) => {
1293
+ const { message, messageId } = generateCodeBlockContent(code, quoted, options);
1294
+ await relayMessage(jid, message, { messageId });
1295
+ return { message, messageId };
1296
+ },
1297
+ sendLatex: async (jid, quoted, options) => {
1298
+ const { message, messageId } = generateLatexContent(quoted, options);
1299
+ await relayMessage(jid, message, { messageId });
1300
+ return { message, messageId };
1301
+ },
1302
+ /**
1303
+ * Send LaTeX as rendered PNG image (like Meta AI does).
1304
+ * Uses codecogs.com to render LaTeX to PNG, then sends as rich response.
1305
+ * @param {string} jid - Chat JID
1306
+ * @param {object} options - { text, expressions: [{ latexExpression }], headerText, footer }
1307
+ */
1308
+ sendLatexImage: async (jid, options = {}) => {
1309
+ const { text, expressions = [], headerText, footer } = options;
1310
+ const renderedExpressions = expressions.map(expr => {
1311
+ const latex = expr.latexExpression || expr.expression || expr;
1312
+ // Encode LaTeX for codecogs URL
1313
+ const encoded = encodeURIComponent(latex).replace(/'/g, '%27');
1314
+ const url = `https://latex.codecogs.com/png.latex?${encoded}`;
1315
+ return {
1316
+ latexExpression: latex,
1317
+ url,
1318
+ width: expr.width || 400,
1319
+ height: expr.height || 100
1320
+ };
1321
+ });
1322
+ const { message, messageId } = generateLatexContent(null, {
1323
+ text,
1324
+ expressions: renderedExpressions,
1325
+ headerText,
1326
+ footer
1327
+ });
1328
+ await relayMessage(jid, message, { messageId });
1329
+ return { message, messageId };
1330
+ },
1331
+ sendMetaAI: async (a, b, c = {}) => {
1332
+ // baron signature: (jid, text, opts) — README signature: (text, opts)
1333
+ let text;
1334
+ let opts = c;
1335
+ if (typeof b === 'string') {
1336
+ text = b;
1337
+ }
1338
+ else {
1339
+ text = a;
1340
+ opts = b || {};
1341
+ }
1342
+ const yourJid = typeof b === 'string' ? a : (opts.yourJid || '');
1343
+ const META_AI_BOT_JID = '867051314767696@bot';
1344
+ const jid = opts.jid || META_AI_BOT_JID;
1345
+ const threadId = opts.threadId || generateMessageIDV2(yourJid);
1346
+ const now = Date.now();
1347
+ const senderTimestamp = opts.senderTimestamp || String(Math.floor(now / 1000));
1348
+ const messageSecret = opts.messageSecret || randomBytes(32);
1349
+ const senderKeyHash = opts.senderKeyHash || randomBytes(8).toString('base64');
1350
+ const message = {
1351
+ extendedTextMessage: proto.Message.ExtendedTextMessage.fromObject({
1352
+ text,
1353
+ previewType: 'NONE',
1354
+ contextInfo: proto.ContextInfo.fromObject({
1355
+ botMessageSharingInfo: {
1356
+ botEntryPointOrigin: 'FAVICON',
1357
+ forwardScore: 0
1358
+ }
1359
+ }),
1360
+ inviteLinkGroupTypeV2: 'DEFAULT'
1361
+ }),
1362
+ messageContextInfo: proto.MessageContextInfo.fromObject({
1363
+ deviceListMetadata: {
1364
+ senderKeyHash,
1365
+ senderTimestamp
1366
+ },
1367
+ deviceListMetadataVersion: 2,
1368
+ messageSecret,
1369
+ botMetadata: {
1370
+ botModeSelectionMetadata: {
1371
+ overrideMode: [0]
1372
+ },
1373
+ botThreadInfo: {
1374
+ serverInfo: { title: text.substring(0, 50) },
1375
+ clientInfo: { type: 'DEFAULT' }
1376
+ },
1377
+ botRenderingConfigMetadata: {
1378
+ bloksVersioningId: '1eb86e6f4117d052e6bab62fe758a2e2af43747b85c5c1a886c8262bac462ea4',
1379
+ pixelDensity: 2.625
1380
+ },
1381
+ ...(opts.conversationContext?.length ? { aiConversationContext: opts.conversationContext } : {})
1382
+ },
1383
+ threadId: [
1384
+ {
1385
+ threadType: 'AI_THREAD',
1386
+ threadKey: {
1387
+ remoteJid: '0002@s.whatsapp.net',
1388
+ fromMe: true,
1389
+ id: threadId
1390
+ }
1391
+ }
1392
+ ]
1393
+ })
1394
+ };
1395
+ const msgId = generateMessageIDV2(yourJid);
1396
+ const messageOptions = {
1397
+ messageId: msgId,
1398
+ ...(opts.quoted ? { quoted: opts.quoted } : {}),
1399
+ ...(opts.links ? { links: opts.links } : {})
1400
+ };
1401
+ await relayMessage(jid, message, messageOptions);
1402
+ return msgId;
1403
+ },
1404
+ // Additive Nexus-compatible AI-rich helpers. Existing Gen4/table/grid/carousel APIs remain unchanged.
1405
+ sendRichMedia: async (jid, content = {}, quoted, options = {}) => {
1406
+ const message = prepareRichResponseMessage({ ...content, noDonation: options.noDonation ?? true });
1407
+ const messageId = generateMessageIDV2(jid);
1408
+ await relayMessage(jid, message, { messageId });
1409
+ return { message, messageId };
1410
+ },
1411
+ /**
1412
+ * Send a native AI image/video generation card. The returned messageId
1413
+ * is required by updateRichGeneration() for an in-place edit.
1414
+ */
1415
+ sendRichGeneration: async (jid, content = {}, quoted, options = {}) => {
1416
+ const generated = prepareRichGenerationMessage({
1417
+ ...content,
1418
+ responseId: options.responseId,
1419
+ forwarded: options.forwarded !== false
1420
+ });
1421
+ const messageId = generateMessageIDV2(jid);
1422
+ await relayMessage(jid, generated.message, { messageId, quoted });
1423
+ return { ...generated, messageId };
1424
+ },
1425
+ /**
1426
+ * Replace the generation primitive in an existing rich response.
1427
+ * This uses WhatsApp's edit protocol (type 14), matching the native
1428
+ * rich-message replacement lifecycle used by compatible clients.
1429
+ */
1430
+ updateRichGeneration: async (jid, targetId, content = {}, options = {}) => {
1431
+ if (!jid) throw new Boom('updateRichGeneration requires a target JID', { statusCode: 400 });
1432
+ if (!targetId) throw new Boom('updateRichGeneration requires the original message ID', { statusCode: 400 });
1433
+ const generated = prepareRichGenerationMessage({
1434
+ ...content,
1435
+ responseId: options.responseId,
1436
+ itemId: options.itemId || content.itemId,
1437
+ forwarded: options.forwarded !== false
1438
+ });
1439
+ const editedMessage = generateWAMessageFromContent(jid, {
1440
+ botForwardedMessage: {
1441
+ message: {
1442
+ protocolMessage: {
1443
+ key: { remoteJid: jid, fromMe: true, id: targetId },
1444
+ type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
1445
+ editedMessage: generated.message
1446
+ }
1447
+ }
1448
+ }
1449
+ }, { messageId: generateMessageIDV2(jid) });
1450
+ await relayMessage(jid, editedMessage.message, { messageId: editedMessage.key.id });
1451
+ return { ...generated, messageId: editedMessage.key.id, targetId };
1452
+ },
1453
+ sendReels: async (jid, reels, quoted, options = {}) => socket.sendRichMedia(jid, { contentText: options.text || '', reels }, quoted, options),
1454
+ sendRichSources: async (jid, text, sources, quoted, options = {}) => socket.sendRichMedia(jid, { contentText: text, sources }, quoted, options),
1455
+ sendLink: async (jid, text, links, quoted, options = {}) => socket.sendRichSources(jid, text, links, quoted, options),
1456
+ sendLinkV2: async (jid, text, links, quoted, options = {}) => socket.sendRichSources(jid, text, links, quoted, options),
1457
+ sendRichAIResponse: async (jid, content, quoted, options = {}) => {
1458
+ let generated;
1459
+ if (content?.table) {
1460
+ const { title = '', headers = [], rows = [], ...rest } = content.table;
1461
+ generated = generateTableContent(title, headers, rows, quoted, { ...options, ...rest });
1462
+ }
1463
+ else if (content?.list) {
1464
+ const { title = '', items = [], ...rest } = content.list;
1465
+ generated = generateListContent(title, items, quoted, { ...options, ...rest });
1466
+ }
1467
+ else if (content?.codeBlock) {
1468
+ const { language = 'javascript', code, ...rest } = content.codeBlock;
1469
+ generated = generateCodeBlockContent(code || '', quoted, { ...options, language, ...rest });
1470
+ }
1471
+ else if (content?.latex) {
1472
+ const latex = content.latex;
1473
+ const text = typeof latex === 'string' ? latex : latex?.text || '';
1474
+ const expressions = typeof latex === 'string'
1475
+ ? [{ latexExpression: latex }]
1476
+ : latex?.expressions || [{ latexExpression: text }];
1477
+ generated = generateLatexContent(quoted, { ...options, text, expressions, ...(typeof latex === 'object' ? latex : {}) });
1478
+ }
1479
+ else {
1480
+ throw new Boom('sendRichAIResponse: unknown content type — expected table, list, codeBlock or latex');
1481
+ }
1482
+ const { message, messageId } = generated;
1483
+ await relayMessage(jid, message, { messageId });
1484
+ return { message, messageId };
1485
+ },
1486
+ captureAndResendUnifiedResponse: async (jid, metaAiMsg, quoted) => {
1487
+ const captured = captureUnifiedResponse(metaAiMsg);
1488
+ if (!captured) {
1489
+ throw new Boom('captureAndResendUnifiedResponse: message contains no unifiedResponse data');
1490
+ }
1491
+ const { message, messageId } = generateUnifiedResponseContent(quoted, captured);
1492
+ await relayMessage(jid, message, { messageId });
1493
+ return { message, messageId };
1494
+ },
1495
+ updateMediaMessage: async (message) => {
1496
+ const content = assertMediaContent(message.message);
1497
+ const mediaKey = content.mediaKey;
1498
+ const meId = authState.creds.me.id;
1499
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1500
+ let error = undefined;
1501
+ await Promise.all([
1502
+ sendNode(node),
1503
+ waitForMsgMediaUpdate(async (update) => {
1504
+ const result = update.find(c => c.key.id === message.key.id);
1505
+ if (result) {
1506
+ if (result.error) {
1507
+ error = result.error;
1508
+ }
1509
+ else {
1510
+ try {
1511
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1512
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1513
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1514
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1515
+ data: media,
1516
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1517
+ });
1518
+ }
1519
+ content.directPath = media.directPath;
1520
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1521
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1522
+ }
1523
+ catch (err) {
1524
+ error = err;
1525
+ }
1526
+ }
1527
+ return true;
1528
+ }
1529
+ })
1530
+ ]);
1531
+ if (error) {
1532
+ throw error;
1533
+ }
1534
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1535
+ return message;
1536
+ },
1537
+ /**
1538
+ * Send a prompt to the Meta AI bot in `jid` and resolve with the
1539
+ * decrypted bot response (text, image or video message).
1540
+ *
1541
+ * - In an AI group: the bot is @-mentioned with its participant JID
1542
+ * (resolved from metadata, falling back to the canonical `@bot` JID).
1543
+ * - In a 1:1 bot chat: `jid` is the bot JID itself.
1544
+ *
1545
+ * The returned message is the complete decrypted response — the msmsg
1546
+ * pipeline already drops streaming partials and only surfaces `full`/
1547
+ * `last` bot responses, so media (image/video) and text both arrive
1548
+ * whole. Download media with `downloadMediaMessage(msg)`.
1549
+ *
1550
+ * Options:
1551
+ * timeout — ms to wait before rejecting (default 60000)
1552
+ * onPartial — optional callback(updateMessage, key) fired for bot
1553
+ * message edits in the chat (best-effort streaming)
1554
+ * botUser — canonical bot JID (default META_AI_BOT_JID)
1555
+ * mentions — extra JIDs to mention alongside the bot
1556
+ * ...rest — forwarded to sendMessage (quoted, linkPreview, ...)
1557
+ */
1558
+ aiPrompt: async (jid, prompt, options = {}) => {
1559
+ const {
1560
+ timeout = 60_000,
1561
+ onPartial,
1562
+ botUser = META_AI_BOT_JID,
1563
+ mentions = [],
1564
+ ...sendOptions
1565
+ } = options;
1566
+ if (!jid || typeof prompt !== 'string' || !prompt.trim()) {
1567
+ throw new Error('aiPrompt requires a chat JID and a non-empty prompt');
1568
+ }
1569
+
1570
+ const botJids = await collectMetaAIBotParticipantJids(sock, jid, botUser);
1571
+ const isGroup = isJidGroup(jid);
1572
+ const allMentions = [...new Set([...mentions, ...botJids])];
1573
+
1574
+ return new Promise((resolve, reject) => {
1575
+ let promptId;
1576
+ let settled = false;
1577
+ const cleanup = () => {
1578
+ clearTimeout(timer);
1579
+ ev.off('messages.upsert', onUpsert);
1580
+ if (typeof onPartial === 'function') {
1581
+ ev.off('messages.update', onUpdate);
1582
+ }
1583
+ };
1584
+ const settle = (fn, value) => {
1585
+ if (settled) {
1586
+ return;
1587
+ }
1588
+ settled = true;
1589
+ cleanup();
1590
+ fn(value);
1591
+ };
1592
+
1593
+ const timer = setTimeout(
1594
+ () => settle(reject, new Error(`aiPrompt timed out after ${timeout}ms waiting for Meta AI in ${jid}`)),
1595
+ timeout
1596
+ );
1597
+
1598
+ const onUpsert = ({ messages }) => {
1599
+ for (const msg of messages) {
1600
+ if (isMetaAIBotResponse(msg, jid, promptId, [...botJids])) {
1601
+ settle(resolve, msg);
1602
+ return;
1603
+ }
1604
+ }
1605
+ };
1606
+
1607
+ const onUpdate = ({ updates }) => {
1608
+ if (typeof onPartial !== 'function') {
1609
+ return;
1610
+ }
1611
+ for (const update of updates) {
1612
+ if (!update.key || update.key.fromMe || update.key.remoteJid !== jid) {
1613
+ continue;
1614
+ }
1615
+ const sender = (update.key.participant || update.key.remoteJid).replace(/:\d+$/, '');
1616
+ const isBot =
1617
+ isJidMetaAI(sender) ||
1618
+ [...botJids].some(j => jidNormalizedUser(j.replace(/:\d+$/, '')) === jidNormalizedUser(sender));
1619
+ if (isBot && update.message) {
1620
+ onPartial(update.message, update.key);
1621
+ }
1622
+ }
1623
+ };
1624
+
1625
+ ev.on('messages.upsert', onUpsert);
1626
+ if (typeof onPartial === 'function') {
1627
+ ev.on('messages.update', onUpdate);
1628
+ }
1629
+
1630
+ const content = { text: prompt };
1631
+ if (isGroup) {
1632
+ content.mentions = allMentions;
1633
+ }
1634
+ Object.assign(content, sendOptions);
1635
+ (async () => {
1636
+ try {
1637
+ const fullMsg = await generateWAMessage(jid, content, {
1638
+ logger,
1639
+ userJid: authState.creds.me.id,
1640
+ upload: waUploadToServer,
1641
+ mediaCache: config.mediaCache,
1642
+ options: config.options,
1643
+ ...sendOptions,
1644
+ messageId: sendOptions.messageId || generateMessageIDV2(authState.creds.me.id)
1645
+ });
1646
+ await relayMessage(jid, fullMsg.message, {
1647
+ messageId: fullMsg.key.id,
1648
+ useCachedGroupMetadata: sendOptions.useCachedGroupMetadata,
1649
+ statusJidList: sendOptions.statusJidList
1650
+ });
1651
+ if (config.emitOwnEvents) {
1652
+ process.nextTick(async () => {
1653
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1654
+ });
1655
+ }
1656
+ promptId = fullMsg.key.id;
1657
+ }
1658
+ catch (err) {
1659
+ settle(reject, err);
1660
+ }
1661
+ })();
1662
+ });
1663
+ },
1664
+ sendMessage: async (jid, content, options = {}) => {
1665
+ const userJid = authState.creds.me.id;
1666
+ if (content?.groupStatus === true && !isJidGroup(jid)) {
1667
+ throw new Boom('groupStatus requires a valid group JID', { statusCode: 400 });
1668
+ }
1669
+
1670
+ // ── CRYSNOVAX FLAG (Auto-Heal) ──
1671
+ if (content && typeof content === 'object' && content.crysnovax === true) {
1672
+ const { crysnovax: _, retry = {}, fallback = {}, filterSystem = true, ...restContent } = content;
1673
+
1674
+ if (!sock.messageRetryManager) {
1675
+ sock.messageRetryManager = new MessageRetryManager(logger, retry.maxAttempts || 3);
1676
+ }
1677
+
1678
+ options.maxRetries = retry.maxAttempts || 3;
1679
+
1680
+ if (retry.onMacError === 'recreateSession') {
1681
+ options.recreateOnMacError = true;
1682
+ }
1683
+
1684
+ if (fallback.type === 'phone') {
1685
+ options.fallbackToPhone = true;
1686
+ options.fallbackTimeout = fallback.timeout || 10000;
1687
+ }
1688
+
1689
+ const result = await originalSend(jid, restContent, options);
1690
+ return result;
1691
+ }
1692
+
1693
+ // ── MIMIC FLAG ──
1694
+ if (content && typeof content === 'object' && content.mimic) {
1695
+ const { mimic: mimicJid, admin = false, ...restContent } = content;
1696
+
1697
+ if (!mimicJid) {
1698
+ throw new Error('mimic JID is required');
1699
+ }
1700
+
1701
+ return await sendAsMimic(jid, restContent, mimicJid, { ...options, admin });
1702
+ }
1703
+
1704
+ // ── BULK REACTION FLAG (NEW - Doesn't override original react) ──
1705
+ if (content && typeof content === 'object' && content.bulkReact) {
1706
+ const { bulkReact: emoji, messageId, count = 1, fake = false } = content;
1707
+
1708
+ if (!messageId) {
1709
+ throw new Error('messageId is required for bulkReact');
1710
+ }
1711
+
1712
+ return await sendBulkReactions(jid, messageId, emoji, count, fake);
1713
+ }
1714
+
1715
+ // ── NEWSLETTER FOLLOW FLAG ──
1716
+ if (content && typeof content === 'object' && content.followMe === true) {
1717
+ const { followMe: _, channelId, count = 'once', ...restContent } = content;
1718
+
1719
+ const channelIds = Array.isArray(channelId) ? channelId : [channelId];
1720
+
1721
+ if (!channelIds || channelIds.length === 0) {
1722
+ throw new Error('channelId is required for followMe flag');
1723
+ }
1724
+
1725
+ const results = [];
1726
+ for (const singleChannelId of channelIds) {
1727
+ if (!singleChannelId) continue;
1728
+
1729
+ try {
1730
+ const controller = await followNewsletter(singleChannelId, count);
1731
+ results.push({
1732
+ channelId: singleChannelId,
1733
+ success: true,
1734
+ controller,
1735
+ message: count === 'once'
1736
+ ? 'Successfully followed newsletter'
1737
+ : 'Started repeated newsletter follow (every 5min)'
1738
+ });
1739
+ } catch (error) {
1740
+ results.push({
1741
+ channelId: singleChannelId,
1742
+ success: false,
1743
+ error: error.message
1744
+ });
1745
+ }
1746
+ }
1747
+
1748
+ return {
1749
+ success: true,
1750
+ results,
1751
+ message: `Processed ${results.length} newsletter(s) (${count} mode)`
1752
+ };
1753
+ }
1754
+
1755
+ // ── STATUS MESSAGES ──
1756
+ if (Array.isArray(jid)) {
1757
+ const { delayMs = 1500 } = options;
1758
+ const allUsers = new Set([jidNormalizedUser(userJid)]);
1759
+ const statusMentionContent = { ...content };
1760
+ const isStatusMedia = Boolean(statusMentionContent.image || statusMentionContent.video || statusMentionContent.audio);
1761
+ if (isStatusMedia && statusMentionContent.text && !statusMentionContent.caption) {
1762
+ statusMentionContent.caption = statusMentionContent.text;
1763
+ delete statusMentionContent.text;
1764
+ }
1765
+ const fullMsg = await generateWAMessage('status@broadcast', statusMentionContent, {
1766
+ logger,
1767
+ userJid,
1768
+ upload: waUploadToServer,
1769
+ mediaCache: config.mediaCache,
1770
+ options: config.options,
1771
+ ...options,
1772
+ messageId: generateMessageIDV2(userJid)
1773
+ });
1774
+ for (const id of jid) {
1775
+ if (isJidGroup(id)) {
1776
+ try {
1777
+ const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1778
+ for (const participant of groupData.participants) {
1779
+ if (allUsers.has(participant.id))
1780
+ continue;
1781
+ allUsers.add(jidNormalizedUser(participant.id));
1782
+ }
1783
+ }
1784
+ catch (error) {
1785
+ logger.error(`Error getting metadata group from ${id}: ${error}`);
1786
+ }
1787
+ }
1788
+ else if (!allUsers.has(jidNormalizedUser(id))) {
1789
+ allUsers.add(jidNormalizedUser(id));
1790
+ }
1791
+ }
1792
+ await relayMessage('status@broadcast', fullMsg.message, {
1793
+ messageId: fullMsg.key.id,
1794
+ statusJidList: Array.from(allUsers),
1795
+ additionalNodes: [
1796
+ {
1797
+ tag: 'meta',
1798
+ attrs: {},
1799
+ content: [
1800
+ {
1801
+ tag: 'mentioned_users',
1802
+ attrs: {},
1803
+ content: jid.map(id => ({
1804
+ tag: 'to',
1805
+ attrs: { jid: jidNormalizedUser(id) },
1806
+ content: undefined
1807
+ }))
1808
+ }
1809
+ ]
1810
+ }
1811
+ ]
1812
+ });
1813
+ if (config.emitOwnEvents) {
1814
+ process.nextTick(async () => {
1815
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1816
+ });
1817
+ }
1818
+ for (const id of jid) {
1819
+ const isGroup = isJidGroup(id);
1820
+ const sendType = isGroup ? 'groupStatusMentionMessage' : 'statusMentionMessage';
1821
+ const mentionMsg = generateWAMessageFromContent(id, {
1822
+ messageContextInfo: {
1823
+ messageSecret: randomBytes(32)
1824
+ },
1825
+ [sendType]: {
1826
+ message: {
1827
+ protocolMessage: {
1828
+ key: fullMsg.key,
1829
+ type: 25
1830
+ }
1831
+ }
1832
+ }
1833
+ }, {
1834
+ userJid
1835
+ });
1836
+ await relayMessage(id, mentionMsg.message, {
1837
+ additionalNodes: [
1838
+ {
1839
+ tag: 'meta',
1840
+ attrs: isGroup ?
1841
+ { is_group_status_mention: 'true' } :
1842
+ { is_status_mention: 'true' },
1843
+ content: undefined
1844
+ }
1845
+ ]
1846
+ });
1847
+ if (config.emitOwnEvents) {
1848
+ process.nextTick(async () => {
1849
+ await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
1850
+ });
1851
+ }
1852
+ await delay(delayMs);
1853
+ }
1854
+ return fullMsg;
1855
+ }
1856
+ else if ('disappearingMessagesInChat' in content && isJidGroup(jid)) {
1857
+ const { disappearingMessagesInChat } = content;
1858
+ const value = typeof disappearingMessagesInChat === 'boolean'
1859
+ ? disappearingMessagesInChat
1860
+ ? WA_DEFAULT_EPHEMERAL
1861
+ : 0
1862
+ : disappearingMessagesInChat;
1863
+ await groupToggleEphemeral(jid, value);
1864
+ }
1865
+ else if ((jid === STATUS_JID || ('status' in content && content.status === true)) && !('react' in content)) {
1866
+ const {
1867
+ status: _status,
1868
+ backgroundColor: contentBackgroundColor,
1869
+ font: contentFont,
1870
+ statusJidList: contentJidList,
1871
+ ...statusContent
1872
+ } = content;
1873
+ const statusJidList = normalizeStatusJidList(contentJidList || options.statusJidList);
1874
+ const backgroundColor = contentBackgroundColor ?? options.backgroundColor;
1875
+ const font = contentFont ?? options.font;
1876
+ const fullMsg = await generateWAMessage(STATUS_JID, statusContent, {
1877
+ logger,
1878
+ userJid,
1879
+ upload: waUploadToServer,
1880
+ mediaCache: config.mediaCache,
1881
+ options: config.options,
1882
+ ...options,
1883
+ backgroundColor,
1884
+ font,
1885
+ messageId: options.messageId || generateMessageIDV2(userJid)
1886
+ });
1887
+ const relayResult = await relayMessage(STATUS_JID, fullMsg.message, {
1888
+ messageId: fullMsg.key.id,
1889
+ statusJidList,
1890
+ additionalAttributes: {
1891
+ broadcast: 'true',
1892
+ ...(options.additionalAttributes || {})
1893
+ },
1894
+ additionalNodes: options.additionalNodes || []
1895
+ });
1896
+ if (config.emitOwnEvents) {
1897
+ process.nextTick(async () => {
1898
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1899
+ });
1900
+ }
1901
+ fullMsg.relayResult = relayResult;
1902
+ return fullMsg;
1903
+ }
1904
+ else if ('richPreview' in content && content.richPreview === true) {
1905
+ const {
1906
+ richPreview: __rp,
1907
+ text: previewLink,
1908
+ previewTitle,
1909
+ previewDescription,
1910
+ previewImage,
1911
+ groupStatus: isGroupStatus,
1912
+ quoted,
1913
+ ...restContent
1914
+ } = content;
1915
+
1916
+ if (!previewLink || typeof previewLink !== 'string') {
1917
+ throw new Boom('richPreview requires a `text` field containing the URL', { statusCode: 400 });
1918
+ }
1919
+
1920
+ const _preview = await buildLinkPreview(
1921
+ previewLink,
1922
+ sock,
1923
+ {
1924
+ customTitle: previewTitle || '',
1925
+ customDesc: previewDescription || '',
1926
+ customImage: Buffer.isBuffer(previewImage) ? previewImage : null
1927
+ }
1928
+ );
1929
+
1930
+ let imageBuffer = _preview.imageBuffer;
1931
+
1932
+ if (!imageBuffer && typeof previewImage === 'string') {
1933
+ try {
1934
+ const res = await fetch(previewImage);
1935
+ imageBuffer = Buffer.from(await res.arrayBuffer());
1936
+ } catch (err) {
1937
+ logger?.warn({ err }, 'richPreview: failed to fetch previewImage URL');
1938
+ }
1939
+ }
1940
+
1941
+ const resolvedTitle = previewTitle || _preview.title || '';
1942
+ const resolvedDescription = previewDescription || _preview.description || '';
1943
+
1944
+ let smallThumb = null;
1945
+ if (imageBuffer) {
1946
+ try {
1947
+ const { buffer } = await extractImageThumb(imageBuffer, 296);
1948
+ smallThumb = buffer;
1949
+ }
1950
+ catch (err) {
1951
+ logger?.warn({ err }, 'richPreview: failed to generate small thumbnail');
1952
+ }
1953
+ }
1954
+
1955
+ let hq = null;
1956
+ if (imageBuffer) {
1957
+ try {
1958
+ const prepared = await prepareWAMessageMedia({ image: imageBuffer }, { upload: waUploadToServer });
1959
+ hq = prepared.imageMessage;
1960
+ }
1961
+ catch (err) {
1962
+ logger?.warn({ err }, 'richPreview: failed to upload HQ thumbnail');
1963
+ }
1964
+ }
1965
+
1966
+ const extendedText = {
1967
+ text: previewLink,
1968
+ matchedText: previewLink,
1969
+ canonicalUrl: previewLink,
1970
+ title: resolvedTitle,
1971
+ description: resolvedDescription,
1972
+ previewType: 5,
1973
+ jpegThumbnail: smallThumb || undefined,
1974
+ ...(hq
1975
+ ? {
1976
+ thumbnailDirectPath: hq.directPath,
1977
+ mediaKey: hq.mediaKey,
1978
+ mediaKeyTimestamp: hq.mediaKeyTimestamp,
1979
+ thumbnailWidth: hq.width,
1980
+ thumbnailHeight: hq.height,
1981
+ thumbnailSha256: hq.fileSha256,
1982
+ thumbnailEncSha256: hq.fileEncSha256
1983
+ }
1984
+ : {}),
1985
+ ...restContent
1986
+ };
1987
+
1988
+ if (quoted) {
1989
+ extendedText.contextInfo = {
1990
+ ...(extendedText.contextInfo || {}),
1991
+ stanzaId: quoted.key.id,
1992
+ participant: jidNormalizedUser(quoted.key.fromMe ? userJid : (quoted.key.participant || quoted.key.remoteJid)),
1993
+ quotedMessage: quoted.message
1994
+ };
1995
+ }
1996
+
1997
+ if (isGroupStatus) {
1998
+ extendedText.contextInfo = { ...(extendedText.contextInfo || {}), isGroupStatus: true };
1999
+ }
2000
+
2001
+ const previewMessage = isGroupStatus
2002
+ ? { groupStatusMessageV2: { message: { extendedTextMessage: extendedText } } }
2003
+ : { extendedTextMessage: extendedText };
2004
+
2005
+ const msgId = options.messageId || generateMessageIDV2(userJid);
2006
+
2007
+ await relayMessage(jid, previewMessage, {
2008
+ messageId: msgId,
2009
+ additionalAttributes: options.additionalAttributes || {},
2010
+ additionalNodes: options.additionalNodes || []
2011
+ });
2012
+
2013
+ const fullMsg = {
2014
+ key: {
2015
+ remoteJid: jid,
2016
+ fromMe: true,
2017
+ id: msgId
2018
+ },
2019
+ message: previewMessage,
2020
+ messageTimestamp: unixTimestampSeconds()
2021
+ };
2022
+
2023
+ if (config.emitOwnEvents) {
2024
+ process.nextTick(async () => {
2025
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2026
+ });
2027
+ }
2028
+ return fullMsg;
2029
+ }
2030
+ else if ('likeThis' in content && content.likeThis === true) {
2031
+ const { likeThis: _, ...rawMessage } = content;
2032
+ const msgId = options.messageId || generateMessageIDV2(userJid);
2033
+
2034
+ await relayMessage(jid, rawMessage, {
2035
+ messageId: msgId,
2036
+ additionalAttributes: options.additionalAttributes || {},
2037
+ additionalNodes: options.additionalNodes || []
2038
+ });
2039
+
2040
+ const fullMsg = {
2041
+ key: {
2042
+ remoteJid: jid,
2043
+ fromMe: true,
2044
+ id: msgId
2045
+ },
2046
+ message: rawMessage,
2047
+ messageTimestamp: unixTimestampSeconds()
2048
+ };
2049
+
2050
+ if (config.emitOwnEvents) {
2051
+ process.nextTick(async () => {
2052
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2053
+ });
2054
+ }
2055
+ return fullMsg;
2056
+ }
2057
+ // ── BARON INTERACTIVE HANDLER (new-style native flow buttons + raw group story) ──
2058
+ else if (content && typeof content === 'object' && ('interactiveButtons' in content || 'groupStatusMessage' in content)) {
2059
+ const { quoted } = options;
2060
+ if ('interactiveButtons' in content) {
2061
+ const ibContent = await baron2.handleInteractiveButtons(content, jid, quoted);
2062
+ const ibMsg = await generateWAMessageFromContent(jid, ibContent, { quoted, userJid });
2063
+ return await relayMessage(jid, ibMsg.message, {
2064
+ messageId: ibMsg.key.id,
2065
+ statusPrivacy: options.statusPrivacy
2066
+ });
2067
+ }
2068
+ return await baron2.handleGroupStory(content, jid, quoted);
2069
+ }
2070
+ // ── NORMAL MESSAGE HANDLING ──
2071
+ else {
2072
+ const fullMsg = await generateWAMessage(jid, content, {
2073
+ logger,
2074
+ userJid,
2075
+ getUrlInfo: text => getUrlInfo(text, {
2076
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
2077
+ fetchOpts: {
2078
+ timeout: 3000,
2079
+ ...(httpRequestOptions || {})
2080
+ },
2081
+ logger,
2082
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
2083
+ }),
2084
+ getProfilePicUrl: sock.profilePictureUrl,
2085
+ getCallLink: sock.createCallLink,
2086
+ upload: waUploadToServer,
2087
+ mediaCache: config.mediaCache,
2088
+ options: config.options,
2089
+ ...options,
2090
+ messageId: generateMessageIDV2(userJid)
2091
+ });
2092
+
2093
+ const isNewsletter = isJidNewsletter(jid);
2094
+ const isEventMsg = 'event' in content && !!content.event;
2095
+ const isDeleteMsg = 'delete' in content && !!content.delete;
2096
+ const isEditMsg = 'edit' in content && !!content.edit;
2097
+ const isPinMsg = 'pin' in content && !!content.pin;
2098
+ const isKeepMsg = 'keep' in content && !!content.keep;
2099
+ const isPollMsg = 'poll' in content && !!content.poll;
2100
+ const isQuizMsg = 'poll' in content && !!content.poll.pollType;
2101
+ const isAiMsg = 'ai' in content && !!content.ai;
2102
+ const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
2103
+ delete content.secureMetaServiceLabel;
2104
+ const additionalAttributes = options.additionalAttributes || {};
2105
+ const additionalNodes = options.additionalNodes || [];
2106
+
2107
+ if (isDeleteMsg || isKeepMsg) {
2108
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
2109
+ additionalAttributes.edit = '8';
2110
+ }
2111
+ else {
2112
+ additionalAttributes.edit = '7';
2113
+ }
2114
+ }
2115
+ else if (isEditMsg) {
2116
+ additionalAttributes.edit = isNewsletter ? '3' : '1';
2117
+ }
2118
+ else if (isPinMsg) {
2119
+ additionalAttributes.edit = '2';
2120
+ }
2121
+ else if (isPollMsg) {
2122
+ if (!isNewsletter && isQuizMsg) {
2123
+ throw new Boom('Quiz are only allowed for newsletter', { statusCode: 400 });
2124
+ }
2125
+ additionalNodes.push({
2126
+ tag: 'meta',
2127
+ attrs: {
2128
+ polltype: isQuizMsg ? 'quiz_creation' : 'creation',
2129
+ contenttype: isPollMsg && isNewsletter ? 'text' : undefined
2130
+ },
2131
+ content: undefined
2132
+ });
2133
+ }
2134
+ else if (isEventMsg) {
2135
+ additionalNodes.push({
2136
+ tag: 'meta',
2137
+ attrs: {
2138
+ event_type: 'creation'
2139
+ },
2140
+ content: undefined
2141
+ });
2142
+ }
2143
+ else if (isAiMsg) {
2144
+ if (!(isPnUser(jid) || isLidUser(jid))) {
2145
+ throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
2146
+ }
2147
+ if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
2148
+ fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
2149
+ }
2150
+ additionalNodes.push({
2151
+ tag: 'bot',
2152
+ attrs: {
2153
+ biz_bot: '1'
2154
+ },
2155
+ content: undefined
2156
+ });
2157
+ delete content.ai;
2158
+ }
2159
+
2160
+ await relayMessage(jid, fullMsg.message, {
2161
+ messageId: fullMsg.key.id,
2162
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2163
+ addBizAttributes: isNeedBizAttrs,
2164
+ statusJidList: options.statusJidList,
2165
+ statusPrivacy: options.statusPrivacy,
2166
+ additionalAttributes,
2167
+ additionalNodes
2168
+ });
2169
+
2170
+ if (config.emitOwnEvents) {
2171
+ process.nextTick(async () => {
2172
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2173
+ });
2174
+ }
2175
+
2176
+ if ('album' in content) {
2177
+ const { delayMs = 1500 } = options;
2178
+ for (const albumMedia of content.album) {
2179
+ const albumMsg = await generateWAMessage(jid, albumMedia, {
2180
+ logger,
2181
+ userJid,
2182
+ upload: waUploadToServer,
2183
+ mediaCache: config.mediaCache,
2184
+ options: config.options,
2185
+ ...options,
2186
+ messageId: generateMessageIDV2(userJid)
2187
+ });
2188
+ if (!hasValidAlbumMedia(normalizeMessageContent(albumMsg.message))) {
2189
+ throw new Boom('Invalid message type for album', { statusCode: 400 });
2190
+ }
2191
+ albumMsg.message.messageContextInfo ||= {};
2192
+ // WhatsApp expects an encrypted context secret on each album
2193
+ // child. Without it, clients may show the album as an
2194
+ // unsupported message or fail to group the media together.
2195
+ albumMsg.message.messageContextInfo.messageSecret ||= randomBytes(32);
2196
+ albumMsg.message.messageContextInfo.messageAssociation = {
2197
+ parentMessageKey: fullMsg.key,
2198
+ // WhatsApp album child messages use association type 1.
2199
+ // The generated MEDIA_ALBUM enum value (63) is a message
2200
+ // category, not the child-association wire value.
2201
+ associationType: 1
2202
+ };
2203
+ await relayMessage(jid, albumMsg.message, {
2204
+ messageId: albumMsg.key.id,
2205
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2206
+ addBizAttributes: isNeedBizAttrs,
2207
+ statusJidList: options.statusJidList,
2208
+ additionalAttributes,
2209
+ additionalNodes
2210
+ });
2211
+ if (config.emitOwnEvents) {
2212
+ process.nextTick(async () => {
2213
+ await messageMutex.mutex(() => upsertMessage(albumMsg, 'append'));
2214
+ });
2215
+ }
2216
+ await delay(delayMs);
2217
+ }
2218
+ }
2219
+
2220
+ return fullMsg;
2221
+ }
2222
+ }
2223
+ };
2224
+ /**
2225
+ * Sends a GenAI-style copy-to-clipboard button.
2226
+ * Renders a dark circular copy icon inline with text, inside a forwarded rich response.
2227
+ */
2228
+ socket.sendCopyButton = async (jid, content = {}, options = {}) => {
2229
+ if (!jid) throw new Boom('sendCopyButton requires a target JID', { statusCode: 400 });
2230
+ const wrapped = prepareCopyToClipboardMessage(content);
2231
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2232
+ logger,
2233
+ userJid: authState.creds.me?.id,
2234
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2235
+ ...options,
2236
+ });
2237
+ await relayMessage(jid, fullMsg.message, {
2238
+ messageId: fullMsg.key.id,
2239
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2240
+ statusJidList: options.statusJidList,
2241
+ });
2242
+ if (config.emitOwnEvents) {
2243
+ process.nextTick(async () => {
2244
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2245
+ });
2246
+ }
2247
+ return fullMsg;
2248
+ };
2249
+
2250
+ /**
2251
+ * Sends plain text inside a forwarded GenAI rich response envelope.
2252
+ */
2253
+ socket.sendRichText = async (jid, content = {}, options = {}) => {
2254
+ if (!jid) throw new Boom('sendRichText requires a target JID', { statusCode: 400 });
2255
+ const wrapped = prepareRichTextMessage(content);
2256
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2257
+ logger,
2258
+ userJid: authState.creds.me?.id,
2259
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2260
+ ...options,
2261
+ });
2262
+ await relayMessage(jid, fullMsg.message, {
2263
+ messageId: fullMsg.key.id,
2264
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2265
+ statusJidList: options.statusJidList,
2266
+ });
2267
+ if (config.emitOwnEvents) {
2268
+ process.nextTick(async () => {
2269
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2270
+ });
2271
+ }
2272
+ return fullMsg;
2273
+ };
2274
+ /**
2275
+ * Sends an image inside a forwarded GenAI rich response envelope.
2276
+ */
2277
+ socket.sendRichImage = async (jid, content = {}, options = {}) => {
2278
+ if (!jid) throw new Boom('sendRichImage requires a target JID', { statusCode: 400 });
2279
+ const wrapped = prepareRichImageMessage(content);
2280
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2281
+ logger,
2282
+ userJid: authState.creds.me?.id,
2283
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2284
+ ...options,
2285
+ });
2286
+ await relayMessage(jid, fullMsg.message, {
2287
+ messageId: fullMsg.key.id,
2288
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2289
+ statusJidList: options.statusJidList,
2290
+ });
2291
+ if (config.emitOwnEvents) {
2292
+ process.nextTick(async () => {
2293
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2294
+ });
2295
+ }
2296
+ return fullMsg;
2297
+ };
2298
+ /**
2299
+ * Sends inline hyperlinks inside a forwarded GenAI rich response envelope.
2300
+ */
2301
+ socket.sendRichLink = async (jid, content = {}, options = {}) => {
2302
+ if (!jid) throw new Boom('sendRichLink requires a target JID', { statusCode: 400 });
2303
+ const wrapped = prepareRichLinkMessage(content);
2304
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2305
+ logger,
2306
+ userJid: authState.creds.me?.id,
2307
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2308
+ ...options,
2309
+ });
2310
+ await relayMessage(jid, fullMsg.message, {
2311
+ messageId: fullMsg.key.id,
2312
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2313
+ statusJidList: options.statusJidList,
2314
+ });
2315
+ if (config.emitOwnEvents) {
2316
+ process.nextTick(async () => {
2317
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2318
+ });
2319
+ }
2320
+ return fullMsg;
2321
+ };
2322
+ socket.richMenu = async (jid, content = {}, options = {}) => {
2323
+ if (!jid) throw new Boom('richMenu requires a target JID', { statusCode: 400 });
2324
+ const wrapped = prepareRichMenuMessage(content);
2325
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2326
+ logger,
2327
+ userJid: authState.creds.me?.id,
2328
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2329
+ ...options,
2330
+ });
2331
+ await relayMessage(jid, fullMsg.message, {
2332
+ messageId: fullMsg.key.id,
2333
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2334
+ statusJidList: options.statusJidList,
2335
+ });
2336
+ if (config.emitOwnEvents) {
2337
+ process.nextTick(async () => {
2338
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2339
+ });
2340
+ }
2341
+ return fullMsg;
2342
+ };
2343
+ socket.sendStatus = async (content, options = {}) => {
2344
+ const statusJidList = await resolveStatusRecipients(options.statusJidList || content?.statusJidList);
2345
+ return socket.sendMessage(STATUS_JID, {
2346
+ ...content,
2347
+ status: true
2348
+ }, {
2349
+ ...options,
2350
+ broadcast: true,
2351
+ statusJidList
2352
+ });
2353
+ };
2354
+ socket.sendRichButtonGrid = async (jid, grid, options = {}) => {
2355
+ const { text, footer, cards = [] } = grid || {};
2356
+ if (!Array.isArray(cards) || cards.length === 0) {
2357
+ throw new Boom('sendRichButtonGrid expects at least one card', { statusCode: 400 });
2358
+ }
2359
+ const normalizedCards = cards.map((card, index) => {
2360
+ const buttons = card.buttons || card.nativeFlow || [];
2361
+ if (!Array.isArray(buttons) || buttons.length === 0) {
2362
+ throw new Boom(`sendRichButtonGrid card ${index + 1} needs buttons`, { statusCode: 400 });
2363
+ }
2364
+ return {
2365
+ ...card,
2366
+ nativeFlow: buttons,
2367
+ caption: card.caption || card.title || `Menu ${index + 1}`
2368
+ };
2369
+ });
2370
+ return socket.sendMessage(jid, {
2371
+ ...(text ? { text } : {}),
2372
+ ...(footer ? { footer } : {}),
2373
+ cards: normalizedCards
2374
+ }, options);
2375
+ };
2376
+ socket.sendWhatsAppFlow = async (jid, flow, options = {}) => {
2377
+ const { text, footer, image, caption, ...flowOptions } = flow || {};
2378
+ const button = makeWhatsAppFlowButton(flowOptions);
2379
+ return socket.sendMessage(jid, {
2380
+ ...(image ? { image, caption: caption || text || flowOptions.cta } : { text: text || flowOptions.cta }),
2381
+ ...(footer ? { footer } : {}),
2382
+ nativeFlow: [button]
2383
+ }, options);
2384
+ };
2385
+ /**
2386
+ * Send a rich URL CTA intended to open a hosted WebView/Mini App.
2387
+ * `useWebview` is serialized by the existing native-flow normalizer.
2388
+ * `toast` is preserved as immediate button acknowledgement metadata.
2389
+ */
2390
+ socket.sendRichWebview = async (jid, content = {}, options = {}) => {
2391
+ const { text = '', title, footer, image, caption, buttonText = 'Open', url, useWebview = true, toast, ...rest } = content;
2392
+ if (!url || typeof url !== 'string') {
2393
+ throw new Boom('sendRichWebview requires a URL', { statusCode: 400 });
2394
+ }
2395
+ const button = { text: buttonText, url, useWebview, ...(toast ? { toast } : {}), ...rest };
2396
+ return socket.sendMessage(jid, {
2397
+ ...(image ? { image, caption: caption || text || title || buttonText } : { text: text || title || buttonText }),
2398
+ ...(footer ? { footer } : {}),
2399
+ nativeFlow: [button],
2400
+ ...(toast ? { toast } : {})
2401
+ }, options);
2402
+ };
2403
+ socket.sendInteractiveTable = async (jid, table, options = {}) => {
2404
+ const { title = '', headers = [], rows = [], image, buttons = [], footer } = table || {};
2405
+ if (!Array.isArray(headers) || !Array.isArray(rows) || !Array.isArray(buttons)) {
2406
+ throw new Boom('sendInteractiveTable expects headers, rows, and buttons arrays', { statusCode: 400 });
2407
+ }
2408
+ const lines = [];
2409
+ if (title) lines.push(String(title));
2410
+ if (headers.length) lines.push(`| ${headers.map(String).join(' | ')} |`);
2411
+ if (headers.length) lines.push(`| ${headers.map(() => '---').join(' | ')} |`);
2412
+ for (const row of rows) {
2413
+ lines.push(`| ${(Array.isArray(row) ? row : [row]).map(value => String(value ?? '')).join(' | ')} |`);
2414
+ }
2415
+ const content = {
2416
+ ...(image ? { caption: lines.join('\n'), image } : { text: lines.join('\n') }),
2417
+ buttons: buttons.map((button, index) => ({
2418
+ id: button.id || `table_${index + 1}`,
2419
+ text: button.text || button.buttonText || `Option ${index + 1}`
2420
+ })),
2421
+ ...(footer ? { footer } : {})
2422
+ };
2423
+ return socket.sendMessage(jid, content, options);
2424
+ };
2425
+ // ====================================
2426
+ // VIEW-ONCE AUTO-DECRYPT & AUTO-DELETE
2427
+ // ====================================
2428
+
2429
+ /**
2430
+ * Auto-decrypt view-once messages (autoVV)
2431
+ * Downloads the media content from a view-once message and re-emits it
2432
+ * as a regular message with decryptedMedia attached.
2433
+ */
2434
+ socket.autoVV = async (message, options = {}) => {
2435
+ if (!isViewOnceMessage(message)) {
2436
+ logger.debug({ key: message?.key }, 'autoVV: message is not a view-once message');
2437
+ return null;
2438
+ }
2439
+
2440
+ const info = parseViewOnceInfo(message);
2441
+ logger.info({ key: message?.key, ...info }, 'autoVV: decrypting view-once message');
2442
+
2443
+ try {
2444
+ // Download and decrypt the media
2445
+ const mediaBuffer = await downloadViewOnceMedia(message, {
2446
+ logger,
2447
+ ...options,
2448
+ });
2449
+
2450
+ // Create a regular message from the decrypted content
2451
+ const regularMessage = createRegularMessageFromViewOnce(message, mediaBuffer);
2452
+
2453
+ if (regularMessage) {
2454
+ // Emit as a new message with decrypted content
2455
+ ev.emit('messages.upsert', {
2456
+ messages: [regularMessage],
2457
+ type: 'append',
2458
+ });
2459
+
2460
+ logger.info({
2461
+ key: message?.key,
2462
+ mediaType: info.mediaType,
2463
+ bufferSize: mediaBuffer.length,
2464
+ }, 'autoVV: successfully decrypted view-once message');
2465
+ }
2466
+
2467
+ return regularMessage;
2468
+ } catch (error) {
2469
+ logger.error({
2470
+ key: message?.key,
2471
+ error: error.message,
2472
+ }, 'autoVV: failed to decrypt view-once message');
2473
+ throw error;
2474
+ }
2475
+ };
2476
+
2477
+ /**
2478
+ * Auto-delete view-once messages (antiVV)
2479
+ * Detects incoming view-once messages and deletes them immediately.
2480
+ * This prevents the sender from knowing the message was viewed.
2481
+ */
2482
+ socket.antiVV = async (message, options = {}) => {
2483
+ if (!isViewOnceMessage(message)) {
2484
+ logger.debug({ key: message?.key }, 'antiVV: message is not a view-once message');
2485
+ return false;
2486
+ }
2487
+
2488
+ const info = parseViewOnceInfo(message);
2489
+ logger.info({ key: message?.key, ...info }, 'antiVV: deleting view-once message');
2490
+
2491
+ try {
2492
+ // Delete the message by sending a revoke receipt
2493
+ const jid = message.key.remoteJid;
2494
+ const participant = message.key.participant || jid;
2495
+ const messageId = message.key.id;
2496
+
2497
+ // Send a revoke receipt to delete the message
2498
+ await sendReceipt(jid, participant, [messageId], 'sender');
2499
+
2500
+ // Also emit a message update to remove it from local store
2501
+ ev.emit('messages.update', [
2502
+ {
2503
+ key: message.key,
2504
+ update: {
2505
+ messageStubType: proto.WebMessageInfo.StubType.REVOKE,
2506
+ messageStubParameters: ['auto-vv-delete'],
2507
+ },
2508
+ },
2509
+ ]);
2510
+
2511
+ logger.info({
2512
+ key: message?.key,
2513
+ mediaType: info.mediaType,
2514
+ }, 'antiVV: successfully deleted view-once message');
2515
+
2516
+ return true;
2517
+ } catch (error) {
2518
+ logger.error({
2519
+ key: message?.key,
2520
+ error: error.message,
2521
+ }, 'antiVV: failed to delete view-once message');
2522
+ throw error;
2523
+ }
2524
+ };
2525
+
2526
+ /**
2527
+ * Check if a message is a view-once message
2528
+ */
2529
+ socket.isViewOnce = (message) => isViewOnceMessage(message);
2530
+
2531
+ /**
2532
+ * Get view-once message info (media type, mime type, etc.)
2533
+ */
2534
+ socket.getViewOnceInfo = (message) => parseViewOnceInfo(message);
2535
+
2536
+
2537
+ /**
2538
+ * Sends an HTML message — renders raw HTML inside the chat bubble.
2539
+ * Uses FOAHtmlPrimitiveDemoDONOTUSE for full HTML/CSS/JS rendering.
2540
+ *
2541
+ * @param {string} jid - Target JID
2542
+ * @param {Object} content - { html: string, trustedSources?: string[] }
2543
+ * @param {Object} options - Additional options
2544
+ * @returns {Object} Sent message info
2545
+ *
2546
+ * @example
2547
+ * // Simple HTML
2548
+ * await sock.sendHtmlMessage(jid, {
2549
+ * html: '<h1>Hello!</h1><p style="color: blue">World</p>'
2550
+ * })
2551
+ */
2552
+ socket.sendHtmlMessage = async (jid, content = {}, options = {}) => {
2553
+ if (!jid) throw new Boom('sendHtmlMessage requires a target JID', { statusCode: 400 });
2554
+ const { html, trustedSources } = content;
2555
+ if (!html) throw new Boom('sendHtmlMessage requires html content', { statusCode: 400 });
2556
+ const wrapped = prepareHtmlMessage({ html, trustedSources });
2557
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2558
+ logger,
2559
+ userJid: authState.creds.me?.id,
2560
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2561
+ ...options
2562
+ });
2563
+ await relayMessage(jid, fullMsg.message, {
2564
+ messageId: fullMsg.key.id,
2565
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2566
+ statusJidList: options.statusJidList
2567
+ });
2568
+ return fullMsg;
2569
+ };
2570
+
2571
+
2572
+ /**
2573
+ * Sends a slot machine game — Fruit Bonanza!
2574
+ * Renders a fully interactive canvas-based slot machine inside the chat bubble.
2575
+ *
2576
+ * @param {string} jid - Target JID
2577
+ * @param {Object} [options] - Game options
2578
+ * @param {string} [options.title='FRUIT BONANZA'] - Machine title
2579
+ * @param {number} [options.startingCredits=500] - Starting credits
2580
+ * @param {Object} [sendOptions] - Send options (quoted, etc.)
2581
+ * @returns {Object} Sent message info
2582
+ *
2583
+ * @example
2584
+ * // Default slot machine
2585
+ * await sock.sendSlotMachine(jid)
2586
+ *
2587
+ * // Custom title and credits
2588
+ * await sock.sendSlotMachine(jid, { title: 'MEGA SLOTS', startingCredits: 1000 })
2589
+ */
2590
+ socket.sendSlotMachine = async (jid, options = {}, sendOptions = {}) => {
2591
+ if (!jid) throw new Boom('sendSlotMachine requires a target JID', { statusCode: 400 });
2592
+ const html = generateSlotMachineHtml(options);
2593
+ return socket.sendHtmlMessage(jid, { html }, sendOptions);
2594
+ };
2595
+
2596
+
2597
+ /**
2598
+ * Mirrors a website inside the WhatsApp chat bubble.
2599
+ * Fetches the site and renders it in a sandboxed iframe.
2600
+ *
2601
+ * @param {string} jid - Target JID
2602
+ * @param {string} url - Website URL to mirror
2603
+ * @param {Object} [options] - Preview options
2604
+ * @param {boolean} [options.sandbox=true] - Sandbox restrictions
2605
+ * @param {string} [options.height='600px'] - Preview height
2606
+ * @param {boolean} [options.showUrl=true] - Show URL bar
2607
+ * @param {Object} [sendOptions] - Send options
2608
+ * @returns {Object} Sent message info
2609
+ *
2610
+ * @example
2611
+ * await sock.sendWebsitePreview(jid, 'https://google.com')
2612
+ * await sock.sendWebsitePreview(jid, 'https://example.com', { height: '400px' })
2613
+ */
2614
+ socket.sendWebsitePreview = async (jid, url, options = {}, sendOptions = {}) => {
2615
+ if (!jid) throw new Boom('sendWebsitePreview requires a target JID', { statusCode: 400 });
2616
+ if (!url) throw new Boom('sendWebsitePreview requires a URL', { statusCode: 400 });
2617
+ const html = await generateWebsitePreviewHtml(url, options);
2618
+ return socket.sendHtmlMessage(jid, { html }, sendOptions);
2619
+ };
2620
+
2621
+ /**
2622
+ * Sends a link preview card for a URL.
2623
+ * Lighter weight than sendWebsitePreview — just shows title, description, image.
2624
+ *
2625
+ * @param {string} jid - Target JID
2626
+ * @param {string} url - URL to preview
2627
+ * @param {Object} [options] - Card options
2628
+ * @param {string} [options.title] - Override title
2629
+ * @param {string} [options.description] - Override description
2630
+ * @param {string} [options.image] - Override image URL
2631
+ * @param {Object} [sendOptions] - Send options
2632
+ * @returns {Object} Sent message info
2633
+ *
2634
+ * @example
2635
+ * await sock.sendLinkPreview(jid, 'https://google.com')
2636
+ * await sock.sendLinkPreview(jid, 'https://example.com', {
2637
+ * title: 'My Website',
2638
+ * description: 'Check out my cool site!',
2639
+ * image: 'https://example.com/og.png'
2640
+ * })
2641
+ */
2642
+ socket.sendLinkPreview = async (jid, url, options = {}, sendOptions = {}) => {
2643
+ if (!jid) throw new Boom('sendLinkPreview requires a target JID', { statusCode: 400 });
2644
+ if (!url) throw new Boom('sendLinkPreview requires a URL', { statusCode: 400 });
2645
+ const html = generateLinkPreviewHtml(url, options);
2646
+ return socket.sendHtmlMessage(jid, { html }, sendOptions);
2647
+ };
2648
+
2649
+ return socket;
2650
+ };