lordceaser-baileys 3.3.8 → 3.4.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 (70) hide show
  1. package/WAProto/index.js +1 -2
  2. package/index.js +4 -16
  3. package/lib/Socket/Client/index.js +0 -1
  4. package/lib/Socket/Client/types.js +1 -2
  5. package/lib/Socket/Client/websocket.js +1 -2
  6. package/lib/Socket/business.js +70 -42
  7. package/lib/Socket/chats.js +731 -21
  8. package/lib/Socket/communities.js +1 -1
  9. package/lib/Socket/groups.js +207 -5
  10. package/lib/Socket/index.js +28 -3
  11. package/lib/Socket/messages-recv.js +381 -9
  12. package/lib/Socket/messages-send.js +2189 -157
  13. package/lib/Socket/mex.js +1 -2
  14. package/lib/Socket/newsletter.js +98 -19
  15. package/lib/Socket/socket.js +64 -17
  16. package/lib/Utils/crypto.js +6 -5
  17. package/lib/Utils/lt-hash.js +3 -8
  18. package/lib/WAUSync/Protocols/USyncContactProtocol.js +7 -3
  19. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +1 -2
  20. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -2
  21. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +1 -2
  22. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +2 -3
  23. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +1 -2
  24. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +1 -2
  25. package/lib/WAUSync/Protocols/index.js +7 -1
  26. package/lib/WAUSync/USyncQuery.js +126 -23
  27. package/lib/WAUSync/USyncUser.js +24 -1
  28. package/lib/WAUSync/index.js +1 -2
  29. package/package.json +2 -6
  30. package/lib/Socket/Socket/Client/index.js +0 -2
  31. package/lib/Socket/Socket/Client/types.js +0 -10
  32. package/lib/Socket/Socket/Client/websocket.js +0 -53
  33. package/lib/Socket/Socket/business.js +0 -407
  34. package/lib/Socket/Socket/chats.js +0 -1908
  35. package/lib/Socket/Socket/communities.js +0 -431
  36. package/lib/Socket/Socket/groups.js +0 -549
  37. package/lib/Socket/Socket/index.js +0 -37
  38. package/lib/Socket/Socket/messages-recv.js +0 -2144
  39. package/lib/Socket/Socket/messages-send.js +0 -3177
  40. package/lib/Socket/Socket/mex.js +0 -41
  41. package/lib/Socket/Socket/newsletter.js +0 -260
  42. package/lib/Socket/Socket/socket.js +0 -1017
  43. package/lib/Utils/_crypto_orig.js +0 -118
  44. package/lib/WAUSync/WAUSync/Protocols/USyncContactProtocol.js +0 -56
  45. package/lib/WAUSync/WAUSync/Protocols/USyncDeviceProtocol.js +0 -53
  46. package/lib/WAUSync/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -26
  47. package/lib/WAUSync/WAUSync/Protocols/USyncStatusProtocol.js +0 -37
  48. package/lib/WAUSync/WAUSync/Protocols/USyncUsernameProtocol.js +0 -24
  49. package/lib/WAUSync/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -50
  50. package/lib/WAUSync/WAUSync/Protocols/UsyncLIDProtocol.js +0 -28
  51. package/lib/WAUSync/WAUSync/Protocols/index.js +0 -12
  52. package/lib/WAUSync/WAUSync/USyncQuery.js +0 -201
  53. package/lib/WAUSync/WAUSync/USyncUser.js +0 -54
  54. package/lib/WAUSync/WAUSync/index.js +0 -3
  55. /package/lib/Socket/{Socket/aigroups.js → aigroups.js} +0 -0
  56. /package/lib/Socket/{Socket/ban-checker.js → ban-checker.js} +0 -0
  57. /package/lib/Socket/{Socket/chats.js[old] → chats.js[old]} +0 -0
  58. /package/lib/Socket/{Socket/graphql.js → graphql.js} +0 -0
  59. /package/lib/Socket/{Socket/groups.js[old] → groups.js[old]} +0 -0
  60. /package/lib/Socket/{Socket/interactive-handler.js → interactive-handler.js} +0 -0
  61. /package/lib/Socket/{Socket/interop.js → interop.js} +0 -0
  62. /package/lib/Socket/{Socket/managed-account.js → managed-account.js} +0 -0
  63. /package/lib/Socket/{Socket/privacy.js → privacy.js} +0 -0
  64. /package/lib/Socket/{Socket/registration.js → registration.js} +0 -0
  65. /package/lib/Socket/{Socket/username.js → username.js} +0 -0
  66. /package/lib/WAUSync/{WAUSync/Protocols → Protocols}/USyncBusinessProtocol.js +0 -0
  67. /package/lib/WAUSync/{WAUSync/Protocols → Protocols}/USyncFeatureProtocol.js +0 -0
  68. /package/lib/WAUSync/{WAUSync/Protocols → Protocols}/USyncPictureProtocol.js +0 -0
  69. /package/lib/WAUSync/{WAUSync/Protocols → Protocols}/USyncSidelistProtocol.js +0 -0
  70. /package/lib/WAUSync/{WAUSync/Protocols → Protocols}/USyncTextStatusProtocol.js +0 -0
@@ -1,77 +1,170 @@
1
1
  import NodeCache from '@cacheable/node-cache';
2
2
  import { Boom } from '@hapi/boom';
3
+ import { randomBytes, randomUUID } from 'crypto';
3
4
  import { proto } from '../../WAProto/index.js';
4
- import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
5
- import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils/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, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, prepareWAMessageMedia, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
6
7
  import { getUrlInfo } from '../Utils/link-preview.js';
8
+ import { prepareRichMenuMessage, prepareA2UIMessage, prepareA2UICommandMenu, prepareAIRichCommandMenu, prepareSocialEntityMessage, prepareInstagramProfileMessage, prepareRichResponseMessage, prepareRichGenerationMessage, prepareCopyToClipboardMessage, prepareRichTextMessage, prepareRichQuoteMessage, prepareRichImageMessage, prepareRichLinkMessage, prepareSocialProfileMessage, prepareUnifiedResponseMessage, prepareRichMapMessage, prepareBotPromptSuggestionsMessage, prepareBotSourcesMessage, prepareRichDynamicMediaMessage, prepareBotPttTranscriptMessage, prepareGridImageMessage, prepareVerticalAlbumMessage, prepareVideoGridMessage, prepareHtmlMessage, prepareRichHtmlMessage, buildRichLabelMessage, attachBotVerificationProofs, hasVerifiableProofs } from '../Utils/rich-message-utils.js';
9
+ import { generateSlotMachineHtml } from '../Utils/games/slot-machine.js';
10
+ import { generateMiniAppHtml } from '../Utils/games/miniapp.js';
11
+ import { generateWebsitePreviewHtml, generateLinkPreviewHtml } from '../Utils/games/website-preview.js';
12
+ import { isViewOnceMessage, extractViewOnceContent, getViewOnceMediaType, getViewOnceMediaContent, downloadViewOnceMedia, createRegularMessageFromViewOnce, parseViewOnceInfo } from '../Utils/view-once-utils.js';
7
13
  import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
8
14
  import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
9
15
  import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
10
- import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
16
+ 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';
11
17
  import { USyncQuery, USyncUser } from '../WAUSync/index.js';
12
- import { makeNewsletterSocket } from './newsletter.js';
18
+ import { captureUnifiedResponse, generateCodeBlockContent, generateLatexContent, generateListContent, generateTableContent, generateUnifiedResponseContent } from '../Utils/message-composer.js';
19
+ import { BotCapabilityType, buildBotRichResponse } from '../Utils/bot-capabilities.js';
20
+ import { Baron } from './interactive-handler.js';
21
+ import { collectMetaAIBotParticipantJids, isMetaAIBotResponse, META_AI_BOT_JID } from './aigroups.js';
22
+ import { makeUsernameSocket } from './username.js';
23
+ import { grepSource } from '../Utils/source-grep.js';
24
+
25
+ const STATUS_JID = 'status@broadcast';
26
+ export const normalizeStatusJidList = (value) => {
27
+ if (!Array.isArray(value) || value.length === 0) {
28
+ throw new Boom('statusJidList must contain at least one recipient JID', { statusCode: 400 });
29
+ }
30
+ const recipients = [...new Set(value.map(jidNormalizedUser).filter(jid => isPnUser(jid) || isLidUser(jid)))];
31
+ if (recipients.length === 0) {
32
+ throw new Boom('statusJidList does not contain any valid user JIDs', { statusCode: 400 });
33
+ }
34
+ return recipients;
35
+ };
36
+
13
37
  export const makeMessagesSocket = (config) => {
14
38
  const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
15
- const sock = makeNewsletterSocket(config);
39
+ const sock = makeUsernameSocket(config);
40
+ let socket;
16
41
  const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
17
42
  const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
18
- /**
19
- * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
20
- * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
21
- * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
22
- */
43
+
23
44
  const inFlightTcTokenIssuance = new Set();
24
45
  const userDevicesCache = config.userDevicesCache ||
25
46
  new NodeCache({
26
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
47
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
27
48
  useClones: false
28
49
  });
29
- /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
30
50
  const devicesMutex = makeMutex();
31
- // Initialize message retry manager if enabled
32
51
  const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
33
- // Prevent race conditions in Signal session encryption by user
34
52
  const encryptionMutex = makeKeyedMutex();
53
+ const mediaConnMutex = makeKeyedMutex();
54
+
35
55
  let mediaConn;
36
- /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
37
56
  let mediaHost = DEF_MEDIA_HOST;
38
- const refreshMediaConn = async (forceGet = false) => {
39
- const media = await mediaConn;
40
- if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
41
- mediaConn = (async () => {
42
- const result = await query({
43
- tag: 'iq',
44
- attrs: {
45
- type: 'set',
46
- xmlns: 'w:m',
47
- to: S_WHATSAPP_NET
48
- },
49
- content: [{ tag: 'media_conn', attrs: {} }]
50
- });
51
- const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
52
- // TODO: explore full length of data that whatsapp provides
53
- const node = {
54
- hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
55
- hostname: attrs.hostname,
56
- maxContentLengthBytes: +attrs.maxContentLengthBytes
57
- })),
58
- auth: mediaConnNode.attrs.auth,
59
- ttl: +mediaConnNode.attrs.ttl,
60
- fetchDate: new Date()
61
- };
62
- logger.debug('fetched media conn');
63
- if (node.hosts[0]) {
64
- mediaHost = node.hosts[0].hostname;
57
+
58
+ // ── BULK REACTION HELPER (NEW) ──
59
+ const sendBulkReactions = async (jid, messageId, emoji, count = 1, fake = false) => {
60
+ const maxReactions = Math.min(Math.max(Number(count) || 1, 1), 1000);
61
+ if (isJidNewsletter(jid)) {
62
+ if (typeof socket.newsletterReactMessage !== 'function') {
63
+ throw new Boom('newsletter reaction API is unavailable', { statusCode: 501 });
64
+ }
65
+ await socket.newsletterReactMessage(jid, messageId, String(emoji || ''));
66
+ return { sent: 1, requested: maxReactions, fake: false, channel: true, jid };
67
+ }
68
+ const makeReaction = () => ({
69
+ react: {
70
+ text: String(emoji || ''),
71
+ key: {
72
+ remoteJid: jid,
73
+ fromMe: false,
74
+ id: messageId
65
75
  }
66
- return node;
67
- })();
76
+ }
77
+ });
78
+ let sent = 0;
79
+ const batchSize = 10;
80
+
81
+ // sendMessage accepts one content object, not an array of messages.
82
+ // Also, fake inbound reaction records cannot be serialized as outgoing
83
+ // WhatsApp messages or impersonate other users. Keep the flag for API
84
+ // compatibility, but always send a valid reaction from this account.
85
+ if (fake) {
86
+ logger.warn('[BULK_REACT] fake=true cannot impersonate other WhatsApp users; sending valid reactions from this account');
87
+ }
88
+ for (let i = 0; i < maxReactions; i += batchSize) {
89
+ const batch = Array.from({ length: Math.min(batchSize, maxReactions - i) }, () =>
90
+ socket.sendMessage(jid, makeReaction(), { ephemeralExpiration: 86400 })
91
+ .then(() => { sent += 1; })
92
+ .catch(error => logger.warn(`[BULK_REACT] Reaction failed: ${error.message}`))
93
+ );
94
+ await Promise.all(batch);
95
+ if (i + batchSize < maxReactions) await delay(100);
68
96
  }
69
- return mediaConn;
97
+
98
+ return { sent, requested: maxReactions, fake: false, jid };
70
99
  };
