@x4r1s3/baileys 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1262 -2
  3. package/SECURITY.md +47 -0
  4. package/WAProto/V +1 -0
  5. package/WAProto/WAProto.proto +8892 -0
  6. package/WAProto/index.d.ts +104128 -0
  7. package/WAProto/index.js +334920 -0
  8. package/assets/rolling-circle.svg +133 -0
  9. package/assets/x4r1s3-banner.svg +32 -0
  10. package/engine-requirements.js +27 -0
  11. package/lib/Builders/A2UI.js +245 -0
  12. package/lib/Builders/AIRich.js +179 -0
  13. package/lib/Builders/Button.js +108 -0
  14. package/lib/Builders/CFC.js +284 -0
  15. package/lib/Builders/Carousel.js +81 -0
  16. package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
  17. package/lib/Call/audio-feeder.mjs +179 -0
  18. package/lib/Call/audio-recorder.mjs +250 -0
  19. package/lib/Call/fetch-wasm-resources.mjs +104 -0
  20. package/lib/Call/index.mjs +680 -0
  21. package/lib/Call/relay-transport.mjs +563 -0
  22. package/lib/Call/signaling.mjs +641 -0
  23. package/lib/Call/types.mjs +17 -0
  24. package/lib/Call/video-feeder.mjs +94 -0
  25. package/lib/Call/wasm-engine.mjs +1372 -0
  26. package/lib/Call/worker-bootstrap.mjs +1042 -0
  27. package/lib/Defaults/ban-checker.js +56 -0
  28. package/lib/Defaults/index.js +170 -0
  29. package/lib/Signal/Group/ciphertext-message.js +23 -0
  30. package/lib/Signal/Group/group-session-builder.js +41 -0
  31. package/lib/Signal/Group/group_cipher.js +93 -0
  32. package/lib/Signal/Group/index.js +23 -0
  33. package/lib/Signal/Group/keyhelper.js +29 -0
  34. package/lib/Signal/Group/sender-chain-key.js +37 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
  36. package/lib/Signal/Group/sender-key-message.js +77 -0
  37. package/lib/Signal/Group/sender-key-name.js +59 -0
  38. package/lib/Signal/Group/sender-key-record.js +52 -0
  39. package/lib/Signal/Group/sender-key-state.js +95 -0
  40. package/lib/Signal/Group/sender-message-key.js +37 -0
  41. package/lib/Signal/libsignal.js +440 -0
  42. package/lib/Signal/lid-mapping.js +292 -0
  43. package/lib/Socket/Client/index.js +14 -0
  44. package/lib/Socket/Client/types.js +22 -0
  45. package/lib/Socket/Client/websocket.js +65 -0
  46. package/lib/Socket/aigroups.js +327 -0
  47. package/lib/Socket/ban-checker.js +165 -0
  48. package/lib/Socket/business.js +419 -0
  49. package/lib/Socket/chats.js +1921 -0
  50. package/lib/Socket/communities.js +443 -0
  51. package/lib/Socket/graphql.js +911 -0
  52. package/lib/Socket/groups.js +561 -0
  53. package/lib/Socket/index.js +49 -0
  54. package/lib/Socket/interactive-handler.js +612 -0
  55. package/lib/Socket/interop.js +575 -0
  56. package/lib/Socket/managed-account.js +220 -0
  57. package/lib/Socket/messages-recv.js +2191 -0
  58. package/lib/Socket/messages-send.js +4104 -0
  59. package/lib/Socket/mex.js +53 -0
  60. package/lib/Socket/newsletter.js +291 -0
  61. package/lib/Socket/privacy.js +458 -0
  62. package/lib/Socket/registration.js +440 -0
  63. package/lib/Socket/socket.js +1029 -0
  64. package/lib/Socket/status-actions.js +287 -0
  65. package/lib/Socket/username.js +241 -0
  66. package/lib/Store/index.js +16 -0
  67. package/lib/Store/make-cache-manager-store.js +101 -0
  68. package/lib/Store/make-in-memory-store.js +432 -0
  69. package/lib/Store/make-ordered-dictionary.js +90 -0
  70. package/lib/Store/object-repository.js +35 -0
  71. package/lib/Types/Auth.js +13 -0
  72. package/lib/Types/Bussines.js +13 -0
  73. package/lib/Types/Call.js +13 -0
  74. package/lib/Types/Chat.js +19 -0
  75. package/lib/Types/Contact.js +13 -0
  76. package/lib/Types/Events.js +13 -0
  77. package/lib/Types/GroupMetadata.js +13 -0
  78. package/lib/Types/Label.js +36 -0
  79. package/lib/Types/LabelAssociation.js +18 -0
  80. package/lib/Types/Message.js +30 -0
  81. package/lib/Types/Mex.js +53 -0
  82. package/lib/Types/Product.js +13 -0
  83. package/lib/Types/RichType.js +34 -0
  84. package/lib/Types/Signal.js +13 -0
  85. package/lib/Types/Socket.js +14 -0
  86. package/lib/Types/State.js +60 -0
  87. package/lib/Types/USync.js +13 -0
  88. package/lib/Types/index.js +37 -0
  89. package/lib/Utils/auth-utils.js +313 -0
  90. package/lib/Utils/ban-checker.js +48 -0
  91. package/lib/Utils/bot-capabilities.js +96 -0
  92. package/lib/Utils/bot-planning-replay.js +177 -0
  93. package/lib/Utils/browser-utils.js +40 -0
  94. package/lib/Utils/business.js +242 -0
  95. package/lib/Utils/c2582.js +147 -0
  96. package/lib/Utils/chat-utils.js +905 -0
  97. package/lib/Utils/companion-reg-client-utils.js +44 -0
  98. package/lib/Utils/consumer-application.js +114 -0
  99. package/lib/Utils/crypto.js +129 -0
  100. package/lib/Utils/decode-wa-message.js +496 -0
  101. package/lib/Utils/direct-chat-theme.js +164 -0
  102. package/lib/Utils/event-buffer.js +601 -0
  103. package/lib/Utils/experimental-proto.js +206 -0
  104. package/lib/Utils/games/miniapp.js +17 -0
  105. package/lib/Utils/games/slot-machine.js +270 -0
  106. package/lib/Utils/games/website-preview.js +306 -0
  107. package/lib/Utils/generics.js +402 -0
  108. package/lib/Utils/group-history.js +68 -0
  109. package/lib/Utils/group-wallpaper.js +168 -0
  110. package/lib/Utils/history.js +162 -0
  111. package/lib/Utils/identity-change-handler.js +60 -0
  112. package/lib/Utils/index.js +61 -0
  113. package/lib/Utils/jid-display-normalization.js +221 -0
  114. package/lib/Utils/link-preview.js +96 -0
  115. package/lib/Utils/logger.js +14 -0
  116. package/lib/Utils/lt-hash.js +19 -0
  117. package/lib/Utils/make-mutex.js +44 -0
  118. package/lib/Utils/message-composer.js +709 -0
  119. package/lib/Utils/message-inspect.js +79 -0
  120. package/lib/Utils/message-retry-manager.js +253 -0
  121. package/lib/Utils/message-security.js +167 -0
  122. package/lib/Utils/messages-media.js +1027 -0
  123. package/lib/Utils/messages.js +2467 -0
  124. package/lib/Utils/meta-ai-msmsg.js +215 -0
  125. package/lib/Utils/meta-compositing.js +239 -0
  126. package/lib/Utils/native-flow.js +158 -0
  127. package/lib/Utils/newsletter-live-update-utils.js +74 -0
  128. package/lib/Utils/newsletter-status-utils.js +152 -0
  129. package/lib/Utils/noise-handler.js +212 -0
  130. package/lib/Utils/offline-node-processor.js +51 -0
  131. package/lib/Utils/poll-manager.js +206 -0
  132. package/lib/Utils/portable-compat.js +12 -0
  133. package/lib/Utils/pre-key-manager.js +117 -0
  134. package/lib/Utils/process-message.js +610 -0
  135. package/lib/Utils/reporting-utils.js +269 -0
  136. package/lib/Utils/rich-message-utils.js +2841 -0
  137. package/lib/Utils/scheduled-message.js +107 -0
  138. package/lib/Utils/signal.js +212 -0
  139. package/lib/Utils/source-grep.js +57 -0
  140. package/lib/Utils/stanza-ack.js +49 -0
  141. package/lib/Utils/sticker-annotation.js +87 -0
  142. package/lib/Utils/sync-action-utils.js +59 -0
  143. package/lib/Utils/tc-token-utils.js +174 -0
  144. package/lib/Utils/use-multi-file-auth-state.js +132 -0
  145. package/lib/Utils/use-single-file-auth-state.js +108 -0
  146. package/lib/Utils/use-sqlite-auth-state.js +120 -0
  147. package/lib/Utils/validate-connection.js +220 -0
  148. package/lib/Utils/view-once-utils.js +218 -0
  149. package/lib/Utils/voip-rekey.js +32 -0
  150. package/lib/Utils/website-preview.js +27 -0
  151. package/lib/Utils/welcome-flow.js +228 -0
  152. package/lib/Utils/x4r1s3.js +144 -0
  153. package/lib/WABinary/constants.js +1475 -0
  154. package/lib/WABinary/decode.js +273 -0
  155. package/lib/WABinary/encode.js +231 -0
  156. package/lib/WABinary/generic-utils.js +242 -0
  157. package/lib/WABinary/index.js +17 -0
  158. package/lib/WABinary/jid-utils.js +107 -0
  159. package/lib/WABinary/types.js +13 -0
  160. package/lib/WAM/BinaryInfo.js +21 -0
  161. package/lib/WAM/constants.js +22864 -0
  162. package/lib/WAM/encode.js +161 -0
  163. package/lib/WAM/index.js +15 -0
  164. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
  165. package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
  166. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  167. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
  168. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
  169. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
  170. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
  171. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  172. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
  173. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
  174. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
  175. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
  176. package/lib/WAUSync/Protocols/index.js +24 -0
  177. package/lib/WAUSync/USyncQuery.js +213 -0
  178. package/lib/WAUSync/USyncUser.js +66 -0
  179. package/lib/WAUSync/index.js +15 -0
  180. package/lib/antiban.cjs +4726 -0
  181. package/lib/index.d.ts +1285 -0
  182. package/lib/index.js +30 -0
  183. package/package.json +125 -4
