@x4r1s3/baileys 0.0.0-stage → 1.0.1

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