71
- /**
72
- * generic send receipt function
73
- * used for receipts of phone call, read, delivery etc.
74
- * */
100
+
101
+ // ── MIMIC HELPER ──
102
+ const sendAsMimic = async (jid, content, mimicJid, options = {}) => {
103
+ const hasPermission = options.admin === true || options.mimicPermission === true;
104
+ if (!hasPermission) {
105
+ throw new Boom('Mimic requires admin permission', { statusCode: 403 });
106
+ }
107
+
108
+ const msgId = generateMessageIDV2(authState.creds.me.id);
109
+
110
+ const fakeKey = {
111
+ remoteJid: jid,
112
+ fromMe: false,
113
+ id: msgId,
114
+ participant: mimicJid
115
+ };
116
+
117
+ const fullMsg = await generateWAMessageFromContent(jid, content, {
118
+ userJid: authState.creds.me.id,
119
+ ...options
120
+ });
121
+
122
+ fullMsg.key = fakeKey;
123
+
124
+ await relayMessage(jid, fullMsg.message, {
125
+ messageId: msgId,
126
+ additionalAttributes: options.additionalAttributes || {},
127
+ additionalNodes: options.additionalNodes || []
128
+ });
129
+
130
+ return fullMsg;
131
+ };
132
+
133
+ const refreshMediaConn = async (forceGet = false) => {
134
+ return mediaConnMutex.mutex('media-conn', async () => {
135
+ const media = await mediaConn;
136
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
137
+ mediaConn = (async () => {
138
+ const result = await query({
139
+ tag: 'iq',
140
+ attrs: {
141
+ type: 'set',
142
+ xmlns: 'w:m',
143
+ to: S_WHATSAPP_NET
144
+ },
145
+ content: [{ tag: 'media_conn', attrs: {} }]
146
+ });
147
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
148
+ const node = {
149
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
150
+ hostname: attrs.hostname,
151
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
152
+ })),
153
+ auth: mediaConnNode.attrs.auth,
154
+ ttl: +mediaConnNode.attrs.ttl,
155
+ fetchDate: new Date()
156
+ };
157
+ logger.debug('fetched media conn');
158
+ if (node.hosts[0]) {
159
+ mediaHost = node.hosts[0].hostname;
160
+ }
161
+ return node;
162
+ })();
163
+ }
164
+ return mediaConn;
165
+ });
166
+ };
167
+
75
168
  const sendReceipt = async (jid, participant, messageIds, type) => {
76
169
  if (!messageIds || messageIds.length === 0) {
77
170
  throw new Boom('missing ids in receipt');
@@ -115,21 +208,20 @@ export const makeMessagesSocket = (config) => {
115
208
  logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
116
209
  await sendNode(node);
117
210
  };
118
- /** Correctly bulk send receipts to multiple chats, participants */
211
+
119
212
  const sendReceipts = async (keys, type) => {
120
213
  const recps = aggregateMessageKeysNotFromMe(keys);
121
214
  for (const { jid, participant, messageIds } of recps) {
122
215
  await sendReceipt(jid, participant, messageIds, type);
123
216
  }
124
217
  };
125
- /** Bulk read messages. Keys can be from different chats & participants */
218
+
126
219
  const readMessages = async (keys) => {
127
220
  const privacySettings = await fetchPrivacySettings();
128
- // based on privacy settings, we have to change the read type
129
221
  const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
130
222
  await sendReceipts(keys, readType);
131
223
  };
132
- /** Fetch all the devices we've to send a message to */
224
+
133
225
  const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
134
226
  const deviceResults = [];
135
227
  if (!useCache) {
@@ -141,6 +233,16 @@ export const makeMessagesSocket = (config) => {
141
233
  const decoded = jidDecode(jid);
142
234
  const user = decoded?.user;
143
235
  const device = decoded?.device;
236
+ // Meta AI/bot JIDs are single device-0 endpoints. USync does not
237
+ // enumerate them, so inject the endpoint instead of dropping it.
238
+ if (user && (isJidMetaAI(jid) || isJidBot(jid))) {
239
+ deviceResults.push({
240
+ user,
241
+ device: typeof device === 'number' ? device : 0,
242
+ jid
243
+ });
244
+ return null;
245
+ }
144
246
  const isExplicitDevice = typeof device === 'number' && device >= 0;
145
247
  if (isExplicitDevice && user) {
146
248
  deviceResults.push({
@@ -192,16 +294,14 @@ export const makeMessagesSocket = (config) => {
192
294
  }
193
295
  const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
194
296
  for (const jid of toFetch) {
195
- query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
297
+ query.withUser(new USyncUser().withId(jid));
196
298
  }
197
299
  const result = await sock.executeUSyncQuery(query);
198
300
  if (result) {
199
- // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
200
301
  const lidResults = result.list.filter(a => !!a.lid);
201
302
  if (lidResults.length > 0) {
202
303
  logger.trace('Storing LID maps from device call');
203
304
  await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
204
- // Force-refresh sessions for newly mapped LIDs to align identity addressing
205
305
  try {
206
306
  const lids = lidResults.map(a => a.lid);
207
307
  if (lids.length) {
@@ -218,10 +318,8 @@ export const makeMessagesSocket = (config) => {
218
318
  deviceMap[item.user] = deviceMap[item.user] || [];
219
319
  deviceMap[item.user]?.push(item);
220
320
  }
221
- // Process each user's devices as a group for bulk LID migration
222
321
  for (const [user, userDevices] of Object.entries(deviceMap)) {
223
322
  const isLidUser = requestedLidUsers.has(user);
224
- // Process all devices for this user
225
323
  for (const item of userDevices) {
226
324
  const finalJid = isLidUser
227
325
  ? jidEncode(user, item.server, item.device)
@@ -240,7 +338,6 @@ export const makeMessagesSocket = (config) => {
240
338
  }
241
339
  await devicesMutex.mutex(async () => {
242
340
  if (userDevicesCache.mset) {
243
- // if the cache supports mset, we can set all devices in one go
244
341
  await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
245
342
  }
246
343
  else {
@@ -268,9 +365,7 @@ export const makeMessagesSocket = (config) => {
268
365
  }
269
366
  return deviceResults;
270
367
  };
271
- /**
272
- * Update Member Label
273
- */
368
+
274
369
  const updateMemberLabel = (jid, memberLabel) => {
275
370
  return relayMessage(jid, {
276
371
  protocolMessage: {
@@ -293,6 +388,7 @@ export const makeMessagesSocket = (config) => {
293
388
  ]
294
389
  });
295
390
  };
391
+
296
392
  const assertSessions = async (jids, force) => {
297
393
  let didFetchNewSession = false;
298
394
  const uniqueJids = [...new Set(jids)];
@@ -308,10 +404,12 @@ export const makeMessagesSocket = (config) => {
308
404
  jidsRequiringFetch.push(jid);
309
405
  }
310
406
  if (jidsRequiringFetch.length) {
311
- // LID if mapped, otherwise original
312
407
  const wireJids = [
313
408
  ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
314
- ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
409
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid),
410
+ // @bot endpoints are not represented by LID/PN USync results,
411
+ // but still require a pre-key fetch to build the Signal session.
412
+ ...jidsRequiringFetch.filter(jid => isJidMetaAI(jid) || isJidBot(jid))
315
413
  ];
316
414
  logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
317
415
  const result = await query({
@@ -339,8 +437,8 @@ export const makeMessagesSocket = (config) => {
339
437
  }
340
438
  return didFetchNewSession;
341
439
  };
440
+
342
441
  const sendPeerDataOperationMessage = async (pdoMessage) => {
343
- //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
344
442
  if (!authState.creds.me?.id) {
345
443
  throw new Boom('Not authenticated');
346
444
  }
@@ -365,6 +463,7 @@ export const makeMessagesSocket = (config) => {
365
463
  });
366
464
  return msgId;
367
465
  };
466
+
368
467
  const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
369
468
  if (!recipientJids.length) {
370
469
  return { nodes: [], shouldIncludeDeviceIdentity: false };
@@ -425,10 +524,13 @@ export const makeMessagesSocket = (config) => {
425
524
  }
426
525
  return { nodes, shouldIncludeDeviceIdentity };
427
526
  };
428
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }) => {
527
+
528
+ 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 }) => {
429
529
  const meId = assertMeId(authState.creds);
430
530
  const meLid = authState.creds.me?.lid;
431
- const isRetryResend = Boolean(participant?.jid);
531
+ const retryParticipants = retryParticipantsExplicit || retryParticipantsOption || (participant?.count != null ? participant : undefined);
532
+ const isRetryResend = Boolean(retryParticipants?.jid && retryParticipants?.count != null);
533
+ const isRecipientOnly = Boolean(participant?.jid && !isRetryResend);
432
534
  let shouldIncludeDeviceIdentity = isRetryResend;
433
535
  const statusJid = 'status@broadcast';
434
536
  const { user, server } = jidDecode(jid);
@@ -446,6 +548,37 @@ export const makeMessagesSocket = (config) => {
446
548
  const binaryNodeContent = [];
447
549
  const devices = [];
448
550
  let reportingMessage;
551
+ const requiresViewOnce = !!(message.buttonsMessage || message.templateMessage || message.listMessage || message.interactiveMessage);
552
+ if (requiresViewOnce) {
553
+ message = {
554
+ viewOnceMessage: {
555
+ message: { ...message }
556
+ }
557
+ };
558
+ }
559
+ const applyForwarded = m => {
560
+ // Auto-inject trusted verification proofs configured once on the socket
561
+ // (config.metaAiRendering.verificationMetadata). Per-message proofs win:
562
+ // an envelope that already carries verificationMetadata is left untouched.
563
+ // The second target covers edited rich envelopes (protocolMessage.editedMessage,
564
+ // used by updateRichGeneration) so an in-place rich update keeps its proofs too.
565
+ const edited = m?.botForwardedMessage?.message?.protocolMessage?.editedMessage;
566
+ const rich = m?.botForwardedMessage?.message?.richResponseMessage || m?.richResponseMessage;
567
+ if (!rich && !edited) return m;
568
+ if (hasVerifiableProofs(config?.metaAiRendering?.verificationMetadata)) {
569
+ attachBotVerificationProofs(m, config.metaAiRendering.verificationMetadata);
570
+ attachBotVerificationProofs(edited, config.metaAiRendering.verificationMetadata);
571
+ }
572
+ if (!rich) return m;
573
+ rich.contextInfo = { ...rich.contextInfo, isForwarded: true, forwardOrigin: 4 };
574
+ return m.botForwardedMessage ? m : { botForwardedMessage: { message: m } };
575
+ };
576
+ if (message?.deviceSentMessage?.message) {
577
+ message.deviceSentMessage.message = applyForwarded(message.deviceSentMessage.message);
578
+ }
579
+ else {
580
+ message = applyForwarded(message);
581
+ }
449
582
  const meMsg = {
450
583
  deviceSentMessage: {
451
584
  destinationJid,
@@ -454,28 +587,31 @@ export const makeMessagesSocket = (config) => {
454
587
  messageContextInfo: message.messageContextInfo
455
588
  };
456
589
  const extraAttrs = {};
457
- if (participant) {
590
+ if (isRetryResend) {
458
591
  if (!isGroup && !isStatus) {
459
592
  additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
460
593
  }
461
- const { user, device } = jidDecode(participant.jid);
462
- devices.push({
463
- user,
464
- device,
465
- jid: participant.jid
466
- });
594
+ const { user, device } = jidDecode(retryParticipants.jid);
595
+ devices.push({ user, device, jid: retryParticipants.jid });
596
+ }
597
+ if ((isRecipientOnly || isSecret || protectedSend || meOnly) && !isGroup && !isStatus) {
598
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
467
599
  }
468
600
  await authState.keys.transaction(async () => {
469
- const mediaType = getMediaType(message);
601
+ const innerMessage = normalizeMessageContent(message);
602
+ const mediaType = getMediaType(innerMessage);
470
603
  if (mediaType) {
471
604
  extraAttrs['mediatype'] = mediaType;
472
605
  }
473
606
  if (isNewsletter) {
474
607
  const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
475
608
  const bytes = encodeNewsletterMessage(patched);
609
+ if (additionalNodes && additionalNodes.length > 0) {
610
+ binaryNodeContent.push(...additionalNodes);
611
+ }
476
612
  binaryNodeContent.push({
477
613
  tag: 'plaintext',
478
- attrs: {},
614
+ attrs: extraAttrs,
479
615
  content: bytes
480
616
  });
481
617
  const stanza = {
@@ -483,7 +619,7 @@ export const makeMessagesSocket = (config) => {
483
619
  attrs: {
484
620
  to: jid,
485
621
  id: msgId,
486
- type: getMessageType(message),
622
+ type: getMessageType(innerMessage),
487
623
  ...(additionalAttributes || {})
488
624
  },
489
625
  content: binaryNodeContent
@@ -492,26 +628,53 @@ export const makeMessagesSocket = (config) => {
492
628
  await sendNode(stanza);
493
629
  return;
494
630
  }
495
- if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
496
- extraAttrs['decrypt-fail'] = 'hide'; // todo: expand for reactions and other types
631
+ const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
632
+ const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
633
+ const isPollUpdate = innerMessage?.pollUpdateMessage;
634
+ if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
635
+ const metaAttrs = {};
636
+ if (isNeedMetaAttrs) {
637
+ metaAttrs.content_type = 'add_on';
638
+ }
639
+ if (isPollUpdate && !isGroupStatus) {
640
+ metaAttrs.polltype = 'vote';
641
+ }
642
+ if (isGroupStatus) {
643
+ metaAttrs.is_group_status = 'true';
644
+ }
645
+ binaryNodeContent.push({
646
+ tag: 'meta',
647
+ attrs: metaAttrs,
648
+ content: undefined
649
+ });
650
+ }
651
+ if (isStatus && statusPrivacy && !additionalAttributes?.edit) {
652
+ binaryNodeContent.push({
653
+ tag: 'meta',
654
+ attrs: { status_setting: statusPrivacy, session_scope: 'status' }
655
+ });
656
+ }
657
+ if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
658
+ extraAttrs['decrypt-fail'] = 'hide';
659
+ }
660
+ if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
661
+ extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
497
662
  }
498
663
  if (isGroupOrStatus && !isRetryResend) {
499
664
  const [groupData, senderKeyMap] = await Promise.all([
500
665
  (async () => {
501
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
666
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
502
667
  if (groupData && Array.isArray(groupData?.participants)) {
503
668
  logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
504
669
  }
505
670
  else if (!isStatus) {
506
- groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
671
+ groupData = await groupMetadata(jid);
507
672
  }
508
673
  return groupData;
509
674
  })(),
510
675
  (async () => {
511
676
  if (!participant && !isStatus) {
512
- // what if sender memory is less accurate than the cached metadata
513
- // on participant change in group, we should do sender memory manipulation
514
- const result = await authState.keys.get('sender-key-memory', [jid]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
677
+ const result = await authState.keys.get('sender-key-memory', [jid]);
515
678
  return result[jid] || {};
516
679
  }
517
680
  return {};
@@ -527,6 +690,16 @@ export const makeMessagesSocket = (config) => {
527
690
  if (isStatus && statusJidList) {
528
691
  participantsList.push(...statusJidList);
529
692
  }
693
+ // Bots invoked through botGroupMetadata are not group members,
694
+ // so include their @bot endpoints in sender-key distribution.
695
+ const botGroupParticipants = message?.messageContextInfo?.botMetadata?.botGroupMetadata?.participantsMetadata || [];
696
+ for (const participant of botGroupParticipants) {
697
+ if (!participant?.botFbid)
698
+ continue;
699
+ const botJid = `${participant.botFbid}@bot`;
700
+ if (!participantsList.includes(botJid))
701
+ participantsList.push(botJid);
702
+ }
530
703
  const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
531
704
  devices.push(...additionalDevices);
532
705
  if (isGroup) {
@@ -552,12 +725,11 @@ export const makeMessagesSocket = (config) => {
552
725
  for (const device of devices) {
553
726
  const deviceJid = device.jid;
554
727
  const hasKey = !!senderKeyMap[deviceJid];
555
- if ((!hasKey || !!participant) &&
728
+ const isBotRecipient = isJidMetaAI(deviceJid) || isJidBot(deviceJid);
729
+ if ((!hasKey || !!participant || isBotRecipient) &&
556
730
  !isHostedLidUser(deviceJid) &&
557
731
  !isHostedPnUser(deviceJid) &&
558
732
  device.device !== 99) {
559
- //todo: revamp all this logic
560
- // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
561
733
  senderKeyRecipients.push(deviceJid);
562
734
  senderKeyMap[deviceJid] = true;
563
735
  }
@@ -584,8 +756,6 @@ export const makeMessagesSocket = (config) => {
584
756
  await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
585
757
  }
586
758
  else {
587
- // ADDRESSING CONSISTENCY: Match own identity to conversation context
588
- // TODO: investigate if this is true
589
759
  let ownId = meId;
590
760
  if (isLid && meLid) {
591
761
  ownId = meLid;
@@ -606,7 +776,7 @@ export const makeMessagesSocket = (config) => {
606
776
  devices.push({
607
777
  user,
608
778
  device: 0,
609
- jid: jidEncode(user, targetUserServer, 0) // rajeh, todo: this entire logic is convoluted and weird.
779
+ jid: jidEncode(user, targetUserServer, 0)
610
780
  });
611
781
  if (user !== ownUser) {
612
782
  const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
@@ -618,13 +788,10 @@ export const makeMessagesSocket = (config) => {
618
788
  });
619
789
  }
620
790
  if (additionalAttributes?.['category'] !== 'peer') {
621
- // Clear placeholders and enumerate actual devices
622
791
  devices.length = 0;
623
- // Use conversation-appropriate sender identity
624
792
  const senderIdentity = isLid && meLid
625
793
  ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
626
794
  : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
627
- // Enumerate devices for sender and target with consistent addressing
628
795
  const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
629
796
  devices.push(...sessionDevices);
630
797
  logger.debug({
@@ -644,8 +811,12 @@ export const makeMessagesSocket = (config) => {
644
811
  logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
645
812
  continue;
646
813
  }
647
- // Check if this is our device (could match either PN or LID user)
648
814
  const isMe = user === mePnUser || user === meLidUser;
815
+ const hasDevice = jid.includes(':');
816
+ if (isRecipientOnly && isMe) continue;
817
+ if (isSecret && !(!isMe && !hasDevice)) continue;
818
+ if (protectedSend && !isMe && hasDevice) continue;
819
+ if (meOnly && !isMe) continue;
649
820
  if (isMe) {
650
821
  meRecipients.push(jid);
651
822
  }
@@ -656,7 +827,6 @@ export const makeMessagesSocket = (config) => {
656
827
  }
657
828
  await assertSessions(allRecipients);
658
829
  const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
659
- // For own devices: use DSM if available (1:1 chats only)
660
830
  createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
661
831
  createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
662
832
  ]);
@@ -668,8 +838,8 @@ export const makeMessagesSocket = (config) => {
668
838
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
669
839
  }
670
840
  if (isRetryResend) {
671
- const isParticipantLid = isLidUser(participant.jid);
672
- const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
841
+ const isParticipantLid = isLidUser(retryParticipants.jid);
842
+ const isMe = areJidsSameUser(retryParticipants.jid, isParticipantLid ? meLid : meId);
673
843
  let messageToSend = message;
674
844
  if (isGroupOrStatus) {
675
845
  let groupSenderIdentity;
@@ -708,14 +878,14 @@ export const makeMessagesSocket = (config) => {
708
878
  : encodeWAMessage(messageToSend);
709
879
  const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
710
880
  data: encodedMessageToSend,
711
- jid: participant.jid
881
+ jid: retryParticipants.jid
712
882
  });
713
883
  binaryNodeContent.push({
714
884
  tag: 'enc',
715
885
  attrs: {
716
886
  v: '2',
717
887
  type,
718
- count: participant.count.toString()
888
+ count: retryParticipants.count.toString()
719
889
  },
720
890
  content: encryptedContent
721
891
  });
@@ -724,7 +894,7 @@ export const makeMessagesSocket = (config) => {
724
894
  if (additionalAttributes?.['category'] === 'peer') {
725
895
  const peerNode = participants[0]?.content?.[0];
726
896
  if (peerNode) {
727
- binaryNodeContent.push(peerNode); // push only enc
897
+ binaryNodeContent.push(peerNode);
728
898
  }
729
899
  }
730
900
  else {
@@ -740,32 +910,28 @@ export const makeMessagesSocket = (config) => {
740
910
  attrs: {
741
911
  id: msgId,
742
912
  to: destinationJid,
743
- type: getMessageType(message),
913
+ type: getMessageType(innerMessage),
744
914
  ...(additionalAttributes || {})
745
915
  },
746
916
  content: binaryNodeContent
747
917
  };
748
- // if the participant to send to is explicitly specified (generally retry recp)
749
- // ensure the message is only sent to that person
750
- // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
751
- if (participant) {
918
+ if (isRetryResend) {
752
919
  if (isJidGroup(destinationJid)) {
753
920
  stanza.attrs.to = destinationJid;
754
- stanza.attrs.participant = participant.jid;
921
+ stanza.attrs.participant = retryParticipants.jid;
755
922
  }
756
- else if (areJidsSameUser(participant.jid, meId)) {
757
- stanza.attrs.to = participant.jid;
923
+ else if (areJidsSameUser(retryParticipants.jid, meId)) {
924
+ stanza.attrs.to = retryParticipants.jid;
758
925
  stanza.attrs.recipient = destinationJid;
759
926
  }
760
927
  else {
761
- stanza.attrs.to = participant.jid;
928
+ stanza.attrs.to = retryParticipants.jid;
762
929
  }
763
930
  }
764
931
  else {
765
932
  stanza.attrs.to = destinationJid;
766
933
  }
767
934
  if (shouldIncludeDeviceIdentity) {
768
- ;
769
935
  stanza.content.push({
770
936
  tag: 'device-identity',
771
937
  attrs: {},
@@ -783,11 +949,10 @@ export const makeMessagesSocket = (config) => {
783
949
  id: msgId,
784
950
  fromMe: true,
785
951
  remoteJid: destinationJid,
786
- participant: participant?.jid
952
+ participant: retryParticipants?.jid
787
953
  };
788
954
  const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
789
955
  if (reportingNode) {
790
- ;
791
956
  stanza.content.push(reportingNode);
792
957
  logger.trace({ jid }, 'added reporting token to message');
793
958
  }
@@ -796,19 +961,15 @@ export const makeMessagesSocket = (config) => {
796
961
  logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
797
962
  }
798
963
  }
799
- // WA Web never attaches tctoken to peer (AppStateSync) messages — server rejects with 479
800
964
  const isPeerMessage = additionalAttributes?.['category'] === 'peer';
801
965
  const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
802
- // Resolve destination to LID for tctoken storage — matches Signal session key pattern
803
966
  const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
804
967
  const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
805
968
  const existingTokenEntry = contactTcTokenData[tcTokenJid];
806
969
  let tcTokenBuffer = existingTokenEntry?.token;
807
- // Treat expired tokens the same as missing — clear from cache
808
970
  if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
809
971
  logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
810
972
  tcTokenBuffer = undefined;
811
- // Preserve senderTimestamp so the fire-and-forget issuance dedupe survives cleanup.
812
973
  const cleared = existingTokenEntry?.senderTimestamp !== undefined
813
974
  ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
814
975
  : null;
@@ -820,22 +981,25 @@ export const makeMessagesSocket = (config) => {
820
981
  }
821
982
  }
822
983
  if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
823
- ;
824
984
  stanza.content.push({
825
985
  tag: 'tctoken',
826
986
  attrs: {},
827
987
  content: tcTokenBuffer
828
988
  });
829
989
  }
990
+ let alreadyHasBizNode = false;
830
991
  if (additionalNodes && additionalNodes.length > 0) {
831
- ;
832
992
  stanza.content.push(...additionalNodes);
993
+ alreadyHasBizNode = !addBizAttributes &&
994
+ additionalNodes.some(node => node.tag === 'biz');
995
+ }
996
+ if ((!alreadyHasBizNode && shouldIncludeBizBinaryNode(innerMessage)) || addBizAttributes) {
997
+ const bizNode = getBizBinaryNode(innerMessage, addBizAttributes);
998
+ stanza.content.push(bizNode);
833
999
  }
834
1000
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
835
1001
  await sendNode(stanza);
836
- // Fire-and-forget: issue our token to the contact AFTER message send.
837
- // WA Web skips protocol messages and PSA/bot contacts (TcTokenChatAction: isRegularUser)
838
- const isProtocolMsg = !!normalizeMessageContent(message)?.protocolMessage;
1002
+ const isProtocolMsg = !!innerMessage?.protocolMessage;
839
1003
  const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
840
1004
  if (is1on1Send &&
841
1005
  !isProtocolMsg &&
@@ -875,34 +1039,83 @@ export const makeMessagesSocket = (config) => {
875
1039
  inFlightTcTokenIssuance.delete(tcTokenJid);
876
1040
  });
877
1041
  }
878
- // Add message to retry cache if enabled
879
- if (messageRetryManager && !participant) {
1042
+ if (messageRetryManager && !retryParticipants) {
880
1043
  messageRetryManager.addRecentMessage(destinationJid, msgId, message);
881
1044
  }
882
1045
  }, meId);
883
1046
  return msgId;
884
1047
  };
1048
+
1049
+ /**
1050
+ * Relay a rich envelope and then replay it as a type-14 edit. Some
1051
+ * WhatsApp clients otherwise show a Download prompt before rendering the
1052
+ * AIRich unifiedResponse. The edit is only applied to bot-forwarded rich
1053
+ * envelopes, so ordinary messages are never duplicated accidentally.
1054
+ * Set renderRichResponse: false for callers that explicitly do not want
1055
+ * the compatibility replay.
1056
+ */
1057
+ const relayRichMessage = async (jid, fullMsg, options = {}) => {
1058
+ const relayOptions = {
1059
+ messageId: fullMsg.key.id,
1060
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1061
+ statusJidList: options.statusJidList,
1062
+ ...options.relayOptions,
1063
+ };
1064
+ await relayMessage(jid, fullMsg.message, relayOptions);
1065
+
1066
+ const richEnvelope = fullMsg.message?.botForwardedMessage?.message?.richResponseMessage;
1067
+ if (options.renderRichResponse !== false && (richEnvelope || options.forceRichEdit || fullMsg.message?.interactiveMessage?.bloksWidget)) {
1068
+ const editContent = proto.Message.fromObject({
1069
+ botForwardedMessage: {
1070
+ message: {
1071
+ protocolMessage: {
1072
+ key: {
1073
+ remoteJid: jid,
1074
+ fromMe: true,
1075
+ id: fullMsg.key.id,
1076
+ },
1077
+ type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
1078
+ editedMessage: fullMsg.message,
1079
+ },
1080
+ },
1081
+ },
1082
+ });
1083
+ const editMessage = generateWAMessageFromContent(jid, editContent, {
1084
+ logger,
1085
+ userJid: authState.creds.me?.id,
1086
+ messageId: generateMessageIDV2(authState.creds.me?.id || jid),
1087
+ });
1088
+ await relayMessage(jid, editMessage.message, {
1089
+ ...relayOptions,
1090
+ messageId: editMessage.key.id,
1091
+ });
1092
+ }
1093
+ return fullMsg;
1094
+ };
1095
+
885
1096
  const getMessageType = (message) => {
886
- const normalizedMessage = normalizeMessageContent(message);
887
- if (!normalizedMessage)
1097
+ if (!message)
888
1098
  return 'text';
889
- if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
1099
+ if (message.reactionMessage || message.encReactionMessage) {
890
1100
  return 'reaction';
891
1101
  }
892
- if (normalizedMessage.pollCreationMessage ||
893
- normalizedMessage.pollCreationMessageV2 ||
894
- normalizedMessage.pollCreationMessageV3 ||
895
- normalizedMessage.pollUpdateMessage) {
1102
+ if (message.pollCreationMessage ||
1103
+ message.pollCreationMessageV2 ||
1104
+ message.pollCreationMessageV3 ||
1105
+ message.pollCreationMessageV5 ||
1106
+ message.pollCreationMessageV6 ||
1107
+ message.pollUpdateMessage) {
896
1108
  return 'poll';
897
1109
  }
898
- if (normalizedMessage.eventMessage) {
1110
+ if (message.eventMessage) {
899
1111
  return 'event';
900
1112
  }
901
- if (getMediaType(normalizedMessage) !== '') {
1113
+ if (getMediaType(message) !== '') {
902
1114
  return 'media';
903
1115
  }
904
1116
  return 'text';
905
1117
  };
1118
+
906
1119
  const getMediaType = (message) => {
907
1120
  if (message.imageMessage) {
908
1121
  return 'image';
@@ -910,9 +1123,15 @@ export const makeMessagesSocket = (config) => {
910
1123
  else if (message.videoMessage) {
911
1124
  return message.videoMessage.gifPlayback ? 'gif' : 'video';
912
1125
  }
1126
+ else if (message.stickerMessage) {
1127
+ return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker';
1128
+ }
913
1129
  else if (message.audioMessage) {
914
1130
  return message.audioMessage.ptt ? 'ptt' : 'audio';
915
1131
  }
1132
+ else if (message.albumMessage) {
1133
+ return 'collection';
1134
+ }
916
1135
  else if (message.contactMessage) {
917
1136
  return 'vcard';
918
1137
  }
@@ -925,8 +1144,8 @@ export const makeMessagesSocket = (config) => {
925
1144
  else if (message.liveLocationMessage) {
926
1145
  return 'livelocation';
927
1146
  }
928
- else if (message.stickerMessage) {
929
- return 'sticker';
1147
+ else if (message.stickerPackMessage) {
1148
+ return 'sticker_pack';
930
1149
  }
931
1150
  else if (message.listMessage) {
932
1151
  return 'list';
@@ -946,11 +1165,18 @@ export const makeMessagesSocket = (config) => {
946
1165
  else if (message.interactiveResponseMessage) {
947
1166
  return 'native_flow_response';
948
1167
  }
949
- else if (message.groupInviteMessage) {
1168
+ else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
950
1169
  return 'url';
951
1170
  }
1171
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/c/')) {
1172
+ return 'cataloglink';
1173
+ }
1174
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/p/')) {
1175
+ return 'productlink';
1176
+ }
952
1177
  return '';
953
1178
  };
1179
+
954
1180
  const issuePrivacyTokens = async (jids, timestamp) => {
955
1181
  const t = (timestamp ?? unixTimestampSeconds()).toString();
956
1182
  const result = await query({
@@ -977,8 +1203,38 @@ export const makeMessagesSocket = (config) => {
977
1203
  });
978
1204
  return result;
979
1205
  };
1206
+
980
1207
  const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1208
+ const baron2 = new Baron(waUploadToServer, relayMessage, config, sock);
981
1209
  const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1210
+
1211
+ const resolveStatusRecipients = async (provided) => {
1212
+ let recipients = provided || config.statusJidList;
1213
+ if (!recipients && typeof config.getStatusJidList === 'function') {
1214
+ recipients = await config.getStatusJidList(sock);
1215
+ }
1216
+ if (!recipients) {
1217
+ const contactSource = config.store?.contacts || config.contactStore?.contacts || config.contacts;
1218
+ if (Array.isArray(contactSource)) {
1219
+ recipients = contactSource;
1220
+ }
1221
+ else if (contactSource && typeof contactSource === 'object') {
1222
+ recipients = Object.keys(contactSource);
1223
+ }
1224
+ }
1225
+ const ownJid = authState.creds.me?.id;
1226
+ try {
1227
+ return normalizeStatusJidList([...(recipients || []), ownJid].filter(Boolean));
1228
+ }
1229
+ catch (error) {
1230
+ throw new Boom('sendStatus requires a non-empty statusJidList or a configured contact source/provider', {
1231
+ statusCode: 400,
1232
+ data: { hint: 'Pass statusJidList, config.statusJidList, config.getStatusJidList, or config.store.contacts' },
1233
+ cause: error
1234
+ });
1235
+ }
1236
+ };
1237
+
982
1238
  registerSocketEndHandler(() => {
983
1239
  if (!config.userDevicesCache && userDevicesCache.close) {
984
1240
  userDevicesCache.close();
@@ -988,7 +1244,8 @@ export const makeMessagesSocket = (config) => {
988
1244
  messageRetryManager.clear();
989
1245
  }
990
1246
  });
991
- return {
1247
+
1248
+ socket = {
992
1249
  ...sock,
993
1250
  userDevicesCache,
994
1251
  devicesMutex,
@@ -999,7 +1256,6 @@ export const makeMessagesSocket = (config) => {
999
1256
  sendReceipts,
1000
1257
  readMessages,
1001
1258
  refreshMediaConn,
1002
- // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1003
1259
  getMediaHost: () => mediaHost,
1004
1260
  waUploadToServer,
1005
1261
  fetchPrivacySettings,
@@ -1008,6 +1264,378 @@ export const makeMessagesSocket = (config) => {
1008
1264
  getUSyncDevices,
1009
1265
  messageRetryManager,
1010
1266
  updateMemberLabel,
1267
+ sendBulkReactions, // ← NEW: Bulk reaction helper
1268
+ sendAsMimic,
1269
+ // Native status mention path. The array-jid sendMessage branch expands
1270
+ // group recipients, emits mentioned_users metadata, and sends the
1271
+ // follow-up statusMentionMessage/groupStatusMentionMessage reference.
1272
+ sendStatusMention: async (content, jids = [], options = {}) => {
1273
+ if (!Array.isArray(jids) || jids.length === 0) {
1274
+ throw new Boom('sendStatusMention requires at least one user or group JID', { statusCode: 400 });
1275
+ }
1276
+ return socket.sendMessage(jids, {
1277
+ ...content,
1278
+ status: true
1279
+ }, options);
1280
+ },
1281
+ sendStatusMentions: async (content, jids = [], options = {}) => {
1282
+ if (!Array.isArray(jids) || jids.length === 0) {
1283
+ throw new Boom('sendStatusMentions requires at least one user or group JID', { statusCode: 400 });
1284
+ }
1285
+ return socket.sendMessage(jids, {
1286
+ ...content,
1287
+ status: true
1288
+ }, options);
1289
+ },
1290
+ sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1291
+ const { message, messageId } = generateTableContent(title, headers, rows, quoted, options);
1292
+ const fullMsg = generateWAMessageFromContent(jid, message, {
1293
+ logger,
1294
+ userJid: authState.creds.me?.id,
1295
+ messageId: options.messageId || messageId || generateMessageIDV2(jid),
1296
+ quoted,
1297
+ ...options
1298
+ });
1299
+ await relayRichMessage(jid, fullMsg, options);
1300
+ return fullMsg;
1301
+ },
1302
+ sendList: async (jid, title, items, quoted, options = {}) => {
1303
+ const { message, messageId } = generateListContent(title, items, quoted, options);
1304
+ const fullMsg = generateWAMessageFromContent(jid, message, {
1305
+ logger,
1306
+ userJid: authState.creds.me?.id,
1307
+ messageId: options.messageId || messageId || generateMessageIDV2(jid),
1308
+ quoted,
1309
+ ...options
1310
+ });
1311
+ await relayRichMessage(jid, fullMsg, options);
1312
+ return fullMsg;
1313
+ },
1314
+ sendCodeBlock: async (jid, code, quoted, options = {}) => {
1315
+ const { message, messageId } = generateCodeBlockContent(code, quoted, options);
1316
+ const fullMsg = generateWAMessageFromContent(jid, message, {
1317
+ logger,
1318
+ userJid: authState.creds.me?.id,
1319
+ messageId: options.messageId || messageId || generateMessageIDV2(jid),
1320
+ quoted,
1321
+ ...options
1322
+ });
1323
+ await relayRichMessage(jid, fullMsg, options);
1324
+ return fullMsg;
1325
+ },
1326
+ sendCarousel: async (jid, cards, options = {}) => {
1327
+ if (!Array.isArray(cards) || cards.length === 0) {
1328
+ throw new Boom('sendCarousel requires a non-empty card array', { statusCode: 400 });
1329
+ }
1330
+ const normalizedCards = cards.map(card => ({
1331
+ ...card,
1332
+ text: card.text ?? card.body?.text,
1333
+ caption: card.caption ?? card.body?.text,
1334
+ footer: card.footer?.text ?? card.footer,
1335
+ buttons: card.buttons ?? card.nativeFlowMessage?.buttons,
1336
+ ...(card.media?.image ? { image: card.media.image } : {}),
1337
+ ...(card.media?.video ? { video: card.media.video } : {}),
1338
+ ...(card.media?.document ? { document: card.media.document } : {})
1339
+ }));
1340
+ const { text, footer, ...messageOptions } = options;
1341
+ const fullMsg = await generateWAMessage(jid, {
1342
+ ...messageOptions,
1343
+ cards: normalizedCards,
1344
+ ...(options.carouselCardType != null ? { carouselCardType: options.carouselCardType } : {}),
1345
+ ...(text !== undefined ? { text } : {}),
1346
+ ...(footer !== undefined ? { footer } : {})
1347
+ }, {
1348
+ logger,
1349
+ userJid,
1350
+ upload: waUploadToServer,
1351
+ mediaCache: config.mediaCache,
1352
+ options: config.options,
1353
+ ...options,
1354
+ messageId: options.messageId || generateMessageIDV2(jid)
1355
+ });
1356
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, ...options });
1357
+ return fullMsg;
1358
+ },
1359
+ sendLatex: async (jid, quoted, options = {}) => {
1360
+ const { message, messageId } = generateLatexContent(quoted, { expressions: [], ...options });
1361
+ const fullMsg = generateWAMessageFromContent(jid, message, {
1362
+ logger,
1363
+ userJid: authState.creds.me?.id,
1364
+ messageId: options.messageId || messageId || generateMessageIDV2(jid),
1365
+ quoted,
1366
+ ...options
1367
+ });
1368
+ await relayRichMessage(jid, fullMsg, options);
1369
+ return fullMsg;
1370
+ },
1371
+ /**
1372
+ * Send LaTeX as rendered PNG image (like Meta AI does).
1373
+ * Uses codecogs.com to render LaTeX to PNG, then sends as rich response.
1374
+ * @param {string} jid - Chat JID
1375
+ * @param {object} options - { text, expressions: [{ latexExpression }], headerText, footer }
1376
+ */
1377
+ sendLatexImage: async (jid, options = {}) => {
1378
+ const { text, expressions = [], headerText, footer } = options;
1379
+ const renderedExpressions = expressions.map(expr => {
1380
+ const latex = expr.latexExpression || expr.expression || expr;
1381
+ // Encode LaTeX for codecogs URL
1382
+ const encoded = encodeURIComponent(latex).replace(/'/g, '%27');
1383
+ const url = `https://latex.codecogs.com/png.latex?${encoded}`;
1384
+ return {
1385
+ latexExpression: latex,
1386
+ url,
1387
+ width: expr.width || 400,
1388
+ height: expr.height || 100
1389
+ };
1390
+ });
1391
+ const { message, messageId } = generateLatexContent(null, {
1392
+ text,
1393
+ expressions: renderedExpressions,
1394
+ headerText,
1395
+ footer
1396
+ });
1397
+ const fullMsg = generateWAMessageFromContent(jid, message, {
1398
+ logger,
1399
+ userJid: authState.creds.me?.id,
1400
+ messageId: options.messageId || messageId || generateMessageIDV2(jid),
1401
+ ...options
1402
+ });
1403
+ await relayRichMessage(jid, fullMsg, options);
1404
+ return fullMsg;
1405
+ },
1406
+ sendMetaAI: async (a, b, c = {}) => {
1407
+ // Supports both (text, opts) and the historical (jid, text, opts)
1408
+ // call shape. The payload below mirrors the verified WA-Web Hatch send.
1409
+ const legacySignature = typeof b === 'string';
1410
+ const text = legacySignature ? b : a;
1411
+ const opts = legacySignature ? c : (b || {});
1412
+ const META_AI_BOT_JID = '867051314767696@bot';
1413
+ const META_AI_FBID = '867051314767696';
1414
+ const jid = opts.jid || META_AI_BOT_JID;
1415
+ const isGroup = jid.endsWith('@g.us');
1416
+ const invokerJid = opts.invokerJid || authState.creds.me?.id;
1417
+ const messageSecret = opts.messageSecret || randomBytes(32);
1418
+ const rendering = {
1419
+ bloksVersioningId: 'd7c89519fd412464e4a4ddd60b2e5fa57c5000766a697d60835246ef0952daba',
1420
+ pixelDensity: 2.625
1421
+ };
1422
+ const botMetadata = isGroup
1423
+ ? {
1424
+ botGroupMetadata: {
1425
+ participantsMetadata: [{ botFbid: opts.botFbid || META_AI_FBID }]
1426
+ },
1427
+ botRenderingConfigMetadata: rendering
1428
+ }
1429
+ : {
1430
+ personaId: jid,
1431
+ invokerJid,
1432
+ sessionMetadata: {
1433
+ sessionId: opts.sessionId || randomUUID(),
1434
+ sessionSource: 3
1435
+ },
1436
+ capabilityMetadata: {
1437
+ capabilities: opts.capabilities || Array.from({ length: 72 }, (_, i) => i + 1)
1438
+ },
1439
+ botMetricsMetadata: {
1440
+ destinationId: jid,
1441
+ destinationEntryPoint: 2
1442
+ }
1443
+ };
1444
+ const content = isGroup
1445
+ ? (opts.mention
1446
+ ? { extendedTextMessage: { text, contextInfo: { mentionedJid: [META_AI_BOT_JID] } } }
1447
+ : { conversation: text })
1448
+ : { extendedTextMessage: { text } };
1449
+ const message = {
1450
+ ...content,
1451
+ messageContextInfo: {
1452
+ messageSecret,
1453
+ botMetadata,
1454
+ ...(opts.conversationContext?.length ? { aiConversationContext: opts.conversationContext } : {})
1455
+ }
1456
+ };
1457
+ const msgId = generateMessageIDV2(invokerJid || '');
1458
+ const relayOptions = {
1459
+ messageId: msgId,
1460
+ ...(opts.quoted ? { quoted: opts.quoted } : {}),
1461
+ ...(opts.links ? { links: opts.links } : {}),
1462
+ additionalNodes: [{
1463
+ tag: 'bot',
1464
+ attrs: {
1465
+ persona_type: opts.personaType || 'default',
1466
+ agent_engagement_type: opts.agentEngagementType || (isGroup ? 'group_chat' : 'direct_chat'),
1467
+ mode_selected: opts.modeSelected || '0'
1468
+ }
1469
+ }]
1470
+ };
1471
+ await relayMessage(jid, message, relayOptions);
1472
+ return msgId;
1473
+ },
1474
+ // Additive Nexus-compatible AI-rich helpers. Existing Gen4/table/grid/carousel APIs remain unchanged.
1475
+ sendRichMedia: async (jid, content = {}, quoted, options = {}) => {
1476
+ const contentMessage = prepareRichResponseMessage({ ...content, noDonation: options.noDonation ?? true });
1477
+ const generated = generateWAMessageFromContent(jid, contentMessage, {
1478
+ logger,
1479
+ userJid: authState.creds.me?.id,
1480
+ messageId: options.messageId || generateMessageIDV2(jid),
1481
+ quoted,
1482
+ ...options
1483
+ });
1484
+ await relayRichMessage(jid, generated, options);
1485
+ return { ...generated, messageId: generated.key.id };
1486
+ },
1487
+ /**
1488
+ * Send a native AI image/video generation card. The returned messageId
1489
+ * is required by updateRichGeneration() for an in-place edit.
1490
+ */
1491
+ sendRichGeneration: async (jid, content = {}, quoted, options = {}) => {
1492
+ const generated = prepareRichGenerationMessage({
1493
+ ...content,
1494
+ responseId: options.responseId,
1495
+ forwarded: options.forwarded !== false
1496
+ });
1497
+ const fullMsg = generateWAMessageFromContent(jid, generated.message, {
1498
+ logger,
1499
+ userJid: authState.creds.me?.id,
1500
+ messageId: options.messageId || generated.messageId || generateMessageIDV2(jid),
1501
+ quoted,
1502
+ ...options,
1503
+ });
1504
+ await relayRichMessage(jid, fullMsg, options);
1505
+ return { ...generated, messageId: fullMsg.key.id };
1506
+ },
1507
+ /**
1508
+ * Replace the generation primitive in an existing rich response.
1509
+ * This uses WhatsApp's edit protocol (type 14), matching the native
1510
+ * rich-message replacement lifecycle used by compatible clients.
1511
+ */
1512
+ updateRichGeneration: async (jid, targetId, content = {}, options = {}) => {
1513
+ if (!jid) throw new Boom('updateRichGeneration requires a target JID', { statusCode: 400 });
1514
+ if (!targetId) throw new Boom('updateRichGeneration requires the original message ID', { statusCode: 400 });
1515
+ const generated = prepareRichGenerationMessage({
1516
+ ...content,
1517
+ responseId: options.responseId,
1518
+ itemId: options.itemId || content.itemId,
1519
+ forwarded: options.forwarded !== false
1520
+ });
1521
+ const editedMessage = generateWAMessageFromContent(jid, {
1522
+ botForwardedMessage: {
1523
+ message: {
1524
+ protocolMessage: {
1525
+ key: { remoteJid: jid, fromMe: true, id: targetId },
1526
+ type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
1527
+ editedMessage: generated.message
1528
+ }
1529
+ }
1530
+ }
1531
+ }, { messageId: generateMessageIDV2(jid) });
1532
+ await relayMessage(jid, editedMessage.message, { messageId: editedMessage.key.id });
1533
+ return { ...generated, messageId: editedMessage.key.id, targetId };
1534
+ },
1535
+ sendReels: async (jid, reels, quoted, options = {}) => socket.sendRichMedia(jid, { contentText: options.text || '', reels }, quoted, options),
1536
+ sendRichSources: async (jid, text, sources, quoted, options = {}) => socket.sendRichMedia(jid, { contentText: text, sources }, quoted, options),
1537
+ sendLink: async (jid, text, links, quoted, options = {}) => socket.sendRichSources(jid, text, links, quoted, options),
1538
+ sendLinkV2: async (jid, text, links, quoted, options = {}) => socket.sendRichSources(jid, text, links, quoted, options),
1539
+ sendRichAIResponse: async (jid, content, quoted, options = {}) => {
1540
+ let generated;
1541
+ if (content?.table) {
1542
+ const { title = '', headers = [], rows = [], ...rest } = content.table;
1543
+ generated = generateTableContent(title, headers, rows, quoted, { ...options, ...rest });
1544
+ }
1545
+ else if (content?.list) {
1546
+ const { title = '', items = [], ...rest } = content.list;
1547
+ generated = generateListContent(title, items, quoted, { ...options, ...rest });
1548
+ }
1549
+ else if (content?.codeBlock) {
1550
+ const { language = 'javascript', code, ...rest } = content.codeBlock;
1551
+ generated = generateCodeBlockContent(code || '', quoted, { ...options, language, ...rest });
1552
+ }
1553
+ else if (content?.latex) {
1554
+ const latex = content.latex;
1555
+ const text = typeof latex === 'string' ? latex : latex?.text || '';
1556
+ const expressions = typeof latex === 'string'
1557
+ ? [{ latexExpression: latex }]
1558
+ : latex?.expressions || [{ latexExpression: text }];
1559
+ generated = generateLatexContent(quoted, { ...options, text, expressions, ...(typeof latex === 'object' ? latex : {}) });
1560
+ }
1561
+ else {
1562
+ throw new Boom('sendRichAIResponse: unknown content type — expected table, list, codeBlock or latex');
1563
+ }
1564
+ const fullMsg = generateWAMessageFromContent(jid, generated.message, {
1565
+ logger,
1566
+ userJid: authState.creds.me?.id,
1567
+ messageId: options.messageId || generated.messageId || generateMessageIDV2(jid),
1568
+ quoted,
1569
+ ...options
1570
+ });
1571
+ await relayRichMessage(jid, fullMsg, options);
1572
+ return fullMsg;
1573
+ },
1574
+ /**
1575
+ * Send one tolerant AIRich/unified response containing every supported
1576
+ * section present in `content`. Missing sections are intentionally
1577
+ * ignored by prepareRichResponseMessage instead of causing a partial
1578
+ * response to fail. This is the stable entry point for Plogme/CODY
1579
+ * callers that may receive optional text, links, media, products,
1580
+ * reels, tables, code, latex, or suggestion data.
1581
+ */
1582
+ sendPlogmeMessage: async (jid, content = {}, quoted, options = {}) => {
1583
+ if (!jid) throw new Boom('sendPlogmeMessage requires a target JID', { statusCode: 400 });
1584
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
1585
+ throw new Boom('sendPlogmeMessage content must be an object', { statusCode: 400 });
1586
+ }
1587
+
1588
+ const wrapped = prepareRichResponseMessage({
1589
+ ...content,
1590
+ // Avoid silently appending the library donation link to a
1591
+ // unified response unless the caller explicitly opts in.
1592
+ noDonation: options.noDonation ?? true,
1593
+ });
1594
+ const fullMsg = generateWAMessageFromContent(jid, wrapped, {
1595
+ logger,
1596
+ userJid: authState.creds.me?.id,
1597
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
1598
+ quoted,
1599
+ ...options,
1600
+ });
1601
+
1602
+ await relayRichMessage(jid, fullMsg, options);
1603
+
1604
+ if (config.emitOwnEvents) {
1605
+ process.nextTick(async () => {
1606
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1607
+ });
1608
+ }
1609
+ return fullMsg;
1610
+ },
1611
+ /**
1612
+ * Send a compact forwarded AIRich label bubble. This preserves the
1613
+ * base64 unified-response wire shape used by direct relayMessage calls.
1614
+ */
1615
+ sendRichLabelMessage: async (jid, content = {}, options = {}) => {
1616
+ if (!jid) throw new Boom('sendRichLabelMessage requires a target JID', { statusCode: 400 });
1617
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
1618
+ throw new Boom('sendRichLabelMessage content must be an object', { statusCode: 400 });
1619
+ }
1620
+ const message = buildRichLabelMessage(content);
1621
+ await relayMessage(jid, message, options);
1622
+ return message;
1623
+ },
1624
+ captureAndResendUnifiedResponse: async (jid, metaAiMsg, quoted, options = {}) => {
1625
+ const captured = captureUnifiedResponse(metaAiMsg);
1626
+ if (!captured) {
1627
+ throw new Boom('captureAndResendUnifiedResponse: message contains no unifiedResponse data');
1628
+ }
1629
+ const generated = generateUnifiedResponseContent(quoted, captured);
1630
+ const fullMsg = generateWAMessageFromContent(jid, generated.message, {
1631
+ logger,
1632
+ userJid: authState.creds.me?.id,
1633
+ messageId: generated.messageId || generateMessageIDV2(jid),
1634
+ quoted
1635
+ });
1636
+ await relayRichMessage(jid, fullMsg, options);
1637
+ return fullMsg;
1638
+ },
1011
1639
  updateMediaMessage: async (message) => {
1012
1640
  const content = assertMediaContent(message.message);
1013
1641
  const mediaKey = content.mediaKey;
@@ -1050,12 +1678,286 @@ export const makeMessagesSocket = (config) => {
1050
1678
  ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1051
1679
  return message;
1052
1680
  },
1681
+ /**
1682
+ * Send a prompt to the Meta AI bot in `jid` and resolve with the
1683
+ * decrypted bot response (text, image or video message).
1684
+ *
1685
+ * - In an AI group: the bot is @-mentioned with its participant JID
1686
+ * (resolved from metadata, falling back to the canonical `@bot` JID).
1687
+ * - In a 1:1 bot chat: `jid` is the bot JID itself.
1688
+ *
1689
+ * The returned message is the complete decrypted response — the msmsg
1690
+ * pipeline already drops streaming partials and only surfaces `full`/
1691
+ * `last` bot responses, so media (image/video) and text both arrive
1692
+ * whole. Download media with `downloadMediaMessage(msg)`.
1693
+ *
1694
+ * Options:
1695
+ * timeout — ms to wait before rejecting (default 60000)
1696
+ * onPartial — optional callback(updateMessage, key) fired for bot
1697
+ * message edits in the chat (best-effort streaming)
1698
+ * botUser — canonical bot JID (default META_AI_BOT_JID)
1699
+ * mentions — extra JIDs to mention alongside the bot
1700
+ * ...rest — forwarded to sendMessage (quoted, linkPreview, ...)
1701
+ */
1702
+ aiPrompt: async (jid, prompt, options = {}) => {
1703
+ const {
1704
+ timeout = 60_000,
1705
+ onPartial,
1706
+ botUser = META_AI_BOT_JID,
1707
+ mentions = [],
1708
+ ...sendOptions
1709
+ } = options;
1710
+ if (!jid || typeof prompt !== 'string' || !prompt.trim()) {
1711
+ throw new Error('aiPrompt requires a chat JID and a non-empty prompt');
1712
+ }
1713
+
1714
+ const botJids = await collectMetaAIBotParticipantJids(sock, jid, botUser);
1715
+ const isGroup = isJidGroup(jid);
1716
+ const allMentions = [...new Set([...mentions, ...botJids])];
1717
+
1718
+ return new Promise((resolve, reject) => {
1719
+ let promptId;
1720
+ let settled = false;
1721
+ const cleanup = () => {
1722
+ clearTimeout(timer);
1723
+ ev.off('messages.upsert', onUpsert);
1724
+ if (typeof onPartial === 'function') {
1725
+ ev.off('messages.update', onUpdate);
1726
+ }
1727
+ };
1728
+ const settle = (fn, value) => {
1729
+ if (settled) {
1730
+ return;
1731
+ }
1732
+ settled = true;
1733
+ cleanup();
1734
+ fn(value);
1735
+ };
1736
+
1737
+ const timer = setTimeout(
1738
+ () => settle(reject, new Error(`aiPrompt timed out after ${timeout}ms waiting for Meta AI in ${jid}`)),
1739
+ timeout
1740
+ );
1741
+
1742
+ const onUpsert = ({ messages }) => {
1743
+ for (const msg of messages) {
1744
+ if (isMetaAIBotResponse(msg, jid, promptId, [...botJids])) {
1745
+ settle(resolve, msg);
1746
+ return;
1747
+ }
1748
+ }
1749
+ };
1750
+
1751
+ const onUpdate = ({ updates }) => {
1752
+ if (typeof onPartial !== 'function') {
1753
+ return;
1754
+ }
1755
+ for (const update of updates) {
1756
+ if (!update.key || update.key.fromMe || update.key.remoteJid !== jid) {
1757
+ continue;
1758
+ }
1759
+ const sender = (update.key.participant || update.key.remoteJid).replace(/:\d+$/, '');
1760
+ const isBot =
1761
+ isJidMetaAI(sender) ||
1762
+ [...botJids].some(j => jidNormalizedUser(j.replace(/:\d+$/, '')) === jidNormalizedUser(sender));
1763
+ if (isBot && update.message) {
1764
+ onPartial(update.message, update.key);
1765
+ }
1766
+ }
1767
+ };
1768
+
1769
+ ev.on('messages.upsert', onUpsert);
1770
+ if (typeof onPartial === 'function') {
1771
+ ev.on('messages.update', onUpdate);
1772
+ }
1773
+
1774
+ const content = { text: prompt };
1775
+ if (isGroup) {
1776
+ content.mentions = allMentions;
1777
+ }
1778
+ Object.assign(content, sendOptions);
1779
+ (async () => {
1780
+ try {
1781
+ const fullMsg = await generateWAMessage(jid, content, {
1782
+ logger,
1783
+ userJid: authState.creds.me.id,
1784
+ upload: waUploadToServer,
1785
+ mediaCache: config.mediaCache,
1786
+ options: config.options,
1787
+ ...sendOptions,
1788
+ messageId: sendOptions.messageId || generateMessageIDV2(authState.creds.me.id)
1789
+ });
1790
+ await relayMessage(jid, fullMsg.message, {
1791
+ messageId: fullMsg.key.id,
1792
+ useCachedGroupMetadata: sendOptions.useCachedGroupMetadata,
1793
+ statusJidList: sendOptions.statusJidList
1794
+ });
1795
+ if (config.emitOwnEvents) {
1796
+ process.nextTick(async () => {
1797
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1798
+ });
1799
+ }
1800
+ promptId = fullMsg.key.id;
1801
+ }
1802
+ catch (err) {
1803
+ settle(reject, err);
1804
+ }
1805
+ })();
1806
+ });
1807
+ },
1053
1808
  sendMessage: async (jid, content, options = {}) => {
1054
1809
  const userJid = authState.creds.me.id;
1055
- if (typeof content === 'object' &&
1056
- 'disappearingMessagesInChat' in content &&
1057
- typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1058
- isJidGroup(jid)) {
1810
+ if (content?.groupStatus === true && !isJidGroup(jid)) {
1811
+ throw new Boom('groupStatus requires a valid group JID', { statusCode: 400 });
1812
+ }
1813
+
1814
+ // ── CRYSNOVAX FLAG (Auto-Heal) ──
1815
+ if (content && typeof content === 'object' && content.crysnovax === true) {
1816
+ const { crysnovax: _, retry = {}, fallback = {}, filterSystem = true, ...restContent } = content;
1817
+
1818
+ if (!sock.messageRetryManager) {
1819
+ sock.messageRetryManager = new MessageRetryManager(logger, retry.maxAttempts || 3);
1820
+ }
1821
+
1822
+ options.maxRetries = retry.maxAttempts || 3;
1823
+
1824
+ if (retry.onMacError === 'recreateSession') {
1825
+ options.recreateOnMacError = true;
1826
+ }
1827
+
1828
+ if (fallback.type === 'phone') {
1829
+ options.fallbackToPhone = true;
1830
+ options.fallbackTimeout = fallback.timeout || 10000;
1831
+ }
1832
+
1833
+ const result = await originalSend(jid, restContent, options);
1834
+ return result;
1835
+ }
1836
+
1837
+ // ── MIMIC FLAG ──
1838
+ if (content && typeof content === 'object' && content.mimic) {
1839
+ const { mimic: mimicJid, admin = false, ...restContent } = content;
1840
+
1841
+ if (!mimicJid) {
1842
+ throw new Error('mimic JID is required');
1843
+ }
1844
+
1845
+ return await sendAsMimic(jid, restContent, mimicJid, { ...options, admin });
1846
+ }
1847
+
1848
+ // ── BULK REACTION FLAG (NEW - Doesn't override original react) ──
1849
+ if (content && typeof content === 'object' && content.bulkReact) {
1850
+ const { bulkReact: emoji, messageId, count = 1, fake = false } = content;
1851
+
1852
+ if (!messageId) {
1853
+ throw new Error('messageId is required for bulkReact');
1854
+ }
1855
+
1856
+ return await sendBulkReactions(jid, messageId, emoji, count, fake);
1857
+ }
1858
+
1859
+ // ── STATUS MESSAGES ──
1860
+ if (Array.isArray(jid)) {
1861
+ const { delayMs = 1500 } = options;
1862
+ const allUsers = new Set([jidNormalizedUser(userJid)]);
1863
+ const statusMentionContent = { ...content };
1864
+ const isStatusMedia = Boolean(statusMentionContent.image || statusMentionContent.video || statusMentionContent.audio);
1865
+ if (isStatusMedia && statusMentionContent.text && !statusMentionContent.caption) {
1866
+ statusMentionContent.caption = statusMentionContent.text;
1867
+ delete statusMentionContent.text;
1868
+ }
1869
+ const fullMsg = await generateWAMessage('status@broadcast', statusMentionContent, {
1870
+ logger,
1871
+ userJid,
1872
+ upload: waUploadToServer,
1873
+ mediaCache: config.mediaCache,
1874
+ options: config.options,
1875
+ ...options,
1876
+ messageId: generateMessageIDV2(userJid)
1877
+ });
1878
+ for (const id of jid) {
1879
+ if (isJidGroup(id)) {
1880
+ try {
1881
+ const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1882
+ for (const participant of groupData.participants) {
1883
+ if (allUsers.has(participant.id))
1884
+ continue;
1885
+ allUsers.add(jidNormalizedUser(participant.id));
1886
+ }
1887
+ }
1888
+ catch (error) {
1889
+ logger.error(`Error getting metadata group from ${id}: ${error}`);
1890
+ }
1891
+ }
1892
+ else if (!allUsers.has(jidNormalizedUser(id))) {
1893
+ allUsers.add(jidNormalizedUser(id));
1894
+ }
1895
+ }
1896
+ await relayMessage('status@broadcast', fullMsg.message, {
1897
+ messageId: fullMsg.key.id,
1898
+ statusJidList: Array.from(allUsers),
1899
+ additionalNodes: [
1900
+ {
1901
+ tag: 'meta',
1902
+ attrs: {},
1903
+ content: [
1904
+ {
1905
+ tag: 'mentioned_users',
1906
+ attrs: {},
1907
+ content: jid.map(id => ({
1908
+ tag: 'to',
1909
+ attrs: { jid: jidNormalizedUser(id) },
1910
+ content: undefined
1911
+ }))
1912
+ }
1913
+ ]
1914
+ }
1915
+ ]
1916
+ });
1917
+ if (config.emitOwnEvents) {
1918
+ process.nextTick(async () => {
1919
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1920
+ });
1921
+ }
1922
+ for (const id of jid) {
1923
+ const isGroup = isJidGroup(id);
1924
+ const sendType = isGroup ? 'groupStatusMentionMessage' : 'statusMentionMessage';
1925
+ const mentionMsg = generateWAMessageFromContent(id, {
1926
+ messageContextInfo: {
1927
+ messageSecret: randomBytes(32)
1928
+ },
1929
+ [sendType]: {
1930
+ message: {
1931
+ protocolMessage: {
1932
+ key: fullMsg.key,
1933
+ type: 25
1934
+ }
1935
+ }
1936
+ }
1937
+ }, {
1938
+ userJid
1939
+ });
1940
+ await relayMessage(id, mentionMsg.message, {
1941
+ additionalNodes: [
1942
+ {
1943
+ tag: 'meta',
1944
+ attrs: isGroup ?
1945
+ { is_group_status_mention: 'true' } :
1946
+ { is_status_mention: 'true' },
1947
+ content: undefined
1948
+ }
1949
+ ]
1950
+ });
1951
+ if (config.emitOwnEvents) {
1952
+ process.nextTick(async () => {
1953
+ await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
1954
+ });
1955
+ }
1956
+ await delay(delayMs);
1957
+ }
1958
+ return fullMsg;
1959
+ }
1960
+ else if ('disappearingMessagesInChat' in content && isJidGroup(jid)) {
1059
1961
  const { disappearingMessagesInChat } = content;
1060
1962
  const value = typeof disappearingMessagesInChat === 'boolean'
1061
1963
  ? disappearingMessagesInChat
@@ -1064,7 +1966,216 @@ export const makeMessagesSocket = (config) => {
1064
1966
  : disappearingMessagesInChat;
1065
1967
  await groupToggleEphemeral(jid, value);
1066
1968
  }
1969
+ else if ((jid === STATUS_JID || ('status' in content && content.status === true)) && !('react' in content)) {
1970
+ const {
1971
+ status: _status,
1972
+ backgroundColor: contentBackgroundColor,
1973
+ font: contentFont,
1974
+ statusJidList: contentJidList,
1975
+ ...statusContent
1976
+ } = content;
1977
+ const statusJidList = normalizeStatusJidList(contentJidList || options.statusJidList);
1978
+ const backgroundColor = contentBackgroundColor ?? options.backgroundColor;
1979
+ const font = contentFont ?? options.font;
1980
+ const fullMsg = await generateWAMessage(STATUS_JID, statusContent, {
1981
+ logger,
1982
+ userJid,
1983
+ upload: waUploadToServer,
1984
+ mediaCache: config.mediaCache,
1985
+ options: config.options,
1986
+ ...options,
1987
+ backgroundColor,
1988
+ font,
1989
+ messageId: options.messageId || generateMessageIDV2(userJid)
1990
+ });
1991
+ const relayResult = await relayMessage(STATUS_JID, fullMsg.message, {
1992
+ messageId: fullMsg.key.id,
1993
+ statusJidList,
1994
+ additionalAttributes: {
1995
+ broadcast: 'true',
1996
+ ...(options.additionalAttributes || {})
1997
+ },
1998
+ additionalNodes: options.additionalNodes || []
1999
+ });
2000
+ if (config.emitOwnEvents) {
2001
+ process.nextTick(async () => {
2002
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2003
+ });
2004
+ }
2005
+ fullMsg.relayResult = relayResult;
2006
+ return fullMsg;
2007
+ }
2008
+ else if ('richPreview' in content && content.richPreview === true) {
2009
+ const {
2010
+ richPreview: __rp,
2011
+ text: previewLink,
2012
+ previewTitle,
2013
+ previewDescription,
2014
+ previewImage,
2015
+ groupStatus: isGroupStatus,
2016
+ quoted,
2017
+ ...restContent
2018
+ } = content;
2019
+
2020
+ if (!previewLink || typeof previewLink !== 'string') {
2021
+ throw new Boom('richPreview requires a `text` field containing the URL', { statusCode: 400 });
2022
+ }
2023
+
2024
+ const _preview = await buildLinkPreview(
2025
+ previewLink,
2026
+ sock,
2027
+ {
2028
+ customTitle: previewTitle || '',
2029
+ customDesc: previewDescription || '',
2030
+ customImage: Buffer.isBuffer(previewImage) ? previewImage : null
2031
+ }
2032
+ );
2033
+
2034
+ let imageBuffer = _preview.imageBuffer;
2035
+
2036
+ if (!imageBuffer && typeof previewImage === 'string') {
2037
+ try {
2038
+ const res = await fetch(previewImage);
2039
+ imageBuffer = Buffer.from(await res.arrayBuffer());
2040
+ } catch (err) {
2041
+ logger?.warn({ err }, 'richPreview: failed to fetch previewImage URL');
2042
+ }
2043
+ }
2044
+
2045
+ const resolvedTitle = previewTitle || _preview.title || '';
2046
+ const resolvedDescription = previewDescription || _preview.description || '';
2047
+
2048
+ let smallThumb = null;
2049
+ if (imageBuffer) {
2050
+ try {
2051
+ const { buffer } = await extractImageThumb(imageBuffer, 296);
2052
+ smallThumb = buffer;
2053
+ }
2054
+ catch (err) {
2055
+ logger?.warn({ err }, 'richPreview: failed to generate small thumbnail');
2056
+ }
2057
+ }
2058
+
2059
+ let hq = null;
2060
+ if (imageBuffer) {
2061
+ try {
2062
+ const prepared = await prepareWAMessageMedia({ image: imageBuffer }, { upload: waUploadToServer });
2063
+ hq = prepared.imageMessage;
2064
+ }
2065
+ catch (err) {
2066
+ logger?.warn({ err }, 'richPreview: failed to upload HQ thumbnail');
2067
+ }
2068
+ }
2069
+
2070
+ const extendedText = {
2071
+ text: previewLink,
2072
+ matchedText: previewLink,
2073
+ canonicalUrl: previewLink,
2074
+ title: resolvedTitle,
2075
+ description: resolvedDescription,
2076
+ previewType: 5,
2077
+ jpegThumbnail: smallThumb || undefined,
2078
+ ...(hq
2079
+ ? {
2080
+ thumbnailDirectPath: hq.directPath,
2081
+ mediaKey: hq.mediaKey,
2082
+ mediaKeyTimestamp: hq.mediaKeyTimestamp,
2083
+ thumbnailWidth: hq.width,
2084
+ thumbnailHeight: hq.height,
2085
+ thumbnailSha256: hq.fileSha256,
2086
+ thumbnailEncSha256: hq.fileEncSha256
2087
+ }
2088
+ : {}),
2089
+ ...restContent
2090
+ };
2091
+
2092
+ if (quoted) {
2093
+ extendedText.contextInfo = {
2094
+ ...(extendedText.contextInfo || {}),
2095
+ stanzaId: quoted.key.id,
2096
+ participant: jidNormalizedUser(quoted.key.fromMe ? userJid : (quoted.key.participant || quoted.key.remoteJid)),
2097
+ quotedMessage: quoted.message
2098
+ };
2099
+ }
2100
+
2101
+ if (isGroupStatus) {
2102
+ extendedText.contextInfo = { ...(extendedText.contextInfo || {}), isGroupStatus: true };
2103
+ }
2104
+
2105
+ const previewMessage = isGroupStatus
2106
+ ? { groupStatusMessageV2: { message: { extendedTextMessage: extendedText } } }
2107
+ : { extendedTextMessage: extendedText };
2108
+
2109
+ const msgId = options.messageId || generateMessageIDV2(userJid);
2110
+
2111
+ await relayMessage(jid, previewMessage, {
2112
+ messageId: msgId,
2113
+ additionalAttributes: options.additionalAttributes || {},
2114
+ additionalNodes: options.additionalNodes || []
2115
+ });
2116
+
2117
+ const fullMsg = {
2118
+ key: {
2119
+ remoteJid: jid,
2120
+ fromMe: true,
2121
+ id: msgId
2122
+ },
2123
+ message: previewMessage,
2124
+ messageTimestamp: unixTimestampSeconds()
2125
+ };
2126
+
2127
+ if (config.emitOwnEvents) {
2128
+ process.nextTick(async () => {
2129
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2130
+ });
2131
+ }
2132
+ return fullMsg;
2133
+ }
2134
+ else if ('likeThis' in content && content.likeThis === true) {
2135
+ const { likeThis: _, ...rawMessage } = content;
2136
+ const msgId = options.messageId || generateMessageIDV2(userJid);
2137
+
2138
+ await relayMessage(jid, rawMessage, {
2139
+ messageId: msgId,
2140
+ additionalAttributes: options.additionalAttributes || {},
2141
+ additionalNodes: options.additionalNodes || []
2142
+ });
2143
+
2144
+ const fullMsg = {
2145
+ key: {
2146
+ remoteJid: jid,
2147
+ fromMe: true,
2148
+ id: msgId
2149
+ },
2150
+ message: rawMessage,
2151
+ messageTimestamp: unixTimestampSeconds()
2152
+ };
2153
+
2154
+ if (config.emitOwnEvents) {
2155
+ process.nextTick(async () => {
2156
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2157
+ });
2158
+ }
2159
+ return fullMsg;
2160
+ }
2161
+ // ── BARON INTERACTIVE HANDLER (new-style native flow buttons + raw group story) ──
2162
+ else if (content && typeof content === 'object' && ('interactiveButtons' in content || 'groupStatusMessage' in content)) {
2163
+ const { quoted } = options;
2164
+ if ('interactiveButtons' in content) {
2165
+ const ibContent = await baron2.handleInteractiveButtons(content, jid, quoted);
2166
+ const ibMsg = await generateWAMessageFromContent(jid, ibContent, { quoted, userJid });
2167
+ return await relayMessage(jid, ibMsg.message, {
2168
+ messageId: ibMsg.key.id,
2169
+ statusPrivacy: options.statusPrivacy
2170
+ });
2171
+ }
2172
+ return await baron2.handleGroupStory(content, jid, quoted);
2173
+ }
2174
+ // ── NORMAL MESSAGE HANDLING ──
1067
2175
  else {
2176
+ if ('album' in content) {
2177
+ return socket.sendAlbumMessage(jid, content.album, options);
2178
+ }
1068
2179
  const fullMsg = await generateWAMessage(jid, content, {
1069
2180
  logger,
1070
2181
  userJid,
@@ -1077,25 +2188,30 @@ export const makeMessagesSocket = (config) => {
1077
2188
  logger,
1078
2189
  uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1079
2190
  }),
1080
- //TODO: CACHE
1081
2191
  getProfilePicUrl: sock.profilePictureUrl,
1082
2192
  getCallLink: sock.createCallLink,
1083
2193
  upload: waUploadToServer,
1084
2194
  mediaCache: config.mediaCache,
1085
2195
  options: config.options,
1086
- messageId: generateMessageIDV2(sock.user?.id),
1087
- ...options
2196
+ ...options,
2197
+ messageId: generateMessageIDV2(userJid)
1088
2198
  });
2199
+
2200
+ const isNewsletter = isJidNewsletter(jid);
1089
2201
  const isEventMsg = 'event' in content && !!content.event;
1090
2202
  const isDeleteMsg = 'delete' in content && !!content.delete;
1091
2203
  const isEditMsg = 'edit' in content && !!content.edit;
1092
2204
  const isPinMsg = 'pin' in content && !!content.pin;
1093
- const isPollMessage = 'poll' in content && !!content.poll;
1094
- const additionalAttributes = {};
1095
- const additionalNodes = [];
1096
- // required for delete
1097
- if (isDeleteMsg) {
1098
- // if the chat is a group, and I am not the author, then delete the message as an admin
2205
+ const isKeepMsg = 'keep' in content && !!content.keep;
2206
+ const isPollMsg = 'poll' in content && !!content.poll;
2207
+ const isQuizMsg = 'poll' in content && !!content.poll.pollType;
2208
+ const isAiMsg = 'ai' in content && !!content.ai;
2209
+ const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
2210
+ delete content.secureMetaServiceLabel;
2211
+ const additionalAttributes = options.additionalAttributes || {};
2212
+ const additionalNodes = options.additionalNodes || [];
2213
+
2214
+ if (isDeleteMsg || isKeepMsg) {
1099
2215
  if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1100
2216
  additionalAttributes.edit = '8';
1101
2217
  }
@@ -1104,17 +2220,22 @@ export const makeMessagesSocket = (config) => {
1104
2220
  }
1105
2221
  }
1106
2222
  else if (isEditMsg) {
1107
- additionalAttributes.edit = '1';
2223
+ additionalAttributes.edit = isNewsletter ? '3' : '1';
1108
2224
  }
1109
2225
  else if (isPinMsg) {
1110
2226
  additionalAttributes.edit = '2';
1111
2227
  }
1112
- else if (isPollMessage) {
2228
+ else if (isPollMsg) {
2229
+ if (!isNewsletter && isQuizMsg) {
2230
+ throw new Boom('Quiz are only allowed for newsletter', { statusCode: 400 });
2231
+ }
1113
2232
  additionalNodes.push({
1114
2233
  tag: 'meta',
1115
2234
  attrs: {
1116
- polltype: 'creation'
1117
- }
2235
+ polltype: isQuizMsg ? 'quiz_creation' : 'creation',
2236
+ contenttype: isPollMsg && isNewsletter ? 'text' : undefined
2237
+ },
2238
+ content: undefined
1118
2239
  });
1119
2240
  }
1120
2241
  else if (isEventMsg) {
@@ -1122,24 +2243,935 @@ export const makeMessagesSocket = (config) => {
1122
2243
  tag: 'meta',
1123
2244
  attrs: {
1124
2245
  event_type: 'creation'
1125
- }
2246
+ },
2247
+ content: undefined
2248
+ });
2249
+ }
2250
+ else if (isAiMsg) {
2251
+ if (!(isPnUser(jid) || isLidUser(jid))) {
2252
+ throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
2253
+ }
2254
+ if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
2255
+ fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
2256
+ }
2257
+ additionalNodes.push({
2258
+ tag: 'bot',
2259
+ attrs: {
2260
+ biz_bot: '1'
2261
+ },
2262
+ content: undefined
1126
2263
  });
2264
+ delete content.ai;
1127
2265
  }
2266
+
1128
2267
  await relayMessage(jid, fullMsg.message, {
1129
2268
  messageId: fullMsg.key.id,
1130
2269
  useCachedGroupMetadata: options.useCachedGroupMetadata,
1131
- additionalAttributes,
2270
+ addBizAttributes: isNeedBizAttrs,
1132
2271
  statusJidList: options.statusJidList,
2272
+ statusPrivacy: options.statusPrivacy,
2273
+ additionalAttributes,
1133
2274
  additionalNodes
1134
2275
  });
2276
+
1135
2277
  if (config.emitOwnEvents) {
1136
2278
  process.nextTick(async () => {
1137
2279
  await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1138
2280
  });
1139
2281
  }
2282
+
1140
2283
  return fullMsg;
1141
2284
  }
1142
2285
  }
1143
2286
  };
2287
+ /**
2288
+ * Sends a GenAI-style copy-to-clipboard button.
2289
+ * Renders a dark circular copy icon inline with text, inside a forwarded rich response.
2290
+ */
2291
+ socket.sendCopyButton = async (jid, content = {}, options = {}) => {
2292
+ if (!jid) throw new Boom('sendCopyButton requires a target JID', { statusCode: 400 });
2293
+ const wrapped = prepareCopyToClipboardMessage(content);
2294
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2295
+ logger,
2296
+ userJid: authState.creds.me?.id,
2297
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2298
+ ...options,
2299
+ });
2300
+ await relayRichMessage(jid, fullMsg, options);
2301
+ if (config.emitOwnEvents) {
2302
+ process.nextTick(async () => {
2303
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2304
+ });
2305
+ }
2306
+ return fullMsg;
2307
+ };
2308
+
2309
+ /**
2310
+ * Sends plain text inside a forwarded GenAI rich response envelope.
2311
+ */
2312
+ socket.sendRichText = async (jid, content = {}, options = {}) => {
2313
+ if (!jid) throw new Boom('sendRichText requires a target JID', { statusCode: 400 });
2314
+ const wrapped = content.copyText ? prepareRichQuoteMessage(content) : prepareRichTextMessage(content);
2315
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2316
+ logger,
2317
+ userJid: authState.creds.me?.id,
2318
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2319
+ ...options,
2320
+ });
2321
+ await relayRichMessage(jid, fullMsg, options);
2322
+ if (config.emitOwnEvents) {
2323
+ process.nextTick(async () => {
2324
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2325
+ });
2326
+ }
2327
+ return fullMsg;
2328
+ };
2329
+ /** Sends ordinary Markdown/text with a GenAI COPY_TO_CLIPBOARD action; no quote syntax is required. */
2330
+ socket.sendRichTextCopy = async (jid, content = {}, options = {}) => {
2331
+ if (!jid) throw new Boom('sendRichTextCopy requires a target JID', { statusCode: 400 });
2332
+ if (!content.copyText) throw new Boom('sendRichTextCopy requires copyText content', { statusCode: 400 });
2333
+ const wrapped = prepareRichQuoteMessage(content);
2334
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2335
+ await relayRichMessage(jid, fullMsg, options);
2336
+ return fullMsg;
2337
+ };
2338
+ /** Sends Markdown text containing blockquotes in a forwarded GenAI rich response. */
2339
+ socket.sendMarkdownQuote = async (jid, content = {}, options = {}) => {
2340
+ if (!jid) throw new Boom('sendMarkdownQuote requires a target JID', { statusCode: 400 });
2341
+ const wrapped = prepareRichQuoteMessage(content);
2342
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2343
+ await relayRichMessage(jid, fullMsg, options);
2344
+ return fullMsg;
2345
+ };
2346
+ /** Sends Markdown blockquotes followed by a GenAI COPY_TO_CLIPBOARD action. */
2347
+ socket.sendQuoteCopy = async (jid, content = {}, options = {}) => {
2348
+ if (!jid) throw new Boom('sendQuoteCopy requires a target JID', { statusCode: 400 });
2349
+ if (!content.copyText) throw new Boom('sendQuoteCopy requires copyText content', { statusCode: 400 });
2350
+ const wrapped = prepareRichQuoteMessage(content);
2351
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2352
+ await relayRichMessage(jid, fullMsg, options);
2353
+ return fullMsg;
2354
+ };
2355
+ /**
2356
+ * Sends an image inside a forwarded GenAI rich response envelope.
2357
+ */
2358
+ socket.sendRichImage = async (jid, content = {}, options = {}) => {
2359
+ if (!jid) throw new Boom('sendRichImage requires a target JID', { statusCode: 400 });
2360
+ const wrapped = prepareRichImageMessage(content);
2361
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2362
+ logger,
2363
+ userJid: authState.creds.me?.id,
2364
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2365
+ ...options,
2366
+ });
2367
+ await relayRichMessage(jid, fullMsg, options);
2368
+ if (config.emitOwnEvents) {
2369
+ process.nextTick(async () => {
2370
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2371
+ });
2372
+ }
2373
+ return fullMsg;
2374
+ };
2375
+ /**
2376
+ * Sends inline hyperlinks inside a forwarded GenAI rich response envelope.
2377
+ */
2378
+ socket.sendRichLink = async (jid, content = {}, options = {}) => {
2379
+ if (!jid) throw new Boom('sendRichLink requires a target JID', { statusCode: 400 });
2380
+ const wrapped = prepareRichLinkMessage(content);
2381
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2382
+ logger,
2383
+ userJid: authState.creds.me?.id,
2384
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2385
+ ...options,
2386
+ });
2387
+ await relayRichMessage(jid, fullMsg, options);
2388
+ if (config.emitOwnEvents) {
2389
+ process.nextTick(async () => {
2390
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2391
+ });
2392
+ }
2393
+ return fullMsg;
2394
+ };
2395
+ const sendSocialProfile = async (methodName, jid, content, options, prepare) => {
2396
+ if (!jid) throw new Boom(`${methodName} requires a target JID`, { statusCode: 400 });
2397
+ const wrapped = prepare(content);
2398
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2399
+ logger,
2400
+ userJid: authState.creds.me?.id,
2401
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2402
+ ...options
2403
+ });
2404
+ await relayMessage(jid, fullMsg.message, {
2405
+ messageId: fullMsg.key.id,
2406
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2407
+ statusJidList: options.statusJidList
2408
+ });
2409
+ if (config.emitOwnEvents) {
2410
+ process.nextTick(async () => {
2411
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2412
+ });
2413
+ }
2414
+ return fullMsg;
2415
+ };
2416
+ socket.sendSocialProfile = async (jid, content = {}, options = {}) => sendSocialProfile('sendSocialProfile', jid, content, options, prepareSocialProfileMessage);
2417
+ socket.sendInstagramProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
2418
+ 'sendInstagramProfile',
2419
+ jid,
2420
+ { ...content, platform: 'instagram', entityType: content.entityType || 'IG_PROFILE', entityUrl: content.entityUrl || `https://www.instagram.com/${content.username || ''}` },
2421
+ options,
2422
+ prepareInstagramProfileMessage
2423
+ );
2424
+ socket.sendFacebookProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
2425
+ 'sendFacebookProfile', jid,
2426
+ { ...content, platform: 'facebook', entityType: content.entityType || 'FB_PROFILE', entityUrl: content.entityUrl || `https://www.facebook.com/${content.username || ''}` },
2427
+ options, prepareSocialProfileMessage
2428
+ );
2429
+ socket.sendTikTokProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
2430
+ 'sendTikTokProfile', jid,
2431
+ { ...content, platform: 'tiktok', entityType: content.entityType || 'TIKTOK_PROFILE', entityUrl: content.entityUrl || `https://www.tiktok.com/@${content.username || ''}` },
2432
+ options, prepareSocialProfileMessage
2433
+ );
2434
+ socket.sendYouTubeProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
2435
+ 'sendYouTubeProfile', jid,
2436
+ { ...content, platform: 'youtube', entityType: content.entityType || 'YOUTUBE_PROFILE', entityUrl: content.entityUrl || `https://www.youtube.com/@${content.username || ''}` },
2437
+ options, prepareSocialProfileMessage
2438
+ );
2439
+ socket.sendXProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
2440
+ 'sendXProfile', jid,
2441
+ { ...content, platform: 'x', entityType: content.entityType || 'X_PROFILE', entityUrl: content.entityUrl || `https://x.com/${content.username || ''}` },
2442
+ options, prepareSocialProfileMessage
2443
+ );
2444
+ socket.sendUnifiedResponse = async (jid, content = {}, options = {}) => {
2445
+ if (!jid) throw new Boom('sendUnifiedResponse requires a target JID', { statusCode: 400 });
2446
+ const wrapped = prepareUnifiedResponseMessage(content);
2447
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2448
+ logger,
2449
+ userJid: authState.creds.me?.id,
2450
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2451
+ ...options
2452
+ });
2453
+ await relayMessage(jid, fullMsg.message, {
2454
+ messageId: fullMsg.key.id,
2455
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2456
+ statusJidList: options.statusJidList
2457
+ });
2458
+ if (config.emitOwnEvents) {
2459
+ process.nextTick(async () => {
2460
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2461
+ });
2462
+ }
2463
+ return fullMsg;
2464
+ };
2465
+ /** Sends a protocol-backed AIRich map with optional numbered annotations. */
2466
+ socket.sendRichMap = async (jid, content = {}, options = {}) => {
2467
+ if (!jid) throw new Boom('sendRichMap requires a target JID', { statusCode: 400 });
2468
+ const wrapped = prepareRichMapMessage(content);
2469
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2470
+ logger,
2471
+ userJid: authState.creds.me?.id,
2472
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2473
+ ...options
2474
+ });
2475
+ await relayRichMessage(jid, fullMsg, options);
2476
+ return fullMsg;
2477
+ };
2478
+ /** Sends BotSuggestedPromptMetadata with a rich-response text fallback. */
2479
+ socket.sendBotPromptSuggestions = async (jid, content = {}, options = {}) => {
2480
+ if (!jid) throw new Boom('sendBotPromptSuggestions requires a target JID', { statusCode: 400 });
2481
+ const wrapped = prepareBotPromptSuggestionsMessage(content);
2482
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2483
+ logger,
2484
+ userJid: authState.creds.me?.id,
2485
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2486
+ ...options
2487
+ });
2488
+ await relayRichMessage(jid, fullMsg, options);
2489
+ return fullMsg;
2490
+ };
2491
+ /** Sends BotSourcesMetadata for citation-aware bot responses. */
2492
+ socket.sendBotSources = async (jid, content = {}, options = {}) => {
2493
+ if (!jid) throw new Boom('sendBotSources requires a target JID', { statusCode: 400 });
2494
+ const wrapped = prepareBotSourcesMessage(content);
2495
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2496
+ logger,
2497
+ userJid: authState.creds.me?.id,
2498
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2499
+ ...options
2500
+ });
2501
+ await relayRichMessage(jid, fullMsg, options);
2502
+ return fullMsg;
2503
+ };
2504
+ /** Sends an experimental AIRich dynamic image/GIF submessage. */
2505
+ socket.sendRichDynamicMedia = async (jid, content = {}, options = {}) => {
2506
+ if (!jid) throw new Boom('sendRichDynamicMedia requires a target JID', { statusCode: 400 });
2507
+ const wrapped = prepareRichDynamicMediaMessage(content);
2508
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2509
+ logger,
2510
+ userJid: authState.creds.me?.id,
2511
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2512
+ ...options
2513
+ });
2514
+ await relayRichMessage(jid, fullMsg, options);
2515
+ return fullMsg;
2516
+ };
2517
+ /** Sends BotPttPromptMetadata containing a caller-provided transcript. */
2518
+ socket.sendBotPttTranscript = async (jid, content = {}, options = {}) => {
2519
+ if (!jid) throw new Boom('sendBotPttTranscript requires a target JID', { statusCode: 400 });
2520
+ const wrapped = prepareBotPttTranscriptMessage(content);
2521
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2522
+ logger,
2523
+ userJid: authState.creds.me?.id,
2524
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2525
+ ...options
2526
+ });
2527
+ await relayRichMessage(jid, fullMsg, options);
2528
+ return fullMsg;
2529
+ };
2530
+ socket.richMenu = async (jid, content = {}, options = {}) => {
2531
+ if (!jid) throw new Boom('richMenu requires a target JID', { statusCode: 400 });
2532
+ const wrapped = prepareRichMenuMessage(content);
2533
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2534
+ logger,
2535
+ userJid: authState.creds.me?.id,
2536
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2537
+ ...options,
2538
+ });
2539
+ await relayRichMessage(jid, fullMsg, options);
2540
+ if (config.emitOwnEvents) {
2541
+ process.nextTick(async () => {
2542
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2543
+ });
2544
+ }
2545
+ return fullMsg;
2546
+ };
2547
+ /**
2548
+ * Sends the A2UI interactive card/menu format used by WhatsApp's large
2549
+ * command-card presentation. This is intentionally separate from richMenu
2550
+ * because it is an interactiveMessage, not an AIRich unifiedResponse.
2551
+ */
2552
+ socket.sendA2UICommandMenu = async (jid, content = {}, options = {}) => {
2553
+ if (!jid) throw new Boom('sendA2UICommandMenu requires a target JID', { statusCode: 400 });
2554
+ const { image, ...menuContent } = content || {};
2555
+ let imageMessage;
2556
+ if (image) {
2557
+ const prepared = await prepareWAMessageMedia({ image }, { upload: waUploadToServer });
2558
+ imageMessage = prepared.imageMessage;
2559
+ }
2560
+ const wrapped = prepareA2UICommandMenu({ ...menuContent, imageMessage });
2561
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2562
+ logger,
2563
+ userJid: authState.creds.me?.id,
2564
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2565
+ ...options,
2566
+ });
2567
+ await relayRichMessage(jid, fullMsg, { ...options, forceRichEdit: true });
2568
+ if (config.emitOwnEvents) {
2569
+ process.nextTick(async () => {
2570
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2571
+ });
2572
+ }
2573
+ return fullMsg;
2574
+ };
2575
+ /** Send arbitrary A2UI/interactive payloads; sendA2UICommandMenu is a preset wrapper. */
2576
+ socket.sendA2UIMessage = async (jid, content = {}, options = {}) => {
2577
+ if (!jid) throw new Boom('sendA2UIMessage requires a target JID', { statusCode: 400 });
2578
+ const { image, ...payload } = content || {};
2579
+ let imageMessage;
2580
+ if (image) {
2581
+ const prepared = await prepareWAMessageMedia({ image }, { upload: waUploadToServer });
2582
+ imageMessage = prepared.imageMessage;
2583
+ }
2584
+ const wrapped = prepareA2UIMessage({ ...payload, imageMessage });
2585
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2586
+ logger,
2587
+ userJid: authState.creds.me?.id,
2588
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2589
+ ...options,
2590
+ });
2591
+ await relayRichMessage(jid, fullMsg, { ...options, forceRichEdit: true });
2592
+ if (config.emitOwnEvents) process.nextTick(async () => { await messageMutex.mutex(() => upsertMessage(fullMsg, 'append')); });
2593
+ return fullMsg;
2594
+ };
2595
+
2596
+ /** Sends the manually serialized AIRich command card shown in the screenshot. */
2597
+ socket.sendAIRichCommandMenu = async (jid, content = {}, options = {}) => {
2598
+ if (!jid) throw new Boom('sendAIRichCommandMenu requires a target JID', { statusCode: 400 });
2599
+ const wrapped = prepareAIRichCommandMenu(content);
2600
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2601
+ logger,
2602
+ userJid: authState.creds.me?.id,
2603
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2604
+ ...options,
2605
+ });
2606
+ await relayRichMessage(jid, fullMsg, options);
2607
+ if (config.emitOwnEvents) {
2608
+ process.nextTick(async () => {
2609
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2610
+ });
2611
+ }
2612
+ return fullMsg;
2613
+ };
2614
+ /** Send a provider-neutral AIRich social/entity result card. */
2615
+ socket.sendSocialEntity = async (jid, content = {}, options = {}) => {
2616
+ if (!jid) throw new Boom('sendSocialEntity requires a target JID', { statusCode: 400 });
2617
+ const wrapped = prepareSocialEntityMessage(content);
2618
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2619
+ logger,
2620
+ userJid: authState.creds.me?.id,
2621
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2622
+ ...options,
2623
+ });
2624
+ await relayRichMessage(jid, fullMsg, options);
2625
+ if (config.emitOwnEvents) process.nextTick(async () => { await messageMutex.mutex(() => upsertMessage(fullMsg, 'append')); });
2626
+ return fullMsg;
2627
+ };
2628
+
2629
+ /** Send the primary Instagram profile result using the universal social/entity API. */
2630
+ socket.sendInstagramProfile = async (jid, content = {}, options = {}) => {
2631
+ if (!jid) throw new Boom('sendInstagramProfile requires a target JID', { statusCode: 400 });
2632
+ const wrapped = prepareInstagramProfileMessage(content);
2633
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2634
+ logger,
2635
+ userJid: authState.creds.me?.id,
2636
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2637
+ ...options,
2638
+ });
2639
+ await relayRichMessage(jid, fullMsg, options);
2640
+ if (config.emitOwnEvents) process.nextTick(async () => { await messageMutex.mutex(() => upsertMessage(fullMsg, 'append')); });
2641
+ return fullMsg;
2642
+ };
2643
+
2644
+ /** Sends a rich response with experimental BotInfrastructureDiagnostics metadata. */
2645
+ socket.sendBotDiagnostics = async (jid, content = {}, options = {}) => {
2646
+ if (!jid) throw new Boom('sendBotDiagnostics requires a target JID', { statusCode: 400 });
2647
+ const { text = 'Bot diagnostics test', botBackend = 0, toolsUsed = [], isThinking = false, botJid = '867051314767696@bot' } = content;
2648
+ const wrapped = {
2649
+ messageContextInfo: { botMetadata: { botInfrastructureDiagnostics: { botBackend, toolsUsed, isThinking } } },
2650
+ botForwardedMessage: { message: { richResponseMessage: { messageType: 1, submessages: [{ messageType: 2, messageText: text }], contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid }, forwardOrigin: 4 } } } }
2651
+ };
2652
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2653
+ await relayRichMessage(jid, fullMsg, options);
2654
+ return fullMsg;
2655
+ };
2656
+ /** Sends a rich response with experimental BotCommandMetadata. */
2657
+ socket.sendBotCommand = async (jid, content = {}, options = {}) => {
2658
+ if (!jid) throw new Boom('sendBotCommand requires a target JID', { statusCode: 400 });
2659
+ const { text = 'Bot command test', commandName = '', commandDescription = '', commandPrompt = '', botJid = '867051314767696@bot' } = content;
2660
+ const wrapped = buildBotRichResponse({ text, botJid, botMetadata: { commandMetadata: { commandName, commandDescription, commandPrompt } } });
2661
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2662
+ await relayRichMessage(jid, fullMsg, options);
2663
+ return fullMsg;
2664
+ };
2665
+ /** Sends a planning/execution-plan rich response with WAProto capabilities. */
2666
+ socket.sendBotPlanning = async (jid, content = {}, options = {}) => {
2667
+ if (!jid) throw new Boom('sendBotPlanning requires a target JID', { statusCode: 400 });
2668
+ const { text = 'Execution plan', steps = [], queryPlan = true, botJid = '867051314767696@bot' } = content;
2669
+ const submessages = [
2670
+ { messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: text },
2671
+ ...steps.map(step => ({
2672
+ messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT,
2673
+ messageText: typeof step === 'string' ? step : `${step.title || step.name || 'Step'}${step.body ? `: ${step.body}` : ''}`
2674
+ }))
2675
+ ];
2676
+ const wrapped = buildBotRichResponse({
2677
+ botJid,
2678
+ submessages,
2679
+ capabilities: [
2680
+ BotCapabilityType.AGENTIC_PLANNING,
2681
+ ...(queryPlan ? [BotCapabilityType.QUERY_PLAN] : [])
2682
+ ]
2683
+ });
2684
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2685
+ await relayRichMessage(jid, fullMsg, options);
2686
+ return fullMsg;
2687
+ };
2688
+ /** Sends a rich response with experimental BotResolvedToolCallMetadata. */
2689
+ socket.sendBotToolResult = async (jid, content = {}, options = {}) => {
2690
+ if (!jid) throw new Boom('sendBotToolResult requires a target JID', { statusCode: 400 });
2691
+ const { text = 'Bot tool result test', toolCallId = `tool-${Date.now()}`, resolutionData, resolutionDataSerialized, botJid = '867051314767696@bot' } = content;
2692
+ const wrapped = buildBotRichResponse({
2693
+ text,
2694
+ botJid,
2695
+ capabilities: [BotCapabilityType.AGENTIC_PLANNING, BotCapabilityType.QUERY_PLAN],
2696
+ botMetadata: {
2697
+ resolvedToolCallMetadata: {
2698
+ toolCallId,
2699
+ resolutionDataSerialized: resolutionDataSerialized ?? JSON.stringify(resolutionData ?? {})
2700
+ }
2701
+ }
2702
+ });
2703
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2704
+ await relayRichMessage(jid, fullMsg, options);
2705
+ return fullMsg;
2706
+ };
2707
+ /**
2708
+ * Sends a real BotProgressIndicatorMetadata planning envelope. The plan is
2709
+ * application-controlled; this advertises the public schema capability but
2710
+ * does not claim to invoke Meta's private planning backend.
2711
+ */
2712
+ socket.sendBotPlan = async (jid, content = {}, options = {}) => {
2713
+ if (!jid) throw new Boom('sendBotPlan requires a target JID', { statusCode: 400 });
2714
+ const {
2715
+ text = 'Execution plan',
2716
+ title = 'Execution plan',
2717
+ steps = [],
2718
+ estimatedCompletionTime,
2719
+ botJid = '867051314767696@bot'
2720
+ } = content;
2721
+ if (!Array.isArray(steps) || steps.length === 0) {
2722
+ throw new Boom('sendBotPlan requires at least one step', { statusCode: 400 });
2723
+ }
2724
+ const planningStatus = proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.PlanningStepStatus;
2725
+ const normalizedSteps = steps.map((step, index) => ({
2726
+ statusTitle: String(step.title || step.name || `Step ${index + 1}`),
2727
+ statusBody: String(step.body || step.description || ''),
2728
+ status: step.status === 'executing' ? planningStatus.EXECUTING
2729
+ : step.status === 'finished' || step.status === 'completed' ? planningStatus.FINISHED
2730
+ : planningStatus.PLANNED,
2731
+ isReasoning: step.isReasoning === true,
2732
+ isEnhancedSearch: step.isEnhancedSearch === true,
2733
+ ...(Array.isArray(step.sections) ? { sections: step.sections } : {})
2734
+ }));
2735
+ const wrapped = {
2736
+ messageContextInfo: { botMetadata: {
2737
+ capabilityMetadata: {
2738
+ capabilities: [
2739
+ proto.BotCapabilityMetadata.BotCapabilityType.AGENTIC_PLANNING,
2740
+ proto.BotCapabilityMetadata.BotCapabilityType.QUERY_PLAN
2741
+ ]
2742
+ },
2743
+ progressIndicatorMetadata: {
2744
+ progressDescription: title,
2745
+ stepsMetadata: normalizedSteps,
2746
+ ...(estimatedCompletionTime ? { estimatedCompletionTime } : {})
2747
+ }
2748
+ } },
2749
+ botForwardedMessage: { message: { richResponseMessage: {
2750
+ messageType: 1,
2751
+ submessages: [{ messageType: 2, messageText: text }],
2752
+ contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid }, forwardOrigin: 4 }
2753
+ } } }
2754
+ };
2755
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2756
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, statusJidList: options.statusJidList });
2757
+ return fullMsg;
2758
+ };
2759
+ socket.sendStatus = async (content, options = {}) => {
2760
+ const statusJidList = await resolveStatusRecipients(options.statusJidList || content?.statusJidList);
2761
+ return socket.sendMessage(STATUS_JID, {
2762
+ ...content,
2763
+ status: true
2764
+ }, {
2765
+ ...options,
2766
+ broadcast: true,
2767
+ statusJidList
2768
+ });
2769
+ };
2770
+ socket.sendRichButtonGrid = async (jid, grid, options = {}) => {
2771
+ const { text, footer, cards = [] } = grid || {};
2772
+ if (!Array.isArray(cards) || cards.length === 0) {
2773
+ throw new Boom('sendRichButtonGrid expects at least one card', { statusCode: 400 });
2774
+ }
2775
+ const normalizedCards = cards.map((card, index) => {
2776
+ const buttons = card.buttons || card.nativeFlow || [];
2777
+ if (!Array.isArray(buttons) || buttons.length === 0) {
2778
+ throw new Boom(`sendRichButtonGrid card ${index + 1} needs buttons`, { statusCode: 400 });
2779
+ }
2780
+ return {
2781
+ ...card,
2782
+ nativeFlow: buttons,
2783
+ caption: card.caption || card.title || `Menu ${index + 1}`
2784
+ };
2785
+ });
2786
+ return socket.sendMessage(jid, {
2787
+ ...(text ? { text } : {}),
2788
+ ...(footer ? { footer } : {}),
2789
+ cards: normalizedCards
2790
+ }, options);
2791
+ };
2792
+ /**
2793
+ * Compatibility entry point for the former Gen4/grid menu.
2794
+ * This is additive: sendRichButtonGrid remains unchanged for existing callers.
2795
+ */
2796
+ socket.HoldOn = async (jid, grid, options = {}) => socket.sendRichButtonGrid(jid, grid, options);
2797
+ socket.sendWhatsAppFlow = async (jid, flow, options = {}) => {
2798
+ const { text, footer, image, caption, ...flowOptions } = flow || {};
2799
+ const button = makeWhatsAppFlowButton(flowOptions);
2800
+ return socket.sendMessage(jid, {
2801
+ ...(image ? { image, caption: caption || text || flowOptions.cta } : { text: text || flowOptions.cta }),
2802
+ ...(footer ? { footer } : {}),
2803
+ nativeFlow: [button]
2804
+ }, options);
2805
+ };
2806
+ /**
2807
+ * Send a rich URL CTA intended to open a hosted WebView/Mini App.
2808
+ * `useWebview` is serialized by the existing native-flow normalizer.
2809
+ * `toast` is preserved as immediate button acknowledgement metadata.
2810
+ */
2811
+ socket.sendRichWebview = async (jid, content = {}, options = {}) => {
2812
+ const { text = '', title, footer, image, caption, buttonText = 'Open', url, useWebview = true, toast, ...rest } = content;
2813
+ if (!url || typeof url !== 'string') {
2814
+ throw new Boom('sendRichWebview requires a URL', { statusCode: 400 });
2815
+ }
2816
+ const button = { text: buttonText, url, useWebview, ...(toast ? { toast } : {}), ...rest };
2817
+ return socket.sendMessage(jid, {
2818
+ ...(image ? { image, caption: caption || text || title || buttonText } : { text: text || title || buttonText }),
2819
+ ...(footer ? { footer } : {}),
2820
+ nativeFlow: [button],
2821
+ ...(toast ? { toast } : {})
2822
+ }, options);
2823
+ };
2824
+ socket.sendInteractiveTable = async (jid, table, options = {}) => {
2825
+ const { title = '', headers = [], rows = [], image, buttons = [], footer } = table || {};
2826
+ if (!Array.isArray(headers) || !Array.isArray(rows) || !Array.isArray(buttons)) {
2827
+ throw new Boom('sendInteractiveTable expects headers, rows, and buttons arrays', { statusCode: 400 });
2828
+ }
2829
+ const lines = [];
2830
+ if (title) lines.push(String(title));
2831
+ if (headers.length) lines.push(`| ${headers.map(String).join(' | ')} |`);
2832
+ if (headers.length) lines.push(`| ${headers.map(() => '---').join(' | ')} |`);
2833
+ for (const row of rows) {
2834
+ lines.push(`| ${(Array.isArray(row) ? row : [row]).map(value => String(value ?? '')).join(' | ')} |`);
2835
+ }
2836
+ const content = {
2837
+ ...(image ? { caption: lines.join('\n'), image } : { text: lines.join('\n') }),
2838
+ buttons: buttons.map((button, index) => ({
2839
+ id: button.id || `table_${index + 1}`,
2840
+ text: button.text || button.buttonText || `Option ${index + 1}`
2841
+ })),
2842
+ ...(footer ? { footer } : {})
2843
+ };
2844
+ return socket.sendMessage(jid, content, options);
2845
+ };
2846
+ // ====================================
2847
+ // VIEW-ONCE AUTO-DECRYPT & AUTO-DELETE
2848
+ // ====================================
2849
+
2850
+ /**
2851
+ * Auto-decrypt view-once messages (autoVV)
2852
+ * Downloads the media content from a view-once message and re-emits it
2853
+ * as a regular message with decryptedMedia attached.
2854
+ */
2855
+ socket.autoVV = async (message, options = {}) => {
2856
+ if (!isViewOnceMessage(message)) {
2857
+ logger.debug({ key: message?.key }, 'autoVV: message is not a view-once message');
2858
+ return null;
2859
+ }
2860
+
2861
+ const info = parseViewOnceInfo(message);
2862
+ logger.info({ key: message?.key, ...info }, 'autoVV: decrypting view-once message');
2863
+
2864
+ try {
2865
+ // Download and decrypt the media
2866
+ const mediaBuffer = await downloadViewOnceMedia(message, {
2867
+ logger,
2868
+ ...options,
2869
+ });
2870
+
2871
+ // Create a regular message from the decrypted content
2872
+ const regularMessage = createRegularMessageFromViewOnce(message, mediaBuffer);
2873
+
2874
+ if (regularMessage) {
2875
+ // Emit as a new message with decrypted content
2876
+ ev.emit('messages.upsert', {
2877
+ messages: [regularMessage],
2878
+ type: 'append',
2879
+ });
2880
+
2881
+ logger.info({
2882
+ key: message?.key,
2883
+ mediaType: info.mediaType,
2884
+ bufferSize: mediaBuffer.length,
2885
+ }, 'autoVV: successfully decrypted view-once message');
2886
+ }
2887
+
2888
+ return regularMessage;
2889
+ } catch (error) {
2890
+ logger.error({
2891
+ key: message?.key,
2892
+ error: error.message,
2893
+ }, 'autoVV: failed to decrypt view-once message');
2894
+ throw error;
2895
+ }
2896
+ };
2897
+
2898
+ /**
2899
+ * Auto-delete view-once messages (antiVV)
2900
+ * Detects incoming view-once messages and deletes them immediately.
2901
+ * This prevents the sender from knowing the message was viewed.
2902
+ */
2903
+ socket.antiVV = async (message, options = {}) => {
2904
+ if (!isViewOnceMessage(message)) {
2905
+ logger.debug({ key: message?.key }, 'antiVV: message is not a view-once message');
2906
+ return false;
2907
+ }
2908
+
2909
+ const info = parseViewOnceInfo(message);
2910
+ logger.info({ key: message?.key, ...info }, 'antiVV: deleting view-once message');
2911
+
2912
+ try {
2913
+ // Delete the message by sending a revoke receipt
2914
+ const jid = message.key.remoteJid;
2915
+ const participant = message.key.participant || jid;
2916
+ const messageId = message.key.id;
2917
+
2918
+ // Send a revoke receipt to delete the message
2919
+ await sendReceipt(jid, participant, [messageId], 'sender');
2920
+
2921
+ // Also emit a message update to remove it from local store
2922
+ ev.emit('messages.update', [
2923
+ {
2924
+ key: message.key,
2925
+ update: {
2926
+ messageStubType: proto.WebMessageInfo.StubType.REVOKE,
2927
+ messageStubParameters: ['auto-vv-delete'],
2928
+ },
2929
+ },
2930
+ ]);
2931
+
2932
+ logger.info({
2933
+ key: message?.key,
2934
+ mediaType: info.mediaType,
2935
+ }, 'antiVV: successfully deleted view-once message');
2936
+
2937
+ return true;
2938
+ } catch (error) {
2939
+ logger.error({
2940
+ key: message?.key,
2941
+ error: error.message,
2942
+ }, 'antiVV: failed to delete view-once message');
2943
+ throw error;
2944
+ }
2945
+ };
2946
+
2947
+ /**
2948
+ * Check if a message is a view-once message
2949
+ */
2950
+ socket.isViewOnce = (message) => isViewOnceMessage(message);
2951
+
2952
+ /**
2953
+ * Get view-once message info (media type, mime type, etc.)
2954
+ */
2955
+ socket.getViewOnceInfo = (message) => parseViewOnceInfo(message);
2956
+
2957
+
2958
+ /**
2959
+ * Sends a full-width vertical AIRich album. Unlike the legacy
2960
+ * albumMessage collection or compact GRID_IMAGE layout, this is one
2961
+ * forwarded unified-response message with one large media item per row.
2962
+ */
2963
+ socket.sendAlbumMessage = async (jid, medias = [], options = {}) => {
2964
+ if (!jid) throw new Boom('sendAlbumMessage requires a target JID', { statusCode: 400 });
2965
+ if (!Array.isArray(medias) || medias.length < 2) {
2966
+ throw new Boom('sendAlbumMessage requires at least two media items', { statusCode: 400 });
2967
+ }
2968
+ const albumItems = medias.map((media) => {
2969
+ const raw = media?.type && media?.data ? media.data : (media?.image ?? media);
2970
+ if (media?.video || media?.type === 'video') {
2971
+ const video = media?.video || raw;
2972
+ const sourceUrl = typeof video === 'string' ? video : (video?.url || video?.videoUrl || '');
2973
+ if (!sourceUrl) throw new Boom('Each video album item requires a video URL', { statusCode: 400 });
2974
+ return { type: 'video', video: { ...video, url: sourceUrl } };
2975
+ }
2976
+ return {
2977
+ type: 'image',
2978
+ image: raw
2979
+ };
2980
+ });
2981
+ const wrapped = prepareVerticalAlbumMessage({
2982
+ items: albumItems,
2983
+ verificationMetadata: options.verificationMetadata
2984
+ });
2985
+ const fullMsg = generateWAMessageFromContent(jid, wrapped, {
2986
+ logger,
2987
+ userJid: authState.creds.me?.id,
2988
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2989
+ ...options
2990
+ });
2991
+ await relayRichMessage(jid, fullMsg, options);
2992
+ if (config.emitOwnEvents) {
2993
+ process.nextTick(async () => {
2994
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2995
+ });
2996
+ }
2997
+ return fullMsg;
2998
+ };
2999
+
3000
+ /**
3001
+ * Sends a unified-response video grid. This uses GenAIVideoPrimitive items
3002
+ * inside GenAIGridLayoutViewModel; it is not the image-only GRID_IMAGE type.
3003
+ */
3004
+ socket.sendVideoGridMessage = async (jid, videos = [], options = {}) => {
3005
+ if (!jid) throw new Boom('sendVideoGridMessage requires a target JID', { statusCode: 400 });
3006
+ if (!Array.isArray(videos) || videos.length < 2) {
3007
+ throw new Boom('sendVideoGridMessage requires at least two videos', { statusCode: 400 });
3008
+ }
3009
+ const wrapped = prepareVideoGridMessage({
3010
+ videos,
3011
+ verificationMetadata: options.verificationMetadata
3012
+ });
3013
+ const fullMsg = generateWAMessageFromContent(jid, wrapped, {
3014
+ logger,
3015
+ userJid: authState.creds.me?.id,
3016
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
3017
+ ...options
3018
+ });
3019
+ await relayRichMessage(jid, fullMsg, options);
3020
+ if (config.emitOwnEvents) {
3021
+ process.nextTick(async () => {
3022
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
3023
+ });
3024
+ }
3025
+ return fullMsg;
3026
+ };
3027
+
3028
+
3029
+ /**
3030
+ * Sends an HTML message — renders raw HTML inside the chat bubble.
3031
+ * Uses FOAHtmlPrimitiveDemoDONOTUSE for full HTML/CSS/JS rendering.
3032
+ *
3033
+ * @param {string} jid - Target JID
3034
+ * @param {Object} content - { html: string, trustedSources?: string[] }
3035
+ * @param {Object} options - Additional options
3036
+ * @returns {Object} Sent message info
3037
+ *
3038
+ * @example
3039
+ * // Simple HTML
3040
+ * await sock.sendHtmlMessage(jid, {
3041
+ * html: '<h1>Hello!</h1><p style="color: blue">World</p>'
3042
+ * })
3043
+ */
3044
+ socket.sendHtmlMessage = async (jid, content = {}, options = {}) => {
3045
+ if (!jid) throw new Boom('sendHtmlMessage requires a target JID', { statusCode: 400 });
3046
+ const { html, trustedSources } = content;
3047
+ if (!html) throw new Boom('sendHtmlMessage requires html content', { statusCode: 400 });
3048
+ const wrapped = prepareHtmlMessage({ html, trustedSources });
3049
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3050
+ logger,
3051
+ userJid: authState.creds.me?.id,
3052
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3053
+ ...options
3054
+ });
3055
+ await relayRichMessage(jid, fullMsg, { ...options, forceRichEdit: true });
3056
+ return fullMsg;
3057
+ };
3058
+
3059
+ /**
3060
+ * Sends an interactive GenAI HTML screen with embedded tabs.
3061
+ * This is distinct from sendHtmlMessage(): it uses the aeacdsnw HTML
3062
+ * primitive and FOAIDNixelButtonSheets envelope used by interactive games.
3063
+ *
3064
+ * @param {string} jid - Target JID
3065
+ * @param {Object} content - { html, title?, tabs?, trustedSources?, url? }
3066
+ * @param {Object} options - Additional relay options
3067
+ */
3068
+ socket.sendRichHtmlMessage = async (jid, content = {}, options = {}) => {
3069
+ if (!jid) throw new Boom('sendRichHtmlMessage requires a target JID', { statusCode: 400 });
3070
+ if (!content.html && !(Array.isArray(content.tabs) && content.tabs.length)) {
3071
+ throw new Boom('sendRichHtmlMessage requires html or tabs content', { statusCode: 400 });
3072
+ }
3073
+ const wrapped = prepareRichHtmlMessage(content);
3074
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3075
+ logger,
3076
+ userJid: authState.creds.me?.id,
3077
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3078
+ ...options
3079
+ });
3080
+ await relayRichMessage(jid, fullMsg, options);
3081
+ return fullMsg;
3082
+ };
3083
+
3084
+ /** Find a word or expression in the installed package source. */
3085
+ socket.grepCode = (pattern, options = {}) => grepSource(pattern, options);
3086
+
3087
+
3088
+ /**
3089
+ * Sends a slot machine game — Fruit Bonanza!
3090
+ * Renders a fully interactive canvas-based slot machine inside the chat bubble.
3091
+ *
3092
+ * @param {string} jid - Target JID
3093
+ * @param {Object} [options] - Game options
3094
+ * @param {string} [options.title='FRUIT BONANZA'] - Machine title
3095
+ * @param {number} [options.startingCredits=500] - Starting credits
3096
+ * @param {Object} [sendOptions] - Send options (quoted, etc.)
3097
+ * @returns {Object} Sent message info
3098
+ *
3099
+ * @example
3100
+ * // Default slot machine
3101
+ * await sock.sendSlotMachine(jid)
3102
+ *
3103
+ * // Custom title and credits
3104
+ * await sock.sendSlotMachine(jid, { title: 'MEGA SLOTS', startingCredits: 1000 })
3105
+ */
3106
+ socket.sendSlotMachine = async (jid, options = {}, sendOptions = {}) => {
3107
+ if (!jid) throw new Boom('sendSlotMachine requires a target JID', { statusCode: 400 });
3108
+ const html = generateSlotMachineHtml(options);
3109
+ return socket.sendHtmlMessage(jid, { html }, sendOptions);
3110
+ };
3111
+
3112
+ /** Sends the attached interactive mini-app through the rich HTML envelope. */
3113
+ socket.sendMiniApp = async (jid, options = {}, sendOptions = {}) => {
3114
+ if (!jid) throw new Boom('sendMiniApp requires a target JID', { statusCode: 400 });
3115
+ return socket.sendRichHtmlMessage(jid, {
3116
+ html: generateMiniAppHtml(options),
3117
+ title: options.title || 'mini-app',
3118
+ url: 'https://pair.crysnova.link',
3119
+ trustedSources: ['pair.crysnova.link']
3120
+ }, sendOptions);
3121
+ };
3122
+
3123
+
3124
+ /**
3125
+ * Mirrors a website inside the WhatsApp chat bubble.
3126
+ * Fetches the site and renders it in a sandboxed iframe.
3127
+ *
3128
+ * @param {string} jid - Target JID
3129
+ * @param {string} url - Website URL to mirror
3130
+ * @param {Object} [options] - Preview options
3131
+ * @param {boolean} [options.sandbox=true] - Sandbox restrictions
3132
+ * @param {string} [options.height='600px'] - Preview height
3133
+ * @param {boolean} [options.showUrl=true] - Show URL bar
3134
+ * @param {Object} [sendOptions] - Send options
3135
+ * @returns {Object} Sent message info
3136
+ *
3137
+ * @example
3138
+ * await sock.sendWebsitePreview(jid, 'https://google.com')
3139
+ * await sock.sendWebsitePreview(jid, 'https://example.com', { height: '400px' })
3140
+ */
3141
+ socket.sendWebsitePreview = async (jid, url, options = {}, sendOptions = {}) => {
3142
+ if (!jid) throw new Boom('sendWebsitePreview requires a target JID', { statusCode: 400 });
3143
+ if (!url) throw new Boom('sendWebsitePreview requires a URL', { statusCode: 400 });
3144
+ const html = await generateWebsitePreviewHtml(url, options);
3145
+ return socket.sendHtmlMessage(jid, { html }, sendOptions);
3146
+ };
3147
+
3148
+ /**
3149
+ * Sends a link preview card for a URL.
3150
+ * Lighter weight than sendWebsitePreview — just shows title, description, image.
3151
+ *
3152
+ * @param {string} jid - Target JID
3153
+ * @param {string} url - URL to preview
3154
+ * @param {Object} [options] - Card options
3155
+ * @param {string} [options.title] - Override title
3156
+ * @param {string} [options.description] - Override description
3157
+ * @param {string} [options.image] - Override image URL
3158
+ * @param {Object} [sendOptions] - Send options
3159
+ * @returns {Object} Sent message info
3160
+ *
3161
+ * @example
3162
+ * await sock.sendLinkPreview(jid, 'https://google.com')
3163
+ * await sock.sendLinkPreview(jid, 'https://example.com', {
3164
+ * title: 'My Website',
3165
+ * description: 'Check out my cool site!',
3166
+ * image: 'https://example.com/og.png'
3167
+ * })
3168
+ */
3169
+ socket.sendLinkPreview = async (jid, url, options = {}, sendOptions = {}) => {
3170
+ if (!jid) throw new Boom('sendLinkPreview requires a target JID', { statusCode: 400 });
3171
+ if (!url) throw new Boom('sendLinkPreview requires a URL', { statusCode: 400 });
3172
+ const html = generateLinkPreviewHtml(url, options);
3173
+ return socket.sendHtmlMessage(jid, { html }, sendOptions);
3174
+ };
3175
+
3176
+ return socket;
1144
3177
  };
1145
- //# sourceMappingURL=messages-send.js.map