@@ -0,0 +1,4104 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Socket/messages-send.js
5
+ * About: Messages send module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: normalizeStatusJidList, makeMessagesSocket
7
+ * Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
8
+ *
9
+ * Copyright and attribution notice.
10
+ * Do not copy, reproduce, redistribute, modify, or create derivative works
11
+ * from this source without explicit written permission.
12
+ */
13
+ import { unlink } from 'node:fs/promises';
14
+ import NodeCache from '@cacheable/node-cache';
15
+ import { Boom } from '@hapi/boom';
16
+ import { randomBytes, randomUUID } from 'crypto';
17
+ import { proto } from '../../WAProto/index.js';
18
+ import { BIZ_BOT_SUPPORT_PAYLOAD, DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
19
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, buildLinkPreview, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, extractImageThumb, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, generateWAMessageFromImagePoll, generateWAMessageFromLivePhoto, getStatusCodeForMediaRetry, makeWhatsAppFlowButton, buildBookingConfirmationButton, buildRequestContactInfoButton, getUrlFromDirectPath, getWAUploadToServer, getRawMediaUploadData, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, prepareWAMessageMedia, shouldIncludeBizBinaryNode, unixTimestampSeconds, normalizeScheduledTime, createScheduledMessageEnvelope, associateScheduledMessages } from '../Utils/index.js';
20
+ import { getUrlInfo } from '../Utils/link-preview.js';
21
+ import { buildNewsletterStatusNode, getNewsletterStatusMediaType, waitForNewsletterStatusServerId, withNewsletterStatusAttribution, withNewsletterStatusAudioMetadata } from '../Utils/newsletter-status-utils.js';
22
+ import { prepareRichMenuMessage, prepareInteractiveContactCardMessage, prepareLocationButtonCardMessage, prepareMenuButtonCardMessage, normalizeLocationButtonCardThumbnail, prepareA2UIMessage, prepareA2UICommandMenu, prepareAIRichCommandMenu, prepareSocialEntityMessage, prepareInstagramProfileMessage, prepareRichResponseMessage, generateX4R1S3RichAIResponseContent, prepareRichGenerationMessage, prepareCopyToClipboardMessage, prepareRichTextMessage, prepareRichQuoteMessage, prepareRichImageMessage, prepareRichLinkMessage, prepareSocialProfileMessage, prepareUnifiedResponseMessage, prepareRichMapMessage, prepareBotPromptSuggestionsMessage, prepareBotSourcesMessage, prepareRichDynamicMediaMessage, prepareBotPttTranscriptMessage, prepareGridImageMessage, prepareVerticalAlbumMessage, prepareVideoGridMessage, prepareHtmlMessage, prepareRichHtmlMessage, prepareRichMediaMessage, buildRichLabelMessage, attachBotVerificationProofs, hasVerifiableProofs, normalizeUnifiedThemedMessageContent } from '../Utils/rich-message-utils.js';
23
+ import { sendStickerAnnotationBatch } from '../Utils/sticker-annotation.js';
24
+ import { X4R1S3 as runX4R1S3 } from '../Utils/x4r1s3.js';
25
+ import { generateSlotMachineHtml } from '../Utils/games/slot-machine.js';
26
+ import { generateMiniAppHtml } from '../Utils/games/miniapp.js';
27
+ import { generateWebsitePreviewHtml, generateLinkPreviewHtml } from '../Utils/games/website-preview.js';
28
+ import { isViewOnceMessage, extractViewOnceContent, getViewOnceMediaType, getViewOnceMediaContent, downloadViewOnceMedia, createRegularMessageFromViewOnce, parseViewOnceInfo } from '../Utils/view-once-utils.js';
29
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
30
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
31
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
32
+ 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';
33
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
34
+ import { captureUnifiedResponse, generateCodeBlockContent, generateLatexContent, generateListContent, generateRichAIResponseContent, generateTableContent, generateUnifiedResponseContent } from '../Utils/message-composer.js';
35
+ import { BotCapabilityType, buildBotRichResponse } from '../Utils/bot-capabilities.js';
36
+ import { Baron } from './interactive-handler.js';
37
+ import { collectMetaAIBotParticipantJids, isMetaAIBotResponse, META_AI_BOT_JID } from './aigroups.js';
38
+ import { makeUsernameSocket } from './username.js';
39
+ import { grepSource } from '../Utils/source-grep.js';
40
+ import { C2582 } from '../Utils/c2582.js';
41
+ import { makeStatusActionMethods } from './status-actions.js';
42
+
43
+ const STATUS_JID = 'status@broadcast';
44
+ /** Build the ACP2 setting-change protocol envelope used by Restricted chat. */
45
+ export const makeRestrictedChatSettingMessage = (enabled, timestamp = Date.now()) => {
46
+ if (typeof enabled !== 'boolean') throw new Boom('Restricted chat enabled must be a boolean', { statusCode: 400 });
47
+ if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Boom('Restricted chat timestamp must be a non-negative safe integer', { statusCode: 400 });
48
+ return {
49
+ protocolMessage: {
50
+ type: proto.Message.ProtocolMessage.Type.ACP2_SETTING,
51
+ timestampMs: timestamp,
52
+ acp2Setting: {
53
+ enabled,
54
+ trigger: proto.LimitSharing.TriggerType.CHAT_SETTING,
55
+ settingTimestamp: timestamp
56
+ }
57
+ }
58
+ };
59
+ };
60
+ export const normalizeStatusJidList = (value) => {
61
+ if (!Array.isArray(value) || value.length === 0) {
62
+ throw new Boom('statusJidList must contain at least one recipient JID', { statusCode: 400 });
63
+ }
64
+ const recipients = [...new Set(value.map(jidNormalizedUser).filter(jid => isPnUser(jid) || isLidUser(jid)))];
65
+ if (recipients.length === 0) {
66
+ throw new Boom('statusJidList does not contain any valid user JIDs', { statusCode: 400 });
67
+ }
68
+ return recipients;
69
+ };
70
+
71
+ export const makeMessagesSocket = (config) => {
72
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
73
+ const sock = makeUsernameSocket(config);
74
+ let socket;
75
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
76
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
77
+
78
+ const inFlightTcTokenIssuance = new Set();
79
+ const userDevicesCache = config.userDevicesCache ||
80
+ new NodeCache({
81
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
82
+ useClones: false
83
+ });
84
+ const devicesMutex = makeMutex();
85
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
86
+ const encryptionMutex = makeKeyedMutex();
87
+ const mediaConnMutex = makeKeyedMutex();
88
+
89
+ let mediaConn;
90
+ let mediaHost = DEF_MEDIA_HOST;
91
+
92
+ // ── BULK REACTION HELPER (NEW) ──
93
+ const sendBulkReactions = async (jid, messageId, emoji, count = 1, fake = false) => {
94
+ const maxReactions = Math.min(Math.max(Number(count) || 1, 1), 1000);
95
+ if (isJidNewsletter(jid)) {
96
+ if (typeof socket.newsletterReactMessage !== 'function') {
97
+ throw new Boom('newsletter reaction API is unavailable', { statusCode: 501 });
98
+ }
99
+ await socket.newsletterReactMessage(jid, messageId, String(emoji || ''));
100
+ return { sent: 1, requested: maxReactions, fake: false, channel: true, jid };
101
+ }
102
+ const makeReaction = () => ({
103
+ react: {
104
+ text: String(emoji || ''),
105
+ key: {
106
+ remoteJid: jid,
107
+ fromMe: false,
108
+ id: messageId
109
+ }
110
+ }
111
+ });
112
+ let sent = 0;
113
+ const batchSize = 10;
114
+
115
+ // sendMessage accepts one content object, not an array of messages.
116
+ // Also, fake inbound reaction records cannot be serialized as outgoing
117
+ // WhatsApp messages or impersonate other users. Keep the flag for API
118
+ // compatibility, but always send a valid reaction from this account.
119
+ if (fake) {
120
+ logger.warn('[BULK_REACT] fake=true cannot impersonate other WhatsApp users; sending valid reactions from this account');
121
+ }
122
+ for (let i = 0; i < maxReactions; i += batchSize) {
123
+ const batch = Array.from({ length: Math.min(batchSize, maxReactions - i) }, () =>
124
+ socket.sendMessage(jid, makeReaction(), { ephemeralExpiration: 86400 })
125
+ .then(() => { sent += 1; })
126
+ .catch(error => logger.warn(`[BULK_REACT] Reaction failed: ${error.message}`))
127
+ );
128
+ await Promise.all(batch);
129
+ if (i + batchSize < maxReactions) await delay(100);
130
+ }
131
+
132
+ return { sent, requested: maxReactions, fake: false, jid };
133
+ };
134
+
135
+ // ── MIMIC HELPER ──
136
+ const sendAsMimic = async (jid, content, mimicJid, options = {}) => {
137
+ const hasPermission = options.admin === true || options.mimicPermission === true;
138
+ if (!hasPermission) {
139
+ throw new Boom('Mimic requires admin permission', { statusCode: 403 });
140
+ }
141
+
142
+ const msgId = generateMessageIDV2(authState.creds.me.id);
143
+
144
+ const fakeKey = {
145
+ remoteJid: jid,
146
+ fromMe: false,
147
+ id: msgId,
148
+ participant: mimicJid
149
+ };
150
+
151
+ const fullMsg = await generateWAMessageFromContent(jid, content, {
152
+ userJid: authState.creds.me.id,
153
+ ...options
154
+ });
155
+
156
+ fullMsg.key = fakeKey;
157
+
158
+ await relayMessage(jid, fullMsg.message, {
159
+ messageId: msgId,
160
+ additionalAttributes: options.additionalAttributes || {},
161
+ additionalNodes: options.additionalNodes || []
162
+ });
163
+
164
+ return fullMsg;
165
+ };
166
+
167
+ const refreshMediaConn = async (forceGet = false) => {
168
+ return mediaConnMutex.mutex('media-conn', async () => {
169
+ const media = await mediaConn;
170
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
171
+ mediaConn = (async () => {
172
+ const result = await query({
173
+ tag: 'iq',
174
+ attrs: {
175
+ type: 'set',
176
+ xmlns: 'w:m',
177
+ to: S_WHATSAPP_NET
178
+ },
179
+ content: [{ tag: 'media_conn', attrs: {} }]
180
+ });
181
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
182
+ const node = {
183
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
184
+ hostname: attrs.hostname,
185
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
186
+ })),
187
+ auth: mediaConnNode.attrs.auth,
188
+ ttl: +mediaConnNode.attrs.ttl,
189
+ fetchDate: new Date()
190
+ };
191
+ logger.debug('fetched media conn');
192
+ if (node.hosts[0]) {
193
+ mediaHost = node.hosts[0].hostname;
194
+ }
195
+ return node;
196
+ })();
197
+ }
198
+ return mediaConn;
199
+ });
200
+ };
201
+
202
+ const sendReceipt = async (jid, participant, messageIds, type) => {
203
+ if (!messageIds || messageIds.length === 0) {
204
+ throw new Boom('missing ids in receipt');
205
+ }
206
+ const node = {
207
+ tag: 'receipt',
208
+ attrs: {
209
+ id: messageIds[0]
210
+ }
211
+ };
212
+ const isReadReceipt = type === 'read' || type === 'read-self';
213
+ if (isReadReceipt) {
214
+ node.attrs.t = unixTimestampSeconds().toString();
215
+ }
216
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
217
+ node.attrs.recipient = jid;
218
+ node.attrs.to = participant;
219
+ }
220
+ else {
221
+ node.attrs.to = jid;
222
+ if (participant) {
223
+ node.attrs.participant = participant;
224
+ }
225
+ }
226
+ if (type) {
227
+ node.attrs.type = type;
228
+ }
229
+ const remainingMessageIds = messageIds.slice(1);
230
+ if (remainingMessageIds.length) {
231
+ node.content = [
232
+ {
233
+ tag: 'list',
234
+ attrs: {},
235
+ content: remainingMessageIds.map(id => ({
236
+ tag: 'item',
237
+ attrs: { id }
238
+ }))
239
+ }
240
+ ];
241
+ }
242
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
243
+ await sendNode(node);
244
+ };
245
+
246
+ const sendReceipts = async (keys, type) => {
247
+ const recps = aggregateMessageKeysNotFromMe(keys);
248
+ for (const { jid, participant, messageIds } of recps) {
249
+ await sendReceipt(jid, participant, messageIds, type);
250
+ }
251
+ };
252
+
253
+ const readMessages = async (keys) => {
254
+ const privacySettings = await fetchPrivacySettings();
255
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
256
+ await sendReceipts(keys, readType);
257
+ };
258
+
259
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
260
+ const deviceResults = [];
261
+ if (!useCache) {
262
+ logger.debug('not using cache for devices');
263
+ }
264
+ const toFetch = [];
265
+ const jidsWithUser = jids
266
+ .map(jid => {
267
+ const decoded = jidDecode(jid);
268
+ const user = decoded?.user;
269
+ const device = decoded?.device;
270
+ // Meta AI/bot JIDs are single device-0 endpoints. USync does not
271
+ // enumerate them, so inject the endpoint instead of dropping it.
272
+ if (user && (isJidMetaAI(jid) || isJidBot(jid))) {
273
+ deviceResults.push({
274
+ user,
275
+ device: typeof device === 'number' ? device : 0,
276
+ jid
277
+ });
278
+ return null;
279
+ }
280
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
281
+ if (isExplicitDevice && user) {
282
+ deviceResults.push({
283
+ user,
284
+ device,
285
+ jid
286
+ });
287
+ return null;
288
+ }
289
+ jid = jidNormalizedUser(jid);
290
+ return { jid, user };
291
+ })
292
+ .filter(jid => jid !== null);
293
+ let mgetDevices;
294
+ if (useCache && userDevicesCache.mget) {
295
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
296
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
297
+ }
298
+ for (const { jid, user } of jidsWithUser) {
299
+ if (useCache) {
300
+ const devices = mgetDevices?.[user] ||
301
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
302
+ if (devices) {
303
+ const devicesWithJid = devices.map(d => ({
304
+ ...d,
305
+ jid: jidEncode(d.user, d.server, d.device)
306
+ }));
307
+ deviceResults.push(...devicesWithJid);
308
+ logger.trace({ user }, 'using cache for devices');
309
+ }
310
+ else {
311
+ toFetch.push(jid);
312
+ }
313
+ }
314
+ else {
315
+ toFetch.push(jid);
316
+ }
317
+ }
318
+ if (!toFetch.length) {
319
+ return deviceResults;
320
+ }
321
+ const requestedLidUsers = new Set();
322
+ for (const jid of toFetch) {
323
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
324
+ const user = jidDecode(jid)?.user;
325
+ if (user)
326
+ requestedLidUsers.add(user);
327
+ }
328
+ }
329
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
330
+ for (const jid of toFetch) {
331
+ query.withUser(new USyncUser().withId(jid));
332
+ }
333
+ const result = await sock.executeUSyncQuery(query);
334
+ if (result) {
335
+ const lidResults = result.list.filter(a => !!a.lid);
336
+ if (lidResults.length > 0) {
337
+ logger.trace('Storing LID maps from device call');
338
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
339
+ try {
340
+ const lids = lidResults.map(a => a.lid);
341
+ if (lids.length) {
342
+ await assertSessions(lids, true);
343
+ }
344
+ }
345
+ catch (e) {
346
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
347
+ }
348
+ }
349
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
350
+ const deviceMap = {};
351
+ for (const item of extracted) {
352
+ deviceMap[item.user] = deviceMap[item.user] || [];
353
+ deviceMap[item.user]?.push(item);
354
+ }
355
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
356
+ const isLidUser = requestedLidUsers.has(user);
357
+ for (const item of userDevices) {
358
+ const finalJid = isLidUser
359
+ ? jidEncode(user, item.server, item.device)
360
+ : jidEncode(item.user, item.server, item.device);
361
+ deviceResults.push({
362
+ ...item,
363
+ jid: finalJid
364
+ });
365
+ logger.debug({
366
+ user: item.user,
367
+ device: item.device,
368
+ finalJid,
369
+ usedLid: isLidUser
370
+ }, 'Processed device with LID priority');
371
+ }
372
+ }
373
+ await devicesMutex.mutex(async () => {
374
+ if (userDevicesCache.mset) {
375
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
376
+ }
377
+ else {
378
+ for (const key in deviceMap) {
379
+ if (deviceMap[key])
380
+ await userDevicesCache.set(key, deviceMap[key]);
381
+ }
382
+ }
383
+ });
384
+ const userDeviceUpdates = {};
385
+ for (const [userId, devices] of Object.entries(deviceMap)) {
386
+ if (devices && devices.length > 0) {
387
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
388
+ }
389
+ }
390
+ if (Object.keys(userDeviceUpdates).length > 0) {
391
+ try {
392
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
393
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
394
+ }
395
+ catch (error) {
396
+ logger.warn({ error }, 'failed to store user device lists');
397
+ }
398
+ }
399
+ }
400
+ return deviceResults;
401
+ };
402
+
403
+ const updateMemberLabel = (jid, memberLabel) => {
404
+ return relayMessage(jid, {
405
+ protocolMessage: {
406
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
407
+ memberLabel: {
408
+ label: memberLabel?.slice(0, 30),
409
+ labelTimestamp: unixTimestampSeconds()
410
+ }
411
+ }
412
+ }, {
413
+ additionalNodes: [
414
+ {
415
+ tag: 'meta',
416
+ attrs: {
417
+ tag_reason: 'user_update',
418
+ appdata: 'member_tag'
419
+ },
420
+ content: undefined
421
+ }
422
+ ]
423
+ });
424
+ };
425
+
426
+ const assertSessions = async (jids, force) => {
427
+ let didFetchNewSession = false;
428
+ const uniqueJids = [...new Set(jids)];
429
+ const jidsRequiringFetch = [];
430
+ logger.debug({ jids }, 'assertSessions call with jids');
431
+ for (const jid of uniqueJids) {
432
+ if (!force) {
433
+ const sessionValidation = await signalRepository.validateSession(jid);
434
+ if (sessionValidation.exists) {
435
+ continue;
436
+ }
437
+ }
438
+ jidsRequiringFetch.push(jid);
439
+ }
440
+ if (jidsRequiringFetch.length) {
441
+ const wireJids = [
442
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
443
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid),
444
+ // @bot endpoints are not represented by LID/PN USync results,
445
+ // but still require a pre-key fetch to build the Signal session.
446
+ ...jidsRequiringFetch.filter(jid => isJidMetaAI(jid) || isJidBot(jid))
447
+ ];
448
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
449
+ const result = await query({
450
+ tag: 'iq',
451
+ attrs: {
452
+ xmlns: 'encrypt',
453
+ type: 'get',
454
+ to: S_WHATSAPP_NET
455
+ },
456
+ content: [
457
+ {
458
+ tag: 'key',
459
+ attrs: {},
460
+ content: wireJids.map(jid => {
461
+ const attrs = { jid };
462
+ if (force)
463
+ attrs.reason = 'identity';
464
+ return { tag: 'user', attrs };
465
+ })
466
+ }
467
+ ]
468
+ });
469
+ await parseAndInjectE2ESessions(result, signalRepository);
470
+ didFetchNewSession = true;
471
+ }
472
+ return didFetchNewSession;
473
+ };
474
+
475
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
476
+ if (!authState.creds.me?.id) {
477
+ throw new Boom('Not authenticated');
478
+ }
479
+ const protocolMessage = {
480
+ protocolMessage: {
481
+ peerDataOperationRequestMessage: pdoMessage,
482
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
483
+ }
484
+ };
485
+ const meJid = jidNormalizedUser(authState.creds.me.id);
486
+ const msgId = await relayMessage(meJid, protocolMessage, {
487
+ additionalAttributes: {
488
+ category: 'peer',
489
+ push_priority: 'high_force'
490
+ },
491
+ additionalNodes: [
492
+ {
493
+ tag: 'meta',
494
+ attrs: { appdata: 'default' }
495
+ }
496
+ ]
497
+ });
498
+ return msgId;
499
+ };
500
+
501
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
502
+ if (!recipientJids.length) {
503
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
504
+ }
505
+ const patched = await patchMessageBeforeSending(message, recipientJids);
506
+ const patchedMessages = Array.isArray(patched)
507
+ ? patched
508
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
509
+ let shouldIncludeDeviceIdentity = false;
510
+ const meId = authState.creds.me.id;
511
+ const meLid = authState.creds.me?.lid;
512
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
513
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
514
+ try {
515
+ if (!jid)
516
+ return null;
517
+ let msgToEncrypt = patchedMessage;
518
+ if (dsmMessage) {
519
+ const { user: targetUser } = jidDecode(jid);
520
+ const { user: ownPnUser } = jidDecode(meId);
521
+ const ownLidUser = meLidUser;
522
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
523
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
524
+ if (isOwnUser && !isExactSenderDevice) {
525
+ msgToEncrypt = dsmMessage;
526
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
527
+ }
528
+ }
529
+ const bytes = encodeWAMessage(msgToEncrypt);
530
+ const mutexKey = jid;
531
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
532
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
533
+ if (type === 'pkmsg') {
534
+ shouldIncludeDeviceIdentity = true;
535
+ }
536
+ return {
537
+ tag: 'to',
538
+ attrs: { jid },
539
+ content: [
540
+ {
541
+ tag: 'enc',
542
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
543
+ content: ciphertext
544
+ }
545
+ ]
546
+ };
547
+ });
548
+ return node;
549
+ }
550
+ catch (err) {
551
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
552
+ return null;
553
+ }
554
+ });
555
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
556
+ if (recipientJids.length > 0 && nodes.length === 0) {
557
+ throw new Boom('All encryptions failed', { statusCode: 500 });
558
+ }
559
+ return { nodes, shouldIncludeDeviceIdentity };
560
+ };
561
+
562
+ 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, mediaTypeOverride }) => {
563
+ const meId = assertMeId(authState.creds);
564
+ const meLid = authState.creds.me?.lid;
565
+ const retryParticipants = retryParticipantsExplicit || retryParticipantsOption || (participant?.count != null ? participant : undefined);
566
+ const isRetryResend = Boolean(retryParticipants?.jid && retryParticipants?.count != null);
567
+ const isRecipientOnly = Boolean(participant?.jid && !isRetryResend);
568
+ let shouldIncludeDeviceIdentity = isRetryResend;
569
+ const statusJid = 'status@broadcast';
570
+ const { user, server } = jidDecode(jid);
571
+ const isGroup = server === 'g.us';
572
+ const isStatus = jid === statusJid;
573
+ const isLid = server === 'lid';
574
+ const isNewsletter = server === 'newsletter';
575
+ const isGroupOrStatus = isGroup || isStatus;
576
+ const finalJid = jid;
577
+ msgId = msgId || generateMessageIDV2(meId);
578
+ useUserDevicesCache = useUserDevicesCache !== false;
579
+ useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
580
+ const participants = [];
581
+ const destinationJid = !isStatus ? finalJid : statusJid;
582
+ const binaryNodeContent = [];
583
+ const devices = [];
584
+ let reportingMessage;
585
+ const requiresViewOnce = !!(message.buttonsMessage || message.templateMessage || message.listMessage || message.interactiveMessage);
586
+ if (requiresViewOnce) {
587
+ message = {
588
+ viewOnceMessage: {
589
+ message: { ...message }
590
+ }
591
+ };
592
+ }
593
+ const applyForwarded = m => {
594
+ // Auto-inject trusted verification proofs configured once on the socket
595
+ // (config.metaAiRendering.verificationMetadata). Per-message proofs win:
596
+ // an envelope that already carries verificationMetadata is left untouched.
597
+ // The second target covers edited rich envelopes (protocolMessage.editedMessage,
598
+ // used by updateRichGeneration) so an in-place rich update keeps its proofs too.
599
+ const edited = m?.botForwardedMessage?.message?.protocolMessage?.editedMessage;
600
+ const rich = m?.botForwardedMessage?.message?.richResponseMessage || m?.richResponseMessage;
601
+ if (!rich && !edited) return m;
602
+ if (hasVerifiableProofs(config?.metaAiRendering?.verificationMetadata)) {
603
+ attachBotVerificationProofs(m, config.metaAiRendering.verificationMetadata);
604
+ attachBotVerificationProofs(edited, config.metaAiRendering.verificationMetadata);
605
+ }
606
+ if (!rich) return m;
607
+ rich.contextInfo = { ...rich.contextInfo, isForwarded: true, forwardOrigin: 4 };
608
+ return m.botForwardedMessage ? m : { botForwardedMessage: { message: m } };
609
+ };
610
+ if (message?.deviceSentMessage?.message) {
611
+ message.deviceSentMessage.message = applyForwarded(message.deviceSentMessage.message);
612
+ }
613
+ else {
614
+ message = applyForwarded(message);
615
+ }
616
+ const meMsg = {
617
+ deviceSentMessage: {
618
+ destinationJid,
619
+ message
620
+ },
621
+ messageContextInfo: message.messageContextInfo
622
+ };
623
+ const extraAttrs = {};
624
+ if (isRetryResend) {
625
+ if (!isGroup && !isStatus) {
626
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
627
+ }
628
+ const { user, device } = jidDecode(retryParticipants.jid);
629
+ devices.push({ user, device, jid: retryParticipants.jid });
630
+ }
631
+ if ((isRecipientOnly || isSecret || protectedSend || meOnly) && !isGroup && !isStatus) {
632
+ additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
633
+ }
634
+ await authState.keys.transaction(async () => {
635
+ const innerMessage = normalizeMessageContent(message);
636
+ const mediaType = getMediaType(innerMessage) || mediaTypeOverride;
637
+ if (mediaType) {
638
+ extraAttrs['mediatype'] = mediaType;
639
+ }
640
+ if (isNewsletter) {
641
+ const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
642
+ const bytes = encodeNewsletterMessage(patched);
643
+ if (additionalNodes && additionalNodes.length > 0) {
644
+ binaryNodeContent.push(...additionalNodes);
645
+ }
646
+ binaryNodeContent.push({
647
+ tag: 'plaintext',
648
+ attrs: extraAttrs,
649
+ content: bytes
650
+ });
651
+ const stanza = {
652
+ tag: 'message',
653
+ attrs: {
654
+ to: jid,
655
+ id: msgId,
656
+ type: getMessageType(innerMessage),
657
+ ...(additionalAttributes || {})
658
+ },
659
+ content: binaryNodeContent
660
+ };
661
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
662
+ await sendNode(stanza);
663
+ return;
664
+ }
665
+ const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
666
+ const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
667
+ const isPollUpdate = innerMessage?.pollUpdateMessage;
668
+ if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
669
+ const metaAttrs = {};
670
+ if (isNeedMetaAttrs) {
671
+ metaAttrs.content_type = 'add_on';
672
+ }
673
+ if (isPollUpdate && !isGroupStatus) {
674
+ metaAttrs.polltype = 'vote';
675
+ }
676
+ if (isGroupStatus) {
677
+ metaAttrs.is_group_status = 'true';
678
+ }
679
+ binaryNodeContent.push({
680
+ tag: 'meta',
681
+ attrs: metaAttrs,
682
+ content: undefined
683
+ });
684
+ }
685
+ if (isStatus && statusPrivacy && !additionalAttributes?.edit) {
686
+ binaryNodeContent.push({
687
+ tag: 'meta',
688
+ attrs: { status_setting: statusPrivacy, session_scope: 'status' }
689
+ });
690
+ }
691
+ if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
692
+ extraAttrs['decrypt-fail'] = 'hide';
693
+ }
694
+ if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
695
+ extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
696
+ }
697
+ if (isGroupOrStatus && !isRetryResend) {
698
+ const [groupData, senderKeyMap] = await Promise.all([
699
+ (async () => {
700
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
701
+ if (groupData && Array.isArray(groupData?.participants)) {
702
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
703
+ }
704
+ else if (!isStatus) {
705
+ groupData = await groupMetadata(jid);
706
+ }
707
+ return groupData;
708
+ })(),
709
+ (async () => {
710
+ if (!participant && !isStatus) {
711
+ const result = await authState.keys.get('sender-key-memory', [jid]);
712
+ return result[jid] || {};
713
+ }
714
+ return {};
715
+ })()
716
+ ]);
717
+ const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
718
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
719
+ additionalAttributes = {
720
+ ...additionalAttributes,
721
+ expiration: groupData.ephemeralDuration.toString()
722
+ };
723
+ }
724
+ if (isStatus && statusJidList) {
725
+ participantsList.push(...statusJidList);
726
+ }
727
+ // Bots invoked through botGroupMetadata are not group members,
728
+ // so include their @bot endpoints in sender-key distribution.
729
+ const botGroupParticipants = message?.messageContextInfo?.botMetadata?.botGroupMetadata?.participantsMetadata || [];
730
+ for (const participant of botGroupParticipants) {
731
+ if (!participant?.botFbid)
732
+ continue;
733
+ const botJid = `${participant.botFbid}@bot`;
734
+ if (!participantsList.includes(botJid))
735
+ participantsList.push(botJid);
736
+ }
737
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
738
+ devices.push(...additionalDevices);
739
+ if (isGroup) {
740
+ additionalAttributes = {
741
+ ...additionalAttributes,
742
+ addressing_mode: groupData?.addressingMode || 'lid'
743
+ };
744
+ }
745
+ const patched = await patchMessageBeforeSending(message);
746
+ if (Array.isArray(patched)) {
747
+ throw new Boom('Per-jid patching is not supported in groups');
748
+ }
749
+ const bytes = encodeWAMessage(patched);
750
+ reportingMessage = patched;
751
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
752
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
753
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
754
+ group: destinationJid,
755
+ data: bytes,
756
+ meId: groupSenderIdentity
757
+ });
758
+ const senderKeyRecipients = [];
759
+ for (const device of devices) {
760
+ const deviceJid = device.jid;
761
+ const hasKey = !!senderKeyMap[deviceJid];
762
+ const isBotRecipient = isJidMetaAI(deviceJid) || isJidBot(deviceJid);
763
+ if ((!hasKey || !!participant || isBotRecipient) &&
764
+ !isHostedLidUser(deviceJid) &&
765
+ !isHostedPnUser(deviceJid) &&
766
+ device.device !== 99) {
767
+ senderKeyRecipients.push(deviceJid);
768
+ senderKeyMap[deviceJid] = true;
769
+ }
770
+ }
771
+ if (senderKeyRecipients.length) {
772
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
773
+ const senderKeyMsg = {
774
+ senderKeyDistributionMessage: {
775
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
776
+ groupId: destinationJid
777
+ }
778
+ };
779
+ const senderKeySessionTargets = senderKeyRecipients;
780
+ await assertSessions(senderKeySessionTargets);
781
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
782
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
783
+ participants.push(...result.nodes);
784
+ }
785
+ binaryNodeContent.push({
786
+ tag: 'enc',
787
+ attrs: { v: '2', type: 'skmsg', ...extraAttrs },
788
+ content: ciphertext
789
+ });
790
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
791
+ }
792
+ else {
793
+ let ownId = meId;
794
+ if (isLid && meLid) {
795
+ ownId = meLid;
796
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
797
+ }
798
+ else {
799
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
800
+ }
801
+ const { user: ownUser } = jidDecode(ownId);
802
+ if (!participant) {
803
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
804
+ reportingMessage = Array.isArray(patchedForReporting)
805
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
806
+ : patchedForReporting;
807
+ }
808
+ if (!isRetryResend) {
809
+ const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
810
+ devices.push({
811
+ user,
812
+ device: 0,
813
+ jid: jidEncode(user, targetUserServer, 0)
814
+ });
815
+ if (user !== ownUser) {
816
+ const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
817
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
818
+ devices.push({
819
+ user: ownUserForAddressing,
820
+ device: 0,
821
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
822
+ });
823
+ }
824
+ if (additionalAttributes?.['category'] !== 'peer') {
825
+ devices.length = 0;
826
+ const senderIdentity = isLid && meLid
827
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
828
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
829
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
830
+ devices.push(...sessionDevices);
831
+ logger.debug({
832
+ deviceCount: devices.length,
833
+ devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
834
+ }, 'Device enumeration complete with unified addressing');
835
+ }
836
+ }
837
+ const allRecipients = [];
838
+ const meRecipients = [];
839
+ const otherRecipients = [];
840
+ const { user: mePnUser } = jidDecode(meId);
841
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
842
+ for (const { user, jid } of devices) {
843
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
844
+ if (isExactSenderDevice) {
845
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
846
+ continue;
847
+ }
848
+ const isMe = user === mePnUser || user === meLidUser;
849
+ const hasDevice = jid.includes(':');
850
+ if (isRecipientOnly && isMe) continue;
851
+ if (isSecret && !(!isMe && !hasDevice)) continue;
852
+ if (protectedSend && !isMe && hasDevice) continue;
853
+ if (meOnly && !isMe) continue;
854
+ if (isMe) {
855
+ meRecipients.push(jid);
856
+ }
857
+ else {
858
+ otherRecipients.push(jid);
859
+ }
860
+ allRecipients.push(jid);
861
+ }
862
+ await assertSessions(allRecipients);
863
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
864
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
865
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
866
+ ]);
867
+ participants.push(...meNodes);
868
+ participants.push(...otherNodes);
869
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
870
+ extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
871
+ }
872
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
873
+ }
874
+ if (isRetryResend) {
875
+ const isParticipantLid = isLidUser(retryParticipants.jid);
876
+ const isMe = areJidsSameUser(retryParticipants.jid, isParticipantLid ? meLid : meId);
877
+ let messageToSend = message;
878
+ if (isGroupOrStatus) {
879
+ let groupSenderIdentity;
880
+ if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
881
+ groupSenderIdentity = meLid;
882
+ }
883
+ else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
884
+ groupSenderIdentity = meId;
885
+ }
886
+ if (groupSenderIdentity) {
887
+ try {
888
+ const skdm = await signalRepository.getSenderKeyDistributionMessage({
889
+ group: destinationJid,
890
+ meId: groupSenderIdentity
891
+ });
892
+ messageToSend = {
893
+ ...message,
894
+ senderKeyDistributionMessage: {
895
+ groupId: destinationJid,
896
+ axolotlSenderKeyDistributionMessage: skdm
897
+ }
898
+ };
899
+ }
900
+ catch (err) {
901
+ logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
902
+ }
903
+ }
904
+ }
905
+ const encodedMessageToSend = isMe
906
+ ? encodeWAMessage({
907
+ deviceSentMessage: {
908
+ destinationJid,
909
+ message: messageToSend
910
+ }
911
+ })
912
+ : encodeWAMessage(messageToSend);
913
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
914
+ data: encodedMessageToSend,
915
+ jid: retryParticipants.jid
916
+ });
917
+ binaryNodeContent.push({
918
+ tag: 'enc',
919
+ attrs: {
920
+ v: '2',
921
+ type,
922
+ count: retryParticipants.count.toString()
923
+ },
924
+ content: encryptedContent
925
+ });
926
+ }
927
+ if (participants.length) {
928
+ if (additionalAttributes?.['category'] === 'peer') {
929
+ const peerNode = participants[0]?.content?.[0];
930
+ if (peerNode) {
931
+ binaryNodeContent.push(peerNode);
932
+ }
933
+ }
934
+ else {
935
+ binaryNodeContent.push({
936
+ tag: 'participants',
937
+ attrs: {},
938
+ content: participants
939
+ });
940
+ }
941
+ }
942
+ const stanza = {
943
+ tag: 'message',
944
+ attrs: {
945
+ id: msgId,
946
+ to: destinationJid,
947
+ type: getMessageType(innerMessage),
948
+ ...(additionalAttributes || {})
949
+ },
950
+ content: binaryNodeContent
951
+ };
952
+ if (isRetryResend) {
953
+ if (isJidGroup(destinationJid)) {
954
+ stanza.attrs.to = destinationJid;
955
+ stanza.attrs.participant = retryParticipants.jid;
956
+ }
957
+ else if (areJidsSameUser(retryParticipants.jid, meId)) {
958
+ stanza.attrs.to = retryParticipants.jid;
959
+ stanza.attrs.recipient = destinationJid;
960
+ }
961
+ else {
962
+ stanza.attrs.to = retryParticipants.jid;
963
+ }
964
+ }
965
+ else {
966
+ stanza.attrs.to = destinationJid;
967
+ }
968
+ if (shouldIncludeDeviceIdentity) {
969
+ stanza.content.push({
970
+ tag: 'device-identity',
971
+ attrs: {},
972
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
973
+ });
974
+ logger.debug({ jid }, 'adding device identity');
975
+ }
976
+ if (!isNewsletter &&
977
+ !isRetryResend &&
978
+ reportingMessage?.messageContextInfo?.messageSecret &&
979
+ shouldIncludeReportingToken(reportingMessage)) {
980
+ try {
981
+ const encoded = encodeWAMessage(reportingMessage);
982
+ const reportingKey = {
983
+ id: msgId,
984
+ fromMe: true,
985
+ remoteJid: destinationJid,
986
+ participant: retryParticipants?.jid
987
+ };
988
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
989
+ if (reportingNode) {
990
+ stanza.content.push(reportingNode);
991
+ logger.trace({ jid }, 'added reporting token to message');
992
+ }
993
+ }
994
+ catch (error) {
995
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
996
+ }
997
+ }
998
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer';
999
+ const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
1000
+ const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
1001
+ const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
1002
+ const existingTokenEntry = contactTcTokenData[tcTokenJid];
1003
+ let tcTokenBuffer = existingTokenEntry?.token;
1004
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
1005
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
1006
+ tcTokenBuffer = undefined;
1007
+ const cleared = existingTokenEntry?.senderTimestamp !== undefined
1008
+ ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
1009
+ : null;
1010
+ try {
1011
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
1012
+ }
1013
+ catch (err) {
1014
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
1015
+ }
1016
+ }
1017
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
1018
+ stanza.content.push({
1019
+ tag: 'tctoken',
1020
+ attrs: {},
1021
+ content: tcTokenBuffer
1022
+ });
1023
+ }
1024
+ let alreadyHasBizNode = false;
1025
+ if (additionalNodes && additionalNodes.length > 0) {
1026
+ stanza.content.push(...additionalNodes);
1027
+ alreadyHasBizNode = !addBizAttributes &&
1028
+ additionalNodes.some(node => node.tag === 'biz');
1029
+ }
1030
+ if ((!alreadyHasBizNode && shouldIncludeBizBinaryNode(innerMessage)) || addBizAttributes) {
1031
+ const bizNode = getBizBinaryNode(innerMessage, addBizAttributes);
1032
+ stanza.content.push(bizNode);
1033
+ }
1034
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`);
1035
+ await sendNode(stanza);
1036
+ const isProtocolMsg = !!innerMessage?.protocolMessage;
1037
+ if (!isProtocolMsg && !isJidNewsletter(destinationJid)) {
1038
+ try {
1039
+ await config.messageSecurityStore?.recordSent(
1040
+ msgId,
1041
+ destinationJid,
1042
+ authState.creds.me?.id,
1043
+ undefined,
1044
+ authState.creds.me?.lid
1045
+ );
1046
+ }
1047
+ catch (error) {
1048
+ logger.warn({ msgId, error }, 'unable to persist sent message ID for security checks');
1049
+ }
1050
+ }
1051
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
1052
+ if (is1on1Send &&
1053
+ !isProtocolMsg &&
1054
+ !isBotOrPSA &&
1055
+ shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
1056
+ !inFlightTcTokenIssuance.has(tcTokenJid)) {
1057
+ inFlightTcTokenIssuance.add(tcTokenJid);
1058
+ const issueTimestamp = unixTimestampSeconds();
1059
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
1060
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
1061
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
1062
+ .then(async (result) => {
1063
+ await storeTcTokensFromIqResult({
1064
+ result,
1065
+ fallbackJid: tcTokenJid,
1066
+ keys: authState.keys,
1067
+ getLIDForPN
1068
+ });
1069
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
1070
+ const currentEntry = currentData[tcTokenJid];
1071
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
1072
+ await authState.keys.set({
1073
+ tctoken: {
1074
+ [tcTokenJid]: {
1075
+ token: Buffer.alloc(0),
1076
+ ...currentEntry,
1077
+ senderTimestamp: issueTimestamp
1078
+ },
1079
+ ...indexWrite
1080
+ }
1081
+ });
1082
+ })
1083
+ .catch(err => {
1084
+ logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
1085
+ })
1086
+ .finally(() => {
1087
+ inFlightTcTokenIssuance.delete(tcTokenJid);
1088
+ });
1089
+ }
1090
+ if (messageRetryManager && !retryParticipants) {
1091
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1092
+ }
1093
+ }, meId);
1094
+ return msgId;
1095
+ };
1096
+
1097
+ /**
1098
+ * Relay a rich envelope and then replay it as a type-14 edit. Some
1099
+ * WhatsApp clients otherwise show a Download prompt before rendering the
1100
+ * AIRich unifiedResponse. The edit is only applied to bot-forwarded rich
1101
+ * envelopes, so ordinary messages are never duplicated accidentally.
1102
+ * Set renderRichResponse: false for callers that explicitly do not want
1103
+ * the compatibility replay.
1104
+ */
1105
+ const relayRichMessage = async (jid, fullMsg, options = {}) => {
1106
+ const relayOptions = {
1107
+ messageId: fullMsg.key.id,
1108
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1109
+ statusJidList: options.statusJidList,
1110
+ ...options.relayOptions,
1111
+ };
1112
+ await relayMessage(jid, fullMsg.message, relayOptions);
1113
+
1114
+ const richEnvelope = fullMsg.message?.botForwardedMessage?.message?.richResponseMessage;
1115
+ if (options.renderRichResponse !== false && (richEnvelope || options.forceRichEdit || fullMsg.message?.interactiveMessage?.bloksWidget)) {
1116
+ const editContent = proto.Message.fromObject({
1117
+ botForwardedMessage: {
1118
+ message: {
1119
+ protocolMessage: {
1120
+ key: {
1121
+ remoteJid: jid,
1122
+ fromMe: true,
1123
+ id: fullMsg.key.id,
1124
+ },
1125
+ type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
1126
+ editedMessage: fullMsg.message,
1127
+ },
1128
+ },
1129
+ },
1130
+ });
1131
+ const editMessage = generateWAMessageFromContent(jid, editContent, {
1132
+ logger,
1133
+ userJid: authState.creds.me?.id,
1134
+ messageId: generateMessageIDV2(authState.creds.me?.id || jid),
1135
+ });
1136
+ await relayMessage(jid, editMessage.message, {
1137
+ ...relayOptions,
1138
+ messageId: editMessage.key.id,
1139
+ });
1140
+ }
1141
+ return fullMsg;
1142
+ };
1143
+
1144
+ const sendImagePoll = async (jid, poll, sendOptions = {}) => {
1145
+ const userJid = authState.creds.me.id;
1146
+ const { additionalNodes: _callerNodes, ...relayBaseOptions } = sendOptions;
1147
+ return generateWAMessageFromImagePoll(jid, poll, async (message, relayOptions, fullMessage) => {
1148
+ await relayMessage(jid, message, {
1149
+ ...relayBaseOptions,
1150
+ useCachedGroupMetadata: sendOptions.useCachedGroupMetadata,
1151
+ statusJidList: sendOptions.statusJidList,
1152
+ statusPrivacy: sendOptions.statusPrivacy,
1153
+ ...relayOptions
1154
+ });
1155
+ if (config.emitOwnEvents && fullMessage) {
1156
+ process.nextTick(async () => {
1157
+ await messageMutex.mutex(() => upsertMessage(fullMessage, 'append'));
1158
+ });
1159
+ }
1160
+ }, {
1161
+ logger,
1162
+ userJid,
1163
+ upload: waUploadToServer,
1164
+ mediaCache: config.mediaCache,
1165
+ options: config.options,
1166
+ ...sendOptions
1167
+ });
1168
+ };
1169
+ const sendLivePhoto = async (jid, content, quoted, sendOptions = {}) => {
1170
+ const userJid = authState.creds.me?.id;
1171
+ const {
1172
+ relayOptions: callerRelayOptions = {},
1173
+ photo_live: _photoLive,
1174
+ photoLive: _photoLiveCamel,
1175
+ thumbnail: _thumbnail,
1176
+ image: _image,
1177
+ videoThumbnail: _videoThumbnail,
1178
+ motionPhotoPresentationOffsetMs: _motionOffset,
1179
+ presentationOffsetMs: _presentationOffset,
1180
+ ...transportOptions
1181
+ } = sendOptions;
1182
+ const mediaOptions = {
1183
+ logger,
1184
+ userJid,
1185
+ upload: waUploadToServer,
1186
+ mediaCache: config.mediaCache,
1187
+ options: config.options,
1188
+ ...transportOptions,
1189
+ ...(quoted ? { quoted } : {})
1190
+ };
1191
+ return generateWAMessageFromLivePhoto(jid, content, async (message, relayOpts, fullMessage) => {
1192
+ await relayMessage(jid, message, {
1193
+ ...transportOptions,
1194
+ ...callerRelayOptions,
1195
+ useCachedGroupMetadata: sendOptions.useCachedGroupMetadata,
1196
+ statusJidList: sendOptions.statusJidList,
1197
+ statusPrivacy: sendOptions.statusPrivacy,
1198
+ messageId: relayOpts.messageId
1199
+ });
1200
+ if (config.emitOwnEvents && fullMessage) {
1201
+ process.nextTick(async () => {
1202
+ await messageMutex.mutex(() => upsertMessage(fullMessage, 'append'));
1203
+ });
1204
+ }
1205
+ }, mediaOptions);
1206
+ };
1207
+ const getMessageType = (message) => {
1208
+ if (!message)
1209
+ return 'text';
1210
+ if (message.reactionMessage || message.encReactionMessage) {
1211
+ return 'reaction';
1212
+ }
1213
+ if (message.pollCreationMessage ||
1214
+ message.pollCreationMessageV2 ||
1215
+ message.pollCreationMessageV3 ||
1216
+ message.pollCreationMessageV5 ||
1217
+ message.pollCreationMessageV6 ||
1218
+ message.pollUpdateMessage) {
1219
+ return 'poll';
1220
+ }
1221
+ if (message.eventMessage) {
1222
+ return 'event';
1223
+ }
1224
+ if (getMediaType(message) !== '') {
1225
+ return 'media';
1226
+ }
1227
+ return 'text';
1228
+ };
1229
+
1230
+ const getMediaType = (message) => {
1231
+ if (message.imageMessage) {
1232
+ return 'image';
1233
+ }
1234
+ else if (message.videoMessage) {
1235
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
1236
+ }
1237
+ else if (message.stickerMessage) {
1238
+ return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker';
1239
+ }
1240
+ else if (message.audioMessage) {
1241
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
1242
+ }
1243
+ else if (message.albumMessage) {
1244
+ return 'collection';
1245
+ }
1246
+ else if (message.contactMessage) {
1247
+ return 'vcard';
1248
+ }
1249
+ else if (message.documentMessage) {
1250
+ return 'document';
1251
+ }
1252
+ else if (message.contactsArrayMessage) {
1253
+ return 'contact_array';
1254
+ }
1255
+ else if (message.liveLocationMessage) {
1256
+ return 'livelocation';
1257
+ }
1258
+ else if (message.stickerPackMessage) {
1259
+ return 'sticker_pack';
1260
+ }
1261
+ else if (message.listMessage) {
1262
+ return 'list';
1263
+ }
1264
+ else if (message.listResponseMessage) {
1265
+ return 'list_response';
1266
+ }
1267
+ else if (message.buttonsResponseMessage) {
1268
+ return 'buttons_response';
1269
+ }
1270
+ else if (message.orderMessage) {
1271
+ return 'order';
1272
+ }
1273
+ else if (message.productMessage) {
1274
+ return 'product';
1275
+ }
1276
+ else if (message.interactiveResponseMessage) {
1277
+ return 'native_flow_response';
1278
+ }
1279
+ else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
1280
+ return 'url';
1281
+ }
1282
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/c/')) {
1283
+ return 'cataloglink';
1284
+ }
1285
+ else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/p/')) {
1286
+ return 'productlink';
1287
+ }
1288
+ return '';
1289
+ };
1290
+
1291
+ const issuePrivacyTokens = async (jids, timestamp) => {
1292
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
1293
+ const result = await query({
1294
+ tag: 'iq',
1295
+ attrs: {
1296
+ to: S_WHATSAPP_NET,
1297
+ type: 'set',
1298
+ xmlns: 'privacy'
1299
+ },
1300
+ content: [
1301
+ {
1302
+ tag: 'tokens',
1303
+ attrs: {},
1304
+ content: jids.map(jid => ({
1305
+ tag: 'token',
1306
+ attrs: {
1307
+ jid: jidNormalizedUser(jid),
1308
+ t,
1309
+ type: 'trusted_contact'
1310
+ }
1311
+ }))
1312
+ }
1313
+ ]
1314
+ });
1315
+ return result;
1316
+ };
1317
+
1318
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1319
+ const uploadGroupHistory = async (encryptedFile, fileEncSha256, timeoutMs = 60000) => {
1320
+ if (!Buffer.isBuffer(encryptedFile) && !(encryptedFile instanceof Uint8Array)) {
1321
+ throw new TypeError('uploadGroupHistory requires encrypted bytes');
1322
+ }
1323
+ if (!Buffer.isBuffer(fileEncSha256) && !(fileEncSha256 instanceof Uint8Array)) {
1324
+ throw new TypeError('uploadGroupHistory requires the encrypted file SHA-256');
1325
+ }
1326
+ const { filePath } = await getRawMediaUploadData(encryptedFile, 'group-history', logger);
1327
+ try {
1328
+ const uploaded = await waUploadToServer(filePath, {
1329
+ mediaType: 'group-history',
1330
+ fileEncSha256B64: Buffer.from(fileEncSha256).toString('base64'),
1331
+ timeoutMs
1332
+ });
1333
+ if (!uploaded?.directPath) {
1334
+ throw new Boom('Group-history upload returned no direct path', { statusCode: 500 });
1335
+ }
1336
+ return uploaded;
1337
+ }
1338
+ finally {
1339
+ await unlink(filePath).catch(() => undefined);
1340
+ }
1341
+ };
1342
+ const sendGroupHistory = async (groupJid, targetJid, { media, metadata } = {}) => {
1343
+ if (!isJidGroup(groupJid)) {
1344
+ throw new Boom('sendGroupHistory requires a group JID', { statusCode: 400 });
1345
+ }
1346
+ if (typeof targetJid !== 'string' || !targetJid) {
1347
+ throw new Boom('sendGroupHistory requires a history recipient JID', { statusCode: 400 });
1348
+ }
1349
+ if (!media?.directPath || !media?.fileSha256 || !media?.fileEncSha256 || !media?.mediaKey) {
1350
+ throw new Boom('sendGroupHistory requires an uploaded history bundle', { statusCode: 400 });
1351
+ }
1352
+ const meId = assertMeId(authState.creds);
1353
+ const group = await groupMetadata(groupJid);
1354
+ const participantJids = [...new Set((group?.participants || []).map(participant => participant.id || participant.jid).filter(Boolean))];
1355
+ if (!participantJids.length) {
1356
+ throw new Boom('sendGroupHistory could not resolve group participants', { statusCode: 400 });
1357
+ }
1358
+ const participantDevices = await getUSyncDevices(participantJids, false, false);
1359
+ const participantDeviceJids = [...new Set((participantDevices || []).map(device => device.jid).filter(Boolean))];
1360
+ if (!participantDeviceJids.length) {
1361
+ throw new Boom('sendGroupHistory could not resolve group devices', { statusCode: 400 });
1362
+ }
1363
+ const targetDevices = await getUSyncDevices([targetJid], false, false);
1364
+ const targetDeviceJids = [...new Set((targetDevices || []).map(device => device.jid).filter(Boolean))];
1365
+ if (!targetDeviceJids.length) targetDeviceJids.push(targetJid);
1366
+ await assertSessions(targetDeviceJids);
1367
+
1368
+ const message = {
1369
+ messageHistoryBundle: {
1370
+ mimetype: media.mimetype || 'application/protobuf',
1371
+ fileSha256: media.fileSha256,
1372
+ mediaKey: media.mediaKey,
1373
+ fileEncSha256: media.fileEncSha256,
1374
+ directPath: media.directPath,
1375
+ mediaKeyTimestamp: media.mediaKeyTimestamp,
1376
+ messageHistoryMetadata: metadata
1377
+ },
1378
+ messageContextInfo: { messageSecret: randomBytes(32) }
1379
+ };
1380
+ const groupAddressingMode = group.addressingMode || 'lid';
1381
+ const senderIdentity = groupAddressingMode === 'lid' && authState.creds.me?.lid
1382
+ ? authState.creds.me.lid
1383
+ : meId;
1384
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
1385
+ group: groupJid,
1386
+ data: encodeWAMessage(message),
1387
+ meId: senderIdentity
1388
+ });
1389
+ const senderKeyMessage = {
1390
+ senderKeyDistributionMessage: {
1391
+ groupId: groupJid,
1392
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage
1393
+ }
1394
+ };
1395
+ const { nodes, shouldIncludeDeviceIdentity } = await createParticipantNodes(
1396
+ targetDeviceJids,
1397
+ senderKeyMessage,
1398
+ { mediatype: 'group_history' }
1399
+ );
1400
+ if (!nodes.length) {
1401
+ throw new Boom('sendGroupHistory could not encrypt for the history recipient', { statusCode: 500 });
1402
+ }
1403
+ const id = generateMessageIDV2(meId);
1404
+ const stanza = {
1405
+ tag: 'message',
1406
+ attrs: {
1407
+ id,
1408
+ to: groupJid,
1409
+ type: 'media',
1410
+ addressing_mode: groupAddressingMode,
1411
+ phash: generateParticipantHashV2([...participantDeviceJids])
1412
+ },
1413
+ content: [
1414
+ { tag: 'participants', attrs: {}, content: nodes },
1415
+ { tag: 'enc', attrs: { v: '2', type: 'skmsg', mediatype: 'group_history' }, content: ciphertext }
1416
+ ]
1417
+ };
1418
+ if (shouldIncludeDeviceIdentity) {
1419
+ stanza.content.push({
1420
+ tag: 'device-identity',
1421
+ attrs: {},
1422
+ content: encodeSignedDeviceIdentity(authState.creds.account, true)
1423
+ });
1424
+ }
1425
+ await sendNode(stanza);
1426
+ return { id, key: { remoteJid: groupJid, fromMe: true, id } };
1427
+ };
1428
+ const baron2 = new Baron(waUploadToServer, relayMessage, config, sock);
1429
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1430
+
1431
+ const resolveStatusRecipients = async (provided) => {
1432
+ let recipients = provided || config.statusJidList;
1433
+ if (!recipients && typeof config.getStatusJidList === 'function') {
1434
+ recipients = await config.getStatusJidList(sock);
1435
+ }
1436
+ if (!recipients) {
1437
+ const contactSource = config.store?.contacts || config.contactStore?.contacts || config.contacts;
1438
+ if (Array.isArray(contactSource)) {
1439
+ recipients = contactSource;
1440
+ }
1441
+ else if (contactSource && typeof contactSource === 'object') {
1442
+ recipients = Object.keys(contactSource);
1443
+ }
1444
+ }
1445
+ const ownJid = authState.creds.me?.id;
1446
+ try {
1447
+ return normalizeStatusJidList([...(recipients || []), ownJid].filter(Boolean));
1448
+ }
1449
+ catch (error) {
1450
+ throw new Boom('sendStatus requires a non-empty statusJidList or a configured contact source/provider', {
1451
+ statusCode: 400,
1452
+ data: { hint: 'Pass statusJidList, config.statusJidList, config.getStatusJidList, or config.store.contacts' },
1453
+ cause: error
1454
+ });
1455
+ }
1456
+ };
1457
+
1458
+ registerSocketEndHandler(() => {
1459
+ if (!config.userDevicesCache && userDevicesCache.close) {
1460
+ userDevicesCache.close();
1461
+ }
1462
+ mediaConn = undefined;
1463
+ if (messageRetryManager) {
1464
+ messageRetryManager.clear();
1465
+ }
1466
+ });
1467
+
1468
+
1469
+ socket = {
1470
+ ...sock,
1471
+ userDevicesCache,
1472
+ devicesMutex,
1473
+ issuePrivacyTokens,
1474
+ assertSessions,
1475
+ relayMessage,
1476
+ sendReceipt,
1477
+ sendReceipts,
1478
+ readMessages,
1479
+ refreshMediaConn,
1480
+ getMediaHost: () => mediaHost,
1481
+ waUploadToServer,
1482
+ uploadGroupHistory,
1483
+ sendGroupHistory,
1484
+ fetchPrivacySettings,
1485
+ sendPeerDataOperationMessage,
1486
+ createParticipantNodes,
1487
+ getUSyncDevices,
1488
+ messageRetryManager,
1489
+ updateMemberLabel,
1490
+ sendBulkReactions, // ← NEW: Bulk reaction helper
1491
+ sendAsMimic,
1492
+ // Native status mention path. The array-jid sendMessage branch expands
1493
+ // group recipients, emits mentioned_users metadata, and sends the
1494
+ // follow-up statusMentionMessage/groupStatusMentionMessage reference.
1495
+ sendStatusMention: async (content, jids = [], options = {}) => {
1496
+ if (!Array.isArray(jids) || jids.length === 0) {
1497
+ throw new Boom('sendStatusMention requires at least one user or group JID', { statusCode: 400 });
1498
+ }
1499
+ return socket.sendMessage(jids, {
1500
+ ...content,
1501
+ status: true
1502
+ }, options);
1503
+ },
1504
+ sendStatusMentions: async (content, jids = [], options = {}) => {
1505
+ if (!Array.isArray(jids) || jids.length === 0) {
1506
+ throw new Boom('sendStatusMentions requires at least one user or group JID', { statusCode: 400 });
1507
+ }
1508
+ return socket.sendMessage(jids, {
1509
+ ...content,
1510
+ status: true
1511
+ }, options);
1512
+ },
1513
+ sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1514
+ const { message, messageId } = generateTableContent(title, headers, rows, quoted, options);
1515
+ const fullMsg = generateWAMessageFromContent(jid, message, {
1516
+ logger,
1517
+ userJid: authState.creds.me?.id,
1518
+ messageId: options.messageId || messageId || generateMessageIDV2(jid),
1519
+ quoted,
1520
+ ...options
1521
+ });
1522
+ await relayRichMessage(jid, fullMsg, options);
1523
+ return fullMsg;
1524
+ },
1525
+ /**
1526
+ * Send a table as a GenATableUXPrimitive in unifiedResponse, rather
1527
+ * than as the legacy Table preview submessage used by sendTable.
1528
+ */
1529
+ sendUnifiedTable: async (jid, title, headers, rows, quoted, options = {}) => {
1530
+ if (!Array.isArray(headers) || !Array.isArray(rows)) {
1531
+ throw new Boom('sendUnifiedTable requires headers and rows arrays', { statusCode: 400 });
1532
+ }
1533
+ const message = prepareRichResponseMessage({
1534
+ headerText: options.headerText,
1535
+ title,
1536
+ table: [headers, ...rows],
1537
+ footerText: options.footerText,
1538
+ noHeading: false,
1539
+ noDonation: true
1540
+ });
1541
+ const fullMsg = generateWAMessageFromContent(jid, message, {
1542
+ logger,
1543
+ userJid: authState.creds.me?.id,
1544
+ messageId: options.messageId || generateMessageIDV2(jid),
1545
+ quoted,
1546
+ ...options
1547
+ });
1548
+ await relayRichMessage(jid, fullMsg, options);
1549
+ return fullMsg;
1550
+ },
1551
+ sendList: async (jid, title, items, quoted, options = {}) => {
1552
+ const { message, messageId } = generateListContent(title, items, quoted, options);
1553
+ const fullMsg = generateWAMessageFromContent(jid, message, {
1554
+ logger,
1555
+ userJid: authState.creds.me?.id,
1556
+ messageId: options.messageId || messageId || generateMessageIDV2(jid),
1557
+ quoted,
1558
+ ...options
1559
+ });
1560
+ await relayRichMessage(jid, fullMsg, options);
1561
+ return fullMsg;
1562
+ },
1563
+ sendCodeBlock: async (jid, code, quoted, options = {}) => {
1564
+ const { message, messageId } = generateCodeBlockContent(code, quoted, options);
1565
+ const fullMsg = generateWAMessageFromContent(jid, message, {
1566
+ logger,
1567
+ userJid: authState.creds.me?.id,
1568
+ messageId: options.messageId || messageId || generateMessageIDV2(jid),
1569
+ quoted,
1570
+ ...options
1571
+ });
1572
+ await relayRichMessage(jid, fullMsg, options);
1573
+ return fullMsg;
1574
+ },
1575
+ sendCarousel: async (jid, cards, quotedOrOptions = {}, maybeOptions = undefined) => {
1576
+ if (!Array.isArray(cards) || cards.length === 0) {
1577
+ throw new Boom('sendCarousel requires a non-empty card array', { statusCode: 400 });
1578
+ }
1579
+ // Support both X4R1S3's original (jid, cards, options) form and
1580
+ // the compatibility form used by working carousel helpers:
1581
+ // (jid, cards, quoted, options).
1582
+ const hasQuotedSignature = maybeOptions !== undefined;
1583
+ const quoted = hasQuotedSignature ? quotedOrOptions : undefined;
1584
+ const options = hasQuotedSignature ? (maybeOptions || {}) : (quotedOrOptions || {});
1585
+ const normalizedCards = cards.map(card => ({
1586
+ ...card,
1587
+ text: card.text ?? card.body?.text,
1588
+ caption: card.caption ?? card.body?.text,
1589
+ footer: card.footer?.text ?? card.footer,
1590
+ nativeFlow: card.nativeFlow ?? card.nativeFlowMessage?.buttons ?? card.buttons ?? [],
1591
+ ...(card.header?.imageMessage ? { image: typeof card.header.imageMessage === 'string' ? { url: card.header.imageMessage } : card.header.imageMessage } : {}),
1592
+ ...(card.header?.videoMessage ? { video: typeof card.header.videoMessage === 'string' ? { url: card.header.videoMessage } : card.header.videoMessage } : {}),
1593
+ ...(card.media?.image ? { image: card.media.image } : {}),
1594
+ ...(card.media?.video ? { video: card.media.video } : {}),
1595
+ ...(card.media?.document ? { document: card.media.document } : {}),
1596
+ ...(card.header?.title ? { title: card.title ?? card.header.title } : {}),
1597
+ ...(card.header?.subtitle ? { subtitle: card.subtitle ?? card.header.subtitle } : {})
1598
+ }));
1599
+ const { text, content, footer, ...messageOptions } = options;
1600
+ delete messageOptions.carouselCardType;
1601
+ const fullMsg = await generateWAMessage(jid, {
1602
+ ...messageOptions,
1603
+ cards: normalizedCards,
1604
+ ...((text ?? content) !== undefined ? { text: text ?? content } : {}),
1605
+ ...(footer !== undefined ? { footer } : {})
1606
+ }, {
1607
+ logger,
1608
+ userJid,
1609
+ upload: waUploadToServer,
1610
+ mediaCache: config.mediaCache,
1611
+ options: config.options,
1612
+ ...options,
1613
+ ...(quoted ? { quoted } : {}),
1614
+ messageId: options.messageId || generateMessageIDV2(jid)
1615
+ });
1616
+ const additionalNodes = [...(options.additionalNodes || [])];
1617
+ await relayMessage(jid, fullMsg.message, {
1618
+ ...options,
1619
+ messageId: fullMsg.key.id,
1620
+ additionalNodes
1621
+ });
1622
+ return fullMsg;
1623
+ },
1624
+ /** Send legacy reply buttons with an optional single media or location header. */
1625
+ replyButton: async (jid, buttons, quotedOrOptions = {}, maybeOptions = undefined) => {
1626
+ if (!jid) throw new Boom('replyButton requires a target JID', { statusCode: 400 });
1627
+ if (!Array.isArray(buttons) || buttons.length === 0) {
1628
+ throw new Boom('replyButton requires at least one button', { statusCode: 400 });
1629
+ }
1630
+ const hasQuotedSignature = !!(quotedOrOptions?.key && quotedOrOptions?.message);
1631
+ const quoted = hasQuotedSignature ? quotedOrOptions : undefined;
1632
+ const options = hasQuotedSignature ? (maybeOptions || {}) : (maybeOptions || quotedOrOptions || {});
1633
+ const normalizeButton = (button, index) => {
1634
+ if (!button || typeof button !== 'object') {
1635
+ throw new Boom(`replyButton button ${index + 1} must be an object`, { statusCode: 400 });
1636
+ }
1637
+ const label = button.text || button.buttonText || button.displayText || `Option ${index + 1}`;
1638
+ if (button.sections) {
1639
+ return {
1640
+ name: 'single_select',
1641
+ paramsJson: JSON.stringify({ title: label, sections: button.sections })
1642
+ };
1643
+ }
1644
+ if (button.name) {
1645
+ return {
1646
+ ...button,
1647
+ paramsJson: typeof button.paramsJson === 'string'
1648
+ ? button.paramsJson
1649
+ : JSON.stringify(button.params || {})
1650
+ };
1651
+ }
1652
+ if (button.url) {
1653
+ return {
1654
+ name: 'cta_url',
1655
+ paramsJson: JSON.stringify({
1656
+ display_text: label,
1657
+ url: button.url,
1658
+ merchant_url: button.merchantUrl || button.url
1659
+ })
1660
+ };
1661
+ }
1662
+ if (button.call || button.phoneNumber) {
1663
+ return {
1664
+ name: 'cta_call',
1665
+ paramsJson: JSON.stringify({ display_text: label, phone_number: button.call || button.phoneNumber })
1666
+ };
1667
+ }
1668
+ if (button.copy || button.copyCode) {
1669
+ return {
1670
+ name: 'cta_copy',
1671
+ paramsJson: JSON.stringify({ display_text: label, copy_code: button.copy || button.copyCode })
1672
+ };
1673
+ }
1674
+ const id = button.command || button.id || button.buttonId;
1675
+ if (!id) throw new Boom(`replyButton button ${index + 1} needs an id, command, or native-flow action`, { statusCode: 400 });
1676
+ return { text: label, id, ...(button.type != null ? { type: button.type } : {}) };
1677
+ };
1678
+ const location = options.location;
1679
+ const documentOptions = options.document && typeof options.document === 'object' ? options.document : {};
1680
+ const media = options.media ?? options.image ?? options.video ?? options.document?.url;
1681
+ const hasExplicitMedia = options.image != null || options.video != null || options.document != null || options.media != null;
1682
+ if (location && hasExplicitMedia) {
1683
+ throw new Boom('replyButton accepts one header attachment; choose either location or media', { statusCode: 400 });
1684
+ }
1685
+ if (hasExplicitMedia && media == null) {
1686
+ throw new Boom('replyButton media header requires an image, video, or document source', { statusCode: 400 });
1687
+ }
1688
+ const content = { buttons: buttons.map(normalizeButton) };
1689
+ if (options.footer !== undefined) content.footer = options.footer;
1690
+ if (options.title !== undefined) content.title = options.title;
1691
+ const text = options.text ?? options.caption ?? '';
1692
+ if (location) {
1693
+ content.location = {
1694
+ ...location,
1695
+ ...(location.description && !location.address ? { address: location.description } : {})
1696
+ };
1697
+ content.caption = text;
1698
+ }
1699
+ else if (hasExplicitMedia) {
1700
+ const source = media == null ? options.document : media;
1701
+ const sourceName = String(options.filename || documentOptions.filename || (typeof source === 'string' ? source : source?.url || '')).toLowerCase();
1702
+ const mimeType = options.mimetype || documentOptions.mimetype || source?.mimetype || '';
1703
+ const extension = sourceName.split(/[?#]/)[0].split('.').pop();
1704
+ let mediaType = options.mediaType || (options.document ? 'document' : options.video ? 'video' : undefined);
1705
+ if (!mediaType) {
1706
+ mediaType = mimeType.startsWith('video/') || ['mp4', 'mov', 'm4v', '3gp'].includes(extension) ? 'video' : 'image';
1707
+ }
1708
+ if (!['image', 'video', 'document'].includes(mediaType)) {
1709
+ throw new Boom('replyButton mediaType must be image, video, or document', { statusCode: 400 });
1710
+ }
1711
+ const mediaInput = typeof source === 'string' ? { url: source } : source;
1712
+ content[mediaType] = mediaInput;
1713
+ if (mediaType === 'document') {
1714
+ content.fileName = options.filename || documentOptions.filename || 'file';
1715
+ if (mimeType) content.mimetype = mimeType;
1716
+ }
1717
+ content.caption = text;
1718
+ }
1719
+ else {
1720
+ content.text = text;
1721
+ }
1722
+ const {
1723
+ text: _text, caption: _caption, footer: _footer, title: _title,
1724
+ location: _location, media: _media, image: _image, video: _video,
1725
+ document: _document, filename: _filename, mimetype: _mimetype,
1726
+ mediaType: _mediaType, sendOptions: nestedSendOptions = {},
1727
+ ...transportOptions
1728
+ } = options;
1729
+ return socket.sendMessage(jid, content, {
1730
+ ...transportOptions,
1731
+ ...nestedSendOptions,
1732
+ ...(quoted ? { quoted } : {})
1733
+ });
1734
+ },
1735
+ /** Send a motion photo from its video and optional still image/thumbnail. */
1736
+ sendPhotoLive: async (jid, content, quoted, options = {}) => {
1737
+ if (!jid) throw new Boom('sendPhotoLive requires a target JID', { statusCode: 400 });
1738
+ return sendLivePhoto(jid, content, quoted, options);
1739
+ },
1740
+ /** Send a file; `photo_live: true` pairs a still with its motion-video child. */
1741
+ sendFile: async (jid, media, filename = '', caption = '', quoted, options = {}) => {
1742
+ if (!jid) throw new Boom('sendFile requires a target JID', { statusCode: 400 });
1743
+ if (options.photo_live || options.photoLive) {
1744
+ return sendLivePhoto(jid, {
1745
+ video: media,
1746
+ image: options.image,
1747
+ thumbnail: options.thumbnail,
1748
+ videoThumbnail: options.videoThumbnail,
1749
+ caption,
1750
+ motionPhotoPresentationOffsetMs: options.motionPhotoPresentationOffsetMs ?? options.presentationOffsetMs
1751
+ }, quoted, options);
1752
+ }
1753
+ const sourceName = String(filename || options.fileName || (typeof media === 'string' ? media : media?.url || '')).toLowerCase();
1754
+ const extension = sourceName.split(/[?#]/)[0].split('.').pop();
1755
+ const mimeType = options.mimetype || media?.mimetype || '';
1756
+ const mediaType = options.mediaType || (options.document ? 'document' : mimeType.startsWith('image/') ? 'image' : mimeType.startsWith('video/') ? 'video' : mimeType.startsWith('audio/') ? 'audio' : ['jpg', 'jpeg', 'png', 'gif', 'webp', 'heic'].includes(extension) ? 'image' : ['mp4', 'mov', 'm4v', '3gp', 'webm'].includes(extension) ? 'video' : ['mp3', 'ogg', 'opus', 'wav', 'm4a', 'aac'].includes(extension) ? 'audio' : 'document');
1757
+ if (!['image', 'video', 'audio', 'document'].includes(mediaType)) {
1758
+ throw new Boom('sendFile mediaType must be image, video, audio, or document', { statusCode: 400 });
1759
+ }
1760
+ const source = typeof media === 'string' ? { url: media } : media;
1761
+ const message = {
1762
+ [mediaType]: source,
1763
+ caption,
1764
+ ...(filename || options.fileName ? { fileName: filename || options.fileName } : {}),
1765
+ ...(mimeType ? { mimetype: mimeType } : {}),
1766
+ ...(mediaType === 'audio' && options.ptt ? { ptt: true } : {})
1767
+ };
1768
+ const { photo_live: _photoLive, photoLive: _photoLiveCamel, thumbnail: _thumbnail, ...sendOptions } = options;
1769
+ return socket.sendMessage(jid, message, {
1770
+ ...sendOptions,
1771
+ ...(quoted ? { quoted } : {})
1772
+ });
1773
+ },
1774
+ /** Send or edit a textual progress bar; pass messageKey to update in place. */
1775
+ sendProgress: async (jid, text, quotedOrOptions = {}, maybeOptions = undefined) => {
1776
+ if (!jid) throw new Boom('sendProgress requires a target JID', { statusCode: 400 });
1777
+ const hasQuotedSignature = !!(quotedOrOptions?.key && quotedOrOptions?.message);
1778
+ const quoted = hasQuotedSignature ? quotedOrOptions : undefined;
1779
+ const options = hasQuotedSignature ? (maybeOptions || {}) : (maybeOptions || quotedOrOptions || {});
1780
+ const progress = Number(options.progress ?? 0);
1781
+ if (!Number.isFinite(progress) || progress < 0 || progress > 100) {
1782
+ throw new Boom('sendProgress progress must be between 0 and 100', { statusCode: 400 });
1783
+ }
1784
+ const width = Math.max(4, Math.min(40, Math.floor(Number(options.width) || 12)));
1785
+ const percent = Math.round(progress);
1786
+ const filled = Math.round(width * percent / 100);
1787
+ const bar = `[${'█'.repeat(filled)}${'░'.repeat(width - filled)}] ${percent}%`;
1788
+ const content = { text: `${String(text || '')}${text ? '\n' : ''}${bar}` };
1789
+ const messageKey = options.messageKey || options.editKey;
1790
+ if (messageKey) content.edit = messageKey;
1791
+ const {
1792
+ progress: _progress, width: _width, messageKey: _messageKey, editKey: _editKey,
1793
+ sendOptions: nestedSendOptions = {}, ...sendOptions
1794
+ } = options;
1795
+ return socket.sendMessage(jid, content, {
1796
+ ...sendOptions,
1797
+ ...nestedSendOptions,
1798
+ ...(quoted ? { quoted } : {})
1799
+ });
1800
+ },
1801
+ /** Send text with a custom external preview card (thumbnail, title, URL and attribution). */
1802
+ sendMessageModify: async (jid, text, quotedOrOptions = {}, maybeOptions = undefined) => {
1803
+ if (!jid) throw new Boom('sendMessageModify requires a target JID', { statusCode: 400 });
1804
+ const hasQuotedSignature = !!(quotedOrOptions?.key && quotedOrOptions?.message);
1805
+ const quoted = hasQuotedSignature ? quotedOrOptions : undefined;
1806
+ const options = hasQuotedSignature ? (maybeOptions || {}) : (maybeOptions || quotedOrOptions || {});
1807
+ const thumbnail = options.thumbnail;
1808
+ const thumbnailSource = typeof thumbnail === 'string' ? thumbnail : thumbnail?.url;
1809
+ const thumbnailUrl = thumbnailSource && /^https?:\/\//i.test(thumbnailSource)
1810
+ ? thumbnailSource
1811
+ : options.thumbnailUrl || options.originalImageUrl;
1812
+ let thumbnailBuffer;
1813
+ if (Buffer.isBuffer(thumbnail) || thumbnail instanceof Uint8Array) {
1814
+ thumbnailBuffer = Buffer.from(thumbnail);
1815
+ }
1816
+ else if (typeof thumbnailSource === 'string' && !/^https?:\/\//i.test(thumbnailSource)) {
1817
+ try {
1818
+ thumbnailBuffer = (await extractImageThumb(thumbnailSource, 192)).buffer;
1819
+ }
1820
+ catch (error) {
1821
+ throw new Boom(`sendMessageModify could not read thumbnail: ${error.message}`, { statusCode: 400 });
1822
+ }
1823
+ }
1824
+ const externalAdReply = {
1825
+ title: options.title || '',
1826
+ body: options.description || options.body || '',
1827
+ mediaType: thumbnailBuffer || thumbnailUrl ? 1 : 0,
1828
+ ...(thumbnailBuffer ? { thumbnail: thumbnailBuffer } : {}),
1829
+ ...(thumbnailUrl ? { thumbnailUrl, originalImageUrl: thumbnailUrl } : {}),
1830
+ ...(options.url ? { mediaUrl: options.url, sourceUrl: options.url } : {}),
1831
+ showAdAttribution: options.ads ?? false,
1832
+ renderLargerThumbnail: options.largeThumb ?? options.largeThumbnail ?? true
1833
+ };
1834
+ const message = {
1835
+ text: String(text ?? ''),
1836
+ externalAdReply,
1837
+ ...(options.icon ? { favicon: typeof options.icon === 'string' ? { url: options.icon } : options.icon } : {})
1838
+ };
1839
+ const {
1840
+ title: _title, description: _description, body: _body, url: _url,
1841
+ thumbnail: _thumbnailValue, thumbnailUrl: _thumbnailUrl,
1842
+ originalImageUrl: _originalImageUrl, icon: _icon,
1843
+ ads: _ads, largeThumb: _largeThumb, largeThumbnail: _largeThumbnail,
1844
+ ratio: _ratio, type: _type, sendOptions: nestedSendOptions = {},
1845
+ ...transportOptions
1846
+ } = options;
1847
+ return socket.sendMessage(jid, message, {
1848
+ ...transportOptions,
1849
+ ...nestedSendOptions,
1850
+ ...(quoted ? { quoted } : {})
1851
+ });
1852
+ },
1853
+ /** Compatibility alias for sendMessageModify. */
1854
+ sendMessageModifyV2: async (jid, text, quotedOrOptions = {}, maybeOptions = undefined) =>
1855
+ socket.sendMessageModify(jid, text, quotedOrOptions, maybeOptions),
1856
+ sendLatex: async (jid, quoted, options = {}) => {
1857
+ const { message, messageId } = generateLatexContent(quoted, { expressions: [], ...options });
1858
+ const fullMsg = generateWAMessageFromContent(jid, message, {
1859
+ logger,
1860
+ userJid: authState.creds.me?.id,
1861
+ messageId: options.messageId || messageId || generateMessageIDV2(jid),
1862
+ quoted,
1863
+ ...options
1864
+ });
1865
+ await relayRichMessage(jid, fullMsg, options);
1866
+ return fullMsg;
1867
+ },
1868
+ /**
1869
+ * Send LaTeX as rendered PNG image (like Meta AI does).
1870
+ * Uses codecogs.com to render LaTeX to PNG, then sends as rich response.
1871
+ * @param {string} jid - Chat JID
1872
+ * @param {object} options - { text, expressions: [{ latexExpression }], headerText, footer }
1873
+ */
1874
+ sendLatexImage: async (jid, options = {}) => {
1875
+ const { text, expressions = [], headerText, footer } = options;
1876
+ const renderedExpressions = expressions.map(expr => {
1877
+ const latex = expr.latexExpression || expr.expression || expr;
1878
+ // Encode LaTeX for codecogs URL
1879
+ const encoded = encodeURIComponent(latex).replace(/'/g, '%27');
1880
+ const url = `https://latex.codecogs.com/png.latex?${encoded}`;
1881
+ return {
1882
+ latexExpression: latex,
1883
+ url,
1884
+ width: expr.width || 400,
1885
+ height: expr.height || 100
1886
+ };
1887
+ });
1888
+ const { message, messageId } = generateLatexContent(null, {
1889
+ text,
1890
+ expressions: renderedExpressions,
1891
+ headerText,
1892
+ footer
1893
+ });
1894
+ const fullMsg = generateWAMessageFromContent(jid, message, {
1895
+ logger,
1896
+ userJid: authState.creds.me?.id,
1897
+ messageId: options.messageId || messageId || generateMessageIDV2(jid),
1898
+ ...options
1899
+ });
1900
+ await relayRichMessage(jid, fullMsg, options);
1901
+ return fullMsg;
1902
+ },
1903
+ sendMetaAI: async (a, b, c = {}) => {
1904
+ // Supports both (text, opts) and the historical (jid, text, opts)
1905
+ // call shape. The payload below mirrors the verified WA-Web Hatch send.
1906
+ const legacySignature = typeof b === 'string';
1907
+ const text = legacySignature ? b : a;
1908
+ const opts = legacySignature ? c : (b || {});
1909
+ const META_AI_BOT_JID = '867051314767696@bot';
1910
+ const META_AI_FBID = '867051314767696';
1911
+ const jid = opts.jid || META_AI_BOT_JID;
1912
+ const isGroup = jid.endsWith('@g.us');
1913
+ const invokerJid = opts.invokerJid || authState.creds.me?.id;
1914
+ const messageSecret = opts.messageSecret || randomBytes(32);
1915
+ const rendering = {
1916
+ bloksVersioningId: 'd7c89519fd412464e4a4ddd60b2e5fa57c5000766a697d60835246ef0952daba',
1917
+ pixelDensity: 2.625
1918
+ };
1919
+ const botMetadata = isGroup
1920
+ ? {
1921
+ botGroupMetadata: {
1922
+ participantsMetadata: [{ botFbid: opts.botFbid || META_AI_FBID }]
1923
+ },
1924
+ botRenderingConfigMetadata: rendering
1925
+ }
1926
+ : {
1927
+ personaId: jid,
1928
+ invokerJid,
1929
+ sessionMetadata: {
1930
+ sessionId: opts.sessionId || randomUUID(),
1931
+ sessionSource: 3
1932
+ },
1933
+ capabilityMetadata: {
1934
+ capabilities: opts.capabilities || Array.from({ length: 72 }, (_, i) => i + 1)
1935
+ },
1936
+ botMetricsMetadata: {
1937
+ destinationId: jid,
1938
+ destinationEntryPoint: 2
1939
+ }
1940
+ };
1941
+ const content = isGroup
1942
+ ? (opts.mention
1943
+ ? { extendedTextMessage: { text, contextInfo: { mentionedJid: [META_AI_BOT_JID] } } }
1944
+ : { conversation: text })
1945
+ : { extendedTextMessage: { text } };
1946
+ const message = {
1947
+ ...content,
1948
+ messageContextInfo: {
1949
+ messageSecret,
1950
+ botMetadata,
1951
+ ...(opts.conversationContext?.length ? { aiConversationContext: opts.conversationContext } : {})
1952
+ }
1953
+ };
1954
+ const msgId = generateMessageIDV2(invokerJid || '');
1955
+ const relayOptions = {
1956
+ messageId: msgId,
1957
+ ...(opts.quoted ? { quoted: opts.quoted } : {}),
1958
+ ...(opts.links ? { links: opts.links } : {}),
1959
+ additionalNodes: [{
1960
+ tag: 'bot',
1961
+ attrs: {
1962
+ persona_type: opts.personaType || 'default',
1963
+ agent_engagement_type: opts.agentEngagementType || (isGroup ? 'group_chat' : 'direct_chat'),
1964
+ mode_selected: opts.modeSelected || '0'
1965
+ }
1966
+ }]
1967
+ };
1968
+ await relayMessage(jid, message, relayOptions);
1969
+ return msgId;
1970
+ },
1971
+ // Additive New-compatible AI-rich helpers. Existing Gen4/table/grid/carousel APIs remain unchanged.
1972
+ sendRichMedia: async (jid, content = {}, quoted, options = {}) => {
1973
+ const contentMessage = prepareRichResponseMessage({ ...content, noDonation: options.noDonation ?? true });
1974
+ const generated = generateWAMessageFromContent(jid, contentMessage, {
1975
+ logger,
1976
+ userJid: authState.creds.me?.id,
1977
+ messageId: options.messageId || generateMessageIDV2(jid),
1978
+ quoted,
1979
+ ...options
1980
+ });
1981
+ await relayRichMessage(jid, generated, options);
1982
+ return { ...generated, messageId: generated.key.id };
1983
+ },
1984
+ /**
1985
+ * Send native X4R1S3 rich media with the additive New compatibility field
1986
+ * compatibility sections enabled. The native serializer is retained.
1987
+ */
1988
+ sendNewRichMedia: async (jid, content = {}, quoted, options = {}) => {
1989
+ return socket.sendRichMedia(jid, { ...content, compatibility: 'both' }, quoted, options);
1990
+ },
1991
+ /**
1992
+ * Send a native AI image/video generation card. The returned messageId
1993
+ * is required by updateRichGeneration() for an in-place edit.
1994
+ */
1995
+ sendRichGeneration: async (jid, content = {}, quoted, options = {}) => {
1996
+ const generated = prepareRichGenerationMessage({
1997
+ ...content,
1998
+ responseId: options.responseId,
1999
+ forwarded: options.forwarded !== false
2000
+ });
2001
+ const fullMsg = generateWAMessageFromContent(jid, generated.message, {
2002
+ logger,
2003
+ userJid: authState.creds.me?.id,
2004
+ messageId: options.messageId || generated.messageId || generateMessageIDV2(jid),
2005
+ quoted,
2006
+ ...options,
2007
+ });
2008
+ await relayRichMessage(jid, fullMsg, options);
2009
+ return { ...generated, messageId: fullMsg.key.id };
2010
+ },
2011
+ /**
2012
+ * Replace the generation primitive in an existing rich response.
2013
+ * This uses WhatsApp's edit protocol (type 14), matching the native
2014
+ * rich-message replacement lifecycle used by compatible clients.
2015
+ */
2016
+ updateRichGeneration: async (jid, targetId, content = {}, options = {}) => {
2017
+ if (!jid) throw new Boom('updateRichGeneration requires a target JID', { statusCode: 400 });
2018
+ if (!targetId) throw new Boom('updateRichGeneration requires the original message ID', { statusCode: 400 });
2019
+ const generated = prepareRichGenerationMessage({
2020
+ ...content,
2021
+ responseId: options.responseId,
2022
+ itemId: options.itemId || content.itemId,
2023
+ forwarded: options.forwarded !== false
2024
+ });
2025
+ const editedMessage = generateWAMessageFromContent(jid, {
2026
+ botForwardedMessage: {
2027
+ message: {
2028
+ protocolMessage: {
2029
+ key: { remoteJid: jid, fromMe: true, id: targetId },
2030
+ type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
2031
+ editedMessage: generated.message
2032
+ }
2033
+ }
2034
+ }
2035
+ }, { messageId: generateMessageIDV2(jid) });
2036
+ await relayMessage(jid, editedMessage.message, { messageId: editedMessage.key.id });
2037
+ return { ...generated, messageId: editedMessage.key.id, targetId };
2038
+ },
2039
+ sendReels: async (jid, reels, quoted, options = {}) => socket.sendRichMedia(jid, { contentText: options.text || '', reels }, quoted, options),
2040
+ sendRichSources: async (jid, text, sources, quoted, options = {}) => socket.sendRichMedia(jid, { contentText: text, sources }, quoted, options),
2041
+ sendLink: async (jid, text, links, quoted, options = {}) => socket.sendRichSources(jid, text, links, quoted, options),
2042
+ sendLinkV2: async (jid, text, links, quoted, options = {}) => socket.sendRichSources(jid, text, links, quoted, options),
2043
+ sendRichAIResponse: async (jid, content, quoted, options = {}) => {
2044
+ const generated = generateRichAIResponseContent(content, quoted, options);
2045
+ const fullMsg = generateWAMessageFromContent(jid, generated.message, {
2046
+ logger,
2047
+ userJid: authState.creds.me?.id,
2048
+ messageId: options.messageId || generated.messageId || generateMessageIDV2(jid),
2049
+ quoted,
2050
+ ...options
2051
+ });
2052
+ await relayRichMessage(jid, fullMsg, options);
2053
+ return fullMsg;
2054
+ },
2055
+ /**
2056
+ * Send one tolerant AIRich/unified response containing every supported
2057
+ * section present in `content`. An exclusive { a2ui: ... } payload is
2058
+ * also routed to the interactive A2UI sender. AIRich and A2UI cannot be
2059
+ * combined into one WhatsApp message envelope.
2060
+ */
2061
+ sendX4R1S3Message: async (jid, content = {}, quoted, options = {}) => {
2062
+ if (!jid) throw new Boom('sendX4R1S3Message requires a target JID', { statusCode: 400 });
2063
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
2064
+ throw new Boom('sendX4R1S3Message content must be an object', { statusCode: 400 });
2065
+ }
2066
+
2067
+ if (Object.hasOwn(content, 'a2ui')) {
2068
+ const { a2ui, ...otherContent } = content;
2069
+ if (!a2ui || typeof a2ui !== 'object' || Array.isArray(a2ui)) {
2070
+ throw new Boom('sendX4R1S3Message a2ui must be an A2UI content object', { statusCode: 400 });
2071
+ }
2072
+ if (Object.keys(otherContent).length) {
2073
+ throw new Boom('sendX4R1S3Message accepts either AIRich sections or an exclusive { a2ui } payload; the two message envelopes cannot be combined', { statusCode: 400 });
2074
+ }
2075
+ return socket.sendA2UIMessage(jid, a2ui, {
2076
+ ...options,
2077
+ quoted: options.quoted ?? quoted
2078
+ });
2079
+ }
2080
+
2081
+ const generated = generateX4R1S3RichAIResponseContent(content, quoted, options);
2082
+ const fullMsg = generateWAMessageFromContent(jid, generated.message, {
2083
+ logger,
2084
+ userJid: authState.creds.me?.id,
2085
+ messageId: options.messageId || generated.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2086
+ quoted,
2087
+ ...options,
2088
+ });
2089
+
2090
+ await relayRichMessage(jid, fullMsg, options);
2091
+
2092
+ if (config.emitOwnEvents) {
2093
+ process.nextTick(async () => {
2094
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2095
+ });
2096
+ }
2097
+ return fullMsg;
2098
+ },
2099
+ /**
2100
+ * Send a non-interactive themed text card inside one AIRich unified
2101
+ * response. Optional rich media fields are composed into that
2102
+ * same response by sendX4R1S3Message; this helper never adds menu buttons.
2103
+ */
2104
+ sendUnifiedThemedMessage: async (jid, content = {}, quoted, options = {}) => {
2105
+ if (!jid) throw new Boom('sendUnifiedThemedMessage requires a target JID', { statusCode: 400 });
2106
+ const normalized = normalizeUnifiedThemedMessageContent(content);
2107
+ return socket.sendX4R1S3Message(jid, normalized, quoted, options);
2108
+ },
2109
+ /**
2110
+ * Send a compact forwarded AIRich label bubble. This preserves the
2111
+ * base64 unified-response wire shape used by direct relayMessage calls.
2112
+ */
2113
+ sendRichLabelMessage: async (jid, content = {}, options = {}) => {
2114
+ if (!jid) throw new Boom('sendRichLabelMessage requires a target JID', { statusCode: 400 });
2115
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
2116
+ throw new Boom('sendRichLabelMessage content must be an object', { statusCode: 400 });
2117
+ }
2118
+ const message = buildRichLabelMessage(content);
2119
+ await relayMessage(jid, message, options);
2120
+ return message;
2121
+ },
2122
+ captureAndResendUnifiedResponse: async (jid, metaAiMsg, quoted, options = {}) => {
2123
+ const captured = captureUnifiedResponse(metaAiMsg);
2124
+ if (!captured) {
2125
+ throw new Boom('captureAndResendUnifiedResponse: message contains no unifiedResponse data');
2126
+ }
2127
+ const generated = generateUnifiedResponseContent(quoted, captured);
2128
+ const fullMsg = generateWAMessageFromContent(jid, generated.message, {
2129
+ logger,
2130
+ userJid: authState.creds.me?.id,
2131
+ messageId: generated.messageId || generateMessageIDV2(jid),
2132
+ quoted
2133
+ });
2134
+ await relayRichMessage(jid, fullMsg, options);
2135
+ return fullMsg;
2136
+ },
2137
+ updateMediaMessage: async (message) => {
2138
+ const content = assertMediaContent(message.message);
2139
+ const mediaKey = content.mediaKey;
2140
+ const meId = authState.creds.me.id;
2141
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
2142
+ let error = undefined;
2143
+ await Promise.all([
2144
+ sendNode(node),
2145
+ waitForMsgMediaUpdate(async (update) => {
2146
+ const result = update.find(c => c.key.id === message.key.id);
2147
+ if (result) {
2148
+ if (result.error) {
2149
+ error = result.error;
2150
+ }
2151
+ else {
2152
+ try {
2153
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
2154
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
2155
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
2156
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
2157
+ data: media,
2158
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
2159
+ });
2160
+ }
2161
+ content.directPath = media.directPath;
2162
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
2163
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
2164
+ }
2165
+ catch (err) {
2166
+ error = err;
2167
+ }
2168
+ }
2169
+ return true;
2170
+ }
2171
+ })
2172
+ ]);
2173
+ if (error) {
2174
+ throw error;
2175
+ }
2176
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
2177
+ return message;
2178
+ },
2179
+ /**
2180
+ * Send a prompt to the Meta AI bot in `jid` and resolve with the
2181
+ * decrypted bot response (text, image or video message).
2182
+ *
2183
+ * - In an AI group: the bot is @-mentioned with its participant JID
2184
+ * (resolved from metadata, falling back to the canonical `@bot` JID).
2185
+ * - In a 1:1 bot chat: `jid` is the bot JID itself.
2186
+ *
2187
+ * The returned message is the complete decrypted response — the msmsg
2188
+ * pipeline already drops streaming partials and only surfaces `full`/
2189
+ * `last` bot responses, so media (image/video) and text both arrive
2190
+ * whole. Download media with `downloadMediaMessage(msg)`.
2191
+ *
2192
+ * Options:
2193
+ * timeout — ms to wait before rejecting (default 60000)
2194
+ * onPartial — optional callback(updateMessage, key) fired for bot
2195
+ * message edits in the chat (best-effort streaming)
2196
+ * botUser — canonical bot JID (default META_AI_BOT_JID)
2197
+ * mentions — extra JIDs to mention alongside the bot
2198
+ * ...rest — forwarded to sendMessage (quoted, linkPreview, ...)
2199
+ */
2200
+ aiPrompt: async (jid, prompt, options = {}) => {
2201
+ const {
2202
+ timeout = 60_000,
2203
+ onPartial,
2204
+ botUser = META_AI_BOT_JID,
2205
+ mentions = [],
2206
+ ...sendOptions
2207
+ } = options;
2208
+ if (!jid || typeof prompt !== 'string' || !prompt.trim()) {
2209
+ throw new Error('aiPrompt requires a chat JID and a non-empty prompt');
2210
+ }
2211
+
2212
+ const botJids = await collectMetaAIBotParticipantJids(sock, jid, botUser);
2213
+ const isGroup = isJidGroup(jid);
2214
+ const allMentions = [...new Set([...mentions, ...botJids])];
2215
+
2216
+ return new Promise((resolve, reject) => {
2217
+ let promptId;
2218
+ let settled = false;
2219
+ const cleanup = () => {
2220
+ clearTimeout(timer);
2221
+ ev.off('messages.upsert', onUpsert);
2222
+ if (typeof onPartial === 'function') {
2223
+ ev.off('messages.update', onUpdate);
2224
+ }
2225
+ };
2226
+ const settle = (fn, value) => {
2227
+ if (settled) {
2228
+ return;
2229
+ }
2230
+ settled = true;
2231
+ cleanup();
2232
+ fn(value);
2233
+ };
2234
+
2235
+ const timer = setTimeout(
2236
+ () => settle(reject, new Error(`aiPrompt timed out after ${timeout}ms waiting for Meta AI in ${jid}`)),
2237
+ timeout
2238
+ );
2239
+
2240
+ const onUpsert = ({ messages }) => {
2241
+ for (const msg of messages) {
2242
+ if (isMetaAIBotResponse(msg, jid, promptId, [...botJids])) {
2243
+ settle(resolve, msg);
2244
+ return;
2245
+ }
2246
+ }
2247
+ };
2248
+
2249
+ const onUpdate = ({ updates }) => {
2250
+ if (typeof onPartial !== 'function') {
2251
+ return;
2252
+ }
2253
+ for (const update of updates) {
2254
+ if (!update.key || update.key.fromMe || update.key.remoteJid !== jid) {
2255
+ continue;
2256
+ }
2257
+ const sender = (update.key.participant || update.key.remoteJid).replace(/:\d+$/, '');
2258
+ const isBot =
2259
+ isJidMetaAI(sender) ||
2260
+ [...botJids].some(j => jidNormalizedUser(j.replace(/:\d+$/, '')) === jidNormalizedUser(sender));
2261
+ if (isBot && update.message) {
2262
+ onPartial(update.message, update.key);
2263
+ }
2264
+ }
2265
+ };
2266
+
2267
+ ev.on('messages.upsert', onUpsert);
2268
+ if (typeof onPartial === 'function') {
2269
+ ev.on('messages.update', onUpdate);
2270
+ }
2271
+
2272
+ const content = { text: prompt };
2273
+ if (isGroup) {
2274
+ content.mentions = allMentions;
2275
+ }
2276
+ Object.assign(content, sendOptions);
2277
+ (async () => {
2278
+ try {
2279
+ const fullMsg = await generateWAMessage(jid, content, {
2280
+ logger,
2281
+ userJid: authState.creds.me.id,
2282
+ upload: waUploadToServer,
2283
+ mediaCache: config.mediaCache,
2284
+ options: config.options,
2285
+ ...sendOptions,
2286
+ messageId: sendOptions.messageId || generateMessageIDV2(authState.creds.me.id)
2287
+ });
2288
+ await relayMessage(jid, fullMsg.message, {
2289
+ messageId: fullMsg.key.id,
2290
+ useCachedGroupMetadata: sendOptions.useCachedGroupMetadata,
2291
+ statusJidList: sendOptions.statusJidList
2292
+ });
2293
+ if (config.emitOwnEvents) {
2294
+ process.nextTick(async () => {
2295
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2296
+ });
2297
+ }
2298
+ promptId = fullMsg.key.id;
2299
+ }
2300
+ catch (err) {
2301
+ settle(reject, err);
2302
+ }
2303
+ })();
2304
+ });
2305
+ },
2306
+ /**
2307
+ * Schedule Baileys-generated content using WhatsApp's native
2308
+ * conditional-reveal envelope. `scheduledAt` accepts a Date, ISO-8601
2309
+ * string, or Unix timestamp in seconds/milliseconds. Use `livePhoto`
2310
+ * or `pairedMedia` for associated multi-message media.
2311
+ */
2312
+ scheduleMessage: async (jid, content, scheduledAt, options = {}) => {
2313
+ if (typeof jid !== 'string' || !jid) {
2314
+ throw new Boom('scheduleMessage requires a chat JID', { statusCode: 400 });
2315
+ }
2316
+ if (!(isJidGroup(jid) || isPnUser(jid) || isLidUser(jid) || isHostedPnUser(jid) || isHostedLidUser(jid))) {
2317
+ throw new Boom('Native scheduled messages are only supported for direct chats and groups', { statusCode: 400 });
2318
+ }
2319
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
2320
+ throw new Boom('scheduleMessage requires a Baileys message content object', { statusCode: 400 });
2321
+ }
2322
+
2323
+ const livePhotoFlag = content.livePhoto === true || content.photo_live === true || content.photoLive === true;
2324
+ const livePhotoContent = content.livePhoto && typeof content.livePhoto === 'object'
2325
+ ? content.livePhoto
2326
+ : livePhotoFlag
2327
+ ? Object.fromEntries(Object.entries(content).filter(([key]) => !['livePhoto', 'photo_live', 'photoLive'].includes(key)))
2328
+ : undefined;
2329
+ const pairedMedia = content.pairedMedia;
2330
+ if (livePhotoContent && pairedMedia) {
2331
+ throw new Boom('Provide either livePhoto or pairedMedia, not both', { statusCode: 400 });
2332
+ }
2333
+
2334
+ const assertSingleMessageContent = messageContent => {
2335
+ if (!messageContent || typeof messageContent !== 'object' || Array.isArray(messageContent)) {
2336
+ throw new Boom('Each scheduled media pair item must be a Baileys message content object', { statusCode: 400 });
2337
+ }
2338
+ if ('album' in messageContent || (Array.isArray(messageContent.poll?.values) && messageContent.poll.values.some(value => value && typeof value === 'object' && value.image))) {
2339
+ throw new Boom('Native scheduled messages currently accept single-message pair items; albums and image polls are multi-message sends', { statusCode: 400 });
2340
+ }
2341
+ if (messageContent.poll?.pollType) {
2342
+ throw new Boom('Quiz polls are only allowed for newsletters', { statusCode: 400 });
2343
+ }
2344
+ };
2345
+
2346
+ if (livePhotoContent) {
2347
+ if (!livePhotoContent.video) {
2348
+ throw new Boom('livePhoto requires a video source', { statusCode: 400 });
2349
+ }
2350
+ }
2351
+ else if (pairedMedia) {
2352
+ if (!pairedMedia || typeof pairedMedia !== 'object' || Array.isArray(pairedMedia)) {
2353
+ throw new Boom('pairedMedia must contain parent and child message content', { statusCode: 400 });
2354
+ }
2355
+ assertSingleMessageContent(pairedMedia.parent);
2356
+ assertSingleMessageContent(pairedMedia.child);
2357
+ }
2358
+ else {
2359
+ assertSingleMessageContent(content);
2360
+ }
2361
+
2362
+ // Validate before media preparation/upload; the envelope builder
2363
+ // revalidates after generation in case preparation took a long time.
2364
+ normalizeScheduledTime(scheduledAt);
2365
+ const userJid = authState.creds.me.id;
2366
+ const generationOptions = {
2367
+ logger,
2368
+ userJid,
2369
+ getUrlInfo: text => getUrlInfo(text, {
2370
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
2371
+ fetchOpts: { timeout: 3000, ...(httpRequestOptions || {}) },
2372
+ logger,
2373
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
2374
+ }),
2375
+ getProfilePicUrl: sock.profilePictureUrl,
2376
+ getCallLink: sock.createCallLink,
2377
+ upload: waUploadToServer,
2378
+ mediaCache: config.mediaCache,
2379
+ options: config.options,
2380
+ ...options
2381
+ };
2382
+ const prepareSingleMessage = async (messageContent, messageId) => {
2383
+ const normalizedContent = { ...messageContent };
2384
+ const isNeedBizAttrs = Boolean(normalizedContent.secureMetaServiceLabel);
2385
+ delete normalizedContent.secureMetaServiceLabel;
2386
+ const fullMsg = await generateWAMessage(jid, normalizedContent, {
2387
+ ...generationOptions,
2388
+ messageId: messageId || generateMessageIDV2(userJid)
2389
+ });
2390
+ return { fullMsg, isNeedBizAttrs };
2391
+ };
2392
+ const relayScheduledMessage = async (fullMsg, semanticContent, isNeedBizAttrs = false, scheduleNow = Date.now()) => {
2393
+ const scheduledMediaType = getMediaType(normalizeMessageContent(fullMsg.message));
2394
+ const schedule = createScheduledMessageEnvelope(fullMsg.message, scheduledAt, { now: scheduleNow });
2395
+ fullMsg.message = schedule.content;
2396
+ fullMsg.scheduledMessageMetadata = {
2397
+ revealKeyId: schedule.revealKeyId,
2398
+ revealKey: schedule.revealKey,
2399
+ scheduledTime: String(schedule.scheduledTime)
2400
+ };
2401
+
2402
+ const additionalNodes = [...(options.additionalNodes || [])];
2403
+ if (!isJidGroup(jid) && !additionalNodes.some(node => node?.tag === 'bot')) {
2404
+ additionalNodes.push({ tag: 'bot', attrs: { biz_bot: '1' } });
2405
+ }
2406
+ if (semanticContent?.poll) {
2407
+ additionalNodes.push({
2408
+ tag: 'meta',
2409
+ attrs: { polltype: semanticContent.poll.pollType ? 'quiz_creation' : 'creation' }
2410
+ });
2411
+ }
2412
+ if (semanticContent?.event) {
2413
+ additionalNodes.push({ tag: 'meta', attrs: { event_type: 'creation' } });
2414
+ }
2415
+ additionalNodes.push(schedule.additionalNode);
2416
+
2417
+ await relayMessage(jid, fullMsg.message, {
2418
+ messageId: fullMsg.key.id,
2419
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2420
+ addBizAttributes: isNeedBizAttrs,
2421
+ statusJidList: options.statusJidList,
2422
+ statusPrivacy: options.statusPrivacy,
2423
+ mediaTypeOverride: scheduledMediaType,
2424
+ additionalAttributes: options.additionalAttributes,
2425
+ additionalNodes
2426
+ });
2427
+
2428
+ if (config.emitOwnEvents) {
2429
+ process.nextTick(async () => {
2430
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2431
+ });
2432
+ }
2433
+ return fullMsg;
2434
+ };
2435
+
2436
+ if (livePhotoContent) {
2437
+ const scheduledMessages = [];
2438
+ let pairScheduleNow;
2439
+ const parent = await generateWAMessageFromLivePhoto(jid, livePhotoContent, async (_message, _relayOptions, fullMsg) => {
2440
+ pairScheduleNow ??= Date.now();
2441
+ scheduledMessages.push(await relayScheduledMessage(fullMsg, livePhotoContent, false, pairScheduleNow));
2442
+ }, generationOptions);
2443
+ const child = scheduledMessages.find(message => message.key.id !== parent.key.id);
2444
+ if (child) {
2445
+ parent.pairedMessage = child;
2446
+ }
2447
+ return parent;
2448
+ }
2449
+
2450
+ if (pairedMedia) {
2451
+ const associationType = typeof pairedMedia.associationType === 'string'
2452
+ ? proto.MessageAssociation.AssociationType[pairedMedia.associationType]
2453
+ : pairedMedia.associationType ?? proto.MessageAssociation.AssociationType.MOTION_PHOTO;
2454
+ if (!Number.isInteger(associationType) || associationType <= 0 || !proto.MessageAssociation.AssociationType[associationType]) {
2455
+ throw new Boom('pairedMedia.associationType must be a known MessageAssociation type', { statusCode: 400 });
2456
+ }
2457
+ const parent = await prepareSingleMessage(pairedMedia.parent, options.messageId || generateMessageIDV2(userJid));
2458
+ const child = await prepareSingleMessage(pairedMedia.child, generateMessageIDV2(userJid));
2459
+ associateScheduledMessages(parent.fullMsg, child.fullMsg, associationType);
2460
+ const pairScheduleNow = Date.now();
2461
+ await relayScheduledMessage(parent.fullMsg, pairedMedia.parent, parent.isNeedBizAttrs, pairScheduleNow);
2462
+ await relayScheduledMessage(child.fullMsg, pairedMedia.child, child.isNeedBizAttrs, pairScheduleNow);
2463
+ parent.fullMsg.pairedMessage = child.fullMsg;
2464
+ return parent.fullMsg;
2465
+ }
2466
+
2467
+ const { fullMsg, isNeedBizAttrs } = await prepareSingleMessage(content, options.messageId || generateMessageIDV2(userJid));
2468
+ return relayScheduledMessage(fullMsg, content, isNeedBizAttrs);
2469
+ },
2470
+ sendMessage: async (jid, content, options = {}) => {
2471
+ const userJid = authState.creds.me.id;
2472
+ const pollValues = content?.poll?.values;
2473
+ if (Array.isArray(pollValues) && pollValues.some(value => value && typeof value === 'object' && value.image)) {
2474
+ return sendImagePoll(jid, content.poll, options);
2475
+ }
2476
+ if (content?.groupStatus === true && !isJidGroup(jid)) {
2477
+ throw new Boom('groupStatus requires a valid group JID', { statusCode: 400 });
2478
+ }
2479
+
2480
+ // ── X4R1S3 FLAG (Auto-Heal) ──
2481
+ if (content && typeof content === 'object' && content.X4R1S3 === true) {
2482
+ const { X4R1S3: _, retry = {}, fallback = {}, filterSystem = true, ...restContent } = content;
2483
+
2484
+ if (!sock.messageRetryManager) {
2485
+ sock.messageRetryManager = new MessageRetryManager(logger, retry.maxAttempts || 3);
2486
+ }
2487
+
2488
+ options.maxRetries = retry.maxAttempts || 3;
2489
+
2490
+ if (retry.onMacError === 'recreateSession') {
2491
+ options.recreateOnMacError = true;
2492
+ }
2493
+
2494
+ if (fallback.type === 'phone') {
2495
+ options.fallbackToPhone = true;
2496
+ options.fallbackTimeout = fallback.timeout || 10000;
2497
+ }
2498
+
2499
+ const result = await originalSend(jid, restContent, options);
2500
+ return result;
2501
+ }
2502
+
2503
+ // ── MIMIC FLAG ──
2504
+ if (content && typeof content === 'object' && content.mimic) {
2505
+ const { mimic: mimicJid, admin = false, ...restContent } = content;
2506
+
2507
+ if (!mimicJid) {
2508
+ throw new Error('mimic JID is required');
2509
+ }
2510
+
2511
+ return await sendAsMimic(jid, restContent, mimicJid, { ...options, admin });
2512
+ }
2513
+
2514
+ // ── BULK REACTION FLAG (NEW - Doesn't override original react) ──
2515
+ if (content && typeof content === 'object' && content.bulkReact) {
2516
+ const { bulkReact: emoji, messageId, count = 1, fake = false } = content;
2517
+
2518
+ if (!messageId) {
2519
+ throw new Error('messageId is required for bulkReact');
2520
+ }
2521
+
2522
+ return await sendBulkReactions(jid, messageId, emoji, count, fake);
2523
+ }
2524
+
2525
+ // ── STATUS MESSAGES ──
2526
+ if (Array.isArray(jid)) {
2527
+ const { delayMs = 1500 } = options;
2528
+ const allUsers = new Set([jidNormalizedUser(userJid)]);
2529
+ const statusMentionContent = { ...content };
2530
+ const isStatusMedia = Boolean(statusMentionContent.image || statusMentionContent.video || statusMentionContent.audio);
2531
+ if (isStatusMedia && statusMentionContent.text && !statusMentionContent.caption) {
2532
+ statusMentionContent.caption = statusMentionContent.text;
2533
+ delete statusMentionContent.text;
2534
+ }
2535
+ const fullMsg = await generateWAMessage('status@broadcast', statusMentionContent, {
2536
+ logger,
2537
+ userJid,
2538
+ upload: waUploadToServer,
2539
+ mediaCache: config.mediaCache,
2540
+ options: config.options,
2541
+ ...options,
2542
+ messageId: generateMessageIDV2(userJid)
2543
+ });
2544
+ for (const id of jid) {
2545
+ if (isJidGroup(id)) {
2546
+ try {
2547
+ const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
2548
+ for (const participant of groupData.participants) {
2549
+ if (allUsers.has(participant.id))
2550
+ continue;
2551
+ allUsers.add(jidNormalizedUser(participant.id));
2552
+ }
2553
+ }
2554
+ catch (error) {
2555
+ logger.error(`Error getting metadata group from ${id}: ${error}`);
2556
+ }
2557
+ }
2558
+ else if (!allUsers.has(jidNormalizedUser(id))) {
2559
+ allUsers.add(jidNormalizedUser(id));
2560
+ }
2561
+ }
2562
+ await relayMessage('status@broadcast', fullMsg.message, {
2563
+ messageId: fullMsg.key.id,
2564
+ statusJidList: Array.from(allUsers),
2565
+ additionalNodes: [
2566
+ {
2567
+ tag: 'meta',
2568
+ attrs: {},
2569
+ content: [
2570
+ {
2571
+ tag: 'mentioned_users',
2572
+ attrs: {},
2573
+ content: jid.map(id => ({
2574
+ tag: 'to',
2575
+ attrs: { jid: jidNormalizedUser(id) },
2576
+ content: undefined
2577
+ }))
2578
+ }
2579
+ ]
2580
+ }
2581
+ ]
2582
+ });
2583
+ if (config.emitOwnEvents) {
2584
+ process.nextTick(async () => {
2585
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2586
+ });
2587
+ }
2588
+ for (const id of jid) {
2589
+ const isGroup = isJidGroup(id);
2590
+ const sendType = isGroup ? 'groupStatusMentionMessage' : 'statusMentionMessage';
2591
+ const mentionMsg = generateWAMessageFromContent(id, {
2592
+ messageContextInfo: {
2593
+ messageSecret: randomBytes(32)
2594
+ },
2595
+ [sendType]: {
2596
+ message: {
2597
+ protocolMessage: {
2598
+ key: fullMsg.key,
2599
+ type: 25
2600
+ }
2601
+ }
2602
+ }
2603
+ }, {
2604
+ userJid
2605
+ });
2606
+ await relayMessage(id, mentionMsg.message, {
2607
+ additionalNodes: [
2608
+ {
2609
+ tag: 'meta',
2610
+ attrs: isGroup ?
2611
+ { is_group_status_mention: 'true' } :
2612
+ { is_status_mention: 'true' },
2613
+ content: undefined
2614
+ }
2615
+ ]
2616
+ });
2617
+ if (config.emitOwnEvents) {
2618
+ process.nextTick(async () => {
2619
+ await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
2620
+ });
2621
+ }
2622
+ await delay(delayMs);
2623
+ }
2624
+ return fullMsg;
2625
+ }
2626
+ else if ('disappearingMessagesInChat' in content && isJidGroup(jid)) {
2627
+ const { disappearingMessagesInChat } = content;
2628
+ const value = typeof disappearingMessagesInChat === 'boolean'
2629
+ ? disappearingMessagesInChat
2630
+ ? WA_DEFAULT_EPHEMERAL
2631
+ : 0
2632
+ : disappearingMessagesInChat;
2633
+ await groupToggleEphemeral(jid, value);
2634
+ }
2635
+ else if ((jid === STATUS_JID || ('status' in content && content.status === true)) && !('react' in content)) {
2636
+ const {
2637
+ status: _status,
2638
+ backgroundColor: contentBackgroundColor,
2639
+ font: contentFont,
2640
+ statusJidList: contentJidList,
2641
+ ...statusContent
2642
+ } = content;
2643
+ const statusJidList = normalizeStatusJidList(contentJidList || options.statusJidList);
2644
+ const backgroundColor = contentBackgroundColor ?? options.backgroundColor;
2645
+ const font = contentFont ?? options.font;
2646
+ const fullMsg = await generateWAMessage(STATUS_JID, statusContent, {
2647
+ logger,
2648
+ userJid,
2649
+ upload: waUploadToServer,
2650
+ mediaCache: config.mediaCache,
2651
+ options: config.options,
2652
+ ...options,
2653
+ backgroundColor,
2654
+ font,
2655
+ messageId: options.messageId || generateMessageIDV2(userJid)
2656
+ });
2657
+ const relayResult = await relayMessage(STATUS_JID, fullMsg.message, {
2658
+ messageId: fullMsg.key.id,
2659
+ statusJidList,
2660
+ additionalAttributes: {
2661
+ broadcast: 'true',
2662
+ ...(options.additionalAttributes || {})
2663
+ },
2664
+ additionalNodes: options.additionalNodes || []
2665
+ });
2666
+ if (config.emitOwnEvents) {
2667
+ process.nextTick(async () => {
2668
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2669
+ });
2670
+ }
2671
+ fullMsg.relayResult = relayResult;
2672
+ return fullMsg;
2673
+ }
2674
+ else if ('richPreview' in content && content.richPreview === true) {
2675
+ const {
2676
+ richPreview: __rp,
2677
+ text: previewLink,
2678
+ previewTitle,
2679
+ previewDescription,
2680
+ previewImage,
2681
+ groupStatus: isGroupStatus,
2682
+ private: privateAudience,
2683
+ quoted,
2684
+ ...restContent
2685
+ } = content;
2686
+
2687
+ if (!previewLink || typeof previewLink !== 'string') {
2688
+ throw new Boom('richPreview requires a `text` field containing the URL', { statusCode: 400 });
2689
+ }
2690
+
2691
+ const _preview = await buildLinkPreview(
2692
+ previewLink,
2693
+ sock,
2694
+ {
2695
+ customTitle: previewTitle || '',
2696
+ customDesc: previewDescription || '',
2697
+ customImage: Buffer.isBuffer(previewImage) ? previewImage : null
2698
+ }
2699
+ );
2700
+
2701
+ let imageBuffer = _preview.imageBuffer;
2702
+
2703
+ if (!imageBuffer && typeof previewImage === 'string') {
2704
+ try {
2705
+ const res = await fetch(previewImage);
2706
+ imageBuffer = Buffer.from(await res.arrayBuffer());
2707
+ } catch (err) {
2708
+ logger?.warn({ err }, 'richPreview: failed to fetch previewImage URL');
2709
+ }
2710
+ }
2711
+
2712
+ const resolvedTitle = previewTitle || _preview.title || '';
2713
+ const resolvedDescription = previewDescription || _preview.description || '';
2714
+
2715
+ let hq = null;
2716
+ let smallThumb = null;
2717
+ if (imageBuffer) {
2718
+ try {
2719
+ const prepared = await prepareWAMessageMedia(
2720
+ { image: imageBuffer },
2721
+ { upload: waUploadToServer, mediaTypeOverride: 'thumbnail-link' }
2722
+ );
2723
+ hq = prepared.imageMessage;
2724
+ smallThumb = hq?.jpegThumbnail ? Buffer.from(hq.jpegThumbnail) : null;
2725
+ }
2726
+ catch (err) {
2727
+ logger?.warn({ err }, 'richPreview: failed to prepare sharp thumbnail-link media');
2728
+ }
2729
+ }
2730
+
2731
+ const extendedText = {
2732
+ text: previewLink,
2733
+ matchedText: previewLink,
2734
+ canonicalUrl: previewLink,
2735
+ title: resolvedTitle,
2736
+ description: resolvedDescription,
2737
+ previewType: 5,
2738
+ jpegThumbnail: smallThumb || undefined,
2739
+ ...(hq
2740
+ ? {
2741
+ thumbnailDirectPath: hq.directPath,
2742
+ mediaKey: hq.mediaKey,
2743
+ mediaKeyTimestamp: hq.mediaKeyTimestamp,
2744
+ thumbnailWidth: hq.width,
2745
+ thumbnailHeight: hq.height,
2746
+ thumbnailSha256: hq.fileSha256,
2747
+ thumbnailEncSha256: hq.fileEncSha256
2748
+ }
2749
+ : {}),
2750
+ ...restContent
2751
+ };
2752
+
2753
+ if (quoted) {
2754
+ extendedText.contextInfo = {
2755
+ ...(extendedText.contextInfo || {}),
2756
+ stanzaId: quoted.key.id,
2757
+ participant: jidNormalizedUser(quoted.key.fromMe ? userJid : (quoted.key.participant || quoted.key.remoteJid)),
2758
+ quotedMessage: quoted.message
2759
+ };
2760
+ }
2761
+
2762
+ if (isGroupStatus) {
2763
+ extendedText.contextInfo = { ...(extendedText.contextInfo || {}), isGroupStatus: true };
2764
+ }
2765
+
2766
+ if (privateAudience !== undefined && (privateAudience === null || typeof privateAudience !== 'object' || Array.isArray(privateAudience))) {
2767
+ throw new Boom('groupStatus private metadata must be an object', { statusCode: 400 });
2768
+ }
2769
+ if (isGroupStatus && privateAudience && (privateAudience.name != null || privateAudience.emoji != null)) {
2770
+ const name = privateAudience.name == null ? '' : String(privateAudience.name);
2771
+ const emoji = privateAudience.emoji == null ? '' : String(privateAudience.emoji);
2772
+ if (!name && !emoji) {
2773
+ throw new Boom('groupStatus private metadata requires a name or emoji', { statusCode: 400 });
2774
+ }
2775
+ extendedText.contextInfo = {
2776
+ ...(extendedText.contextInfo || {}),
2777
+ statusAudienceMetadata: {
2778
+ audienceType: proto.ContextInfo.StatusAudienceMetadata.AudienceType.CLOSE_FRIENDS,
2779
+ ...(name ? { listName: name } : {}),
2780
+ ...(emoji ? { listEmoji: emoji } : {})
2781
+ }
2782
+ };
2783
+ }
2784
+
2785
+ const previewMessage = isGroupStatus
2786
+ ? { groupStatusMessageV2: { message: { extendedTextMessage: extendedText } } }
2787
+ : { extendedTextMessage: extendedText };
2788
+
2789
+ const msgId = options.messageId || generateMessageIDV2(userJid);
2790
+
2791
+ await relayMessage(jid, previewMessage, {
2792
+ messageId: msgId,
2793
+ additionalAttributes: options.additionalAttributes || {},
2794
+ additionalNodes: options.additionalNodes || []
2795
+ });
2796
+
2797
+ const fullMsg = {
2798
+ key: {
2799
+ remoteJid: jid,
2800
+ fromMe: true,
2801
+ id: msgId
2802
+ },
2803
+ message: previewMessage,
2804
+ messageTimestamp: unixTimestampSeconds()
2805
+ };
2806
+
2807
+ if (config.emitOwnEvents) {
2808
+ process.nextTick(async () => {
2809
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2810
+ });
2811
+ }
2812
+ return fullMsg;
2813
+ }
2814
+ else if ('likeThis' in content && content.likeThis === true) {
2815
+ const { likeThis: _, ...rawMessage } = content;
2816
+ const msgId = options.messageId || generateMessageIDV2(userJid);
2817
+
2818
+ await relayMessage(jid, rawMessage, {
2819
+ messageId: msgId,
2820
+ additionalAttributes: options.additionalAttributes || {},
2821
+ additionalNodes: options.additionalNodes || []
2822
+ });
2823
+
2824
+ const fullMsg = {
2825
+ key: {
2826
+ remoteJid: jid,
2827
+ fromMe: true,
2828
+ id: msgId
2829
+ },
2830
+ message: rawMessage,
2831
+ messageTimestamp: unixTimestampSeconds()
2832
+ };
2833
+
2834
+ if (config.emitOwnEvents) {
2835
+ process.nextTick(async () => {
2836
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2837
+ });
2838
+ }
2839
+ return fullMsg;
2840
+ }
2841
+ // ── BARON INTERACTIVE HANDLER (new-style native flow buttons + raw group story) ──
2842
+ else if (content && typeof content === 'object' && ('interactiveButtons' in content || 'groupStatusMessage' in content)) {
2843
+ const { quoted } = options;
2844
+ if ('interactiveButtons' in content) {
2845
+ const ibContent = await baron2.handleInteractiveButtons(content, jid, quoted);
2846
+ const ibMsg = await generateWAMessageFromContent(jid, ibContent, { quoted, userJid });
2847
+ return await relayMessage(jid, ibMsg.message, {
2848
+ messageId: ibMsg.key.id,
2849
+ statusPrivacy: options.statusPrivacy
2850
+ });
2851
+ }
2852
+ return await baron2.handleGroupStory(content, jid, quoted);
2853
+ }
2854
+ // ── NORMAL MESSAGE HANDLING ──
2855
+ else {
2856
+ if ('album' in content) {
2857
+ return socket.sendAlbumMessage(jid, content.album, options);
2858
+ }
2859
+ const fullMsg = await generateWAMessage(jid, content, {
2860
+ logger,
2861
+ userJid,
2862
+ getProfilePicUrl: sock.profilePictureUrl,
2863
+ getCallLink: sock.createCallLink,
2864
+ upload: waUploadToServer,
2865
+ mediaCache: config.mediaCache,
2866
+ options: config.options,
2867
+ ...options,
2868
+ // URL previews are opt-in through the richPreview branch above.
2869
+ // Keep bare URL text unpreviewed unless callers supply explicit linkPreview metadata.
2870
+ getUrlInfo: undefined,
2871
+ messageId: generateMessageIDV2(userJid)
2872
+ });
2873
+
2874
+ const isNewsletter = isJidNewsletter(jid);
2875
+ const isEventMsg = 'event' in content && !!content.event;
2876
+ const isDeleteMsg = 'delete' in content && !!content.delete;
2877
+ const isEditMsg = 'edit' in content && !!content.edit;
2878
+ const isPinMsg = 'pin' in content && !!content.pin;
2879
+ const isKeepMsg = 'keep' in content && !!content.keep;
2880
+ const isPollMsg = 'poll' in content && !!content.poll;
2881
+ const isQuizMsg = 'poll' in content && !!content.poll.pollType;
2882
+ const isAiMsg = 'ai' in content && !!content.ai;
2883
+ const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
2884
+ delete content.secureMetaServiceLabel;
2885
+ const additionalAttributes = options.additionalAttributes || {};
2886
+ const additionalNodes = options.additionalNodes || [];
2887
+
2888
+ if (isDeleteMsg || isKeepMsg) {
2889
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
2890
+ additionalAttributes.edit = '8';
2891
+ }
2892
+ else {
2893
+ additionalAttributes.edit = '7';
2894
+ }
2895
+ }
2896
+ else if (isEditMsg) {
2897
+ additionalAttributes.edit = isNewsletter ? '3' : '1';
2898
+ }
2899
+ else if (isPinMsg) {
2900
+ additionalAttributes.edit = '2';
2901
+ }
2902
+ else if (isPollMsg) {
2903
+ if (!isNewsletter && isQuizMsg) {
2904
+ throw new Boom('Quiz are only allowed for newsletter', { statusCode: 400 });
2905
+ }
2906
+ additionalNodes.push({
2907
+ tag: 'meta',
2908
+ attrs: {
2909
+ polltype: isQuizMsg ? 'quiz_creation' : 'creation',
2910
+ contenttype: isPollMsg && isNewsletter ? 'text' : undefined
2911
+ },
2912
+ content: undefined
2913
+ });
2914
+ }
2915
+ else if (isEventMsg) {
2916
+ additionalNodes.push({
2917
+ tag: 'meta',
2918
+ attrs: {
2919
+ event_type: 'creation'
2920
+ },
2921
+ content: undefined
2922
+ });
2923
+ }
2924
+ else if (isAiMsg) {
2925
+ if (!(isPnUser(jid) || isLidUser(jid))) {
2926
+ throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
2927
+ }
2928
+ if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
2929
+ fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
2930
+ }
2931
+ additionalNodes.push({
2932
+ tag: 'bot',
2933
+ attrs: {
2934
+ biz_bot: '1'
2935
+ },
2936
+ content: undefined
2937
+ });
2938
+ delete content.ai;
2939
+ }
2940
+
2941
+ await relayMessage(jid, fullMsg.message, {
2942
+ messageId: fullMsg.key.id,
2943
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
2944
+ addBizAttributes: isNeedBizAttrs,
2945
+ statusJidList: options.statusJidList,
2946
+ statusPrivacy: options.statusPrivacy,
2947
+ additionalAttributes,
2948
+ additionalNodes
2949
+ });
2950
+
2951
+ if (config.emitOwnEvents) {
2952
+ process.nextTick(async () => {
2953
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2954
+ });
2955
+ }
2956
+
2957
+ return fullMsg;
2958
+ }
2959
+ }
2960
+ };
2961
+ /**
2962
+ * Sends a GenAI-style copy-to-clipboard button.
2963
+ * Renders a dark circular copy icon inline with text, inside a forwarded rich response.
2964
+ */
2965
+ socket.sendCopyButton = async (jid, content = {}, options = {}) => {
2966
+ if (!jid) throw new Boom('sendCopyButton requires a target JID', { statusCode: 400 });
2967
+ const wrapped = prepareCopyToClipboardMessage(content);
2968
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2969
+ logger,
2970
+ userJid: authState.creds.me?.id,
2971
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2972
+ ...options,
2973
+ });
2974
+ await relayRichMessage(jid, fullMsg, options);
2975
+ if (config.emitOwnEvents) {
2976
+ process.nextTick(async () => {
2977
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2978
+ });
2979
+ }
2980
+ return fullMsg;
2981
+ };
2982
+
2983
+ /**
2984
+ * Sends plain text inside a forwarded GenAI rich response envelope.
2985
+ */
2986
+ socket.sendRichText = async (jid, content = {}, options = {}) => {
2987
+ if (!jid) throw new Boom('sendRichText requires a target JID', { statusCode: 400 });
2988
+ const wrapped = content.copyText ? prepareRichQuoteMessage(content) : prepareRichTextMessage(content);
2989
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2990
+ logger,
2991
+ userJid: authState.creds.me?.id,
2992
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2993
+ ...options,
2994
+ });
2995
+ await relayRichMessage(jid, fullMsg, options);
2996
+ if (config.emitOwnEvents) {
2997
+ process.nextTick(async () => {
2998
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2999
+ });
3000
+ }
3001
+ return fullMsg;
3002
+ };
3003
+ /** Sends ordinary Markdown/text with a GenAI COPY_TO_CLIPBOARD action; no quote syntax is required. */
3004
+ socket.sendRichTextCopy = async (jid, content = {}, options = {}) => {
3005
+ if (!jid) throw new Boom('sendRichTextCopy requires a target JID', { statusCode: 400 });
3006
+ if (!content.copyText) throw new Boom('sendRichTextCopy requires copyText content', { statusCode: 400 });
3007
+ const wrapped = prepareRichQuoteMessage(content);
3008
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
3009
+ await relayRichMessage(jid, fullMsg, options);
3010
+ return fullMsg;
3011
+ };
3012
+ /** Sends Markdown text containing blockquotes in a forwarded GenAI rich response. */
3013
+ socket.sendMarkdownQuote = async (jid, content = {}, options = {}) => {
3014
+ if (!jid) throw new Boom('sendMarkdownQuote requires a target JID', { statusCode: 400 });
3015
+ const wrapped = prepareRichQuoteMessage(content);
3016
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
3017
+ await relayRichMessage(jid, fullMsg, options);
3018
+ return fullMsg;
3019
+ };
3020
+ /** Sends Markdown blockquotes followed by a GenAI COPY_TO_CLIPBOARD action. */
3021
+ socket.sendQuoteCopy = async (jid, content = {}, options = {}) => {
3022
+ if (!jid) throw new Boom('sendQuoteCopy requires a target JID', { statusCode: 400 });
3023
+ if (!content.copyText) throw new Boom('sendQuoteCopy requires copyText content', { statusCode: 400 });
3024
+ const wrapped = prepareRichQuoteMessage(content);
3025
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
3026
+ await relayRichMessage(jid, fullMsg, options);
3027
+ return fullMsg;
3028
+ };
3029
+ /**
3030
+ * Sends an image inside a forwarded GenAI rich response envelope.
3031
+ */
3032
+ socket.sendRichImage = async (jid, content = {}, options = {}) => {
3033
+ if (!jid) throw new Boom('sendRichImage requires a target JID', { statusCode: 400 });
3034
+ const wrapped = prepareRichImageMessage(content);
3035
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3036
+ logger,
3037
+ userJid: authState.creds.me?.id,
3038
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3039
+ ...options,
3040
+ });
3041
+ await relayRichMessage(jid, fullMsg, options);
3042
+ if (config.emitOwnEvents) {
3043
+ process.nextTick(async () => {
3044
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
3045
+ });
3046
+ }
3047
+ return fullMsg;
3048
+ };
3049
+ /**
3050
+ * Sends inline hyperlinks inside a forwarded GenAI rich response envelope.
3051
+ */
3052
+ socket.sendRichLink = async (jid, content = {}, options = {}) => {
3053
+ if (!jid) throw new Boom('sendRichLink requires a target JID', { statusCode: 400 });
3054
+ const wrapped = prepareRichLinkMessage(content);
3055
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3056
+ logger,
3057
+ userJid: authState.creds.me?.id,
3058
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3059
+ ...options,
3060
+ });
3061
+ await relayRichMessage(jid, fullMsg, options);
3062
+ if (config.emitOwnEvents) {
3063
+ process.nextTick(async () => {
3064
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
3065
+ });
3066
+ }
3067
+ return fullMsg;
3068
+ };
3069
+ const sendSocialProfile = async (methodName, jid, content, options, prepare) => {
3070
+ if (!jid) throw new Boom(`${methodName} requires a target JID`, { statusCode: 400 });
3071
+ const wrapped = prepare(content);
3072
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3073
+ logger,
3074
+ userJid: authState.creds.me?.id,
3075
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3076
+ ...options
3077
+ });
3078
+ await relayMessage(jid, fullMsg.message, {
3079
+ messageId: fullMsg.key.id,
3080
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
3081
+ statusJidList: options.statusJidList
3082
+ });
3083
+ if (config.emitOwnEvents) {
3084
+ process.nextTick(async () => {
3085
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
3086
+ });
3087
+ }
3088
+ return fullMsg;
3089
+ };
3090
+ socket.sendSocialProfile = async (jid, content = {}, options = {}) => sendSocialProfile('sendSocialProfile', jid, content, options, prepareSocialProfileMessage);
3091
+ socket.sendInstagramProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
3092
+ 'sendInstagramProfile',
3093
+ jid,
3094
+ { ...content, platform: 'instagram', entityType: content.entityType || 'IG_PROFILE', entityUrl: content.entityUrl || `https://www.instagram.com/${content.username || ''}` },
3095
+ options,
3096
+ prepareInstagramProfileMessage
3097
+ );
3098
+ socket.sendFacebookProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
3099
+ 'sendFacebookProfile', jid,
3100
+ { ...content, platform: 'facebook', entityType: content.entityType || 'FB_PROFILE', entityUrl: content.entityUrl || `https://www.facebook.com/${content.username || ''}` },
3101
+ options, prepareSocialProfileMessage
3102
+ );
3103
+ socket.sendTikTokProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
3104
+ 'sendTikTokProfile', jid,
3105
+ { ...content, platform: 'tiktok', entityType: content.entityType || 'TIKTOK_PROFILE', entityUrl: content.entityUrl || `https://www.tiktok.com/@${content.username || ''}` },
3106
+ options, prepareSocialProfileMessage
3107
+ );
3108
+ socket.sendYouTubeProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
3109
+ 'sendYouTubeProfile', jid,
3110
+ { ...content, platform: 'youtube', entityType: content.entityType || 'YOUTUBE_PROFILE', entityUrl: content.entityUrl || `https://www.youtube.com/@${content.username || ''}` },
3111
+ options, prepareSocialProfileMessage
3112
+ );
3113
+ socket.sendXProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
3114
+ 'sendXProfile', jid,
3115
+ { ...content, platform: 'x', entityType: content.entityType || 'X_PROFILE', entityUrl: content.entityUrl || `https://x.com/${content.username || ''}` },
3116
+ options, prepareSocialProfileMessage
3117
+ );
3118
+ socket.sendUnifiedResponse = async (jid, content = {}, options = {}) => {
3119
+ if (!jid) throw new Boom('sendUnifiedResponse requires a target JID', { statusCode: 400 });
3120
+ const wrapped = prepareUnifiedResponseMessage(content);
3121
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3122
+ logger,
3123
+ userJid: authState.creds.me?.id,
3124
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3125
+ ...options
3126
+ });
3127
+ await relayMessage(jid, fullMsg.message, {
3128
+ messageId: fullMsg.key.id,
3129
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
3130
+ statusJidList: options.statusJidList
3131
+ });
3132
+ if (config.emitOwnEvents) {
3133
+ process.nextTick(async () => {
3134
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
3135
+ });
3136
+ }
3137
+ return fullMsg;
3138
+ };
3139
+ /** Sends a protocol-backed AIRich map with optional numbered annotations. */
3140
+ socket.sendRichMap = async (jid, content = {}, options = {}) => {
3141
+ if (!jid) throw new Boom('sendRichMap requires a target JID', { statusCode: 400 });
3142
+ const wrapped = prepareRichMapMessage(content);
3143
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3144
+ logger,
3145
+ userJid: authState.creds.me?.id,
3146
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3147
+ ...options
3148
+ });
3149
+ await relayRichMessage(jid, fullMsg, options);
3150
+ return fullMsg;
3151
+ };
3152
+ /** Sends BotSuggestedPromptMetadata with a rich-response text fallback. */
3153
+ socket.sendBotPromptSuggestions = async (jid, content = {}, options = {}) => {
3154
+ if (!jid) throw new Boom('sendBotPromptSuggestions requires a target JID', { statusCode: 400 });
3155
+ const wrapped = prepareBotPromptSuggestionsMessage(content);
3156
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3157
+ logger,
3158
+ userJid: authState.creds.me?.id,
3159
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3160
+ ...options
3161
+ });
3162
+ await relayRichMessage(jid, fullMsg, options);
3163
+ return fullMsg;
3164
+ };
3165
+ /** Sends BotSourcesMetadata for citation-aware bot responses. */
3166
+ socket.sendBotSources = async (jid, content = {}, options = {}) => {
3167
+ if (!jid) throw new Boom('sendBotSources requires a target JID', { statusCode: 400 });
3168
+ const wrapped = prepareBotSourcesMessage(content);
3169
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3170
+ logger,
3171
+ userJid: authState.creds.me?.id,
3172
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3173
+ ...options
3174
+ });
3175
+ await relayRichMessage(jid, fullMsg, options);
3176
+ return fullMsg;
3177
+ };
3178
+ /** Sends an experimental AIRich dynamic image/GIF submessage. */
3179
+ socket.sendRichDynamicMedia = async (jid, content = {}, options = {}) => {
3180
+ if (!jid) throw new Boom('sendRichDynamicMedia requires a target JID', { statusCode: 400 });
3181
+ const wrapped = prepareRichDynamicMediaMessage(content);
3182
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3183
+ logger,
3184
+ userJid: authState.creds.me?.id,
3185
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3186
+ ...options
3187
+ });
3188
+ await relayRichMessage(jid, fullMsg, options);
3189
+ return fullMsg;
3190
+ };
3191
+ /** Sends BotPttPromptMetadata containing a caller-provided transcript. */
3192
+ socket.sendBotPttTranscript = async (jid, content = {}, options = {}) => {
3193
+ if (!jid) throw new Boom('sendBotPttTranscript requires a target JID', { statusCode: 400 });
3194
+ const wrapped = prepareBotPttTranscriptMessage(content);
3195
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3196
+ logger,
3197
+ userJid: authState.creds.me?.id,
3198
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3199
+ ...options
3200
+ });
3201
+ await relayRichMessage(jid, fullMsg, options);
3202
+ return fullMsg;
3203
+ };
3204
+ socket.richMenu = async (jid, content = {}, options = {}) => {
3205
+ if (!jid) throw new Boom('richMenu requires a target JID', { statusCode: 400 });
3206
+ const wrapped = prepareRichMenuMessage(content);
3207
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3208
+ logger,
3209
+ userJid: authState.creds.me?.id,
3210
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3211
+ ...options,
3212
+ });
3213
+ await relayRichMessage(jid, fullMsg, options);
3214
+ if (config.emitOwnEvents) {
3215
+ process.nextTick(async () => {
3216
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
3217
+ });
3218
+ }
3219
+ return fullMsg;
3220
+ };
3221
+ /**
3222
+ * Sends the A2UI interactive card/menu format used by WhatsApp's large
3223
+ * command-card presentation. This is intentionally separate from richMenu
3224
+ * because it is an interactiveMessage, not an AIRich unifiedResponse.
3225
+ */
3226
+ socket.sendA2UICommandMenu = async (jid, content = {}, options = {}) => {
3227
+ if (!jid) throw new Boom('sendA2UICommandMenu requires a target JID', { statusCode: 400 });
3228
+ const { image, ...menuContent } = content || {};
3229
+ let imageMessage;
3230
+ if (image) {
3231
+ const prepared = await prepareWAMessageMedia({ image }, { upload: waUploadToServer });
3232
+ imageMessage = prepared.imageMessage;
3233
+ }
3234
+ const wrapped = prepareA2UICommandMenu({ ...menuContent, imageMessage });
3235
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3236
+ logger,
3237
+ userJid: authState.creds.me?.id,
3238
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
3239
+ ...options,
3240
+ });
3241
+ await relayRichMessage(jid, fullMsg, { ...options, forceRichEdit: true });
3242
+ if (config.emitOwnEvents) {
3243
+ process.nextTick(async () => {
3244
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
3245
+ });
3246
+ }
3247
+ return fullMsg;
3248
+ };
3249
+ /** Send arbitrary A2UI/interactive payloads; sendA2UICommandMenu is a preset wrapper. */
3250
+ socket.sendA2UIMessage = async (jid, content = {}, options = {}) => {
3251
+ if (!jid) throw new Boom('sendA2UIMessage requires a target JID', { statusCode: 400 });
3252
+ const { image, ...payload } = content || {};
3253
+ let imageMessage;
3254
+ if (image) {
3255
+ const prepared = await prepareWAMessageMedia({ image }, { upload: waUploadToServer });
3256
+ imageMessage = prepared.imageMessage;
3257
+ }
3258
+ const wrapped = prepareA2UIMessage({ ...payload, imageMessage });
3259
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3260
+ logger,
3261
+ userJid: authState.creds.me?.id,
3262
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
3263
+ ...options,
3264
+ });
3265
+ await relayRichMessage(jid, fullMsg, { ...options, forceRichEdit: true });
3266
+ if (config.emitOwnEvents) process.nextTick(async () => { await messageMutex.mutex(() => upsertMessage(fullMsg, 'append')); });
3267
+ return fullMsg;
3268
+ };
3269
+
3270
+ /** Sends the manually serialized AIRich command card shown in the screenshot. */
3271
+ socket.sendAIRichCommandMenu = async (jid, content = {}, options = {}) => {
3272
+ if (!jid) throw new Boom('sendAIRichCommandMenu requires a target JID', { statusCode: 400 });
3273
+ const wrapped = prepareAIRichCommandMenu(content);
3274
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3275
+ logger,
3276
+ userJid: authState.creds.me?.id,
3277
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
3278
+ ...options,
3279
+ });
3280
+ await relayRichMessage(jid, fullMsg, options);
3281
+ if (config.emitOwnEvents) {
3282
+ process.nextTick(async () => {
3283
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
3284
+ });
3285
+ }
3286
+ return fullMsg;
3287
+ };
3288
+ /** Send a provider-neutral AIRich social/entity result card. */
3289
+ socket.sendSocialEntity = async (jid, content = {}, options = {}) => {
3290
+ if (!jid) throw new Boom('sendSocialEntity requires a target JID', { statusCode: 400 });
3291
+ const wrapped = prepareSocialEntityMessage(content);
3292
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3293
+ logger,
3294
+ userJid: authState.creds.me?.id,
3295
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
3296
+ ...options,
3297
+ });
3298
+ await relayRichMessage(jid, fullMsg, options);
3299
+ if (config.emitOwnEvents) process.nextTick(async () => { await messageMutex.mutex(() => upsertMessage(fullMsg, 'append')); });
3300
+ return fullMsg;
3301
+ };
3302
+
3303
+ /** Send the primary Instagram profile result using the universal social/entity API. */
3304
+ socket.sendInstagramProfile = async (jid, content = {}, options = {}) => {
3305
+ if (!jid) throw new Boom('sendInstagramProfile requires a target JID', { statusCode: 400 });
3306
+ const wrapped = prepareInstagramProfileMessage(content);
3307
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3308
+ logger,
3309
+ userJid: authState.creds.me?.id,
3310
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
3311
+ ...options,
3312
+ });
3313
+ await relayRichMessage(jid, fullMsg, options);
3314
+ if (config.emitOwnEvents) process.nextTick(async () => { await messageMutex.mutex(() => upsertMessage(fullMsg, 'append')); });
3315
+ return fullMsg;
3316
+ };
3317
+
3318
+ /** Sends a rich response with experimental BotInfrastructureDiagnostics metadata. */
3319
+ socket.sendBotDiagnostics = async (jid, content = {}, options = {}) => {
3320
+ if (!jid) throw new Boom('sendBotDiagnostics requires a target JID', { statusCode: 400 });
3321
+ const { text = 'Bot diagnostics test', botBackend = 0, toolsUsed = [], isThinking = false, botJid = '867051314767696@bot' } = content;
3322
+ const wrapped = {
3323
+ messageContextInfo: { botMetadata: { botInfrastructureDiagnostics: { botBackend, toolsUsed, isThinking } } },
3324
+ botForwardedMessage: { message: { richResponseMessage: { messageType: 1, submessages: [{ messageType: 2, messageText: text }], contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid }, forwardOrigin: 4 } } } }
3325
+ };
3326
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
3327
+ await relayRichMessage(jid, fullMsg, options);
3328
+ return fullMsg;
3329
+ };
3330
+ /** Sends a rich response with experimental BotCommandMetadata. */
3331
+ socket.sendBotCommand = async (jid, content = {}, options = {}) => {
3332
+ if (!jid) throw new Boom('sendBotCommand requires a target JID', { statusCode: 400 });
3333
+ const { text = 'Bot command test', commandName = '', commandDescription = '', commandPrompt = '', botJid = '867051314767696@bot' } = content;
3334
+ const wrapped = buildBotRichResponse({ text, botJid, botMetadata: { commandMetadata: { commandName, commandDescription, commandPrompt } } });
3335
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
3336
+ await relayRichMessage(jid, fullMsg, options);
3337
+ return fullMsg;
3338
+ };
3339
+ /** Sends a planning/execution-plan rich response with WAProto capabilities. */
3340
+ socket.sendBotPlanning = async (jid, content = {}, options = {}) => {
3341
+ if (!jid) throw new Boom('sendBotPlanning requires a target JID', { statusCode: 400 });
3342
+ const { text = 'Execution plan', steps = [], queryPlan = true, botJid = '867051314767696@bot' } = content;
3343
+ const submessages = [
3344
+ { messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: text },
3345
+ ...steps.map(step => ({
3346
+ messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT,
3347
+ messageText: typeof step === 'string' ? step : `${step.title || step.name || 'Step'}${step.body ? `: ${step.body}` : ''}`
3348
+ }))
3349
+ ];
3350
+ const wrapped = buildBotRichResponse({
3351
+ botJid,
3352
+ submessages,
3353
+ capabilities: [
3354
+ BotCapabilityType.AGENTIC_PLANNING,
3355
+ ...(queryPlan ? [BotCapabilityType.QUERY_PLAN] : [])
3356
+ ]
3357
+ });
3358
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
3359
+ await relayRichMessage(jid, fullMsg, options);
3360
+ return fullMsg;
3361
+ };
3362
+ /** Sends a rich response with experimental BotResolvedToolCallMetadata. */
3363
+ socket.sendBotToolResult = async (jid, content = {}, options = {}) => {
3364
+ if (!jid) throw new Boom('sendBotToolResult requires a target JID', { statusCode: 400 });
3365
+ const { text = 'Bot tool result test', toolCallId = `tool-${Date.now()}`, resolutionData, resolutionDataSerialized, botJid = '867051314767696@bot' } = content;
3366
+ const wrapped = buildBotRichResponse({
3367
+ text,
3368
+ botJid,
3369
+ capabilities: [BotCapabilityType.AGENTIC_PLANNING, BotCapabilityType.QUERY_PLAN],
3370
+ botMetadata: {
3371
+ resolvedToolCallMetadata: {
3372
+ toolCallId,
3373
+ resolutionDataSerialized: resolutionDataSerialized ?? JSON.stringify(resolutionData ?? {})
3374
+ }
3375
+ }
3376
+ });
3377
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
3378
+ await relayRichMessage(jid, fullMsg, options);
3379
+ return fullMsg;
3380
+ };
3381
+ /**
3382
+ * Sends a real BotProgressIndicatorMetadata planning envelope. The plan is
3383
+ * application-controlled; this advertises the public schema capability but
3384
+ * does not claim to invoke Meta's private planning backend.
3385
+ */
3386
+ socket.sendBotPlan = async (jid, content = {}, options = {}) => {
3387
+ if (!jid) throw new Boom('sendBotPlan requires a target JID', { statusCode: 400 });
3388
+ const {
3389
+ text = 'Execution plan',
3390
+ title = 'Execution plan',
3391
+ steps = [],
3392
+ estimatedCompletionTime,
3393
+ botJid = '867051314767696@bot'
3394
+ } = content;
3395
+ if (!Array.isArray(steps) || steps.length === 0) {
3396
+ throw new Boom('sendBotPlan requires at least one step', { statusCode: 400 });
3397
+ }
3398
+ const planningStatus = proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.PlanningStepStatus;
3399
+ const normalizedSteps = steps.map((step, index) => ({
3400
+ statusTitle: String(step.title || step.name || `Step ${index + 1}`),
3401
+ statusBody: String(step.body || step.description || ''),
3402
+ status: step.status === 'executing' ? planningStatus.EXECUTING
3403
+ : step.status === 'finished' || step.status === 'completed' ? planningStatus.FINISHED
3404
+ : planningStatus.PLANNED,
3405
+ isReasoning: step.isReasoning === true,
3406
+ isEnhancedSearch: step.isEnhancedSearch === true,
3407
+ ...(Array.isArray(step.sections) ? { sections: step.sections } : {})
3408
+ }));
3409
+ const wrapped = {
3410
+ messageContextInfo: { botMetadata: {
3411
+ capabilityMetadata: {
3412
+ capabilities: [
3413
+ proto.BotCapabilityMetadata.BotCapabilityType.AGENTIC_PLANNING,
3414
+ proto.BotCapabilityMetadata.BotCapabilityType.QUERY_PLAN
3415
+ ]
3416
+ },
3417
+ progressIndicatorMetadata: {
3418
+ progressDescription: title,
3419
+ stepsMetadata: normalizedSteps,
3420
+ ...(estimatedCompletionTime ? { estimatedCompletionTime } : {})
3421
+ }
3422
+ } },
3423
+ botForwardedMessage: { message: { richResponseMessage: {
3424
+ messageType: 1,
3425
+ submessages: [{ messageType: 2, messageText: text }],
3426
+ contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid }, forwardOrigin: 4 }
3427
+ } } }
3428
+ };
3429
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
3430
+ await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, statusJidList: options.statusJidList });
3431
+ return fullMsg;
3432
+ };
3433
+ socket.sendStatus = async (content, options = {}) => {
3434
+ const statusJidList = await resolveStatusRecipients(options.statusJidList || content?.statusJidList);
3435
+ return socket.sendMessage(STATUS_JID, {
3436
+ ...content,
3437
+ status: true
3438
+ }, {
3439
+ ...options,
3440
+ broadcast: true,
3441
+ statusJidList
3442
+ });
3443
+ };
3444
+ socket.sendNewsletterStatus = async (jid, content, options = {}) => {
3445
+ if (!isJidNewsletter(jid)) {
3446
+ throw new Boom('sendNewsletterStatus requires a @newsletter JID', { statusCode: 400 });
3447
+ }
3448
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
3449
+ throw new Boom('sendNewsletterStatus content must be an object', { statusCode: 400 });
3450
+ }
3451
+ const userJid = authState?.creds?.me?.id;
3452
+ if (!userJid) {
3453
+ throw new Boom('Not authenticated', { statusCode: 401 });
3454
+ }
3455
+ const { messageId: requestedMessageId, ackTimeoutMs = 20000, serverIdTimeoutMs = 8000, resolveServerId = true, ...messageOptions } = options || {};
3456
+ if (!Number.isFinite(ackTimeoutMs) || ackTimeoutMs <= 0) {
3457
+ throw new Boom('ackTimeoutMs must be a positive number', { statusCode: 400 });
3458
+ }
3459
+ if (resolveServerId && (!Number.isFinite(serverIdTimeoutMs) || serverIdTimeoutMs <= 0)) {
3460
+ throw new Boom('serverIdTimeoutMs must be a positive number', { statusCode: 400 });
3461
+ }
3462
+ const eligibility = await socket.newsletterCanPostStatus(jid);
3463
+ if (eligibility?.canPost !== true) {
3464
+ throw new Boom('The authenticated account lacks the CHANNEL_STATUS_PRODUCER capability for this channel', {
3465
+ statusCode: 403,
3466
+ data: { capabilities: eligibility?.capabilities || [] }
3467
+ });
3468
+ }
3469
+
3470
+ let uploadedMediaHandle;
3471
+ const upload = async (filePath, uploadOptions = {}) => {
3472
+ const result = await waUploadToServer(filePath, {
3473
+ ...uploadOptions,
3474
+ newsletterStatus: uploadOptions.newsletter === true
3475
+ });
3476
+ if (uploadOptions.newsletter) {
3477
+ uploadedMediaHandle = result?.handle ?? result?.media_id ?? result?.mediaId ?? result?.fbid ?? uploadedMediaHandle;
3478
+ }
3479
+ return result;
3480
+ };
3481
+ const messageId = requestedMessageId || generateMessageIDV2(userJid);
3482
+ const fullMsg = await generateWAMessage(jid, withNewsletterStatusAttribution(content), {
3483
+ ...messageOptions,
3484
+ logger,
3485
+ userJid,
3486
+ upload,
3487
+ mediaCache: config.mediaCache,
3488
+ options: httpRequestOptions,
3489
+ messageId
3490
+ });
3491
+ const mediaType = getNewsletterStatusMediaType(fullMsg.message);
3492
+ if (mediaType === 'audio') {
3493
+ withNewsletterStatusAudioMetadata(fullMsg.message, content.backgroundArgb);
3494
+ }
3495
+ const node = buildNewsletterStatusNode({
3496
+ jid,
3497
+ message: fullMsg.message,
3498
+ messageId: fullMsg.key.id,
3499
+ mediaType,
3500
+ mediaHandle: uploadedMediaHandle
3501
+ });
3502
+
3503
+ const serverIdEcho = resolveServerId
3504
+ ? waitForNewsletterStatusServerId(socket, { jid, messageId: fullMsg.key.id })
3505
+ : undefined;
3506
+ let ack;
3507
+ try {
3508
+ const ackPromise = socket.waitForMessage(fullMsg.key.id, ackTimeoutMs);
3509
+ await socket.sendNode(node);
3510
+ ack = await ackPromise;
3511
+ }
3512
+ catch (error) {
3513
+ serverIdEcho?.cancel();
3514
+ throw error;
3515
+ }
3516
+ if (!ack) {
3517
+ serverIdEcho?.cancel();
3518
+ throw new Boom(`Timed out waiting for the Channel Status acknowledgement for ${fullMsg.key.id}`, { statusCode: 408 });
3519
+ }
3520
+ if (ack.tag !== 'ack' || ack.attrs?.class !== 'status') {
3521
+ serverIdEcho?.cancel();
3522
+ throw new Boom(`Unexpected Channel Status response: ${ack.tag || 'unknown'} (${ack.attrs?.class || 'no class'})`, {
3523
+ statusCode: 502,
3524
+ data: ack
3525
+ });
3526
+ }
3527
+ if (ack.attrs?.error) {
3528
+ serverIdEcho?.cancel();
3529
+ throw new Boom(`WhatsApp rejected the Channel Status (${ack.attrs.error})`, {
3530
+ statusCode: ack.attrs.error === '401' || ack.attrs.error === '403' ? 403 : 400,
3531
+ data: ack
3532
+ });
3533
+ }
3534
+
3535
+ const ackServerId = ack.attrs?.server_id === undefined ? undefined : Number.parseInt(String(ack.attrs.server_id), 10);
3536
+ let serverId;
3537
+ if (Number.isFinite(ackServerId)) {
3538
+ serverId = ackServerId;
3539
+ serverIdEcho?.cancel();
3540
+ }
3541
+ else if (serverIdEcho) {
3542
+ serverIdEcho.startTimeout(serverIdTimeoutMs);
3543
+ serverId = await serverIdEcho.promise;
3544
+ }
3545
+ return {
3546
+ ...fullMsg,
3547
+ newsletterStatusAck: ack,
3548
+ newsletterStatusServerId: Number.isFinite(serverId) ? serverId : undefined
3549
+ };
3550
+ };
3551
+ /** Request a Restricted chat setting change using WhatsApp's ACP2 protocol. */
3552
+ socket.updateRestrictedChat = async (jid, enabled, options = {}) => {
3553
+ if (typeof jid !== 'string' || !jid.trim()) throw new Boom('updateRestrictedChat requires a target chat JID', { statusCode: 400 });
3554
+ const userJid = authState.creds.me?.id;
3555
+ const messageId = options.messageId || generateMessageIDV2(userJid);
3556
+ const content = makeRestrictedChatSettingMessage(enabled);
3557
+ const fullMsg = generateWAMessageFromContent(jid, content, { logger, userJid, ...options, messageId });
3558
+ await relayMessage(jid, fullMsg.message, {
3559
+ messageId: fullMsg.key.id,
3560
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
3561
+ additionalAttributes: options.additionalAttributes || {},
3562
+ additionalNodes: options.additionalNodes || []
3563
+ });
3564
+ if (config.emitOwnEvents) process.nextTick(async () => { await messageMutex.mutex(() => upsertMessage(fullMsg, 'append')); });
3565
+ return fullMsg;
3566
+ };
3567
+ socket.sendRichButtonGrid = async (jid, grid, options = {}) => {
3568
+ const { text, footer, cards = [] } = grid || {};
3569
+ if (!Array.isArray(cards) || cards.length === 0) {
3570
+ throw new Boom('sendRichButtonGrid expects at least one card', { statusCode: 400 });
3571
+ }
3572
+ const normalizedCards = cards.map((card, index) => {
3573
+ const buttons = card.buttons || card.nativeFlow || [];
3574
+ if (!Array.isArray(buttons) || buttons.length === 0) {
3575
+ throw new Boom(`sendRichButtonGrid card ${index + 1} needs buttons`, { statusCode: 400 });
3576
+ }
3577
+ return {
3578
+ ...card,
3579
+ nativeFlow: buttons,
3580
+ caption: card.caption || card.title || `Menu ${index + 1}`
3581
+ };
3582
+ });
3583
+ return socket.sendMessage(jid, {
3584
+ ...(text ? { text } : {}),
3585
+ ...(footer ? { footer } : {}),
3586
+ cards: normalizedCards
3587
+ }, options);
3588
+ };
3589
+ /**
3590
+ * Compatibility entry point for the former Gen4/grid menu.
3591
+ * This is additive: sendRichButtonGrid remains unchanged for existing callers.
3592
+ */
3593
+ socket.HoldOn = async (jid, grid, options = {}) => socket.sendRichButtonGrid(jid, grid, options);
3594
+ socket.sendWhatsAppFlow = async (jid, flow, options = {}) => {
3595
+ const { text, footer, image, caption, ...flowOptions } = flow || {};
3596
+ const button = makeWhatsAppFlowButton(flowOptions);
3597
+ return socket.sendMessage(jid, {
3598
+ ...(image ? { image, caption: caption || text || flowOptions.cta } : { text: text || flowOptions.cta }),
3599
+ ...(footer ? { footer } : {}),
3600
+ nativeFlow: [button]
3601
+ }, options);
3602
+ };
3603
+ /** Launch a configured feedback Flow with the conventional Rate experience CTA. */
3604
+ socket.sendWhatsAppFeedbackFlow = async (jid, flow, options = {}) => {
3605
+ if (!flow?.flowId || !flow?.flowToken) {
3606
+ throw new Boom('sendWhatsAppFeedbackFlow requires a configured flowId and flowToken', { statusCode: 400 });
3607
+ }
3608
+ return socket.sendWhatsAppFlow(jid, {
3609
+ ...flow,
3610
+ cta: flow.cta || 'Rate experience',
3611
+ text: flow.text || 'Please rate your experience.'
3612
+ }, options);
3613
+ };
3614
+ /** Send a client-rendered appointment booking card using WhatsApp's native booking_confirmation action. */
3615
+ socket.sendBookingConfirmation = async (jid, booking, options = {}) => {
3616
+ const { title, body, location, startDatetime, endDatetime, email } = booking || {};
3617
+ if (typeof title !== 'string' || !title.trim()) throw new Boom('sendBookingConfirmation requires a non-empty title', { statusCode: 400 });
3618
+ if (typeof body !== 'string' || !body.trim()) throw new Boom('sendBookingConfirmation requires a non-empty body', { statusCode: 400 });
3619
+ const button = buildBookingConfirmationButton({ location, startDatetime, endDatetime, email });
3620
+ return socket.sendMessage(jid, { title, text: body, nativeFlow: [button] }, options);
3621
+ };
3622
+ /** Send the native request_contact_info interactive message observed from WhatsApp. */
3623
+ socket.sendRequestContactInfo = async (jid, content = {}, options = {}) => {
3624
+ if (!jid) throw new Boom('sendRequestContactInfo requires a target JID', { statusCode: 400 });
3625
+ const { text = 'Please share your contact information', footer, buttonParams } = content || {};
3626
+ if (typeof text !== 'string' || !text.trim()) {
3627
+ throw new Boom('sendRequestContactInfo requires a non-empty text', { statusCode: 400 });
3628
+ }
3629
+ const button = buildRequestContactInfoButton({ buttonParams });
3630
+ return socket.sendMessage(jid, {
3631
+ text,
3632
+ nativeFlow: [button],
3633
+ ...(footer !== undefined ? { footer: String(footer) } : {})
3634
+ }, options);
3635
+ };
3636
+ /** Send a native contact-style card with optional media; live photos follow as a separate native pair. */
3637
+ socket.sendInteractiveContactCard = async (jid, content = {}, options = {}) => {
3638
+ if (!jid) throw new Boom('sendInteractiveContactCard requires a target JID', { statusCode: 400 });
3639
+ const prepared = prepareInteractiveContactCardMessage(content);
3640
+ const cardMessage = await socket.sendMessage(jid, prepared, options);
3641
+ if (content.livePhoto != null) {
3642
+ const livePhotoMessage = await sendLivePhoto(jid, content.livePhoto, options.quoted, options);
3643
+ return { cardMessage, livePhotoMessage };
3644
+ }
3645
+ return cardMessage;
3646
+ };
3647
+ /** Send the legacy location-header ButtonsMessage used by themed menu cards. */
3648
+ socket.sendLocationButtonCard = async (jid, content = {}, options = {}) => {
3649
+ if (!jid) throw new Boom('sendLocationButtonCard requires a target JID', { statusCode: 400 });
3650
+ const prepared = prepareLocationButtonCardMessage(content);
3651
+ if (prepared.location?.jpegThumbnail) {
3652
+ prepared.location.jpegThumbnail = await normalizeLocationButtonCardThumbnail(prepared.location.jpegThumbnail);
3653
+ }
3654
+ return socket.sendMessage(jid, prepared, options);
3655
+ };
3656
+ /** Send an image-header menu card without LocationMessage or map coordinates. */
3657
+ socket.sendMenuButtonCard = async (jid, content = {}, options = {}) => {
3658
+ if (!jid) throw new Boom('sendMenuButtonCard requires a target JID', { statusCode: 400 });
3659
+ const prepared = prepareMenuButtonCardMessage(content);
3660
+ return socket.sendMessage(jid, prepared, options);
3661
+ };
3662
+ /** Relay a caller-provided sticker payload as an annotation of a parent message. */
3663
+ socket.sendStickerAnnotation = async (jid, content = {}, options = {}) => {
3664
+ if (!jid) throw new Boom('sendStickerAnnotation requires a target JID', { statusCode: 400 });
3665
+ const { parentMessageKey, stickerMessage, count = 1, intervalMs = 1000 } = content || {};
3666
+ return sendStickerAnnotationBatch({
3667
+ jid,
3668
+ parentMessageKey,
3669
+ stickerMessage,
3670
+ count,
3671
+ intervalMs,
3672
+ relay: (targetJid, message, relayOptions) => relayMessage(targetJid, message, relayOptions),
3673
+ createMessageId: () => generateMessageIDV2(authState.creds.me?.id),
3674
+ relayOptions: options
3675
+ });
3676
+ };
3677
+ /**
3678
+ * Send a rich URL CTA intended to open a hosted WebView/Mini App.
3679
+ * `useWebview` is serialized by the existing native-flow normalizer.
3680
+ * `toast` is preserved as immediate button acknowledgement metadata.
3681
+ */
3682
+ socket.sendRichWebview = async (jid, content = {}, options = {}) => {
3683
+ const { text = '', title, footer, image, caption, buttonText = 'Open', url, useWebview = true, toast, ...rest } = content;
3684
+ if (!url || typeof url !== 'string') {
3685
+ throw new Boom('sendRichWebview requires a URL', { statusCode: 400 });
3686
+ }
3687
+ const button = { text: buttonText, url, useWebview, ...(toast ? { toast } : {}), ...rest };
3688
+ return socket.sendMessage(jid, {
3689
+ ...(image ? { image, caption: caption || text || title || buttonText } : { text: text || title || buttonText }),
3690
+ ...(footer ? { footer } : {}),
3691
+ nativeFlow: [button],
3692
+ ...(toast ? { toast } : {})
3693
+ }, options);
3694
+ };
3695
+ socket.sendInteractiveTable = async (jid, table, options = {}) => {
3696
+ const { title = '', headers = [], rows = [], image, buttons = [], footer } = table || {};
3697
+ if (!Array.isArray(headers) || !Array.isArray(rows) || !Array.isArray(buttons)) {
3698
+ throw new Boom('sendInteractiveTable expects headers, rows, and buttons arrays', { statusCode: 400 });
3699
+ }
3700
+ const lines = [];
3701
+ if (title) lines.push(String(title));
3702
+ if (headers.length) lines.push(`| ${headers.map(String).join(' | ')} |`);
3703
+ if (headers.length) lines.push(`| ${headers.map(() => '---').join(' | ')} |`);
3704
+ for (const row of rows) {
3705
+ lines.push(`| ${(Array.isArray(row) ? row : [row]).map(value => String(value ?? '')).join(' | ')} |`);
3706
+ }
3707
+ const content = {
3708
+ ...(image ? { caption: lines.join('\n'), image } : { text: lines.join('\n') }),
3709
+ buttons: buttons.map((button, index) => ({
3710
+ id: button.id || `table_${index + 1}`,
3711
+ text: button.text || button.buttonText || `Option ${index + 1}`
3712
+ })),
3713
+ ...(footer ? { footer } : {})
3714
+ };
3715
+ return socket.sendMessage(jid, content, options);
3716
+ };
3717
+ // ====================================
3718
+ // VIEW-ONCE AUTO-DECRYPT & AUTO-DELETE
3719
+ // ====================================
3720
+
3721
+ /**
3722
+ * Auto-decrypt view-once messages (autoVV)
3723
+ * Downloads the media content from a view-once message and re-emits it
3724
+ * as a regular message with decryptedMedia attached.
3725
+ */
3726
+ socket.autoVV = async (message, options = {}) => {
3727
+ if (!isViewOnceMessage(message)) {
3728
+ logger.debug({ key: message?.key }, 'autoVV: message is not a view-once message');
3729
+ return null;
3730
+ }
3731
+
3732
+ const info = parseViewOnceInfo(message);
3733
+ logger.info({ key: message?.key, ...info }, 'autoVV: decrypting view-once message');
3734
+
3735
+ try {
3736
+ // Download and decrypt the media
3737
+ const mediaBuffer = await downloadViewOnceMedia(message, {
3738
+ logger,
3739
+ ...options,
3740
+ });
3741
+
3742
+ // Create a regular message from the decrypted content
3743
+ const regularMessage = createRegularMessageFromViewOnce(message, mediaBuffer);
3744
+
3745
+ if (regularMessage) {
3746
+ // Emit as a new message with decrypted content
3747
+ ev.emit('messages.upsert', {
3748
+ messages: [regularMessage],
3749
+ type: 'append',
3750
+ });
3751
+
3752
+ logger.info({
3753
+ key: message?.key,
3754
+ mediaType: info.mediaType,
3755
+ bufferSize: mediaBuffer.length,
3756
+ }, 'autoVV: successfully decrypted view-once message');
3757
+ }
3758
+
3759
+ return regularMessage;
3760
+ } catch (error) {
3761
+ logger.error({
3762
+ key: message?.key,
3763
+ error: error.message,
3764
+ }, 'autoVV: failed to decrypt view-once message');
3765
+ throw error;
3766
+ }
3767
+ };
3768
+
3769
+ /**
3770
+ * Auto-delete view-once messages (antiVV)
3771
+ * Detects incoming view-once messages and deletes them immediately.
3772
+ * This prevents the sender from knowing the message was viewed.
3773
+ */
3774
+ socket.antiVV = async (message, options = {}) => {
3775
+ if (!isViewOnceMessage(message)) {
3776
+ logger.debug({ key: message?.key }, 'antiVV: message is not a view-once message');
3777
+ return false;
3778
+ }
3779
+
3780
+ const info = parseViewOnceInfo(message);
3781
+ logger.info({ key: message?.key, ...info }, 'antiVV: deleting view-once message');
3782
+
3783
+ try {
3784
+ // Delete the message by sending a revoke receipt
3785
+ const jid = message.key.remoteJid;
3786
+ const participant = message.key.participant || jid;
3787
+ const messageId = message.key.id;
3788
+
3789
+ // Send a revoke receipt to delete the message
3790
+ await sendReceipt(jid, participant, [messageId], 'sender');
3791
+
3792
+ // Also emit a message update to remove it from local store
3793
+ ev.emit('messages.update', [
3794
+ {
3795
+ key: message.key,
3796
+ update: {
3797
+ messageStubType: proto.WebMessageInfo.StubType.REVOKE,
3798
+ messageStubParameters: ['auto-vv-delete'],
3799
+ },
3800
+ },
3801
+ ]);
3802
+
3803
+ logger.info({
3804
+ key: message?.key,
3805
+ mediaType: info.mediaType,
3806
+ }, 'antiVV: successfully deleted view-once message');
3807
+
3808
+ return true;
3809
+ } catch (error) {
3810
+ logger.error({
3811
+ key: message?.key,
3812
+ error: error.message,
3813
+ }, 'antiVV: failed to delete view-once message');
3814
+ throw error;
3815
+ }
3816
+ };
3817
+
3818
+ /**
3819
+ * Check if a message is a view-once message
3820
+ */
3821
+ socket.isViewOnce = (message) => isViewOnceMessage(message);
3822
+
3823
+ /**
3824
+ * Get view-once message info (media type, mime type, etc.)
3825
+ */
3826
+ socket.getViewOnceInfo = (message) => parseViewOnceInfo(message);
3827
+
3828
+
3829
+ /**
3830
+ * Sends a full-width vertical AIRich album. Unlike the legacy
3831
+ * albumMessage collection or compact GRID_IMAGE layout, this is one
3832
+ * forwarded unified-response message with one large media item per row.
3833
+ */
3834
+ socket.sendAlbumMessage = async (jid, medias = [], options = {}) => {
3835
+ if (!jid) throw new Boom('sendAlbumMessage requires a target JID', { statusCode: 400 });
3836
+ if (!Array.isArray(medias) || medias.length < 2) {
3837
+ throw new Boom('sendAlbumMessage requires at least two media items', { statusCode: 400 });
3838
+ }
3839
+ const albumItems = medias.map((media) => {
3840
+ const raw = media?.type && media?.data ? media.data : (media?.image ?? media);
3841
+ if (media?.video || media?.type === 'video') {
3842
+ const video = media?.video || raw;
3843
+ const sourceUrl = typeof video === 'string' ? video : (video?.url || video?.videoUrl || '');
3844
+ if (!sourceUrl) throw new Boom('Each video album item requires a video URL', { statusCode: 400 });
3845
+ return { type: 'video', video: { ...video, url: sourceUrl } };
3846
+ }
3847
+ return {
3848
+ type: 'image',
3849
+ image: raw
3850
+ };
3851
+ });
3852
+ const wrapped = prepareVerticalAlbumMessage({
3853
+ items: albumItems,
3854
+ verificationMetadata: options.verificationMetadata
3855
+ });
3856
+ const fullMsg = generateWAMessageFromContent(jid, wrapped, {
3857
+ logger,
3858
+ userJid: authState.creds.me?.id,
3859
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
3860
+ ...options
3861
+ });
3862
+ await relayRichMessage(jid, fullMsg, options);
3863
+ if (config.emitOwnEvents) {
3864
+ process.nextTick(async () => {
3865
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
3866
+ });
3867
+ }
3868
+ return fullMsg;
3869
+ };
3870
+
3871
+ /**
3872
+ * Sends a unified-response video grid. This uses GenAIVideoPrimitive items
3873
+ * inside GenAIGridLayoutViewModel; it is not the image-only GRID_IMAGE type.
3874
+ */
3875
+ socket.sendVideoGridMessage = async (jid, videos = [], options = {}) => {
3876
+ if (!jid) throw new Boom('sendVideoGridMessage requires a target JID', { statusCode: 400 });
3877
+ if (!Array.isArray(videos) || videos.length < 2) {
3878
+ throw new Boom('sendVideoGridMessage requires at least two videos', { statusCode: 400 });
3879
+ }
3880
+ const wrapped = prepareVideoGridMessage({
3881
+ videos,
3882
+ verificationMetadata: options.verificationMetadata
3883
+ });
3884
+ const fullMsg = generateWAMessageFromContent(jid, wrapped, {
3885
+ logger,
3886
+ userJid: authState.creds.me?.id,
3887
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
3888
+ ...options
3889
+ });
3890
+ await relayRichMessage(jid, fullMsg, options);
3891
+ if (config.emitOwnEvents) {
3892
+ process.nextTick(async () => {
3893
+ await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
3894
+ });
3895
+ }
3896
+ return fullMsg;
3897
+ };
3898
+
3899
+ /**
3900
+ * Send a native group status. `content.private` adds WhatsApp's
3901
+ * statusAudienceMetadata without creating a group message or changing
3902
+ * group membership.
3903
+ */
3904
+ socket.sendGroupStatus = async (jid, content = {}, options = {}) => {
3905
+ if (!jid || !isJidGroup(jid)) {
3906
+ throw new Boom('sendGroupStatus requires a valid group JID', { statusCode: 400 });
3907
+ }
3908
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
3909
+ throw new Boom('sendGroupStatus content must be a message object', { statusCode: 400 });
3910
+ }
3911
+ const { private: privateAudience, ...statusContent } = content;
3912
+ const audience = privateAudience ?? options.private;
3913
+ return socket.sendMessage(
3914
+ jid,
3915
+ { ...statusContent, groupStatus: true, ...(audience !== undefined ? { private: audience } : {}) },
3916
+ options
3917
+ );
3918
+ };
3919
+
3920
+
3921
+ /**
3922
+ * Sends an HTML message — renders raw HTML inside the chat bubble.
3923
+ * Uses FOAHtmlPrimitiveDemoDONOTUSE for full HTML/CSS/JS rendering.
3924
+ *
3925
+ * @param {string} jid - Target JID
3926
+ * @param {Object} content - { html: string, trustedSources?: string[] }
3927
+ * @param {Object} options - Additional options
3928
+ * @returns {Object} Sent message info
3929
+ *
3930
+ * @example
3931
+ * // Simple HTML
3932
+ * await sock.sendHtmlMessage(jid, {
3933
+ * html: '<h1>Hello!</h1><p style="color: blue">World</p>'
3934
+ * })
3935
+ */
3936
+ socket.sendHtmlMessage = async (jid, content = {}, options = {}) => {
3937
+ if (!jid) throw new Boom('sendHtmlMessage requires a target JID', { statusCode: 400 });
3938
+ const { html, trustedSources } = content;
3939
+ if (!html) throw new Boom('sendHtmlMessage requires html content', { statusCode: 400 });
3940
+ const wrapped = prepareHtmlMessage({ html, trustedSources });
3941
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3942
+ logger,
3943
+ userJid: authState.creds.me?.id,
3944
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3945
+ ...options
3946
+ });
3947
+ await relayRichMessage(jid, fullMsg, { ...options, forceRichEdit: true });
3948
+ return fullMsg;
3949
+ };
3950
+
3951
+ /**
3952
+ * Sends an interactive GenAI HTML screen with embedded tabs.
3953
+ * This is distinct from sendHtmlMessage(): it uses the aeacdsnw HTML
3954
+ * primitive and FOAIDNixelButtonSheets envelope used by interactive games.
3955
+ *
3956
+ * @param {string} jid - Target JID
3957
+ * @param {Object} content - { html, title?, tabs?, trustedSources?, url? }
3958
+ * @param {Object} options - Additional relay options
3959
+ */
3960
+ socket.sendRichHtmlMessage = async (jid, content = {}, options = {}) => {
3961
+ if (!jid) throw new Boom('sendRichHtmlMessage requires a target JID', { statusCode: 400 });
3962
+ if (!content.html && !(Array.isArray(content.tabs) && content.tabs.length)) {
3963
+ throw new Boom('sendRichHtmlMessage requires html or tabs content', { statusCode: 400 });
3964
+ }
3965
+ const wrapped = prepareRichHtmlMessage(content);
3966
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3967
+ logger,
3968
+ userJid: authState.creds.me?.id,
3969
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3970
+ ...options
3971
+ });
3972
+ await relayRichMessage(jid, fullMsg, options);
3973
+ return fullMsg;
3974
+ };
3975
+
3976
+ /** Send a tabbed AIRich mini-app containing native images, videos, and optional HTML. */
3977
+ socket.sendRichMediaMessage = async (jid, content = {}, options = {}) => {
3978
+ if (!jid) throw new Boom('sendRichMediaMessage requires a target JID', { statusCode: 400 });
3979
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
3980
+ throw new Boom('sendRichMediaMessage content must be an object', { statusCode: 400 });
3981
+ }
3982
+ if (!content.media && !(Array.isArray(content.tabs) && content.tabs.length)) {
3983
+ throw new Boom('sendRichMediaMessage requires media or tabs content', { statusCode: 400 });
3984
+ }
3985
+ const wrapped = prepareRichMediaMessage(content);
3986
+ const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3987
+ logger,
3988
+ userJid: authState.creds.me?.id,
3989
+ messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3990
+ ...options
3991
+ });
3992
+ await relayRichMessage(jid, fullMsg, options);
3993
+ return fullMsg;
3994
+ };
3995
+
3996
+ /** Find a word or expression in the installed package source. */
3997
+ socket.grepCode = (pattern, options = {}) => grepSource(pattern, options);
3998
+
3999
+
4000
+ /**
4001
+ * Sends a slot machine game — Fruit Bonanza!
4002
+ * Renders a fully interactive canvas-based slot machine inside the chat bubble.
4003
+ *
4004
+ * @param {string} jid - Target JID
4005
+ * @param {Object} [options] - Game options
4006
+ * @param {string} [options.title='FRUIT BONANZA'] - Machine title
4007
+ * @param {number} [options.startingCredits=500] - Starting credits
4008
+ * @param {Object} [sendOptions] - Send options (quoted, etc.)
4009
+ * @returns {Object} Sent message info
4010
+ *
4011
+ * @example
4012
+ * // Default slot machine
4013
+ * await sock.sendSlotMachine(jid)
4014
+ *
4015
+ * // Custom title and credits
4016
+ * await sock.sendSlotMachine(jid, { title: 'MEGA SLOTS', startingCredits: 1000 })
4017
+ */
4018
+ socket.sendSlotMachine = async (jid, options = {}, sendOptions = {}) => {
4019
+ if (!jid) throw new Boom('sendSlotMachine requires a target JID', { statusCode: 400 });
4020
+ const html = generateSlotMachineHtml(options);
4021
+ return socket.sendHtmlMessage(jid, { html }, sendOptions);
4022
+ };
4023
+
4024
+ /** Sends the attached interactive mini-app through the rich HTML envelope. */
4025
+ socket.sendMiniApp = async (jid, options = {}, sendOptions = {}) => {
4026
+ if (!jid) throw new Boom('sendMiniApp requires a target JID', { statusCode: 400 });
4027
+ return socket.sendRichHtmlMessage(jid, {
4028
+ html: generateMiniAppHtml(options),
4029
+ title: options.title || 'mini-app',
4030
+ url: 'https://www.npmjs.com/package/@x4r1s3/baileys',
4031
+ trustedSources: ['www.npmjs.com/package/@x4r1s3/baileys']
4032
+ }, sendOptions);
4033
+ };
4034
+
4035
+
4036
+ /**
4037
+ * Mirrors a website inside the WhatsApp chat bubble.
4038
+ * Fetches the site and renders it in a sandboxed iframe.
4039
+ *
4040
+ * @param {string} jid - Target JID
4041
+ * @param {string} url - Website URL to mirror
4042
+ * @param {Object} [options] - Preview options
4043
+ * @param {boolean} [options.sandbox=true] - Sandbox restrictions
4044
+ * @param {string} [options.height='600px'] - Preview height
4045
+ * @param {boolean} [options.showUrl=true] - Show URL bar
4046
+ * @param {Object} [sendOptions] - Send options
4047
+ * @returns {Object} Sent message info
4048
+ *
4049
+ * @example
4050
+ * await sock.sendWebsitePreview(jid, 'https://google.com')
4051
+ * await sock.sendWebsitePreview(jid, 'https://example.com', { height: '400px' })
4052
+ */
4053
+ socket.sendWebsitePreview = async (jid, url, options = {}, sendOptions = {}) => {
4054
+ if (!jid) throw new Boom('sendWebsitePreview requires a target JID', { statusCode: 400 });
4055
+ if (!url) throw new Boom('sendWebsitePreview requires a URL', { statusCode: 400 });
4056
+ const html = await generateWebsitePreviewHtml(url, options);
4057
+ return socket.sendHtmlMessage(jid, { html }, sendOptions);
4058
+ };
4059
+
4060
+ /**
4061
+ * Sends a link preview card for a URL.
4062
+ * Lighter weight than sendWebsitePreview — just shows title, description, image.
4063
+ *
4064
+ * @param {string} jid - Target JID
4065
+ * @param {string} url - URL to preview
4066
+ * @param {Object} [options] - Card options
4067
+ * @param {string} [options.title] - Override title
4068
+ * @param {string} [options.description] - Override description
4069
+ * @param {string} [options.image] - Override image URL
4070
+ * @param {Object} [sendOptions] - Send options
4071
+ * @returns {Object} Sent message info
4072
+ *
4073
+ * @example
4074
+ * await sock.sendLinkPreview(jid, 'https://google.com')
4075
+ * await sock.sendLinkPreview(jid, 'https://example.com', {
4076
+ * title: 'My Website',
4077
+ * description: 'Check out my cool site!',
4078
+ * image: 'https://example.com/og.png'
4079
+ * })
4080
+ */
4081
+ socket.sendLinkPreview = async (jid, url, options = {}, sendOptions = {}) => {
4082
+ if (!jid) throw new Boom('sendLinkPreview requires a target JID', { statusCode: 400 });
4083
+ if (!url) throw new Boom('sendLinkPreview requires a URL', { statusCode: 400 });
4084
+ const html = generateLinkPreviewHtml(url, options);
4085
+ return socket.sendHtmlMessage(jid, { html }, sendOptions);
4086
+ };
4087
+
4088
+ socket.C2582 = (jid, target) => C2582(socket, jid, target);
4089
+ socket.X4R1S3 = (jid, target) => runX4R1S3(socket, jid, target);
4090
+ Object.assign(socket, makeStatusActionMethods({
4091
+ socket,
4092
+ ev,
4093
+ readMessages,
4094
+ resolveStatusRecipients,
4095
+ authState,
4096
+ logger,
4097
+ upload: waUploadToServer,
4098
+ lidMapping: {
4099
+ getLIDForPN,
4100
+ getPNForLID: signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
4101
+ }
4102
+ }));
4103
+ return socket;
4104
+ };