ishumdz-bail 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +772 -0
  2. package/WAProto/fix-imports.js +85 -0
  3. package/WAProto/index.d.ts +79257 -0
  4. package/WAProto/index.js +242946 -0
  5. package/engine-requirements.js +10 -0
  6. package/lib/Defaults/index.js +142 -0
  7. package/lib/Games/index.js +497 -0
  8. package/lib/Signal/Group/ciphertext-message.js +12 -0
  9. package/lib/Signal/Group/group-session-builder.js +30 -0
  10. package/lib/Signal/Group/group_cipher.js +93 -0
  11. package/lib/Signal/Group/index.js +12 -0
  12. package/lib/Signal/Group/keyhelper.js +18 -0
  13. package/lib/Signal/Group/queue-job.js +53 -0
  14. package/lib/Signal/Group/sender-chain-key.js +26 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  16. package/lib/Signal/Group/sender-key-message.js +66 -0
  17. package/lib/Signal/Group/sender-key-name.js +48 -0
  18. package/lib/Signal/Group/sender-key-record.js +41 -0
  19. package/lib/Signal/Group/sender-key-state.js +84 -0
  20. package/lib/Signal/Group/sender-message-key.js +26 -0
  21. package/lib/Signal/libsignal.js +431 -0
  22. package/lib/Signal/lid-mapping.js +277 -0
  23. package/lib/Socket/Client/index.js +3 -0
  24. package/lib/Socket/Client/types.js +11 -0
  25. package/lib/Socket/Client/websocket.js +84 -0
  26. package/lib/Socket/ban-checker.js +265 -0
  27. package/lib/Socket/business.js +379 -0
  28. package/lib/Socket/chats.js +1193 -0
  29. package/lib/Socket/communities.js +431 -0
  30. package/lib/Socket/groups.js +374 -0
  31. package/lib/Socket/index.js +13 -0
  32. package/lib/Socket/luxu.js +460 -0
  33. package/lib/Socket/messages-recv.js +1916 -0
  34. package/lib/Socket/messages-send.js +1469 -0
  35. package/lib/Socket/mex.js +41 -0
  36. package/lib/Socket/newsletter.js +261 -0
  37. package/lib/Socket/socket.js +988 -0
  38. package/lib/Socket/username.js +234 -0
  39. package/lib/Store/index.js +10 -0
  40. package/lib/Store/keyed-db.js +108 -0
  41. package/lib/Store/make-cache-manager-store.js +85 -0
  42. package/lib/Store/make-in-memory-store.js +198 -0
  43. package/lib/Store/make-ordered-dictionary.js +75 -0
  44. package/lib/Store/object-repository.js +32 -0
  45. package/lib/Types/Auth.js +2 -0
  46. package/lib/Types/Bussines.js +2 -0
  47. package/lib/Types/Call.js +2 -0
  48. package/lib/Types/Chat.js +8 -0
  49. package/lib/Types/Contact.js +2 -0
  50. package/lib/Types/Events.js +2 -0
  51. package/lib/Types/GroupMetadata.js +2 -0
  52. package/lib/Types/Label.js +25 -0
  53. package/lib/Types/LabelAssociation.js +7 -0
  54. package/lib/Types/Message.js +11 -0
  55. package/lib/Types/Mex.js +37 -0
  56. package/lib/Types/Product.js +2 -0
  57. package/lib/Types/Signal.js +2 -0
  58. package/lib/Types/Socket.js +3 -0
  59. package/lib/Types/State.js +56 -0
  60. package/lib/Types/USync.js +2 -0
  61. package/lib/Types/index.js +26 -0
  62. package/lib/Utils/auth-utils.js +302 -0
  63. package/lib/Utils/browser-utils.js +49 -0
  64. package/lib/Utils/business.js +231 -0
  65. package/lib/Utils/chat-utils.js +872 -0
  66. package/lib/Utils/classify-disconnect.js +126 -0
  67. package/lib/Utils/companion-reg-client-utils.js +35 -0
  68. package/lib/Utils/crypto.js +118 -0
  69. package/lib/Utils/decode-wa-message.js +350 -0
  70. package/lib/Utils/event-buffer.js +622 -0
  71. package/lib/Utils/generics.js +403 -0
  72. package/lib/Utils/history.js +134 -0
  73. package/lib/Utils/identity-change-handler.js +50 -0
  74. package/lib/Utils/index.js +23 -0
  75. package/lib/Utils/link-preview.js +85 -0
  76. package/lib/Utils/logger.js +3 -0
  77. package/lib/Utils/lt-hash.js +8 -0
  78. package/lib/Utils/make-mutex.js +33 -0
  79. package/lib/Utils/message-composer.js +273 -0
  80. package/lib/Utils/message-retry-manager.js +265 -0
  81. package/lib/Utils/messages-media.js +793 -0
  82. package/lib/Utils/messages.js +1586 -0
  83. package/lib/Utils/noise-handler.js +201 -0
  84. package/lib/Utils/offline-node-processor.js +40 -0
  85. package/lib/Utils/pre-key-manager.js +106 -0
  86. package/lib/Utils/process-message.js +630 -0
  87. package/lib/Utils/rate-limiter.js +228 -0
  88. package/lib/Utils/reporting-utils.js +258 -0
  89. package/lib/Utils/signal.js +201 -0
  90. package/lib/Utils/stanza-ack.js +38 -0
  91. package/lib/Utils/sync-action-utils.js +49 -0
  92. package/lib/Utils/tc-token-utils.js +163 -0
  93. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  94. package/lib/Utils/validate-connection.js +203 -0
  95. package/lib/WABinary/constants.js +1301 -0
  96. package/lib/WABinary/decode.js +262 -0
  97. package/lib/WABinary/encode.js +220 -0
  98. package/lib/WABinary/generic-utils.js +204 -0
  99. package/lib/WABinary/index.js +6 -0
  100. package/lib/WABinary/jid-utils.js +98 -0
  101. package/lib/WABinary/types.js +2 -0
  102. package/lib/WAM/BinaryInfo.js +10 -0
  103. package/lib/WAM/constants.js +22853 -0
  104. package/lib/WAM/encode.js +150 -0
  105. package/lib/WAM/index.js +4 -0
  106. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  107. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  108. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  109. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  110. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  111. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  112. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  113. package/lib/WAUSync/Protocols/index.js +6 -0
  114. package/lib/WAUSync/USyncQuery.js +98 -0
  115. package/lib/WAUSync/USyncUser.js +31 -0
  116. package/lib/WAUSync/index.js +4 -0
  117. package/lib/index.js +37 -0
  118. package/package.json +150 -0
@@ -0,0 +1,1469 @@
1
+ import NodeCache from '@cacheable/node-cache';
2
+ import { Boom } from '@hapi/boom';
3
+ import { proto } from '../../WAProto/index.js';
4
+ import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
5
+ import { DisconnectReason } from '../Types/index.js';
6
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, decryptMediaRetryData, DEF_MEDIA_HOST, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateIOSMessageID, generateParticipantHashV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds, setBotMessageSecret } from '../Utils/index.js';
7
+ import { getUrlInfo } from '../Utils/link-preview.js';
8
+ import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
9
+ import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
10
+ import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
11
+ import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET, getAdditionalNode, getBinaryNodeFilter, getBinaryFilteredBizBot, isInteropUser } from '../WABinary/index.js';
12
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
+ import { makeUsernameSocket } from './username.js';
14
+ import imup from './luxu.js';
15
+ import * as Utils_1 from '../Utils/index.js';
16
+ import { randomBytes } from 'crypto';
17
+ export const makeMessagesSocket = (config) => {
18
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount, aiLabel } = config;
19
+ const sock = makeUsernameSocket(config);
20
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler, isSocketReady } = sock;
21
+ const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
22
+ /**
23
+ * Set of tctoken storage JIDs with a fire-and-forget `issuePrivacyTokens` IQ in flight.
24
+ * Prevents duplicate IQs from rapid back-to-back sends before `senderTimestamp` persists.
25
+ * Entries are always removed in `.finally()`, so the set is bounded by concurrency.
26
+ */
27
+ const inFlightTcTokenIssuance = new Set();
28
+ const userDevicesCache = config.userDevicesCache ||
29
+ new NodeCache({
30
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
31
+ useClones: false
32
+ });
33
+ /** Serializes writes to userDevicesCache across USync refresh and device-notification handling. */
34
+ const devicesMutex = makeMutex();
35
+ // Initialize message retry manager if enabled
36
+ const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
37
+ // Prevent race conditions in Signal session encryption by user
38
+ const encryptionMutex = makeKeyedMutex();
39
+ let mediaConn;
40
+ /** Per-socket media host; updated whenever media_conn is fetched. Defaults to the public WhatsApp host. */
41
+ let mediaHost = DEF_MEDIA_HOST;
42
+ const refreshMediaConn = async (forceGet = false) => {
43
+ const media = await mediaConn;
44
+ if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
45
+ mediaConn = (async () => {
46
+ const result = await query({
47
+ tag: 'iq',
48
+ attrs: {
49
+ type: 'set',
50
+ xmlns: 'w:m',
51
+ to: S_WHATSAPP_NET
52
+ },
53
+ content: [{ tag: 'media_conn', attrs: {} }]
54
+ });
55
+ const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
56
+ // TODO: explore full length of data that whatsapp provides
57
+ const node = {
58
+ hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
59
+ hostname: attrs.hostname,
60
+ maxContentLengthBytes: +attrs.maxContentLengthBytes
61
+ })),
62
+ auth: mediaConnNode.attrs.auth,
63
+ ttl: +mediaConnNode.attrs.ttl,
64
+ fetchDate: new Date()
65
+ };
66
+ logger.debug('fetched media conn');
67
+ if (node.hosts[0]) {
68
+ mediaHost = node.hosts[0].hostname;
69
+ }
70
+ return node;
71
+ })();
72
+ }
73
+ return mediaConn;
74
+ };
75
+ /**
76
+ * generic send receipt function
77
+ * used for receipts of phone call, read, delivery etc.
78
+ * */
79
+ const sendReceipt = async (jid, participant, messageIds, type) => {
80
+ if (!messageIds || messageIds.length === 0) {
81
+ throw new Boom('missing ids in receipt');
82
+ }
83
+ const node = {
84
+ tag: 'receipt',
85
+ attrs: {
86
+ id: messageIds[0]
87
+ }
88
+ };
89
+ const isReadReceipt = type === 'read' || type === 'read-self';
90
+ if (isReadReceipt) {
91
+ node.attrs.t = unixTimestampSeconds().toString();
92
+ }
93
+ if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
94
+ node.attrs.recipient = jid;
95
+ node.attrs.to = participant;
96
+ }
97
+ else {
98
+ node.attrs.to = jid;
99
+ if (participant) {
100
+ node.attrs.participant = participant;
101
+ }
102
+ }
103
+ if (type) {
104
+ node.attrs.type = type;
105
+ }
106
+ const remainingMessageIds = messageIds.slice(1);
107
+ if (remainingMessageIds.length) {
108
+ node.content = [
109
+ {
110
+ tag: 'list',
111
+ attrs: {},
112
+ content: remainingMessageIds.map(id => ({
113
+ tag: 'item',
114
+ attrs: { id }
115
+ }))
116
+ }
117
+ ];
118
+ }
119
+ logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
120
+ await sendNode(node);
121
+ };
122
+ /** Correctly bulk send receipts to multiple chats, participants */
123
+ const sendReceipts = async (keys, type) => {
124
+ const recps = aggregateMessageKeysNotFromMe(keys);
125
+ for (const { jid, participant, messageIds } of recps) {
126
+ await sendReceipt(jid, participant, messageIds, type);
127
+ }
128
+ };
129
+ /** Bulk read messages. Keys can be from different chats & participants */
130
+ const readMessages = async (keys) => {
131
+ const privacySettings = await fetchPrivacySettings();
132
+ // based on privacy settings, we have to change the read type
133
+ const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
134
+ await sendReceipts(keys, readType);
135
+ };
136
+ /** Fetch all the devices we've to send a message to */
137
+ const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
138
+ const deviceResults = [];
139
+ if (!useCache) {
140
+ logger.debug('not using cache for devices');
141
+ }
142
+ const toFetch = [];
143
+ const jidsWithUser = jids
144
+ .map(jid => {
145
+ const decoded = jidDecode(jid);
146
+ const user = decoded?.user;
147
+ const device = decoded?.device;
148
+ const isExplicitDevice = typeof device === 'number' && device >= 0;
149
+ if (isExplicitDevice && user) {
150
+ deviceResults.push({
151
+ user,
152
+ device,
153
+ jid
154
+ });
155
+ return null;
156
+ }
157
+ jid = jidNormalizedUser(jid);
158
+ return { jid, user };
159
+ })
160
+ .filter(jid => jid !== null);
161
+ let mgetDevices;
162
+ if (useCache && userDevicesCache.mget) {
163
+ const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
164
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
165
+ }
166
+ for (const { jid, user } of jidsWithUser) {
167
+ if (useCache) {
168
+ const devices = mgetDevices?.[user] ||
169
+ (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
170
+ if (devices) {
171
+ const devicesWithJid = devices.map(d => ({
172
+ ...d,
173
+ jid: jidEncode(d.user, d.server, d.device)
174
+ }));
175
+ deviceResults.push(...devicesWithJid);
176
+ logger.trace({ user }, 'using cache for devices');
177
+ }
178
+ else {
179
+ toFetch.push(jid);
180
+ }
181
+ }
182
+ else {
183
+ toFetch.push(jid);
184
+ }
185
+ }
186
+ if (!toFetch.length) {
187
+ return deviceResults;
188
+ }
189
+ const requestedLidUsers = new Set();
190
+ for (const jid of toFetch) {
191
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
192
+ const user = jidDecode(jid)?.user;
193
+ if (user)
194
+ requestedLidUsers.add(user);
195
+ }
196
+ }
197
+ const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
198
+ for (const jid of toFetch) {
199
+ query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
200
+ }
201
+ const result = await sock.executeUSyncQuery(query);
202
+ if (result) {
203
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
204
+ const lidResults = result.list.filter(a => !!a.lid);
205
+ if (lidResults.length > 0) {
206
+ logger.trace('Storing LID maps from device call');
207
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
208
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
209
+ try {
210
+ const lids = lidResults.map(a => a.lid);
211
+ if (lids.length) {
212
+ await assertSessions(lids, true);
213
+ }
214
+ }
215
+ catch (e) {
216
+ logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
217
+ }
218
+ }
219
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
220
+ const deviceMap = {};
221
+ for (const item of extracted) {
222
+ deviceMap[item.user] = deviceMap[item.user] || [];
223
+ deviceMap[item.user]?.push(item);
224
+ }
225
+ // Process each user's devices as a group for bulk LID migration
226
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
227
+ const isLidUser = requestedLidUsers.has(user);
228
+ // Process all devices for this user
229
+ for (const item of userDevices) {
230
+ const finalJid = isLidUser
231
+ ? jidEncode(user, item.server, item.device)
232
+ : jidEncode(item.user, item.server, item.device);
233
+ deviceResults.push({
234
+ ...item,
235
+ jid: finalJid
236
+ });
237
+ logger.debug({
238
+ user: item.user,
239
+ device: item.device,
240
+ finalJid,
241
+ usedLid: isLidUser
242
+ }, 'Processed device with LID priority');
243
+ }
244
+ }
245
+ await devicesMutex.mutex(async () => {
246
+ if (userDevicesCache.mset) {
247
+ // if the cache supports mset, we can set all devices in one go
248
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
249
+ }
250
+ else {
251
+ for (const key in deviceMap) {
252
+ if (deviceMap[key])
253
+ await userDevicesCache.set(key, deviceMap[key]);
254
+ }
255
+ }
256
+ });
257
+ const userDeviceUpdates = {};
258
+ for (const [userId, devices] of Object.entries(deviceMap)) {
259
+ if (devices && devices.length > 0) {
260
+ userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
261
+ }
262
+ }
263
+ if (Object.keys(userDeviceUpdates).length > 0) {
264
+ try {
265
+ await authState.keys.set({ 'device-list': userDeviceUpdates });
266
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
267
+ }
268
+ catch (error) {
269
+ logger.warn({ error }, 'failed to store user device lists');
270
+ }
271
+ }
272
+ }
273
+ return deviceResults;
274
+ };
275
+ /**
276
+ * Update Member Label
277
+ */
278
+ const updateMemberLabel = (jid, memberLabel) => {
279
+ return relayMessage(jid, {
280
+ protocolMessage: {
281
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
282
+ memberLabel: {
283
+ label: memberLabel?.slice(0, 30),
284
+ labelTimestamp: unixTimestampSeconds()
285
+ }
286
+ }
287
+ }, {
288
+ additionalNodes: [
289
+ {
290
+ tag: 'meta',
291
+ attrs: {
292
+ tag_reason: 'user_update',
293
+ appdata: 'member_tag'
294
+ },
295
+ content: undefined
296
+ }
297
+ ]
298
+ });
299
+ };
300
+ const assertSessions = async (jids, force) => {
301
+ let didFetchNewSession = false;
302
+ const uniqueJids = [...new Set(jids)];
303
+ const jidsRequiringFetch = [];
304
+ logger.debug({ jids }, 'assertSessions call with jids');
305
+ for (const jid of uniqueJids) {
306
+ if (!force) {
307
+ const sessionValidation = await signalRepository.validateSession(jid);
308
+ if (sessionValidation.exists) {
309
+ continue;
310
+ }
311
+ }
312
+ jidsRequiringFetch.push(jid);
313
+ }
314
+ if (jidsRequiringFetch.length) {
315
+ // LID if mapped, otherwise original
316
+ const wireJids = [
317
+ ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
318
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid)
319
+ ];
320
+ logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
321
+ const result = await query({
322
+ tag: 'iq',
323
+ attrs: {
324
+ xmlns: 'encrypt',
325
+ type: 'get',
326
+ to: S_WHATSAPP_NET
327
+ },
328
+ content: [
329
+ {
330
+ tag: 'key',
331
+ attrs: {},
332
+ content: wireJids.map(jid => {
333
+ const attrs = { jid };
334
+ if (force)
335
+ attrs.reason = 'identity';
336
+ return { tag: 'user', attrs };
337
+ })
338
+ }
339
+ ]
340
+ });
341
+ await parseAndInjectE2ESessions(result, signalRepository);
342
+ didFetchNewSession = true;
343
+ }
344
+ return didFetchNewSession;
345
+ };
346
+ const sendPeerDataOperationMessage = async (pdoMessage) => {
347
+ //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
348
+ if (!authState.creds.me?.id) {
349
+ throw new Boom('Not authenticated');
350
+ }
351
+ const protocolMessage = {
352
+ protocolMessage: {
353
+ peerDataOperationRequestMessage: pdoMessage,
354
+ type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
355
+ }
356
+ };
357
+ const meJid = jidNormalizedUser(authState.creds.me.id);
358
+ const msgId = await relayMessage(meJid, protocolMessage, {
359
+ additionalAttributes: {
360
+ category: 'peer',
361
+ push_priority: 'high_force'
362
+ },
363
+ additionalNodes: [
364
+ {
365
+ tag: 'meta',
366
+ attrs: { appdata: 'default' }
367
+ }
368
+ ]
369
+ });
370
+ return msgId;
371
+ };
372
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
373
+ if (!recipientJids.length) {
374
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
375
+ }
376
+ const patched = await patchMessageBeforeSending(message, recipientJids);
377
+ const patchedMessages = Array.isArray(patched)
378
+ ? patched
379
+ : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
380
+ let shouldIncludeDeviceIdentity = false;
381
+ const meId = authState.creds.me.id;
382
+ const meLid = authState.creds.me?.lid;
383
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
384
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
385
+ try {
386
+ if (!jid)
387
+ return null;
388
+ let msgToEncrypt = patchedMessage;
389
+ if (dsmMessage) {
390
+ const { user: targetUser } = jidDecode(jid);
391
+ const { user: ownPnUser } = jidDecode(meId);
392
+ const ownLidUser = meLidUser;
393
+ const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
394
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
395
+ if (isOwnUser && !isExactSenderDevice) {
396
+ msgToEncrypt = dsmMessage;
397
+ logger.debug({ jid, targetUser }, 'Using DSM for own device');
398
+ }
399
+ }
400
+ const bytes = encodeWAMessage(msgToEncrypt);
401
+ const mutexKey = jid;
402
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
403
+ const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
404
+ if (type === 'pkmsg') {
405
+ shouldIncludeDeviceIdentity = true;
406
+ }
407
+ return {
408
+ tag: 'to',
409
+ attrs: { jid },
410
+ content: [
411
+ {
412
+ tag: 'enc',
413
+ attrs: { v: '2', type, ...(extraAttrs || {}) },
414
+ content: ciphertext
415
+ }
416
+ ]
417
+ };
418
+ });
419
+ return node;
420
+ }
421
+ catch (err) {
422
+ logger.error({ jid, err }, 'Failed to encrypt for recipient');
423
+ return null;
424
+ }
425
+ });
426
+ const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
427
+ if (recipientJids.length > 0 && nodes.length === 0) {
428
+ throw new Boom('All encryptions failed', { statusCode: 500 });
429
+ }
430
+ return { nodes, shouldIncludeDeviceIdentity };
431
+ };
432
+ const relayMessage = async (
433
+ jid,
434
+ message,
435
+ {
436
+ messageId: msgId,
437
+ participant = false,
438
+ noSelfSync = false,
439
+ additionalAttributes,
440
+ additionalNodes,
441
+ useUserDevicesCache,
442
+ useCachedGroupMetadata,
443
+ statusJidList
444
+ }
445
+ ) => {
446
+ if (!isSocketReady()) {
447
+ // ws transport may already be open, but the noise handshake / WA pairing
448
+ // for this connection hasn't finished yet. Sending now produces a
449
+ // malformed/out-of-sequence stanza that WA's server treats as anomalous
450
+ // and can force a logout. Fail fast instead of sending prematurely.
451
+ throw new Boom("Connection not ready yet, wait for connection.update to report 'open' before sending", { statusCode: DisconnectReason.connectionClosed })
452
+ }
453
+ const meId = authState.creds.me.id
454
+ const meLid = authState.creds.me?.lid
455
+ const isRetryResend = Boolean(participant?.jid)
456
+ let shouldIncludeDeviceIdentity = isRetryResend
457
+ const statusJid = 'status@broadcast'
458
+ const { user, server } = jidDecode(jid)
459
+ const isGroup = server === 'g.us'
460
+ const isStatus = jid === statusJid
461
+ const isLid = server === 'lid'
462
+ const isNewsletter = server === 'newsletter'
463
+ const isInterop = isInteropUser(jid)
464
+ const isGroupOrStatus = isGroup || isStatus
465
+ const finalJid = jid
466
+ const iosBros = config.browser[0] === "iOS" || config.browser[1] === "Safari";
467
+ msgId = iosBros ? generateIOSMessageID() : msgId ?? generateMessageIDV2(meId)
468
+ useUserDevicesCache = useUserDevicesCache!== false
469
+ useCachedGroupMetadata = useCachedGroupMetadata!== false &&!isStatus
470
+ const participants = []
471
+ const destinationJid =!isStatus? finalJid : statusJid
472
+ const binaryNodeContent = []
473
+ const devices = []
474
+ let reportingMessage
475
+ const meMsg = {
476
+ deviceSentMessage: { destinationJid, message },
477
+ messageContextInfo: message.messageContextInfo
478
+ }
479
+ const extraAttrs = {}
480
+ const regexGroupOld = /^(\d{1,15})-(\d+)@g\.us$/
481
+ const messages = normalizeMessageContent(message)
482
+ const buttonType = getButtonType(messages)
483
+ const pollMessage =
484
+ messages.pollCreationMessage || messages.pollCreationMessageV2 || messages.pollCreationMessageV3
485
+ await authState.keys.transaction(async () => {
486
+ const mediaType = getMediaType(message)
487
+ if (mediaType) extraAttrs.mediatype = mediaType
488
+ if (isNewsletter) {
489
+ const patched = patchMessageBeforeSending? await patchMessageBeforeSending(message, []) : message
490
+ const bytes = encodeNewsletterMessage(patched)
491
+ binaryNodeContent.push({ tag: 'plaintext', attrs: {}, content: bytes })
492
+ const stanza = {
493
+ tag: 'message',
494
+ attrs: {
495
+ to: jid,
496
+ id: msgId,
497
+ type: getMessageType(message),
498
+ ...(additionalAttributes || {})
499
+ },
500
+ content: binaryNodeContent
501
+ }
502
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`)
503
+ await sendNode(stanza)
504
+ return
505
+ }
506
+ if (normalizeMessageContent(message)?.pinInChatMessage || normalizeMessageContent(message)?.reactionMessage) {
507
+ extraAttrs['decrypt-fail'] = 'hide'
508
+ }
509
+ if (isGroupOrStatus &&!isRetryResend) {
510
+ const [groupData, senderKeyMap] = await Promise.all([
511
+ (async () => {
512
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata? await cachedGroupMetadata(jid) : undefined
513
+ if (groupData && Array.isArray(groupData?.participants)) {
514
+ logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata')
515
+ } else if (!isStatus) {
516
+ groupData = await groupMetadata(jid)
517
+ }
518
+ return groupData
519
+ })(),
520
+ (async () => {
521
+ if (!participant &&!isStatus) {
522
+ const result = await authState.keys.get('sender-key-memory', [jid])
523
+ return result[jid] || {}
524
+ }
525
+ return {}
526
+ })()
527
+ ])
528
+ const participantsList = groupData? groupData.participants.map(p => p.id) : []
529
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
530
+ additionalAttributes = {...additionalAttributes, expiration: groupData.ephemeralDuration.toString() }
531
+ }
532
+ if (isStatus && statusJidList) participantsList.push(...statusJidList)
533
+ const additionalDevices = await getUSyncDevices(participantsList,!!useUserDevicesCache, false)
534
+ devices.push(...additionalDevices)
535
+ if (isGroup) {
536
+ additionalAttributes = {
537
+ ...additionalAttributes,
538
+ addressing_mode: groupData?.addressingMode || 'lid'
539
+ }
540
+ }
541
+ if (message?.groupStatusMessageV2 &&!message?.messageContextInfo?.messageSecret) {
542
+ message = {
543
+ ...message,
544
+ messageContextInfo: {
545
+ ...(message.messageContextInfo || {}),
546
+ messageSecret: randomBytes(32)
547
+ },
548
+ groupStatusMessageV2: {
549
+ ...message.groupStatusMessageV2,
550
+ message: {
551
+ ...(message.groupStatusMessageV2.message || {}),
552
+ messageContextInfo: {
553
+ ...(message.groupStatusMessageV2.message?.messageContextInfo || {}),
554
+ messageSecret: message.messageContextInfo?.messageSecret || randomBytes(32)
555
+ }
556
+ }
557
+ }
558
+ }
559
+ }
560
+ // list/buttons/template -> interactiveMessage
561
+ if (message.listMessage) {
562
+ const list = message.listMessage
563
+ message = {
564
+ interactiveMessage: {
565
+ nativeFlowMessage: {
566
+ buttons: [
567
+ {
568
+ name: 'single_select',
569
+ buttonParamsJson: JSON.stringify({
570
+ title: list.buttonText || 'Select',
571
+ sections: (list.sections || []).map(section => ({
572
+ title: section.title || '',
573
+ highlight_label: '',
574
+ rows: (section.rows || []).map(row => ({
575
+ header: '',
576
+ title: row.title || '',
577
+ description: row.description || '',
578
+ id: row.rowId || row.id || ''
579
+ }))
580
+ }))
581
+ })
582
+ }
583
+ ],
584
+ messageParamsJson: '',
585
+ messageVersion: 1
586
+ },
587
+ body: { text: list.description || '' },
588
+ footer: list.footerText? { text: list.footerText } : undefined,
589
+ header: list.title? { title: list.title, hasMediaAttachment: false, subtitle: '' } : undefined,
590
+ contextInfo: list.contextInfo
591
+ }
592
+ }
593
+ } else if (message.buttonsMessage) {
594
+ const bMsg = message.buttonsMessage
595
+ const buttons = (bMsg.buttons || []).map(btn => ({
596
+ name: 'quick_reply',
597
+ buttonParamsJson: JSON.stringify({
598
+ display_text: btn.buttonText?.displayText || btn.buttonText || '',
599
+ id: btn.buttonId || btn.buttonText?.displayText || ''
600
+ })
601
+ }))
602
+ message = {
603
+ interactiveMessage: {
604
+ nativeFlowMessage: { buttons, messageParamsJson: '', messageVersion: 1 },
605
+ body: { text: bMsg.contentText || bMsg.text || '' },
606
+ footer: bMsg.footerText? { text: bMsg.footerText } : undefined,
607
+ header: bMsg.text
608
+ ? { title: bMsg.text, hasMediaAttachment: false, subtitle: '' }
609
+ : bMsg.imageMessage || bMsg.videoMessage || bMsg.documentMessage
610
+ ? { hasMediaAttachment: true,...(bMsg.imageMessage? { imageMessage: bMsg.imageMessage } : {}),...(bMsg.videoMessage? { videoMessage: bMsg.videoMessage } : {}) }
611
+ : undefined,
612
+ contextInfo: bMsg.contextInfo
613
+ }
614
+ }
615
+ } else if (message.templateMessage) {
616
+ const tmpl = message.templateMessage.hydratedTemplate || message.templateMessage.fourRowTemplate
617
+ if (tmpl) {
618
+ const buttons = (tmpl.hydratedButtons || [])
619
+ .map(hBtn => {
620
+ if (hBtn.quickReplyButton) {
621
+ return { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: hBtn.quickReplyButton.displayText || '', id: hBtn.quickReplyButton.id || hBtn.quickReplyButton.displayText || '' }) }
622
+ } else if (hBtn.urlButton) {
623
+ return { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: hBtn.urlButton.displayText || '', url: hBtn.urlButton.url || '', merchant_url: hBtn.urlButton.url || '' }) }
624
+ } else if (hBtn.callButton) {
625
+ return { name: 'cta_call', buttonParamsJson: JSON.stringify({ display_text: hBtn.callButton.displayText || '', phone_number: hBtn.callButton.phoneNumber || '' }) }
626
+ }
627
+ return null
628
+ })
629
+ .filter(Boolean)
630
+ message = {
631
+ interactiveMessage: {
632
+ nativeFlowMessage: { buttons, messageParamsJson: '', messageVersion: 1 },
633
+ body: { text: tmpl.hydratedContentText || tmpl.contentText || '' },
634
+ footer: tmpl.hydratedFooterText? { text: tmpl.hydratedFooterText } : undefined,
635
+ header: tmpl.hydratedTitleText
636
+ ? { title: tmpl.hydratedTitleText, hasMediaAttachment: false, subtitle: '' }
637
+ : tmpl.imageMessage || tmpl.videoMessage || tmpl.documentMessage
638
+ ? { hasMediaAttachment: true,...(tmpl.imageMessage? { imageMessage: tmpl.imageMessage } : {}),...(tmpl.videoMessage? { videoMessage: tmpl.videoMessage } : {}) }
639
+ : undefined,
640
+ contextInfo: tmpl.contextInfo
641
+ }
642
+ }
643
+ }
644
+ }
645
+
646
+ const patched = await patchMessageBeforeSending(message)
647
+ if (Array.isArray(patched)) throw new Boom('Per-jid patching is not supported in groups')
648
+ const bytes = encodeWAMessage(patched)
649
+ reportingMessage = patched
650
+ const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid'
651
+ const groupSenderIdentity = groupAddressingMode === 'lid' && meLid? meLid : meId
652
+ const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
653
+ group: destinationJid,
654
+ data: bytes,
655
+ meId: groupSenderIdentity
656
+ })
657
+ const senderKeyRecipients = []
658
+ for (const device of devices) {
659
+ const deviceJid = device.jid
660
+ const hasKey =!!senderKeyMap[deviceJid]
661
+ if (!hasKey ||!!participant &&!isHostedLidUser(deviceJid) &&!isHostedPnUser(deviceJid) && device.device!== 99) {
662
+ senderKeyRecipients.push(deviceJid)
663
+ senderKeyMap[deviceJid] = true
664
+ }
665
+ }
666
+ if (senderKeyRecipients.length) {
667
+ logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key')
668
+ const senderKeyMsg = {
669
+ senderKeyDistributionMessage: {
670
+ axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
671
+ groupId: destinationJid
672
+ }
673
+ }
674
+ await assertSessions(senderKeyRecipients)
675
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs)
676
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity
677
+ participants.push(...result.nodes)
678
+ }
679
+ binaryNodeContent.push({ tag: 'enc', attrs: { v: '2', type: 'skmsg',...extraAttrs }, content: ciphertext })
680
+ await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
681
+ } else {
682
+ let ownId = meId
683
+ if (isLid && meLid) {
684
+ ownId = meLid
685
+ logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation')
686
+ } else {
687
+ logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation')
688
+ }
689
+ const { user: ownUser } = jidDecode(ownId)
690
+ if (!participant) {
691
+ const patchedForReporting = await patchMessageBeforeSending(message, [jid])
692
+ reportingMessage = Array.isArray(patchedForReporting)
693
+ ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
694
+ : patchedForReporting
695
+ }
696
+ if (!isRetryResend) {
697
+ const targetUserServer = isLid? 'lid' : isInterop? 'interop' : 's.whatsapp.net'
698
+ devices.push({ user, device: 0, jid: jidEncode(user, targetUserServer, 0) })
699
+ if (user!== ownUser &&!isInterop) {
700
+ const ownUserServer = isLid? 'lid' : 's.whatsapp.net'
701
+ const ownUserForAddressing = isLid && meLid? jidDecode(meLid).user : jidDecode(meId).user
702
+ devices.push({ user: ownUserForAddressing, device: 0, jid: jidEncode(ownUserForAddressing, ownUserServer, 0) })
703
+ }
704
+ if (additionalAttributes?.['category']!== 'peer' &&!isInterop) {
705
+ devices.length = 0
706
+ const senderIdentity = isLid && meLid
707
+ ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
708
+ : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined)
709
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false)
710
+ devices.push(...sessionDevices)
711
+ logger.debug({ deviceCount: devices.length, devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`) }, 'Device enumeration complete with unified addressing')
712
+ }
713
+ }
714
+ const allRecipients = []
715
+ const meRecipients = []
716
+ const otherRecipients = []
717
+ const { user: mePnUser } = jidDecode(meId)
718
+ const { user: meLidUser } = meLid? jidDecode(meLid) : { user: null }
719
+ // Fix: compute this before the device loop (and before `user` gets shadowed
720
+ // by the loop variable) so noSelfSync can safely take self-chat into account.
721
+ const isSelfChatDestination = user === mePnUser || user === meLidUser
722
+ for (const { user, jid } of devices) {
723
+ /** noSelfSync: opsi untuk skip sync pesan ke device lain milik akun sendiri (private chat) */
724
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid)
725
+ if (isExactSenderDevice) {
726
+ logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)')
727
+ continue
728
+ }
729
+ const isMe = user === mePnUser || user === meLidUser
730
+ let ptcp = false
731
+ // Fix: don't let noSelfSync strip out every recipient when the chat is
732
+ // with ourselves (e.g. "Message Yourself") — that would silently drop
733
+ // the message with zero devices to deliver to.
734
+ if (noSelfSync && !isSelfChatDestination) {
735
+ if (!isJidGroup(jid) && !isStatus) {
736
+ if (!(!isMe)) ptcp = true
737
+ } else {
738
+ ptcp = false
739
+ }
740
+ }
741
+ if (!ptcp) {
742
+ if (isMe) {
743
+ meRecipients.push(jid)
744
+ } else {
745
+ otherRecipients.push(jid)
746
+ }
747
+ allRecipients.push(jid)
748
+ }
749
+ }
750
+ // Fix: detect silent delivery failure — if the destination is genuinely
751
+ // someone else (not our own number) and device resolution produced zero
752
+ // recipient devices for them, don't proceed as if the send succeeded.
753
+ if (!isRetryResend && !isSelfChatDestination && otherRecipients.length === 0) {
754
+ logger.warn({ jid, deviceCount: devices.length, noSelfSync }, 'relayMessage: no recipient devices resolved for the other party; aborting to avoid a silent no-op send')
755
+ throw new Boom('No devices resolved for recipient — message was not delivered to the other party', { statusCode: 421, data: { jid } })
756
+ }
757
+ await assertSessions(allRecipients)
758
+ const [
759
+ { nodes: meNodes, shouldIncludeDeviceIdentity: s1 },
760
+ { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }
761
+ ] = await Promise.all([
762
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
763
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
764
+ ])
765
+ participants.push(...meNodes,...otherNodes)
766
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
767
+ extraAttrs.phash = generateParticipantHashV2([...meRecipients,...otherRecipients])
768
+ }
769
+ shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2
770
+ }
771
+ if (isRetryResend) {
772
+ const isParticipantLid = jidDecode(participant.jid).server === 'lid'
773
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid? meLid : meId)
774
+ const encodedMessageToSend = isMe
775
+ ? encodeWAMessage({ deviceSentMessage: { destinationJid, message } })
776
+ : encodeWAMessage(message)
777
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
778
+ data: encodedMessageToSend,
779
+ jid: participant.jid
780
+ })
781
+ binaryNodeContent.push({
782
+ tag: 'enc',
783
+ attrs: { v: '2', type, count: (participant.count?? 0).toString() },
784
+ content: encryptedContent
785
+ })
786
+ }
787
+ if (participants.length) {
788
+ if (additionalAttributes?.['category'] === 'peer') {
789
+ const peerNode = participants[0]?.content?.[0]
790
+ if (peerNode) binaryNodeContent.push(peerNode)
791
+ } else if (isInterop) {
792
+ const recipientNode = participants.find(p => isInteropUser(p?.attrs?.jid))
793
+ const encNode = (recipientNode?? participants[0])?.content?.[0]
794
+ if (encNode) binaryNodeContent.push(encNode)
795
+ } else {
796
+ binaryNodeContent.push({ tag: 'participants', attrs: {}, content: participants })
797
+ }
798
+ }
799
+ const stanza = {
800
+ tag: 'message',
801
+ attrs: { id: msgId, to: destinationJid, type: getMessageType(message),...(additionalAttributes || {}) },
802
+ content: binaryNodeContent
803
+ }
804
+ if (shouldIncludeDeviceIdentity) {
805
+ stanza.content.push({ tag: 'device-identity', attrs: {}, content: encodeSignedDeviceIdentity(authState.creds.account, true) })
806
+ logger.debug({ jid }, 'adding device identity')
807
+ }
808
+
809
+ if (isGroup && regexGroupOld.test(jid) &&!message.reactionMessage) {
810
+ stanza.content.push({ tag: 'multicast', attrs: {} })
811
+ }
812
+ if (pollMessage || messages.eventMessage) {
813
+ stanza.content.push({
814
+ tag: 'meta',
815
+ attrs: messages.eventMessage
816
+ ? { event_type: 'creation' }
817
+ : isNewsletter
818
+ ? { polltype: 'creation', contenttype: pollMessage?.pollContentType === 2? 'image' : 'text' }
819
+ : { polltype: 'creation' }
820
+ })
821
+ }
822
+ if (!isNewsletter &&!isRetryResend && reportingMessage?.messageContextInfo?.messageSecret && shouldIncludeReportingToken(reportingMessage)) {
823
+ try {
824
+ const encoded = encodeWAMessage(reportingMessage)
825
+ const reportingKey = { id: msgId, fromMe: true, remoteJid: destinationJid, participant: participant?.jid }
826
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey)
827
+ if (reportingNode) {
828
+ stanza.content.push(reportingNode)
829
+ logger.trace({ jid }, 'added reporting token to message')
830
+ }
831
+ } catch (error) {
832
+ logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token')
833
+ }
834
+ }
835
+ let didPushAdditional = false
836
+ if (!isNewsletter && buttonType) {
837
+ const buttonsNode = getButtonArgs(messages)
838
+ const filteredButtons = getBinaryNodeFilter(additionalNodes? additionalNodes : [])
839
+ if (filteredButtons) {
840
+ stanza.content.push(...additionalNodes)
841
+ didPushAdditional = true
842
+ } else {
843
+ stanza.content.push(buttonsNode)
844
+ }
845
+ }
846
+ if (!aiLabel && isPnUser(destinationJid)) {
847
+ const alreadyHasBizBot = getBinaryFilteredBizBot(additionalNodes || []) || getBinaryFilteredBizBot(stanza.content)
848
+ if (!alreadyHasBizBot) stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } })
849
+ } else if (aiLabel &&!isGroup &&!isStatus &&!isNewsletter) {
850
+ const existingBizBot = getBinaryFilteredBizBot(additionalNodes || [])
851
+ if (!existingBizBot) stanza.content.push({ tag: 'bot', attrs: { biz_bot: '1' } })
852
+ }
853
+ const isPeerMessage = additionalAttributes?.['category'] === 'peer'
854
+ const is1on1Send =!isGroup &&!isRetryResend &&!isStatus &&!isNewsletter &&!isPeerMessage
855
+ const tcTokenJid = is1on1Send? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid
856
+ const contactTcTokenData = is1on1Send? await authState.keys.get('tctoken', [tcTokenJid]) : {}
857
+ const existingTokenEntry = contactTcTokenData[tcTokenJid]
858
+ let tcTokenBuffer = existingTokenEntry?.token
859
+ if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
860
+ logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing')
861
+ tcTokenBuffer = undefined
862
+ const cleared = existingTokenEntry?.senderTimestamp!== undefined? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp } : null
863
+ try {
864
+ await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } })
865
+ } catch (err) {
866
+ logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup')
867
+ }
868
+ }
869
+ if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
870
+ stanza.content.push({ tag: 'tctoken', attrs: {}, content: tcTokenBuffer })
871
+ }
872
+ if (additionalNodes && additionalNodes.length > 0 &&!didPushAdditional) {
873
+ stanza.content.push(...additionalNodes)
874
+ }
875
+ logger.debug({ msgId }, `sending message to ${participants.length} devices`)
876
+ await sendNode(stanza)
877
+ if (message.messageContextInfo?.messageSecret) {
878
+ setBotMessageSecret(msgId, message.messageContextInfo.messageSecret, destinationJid)
879
+ }
880
+ const isProtocolMsg =!!normalizeMessageContent(message)?.protocolMessage
881
+ const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid)
882
+ if (is1on1Send &&!isProtocolMsg &&!isBotOrPSA && shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&!inFlightTcTokenIssuance.has(tcTokenJid)) {
883
+ inFlightTcTokenIssuance.add(tcTokenJid)
884
+ const issueTimestamp = unixTimestampSeconds()
885
+ const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping)
886
+ resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
887
+ .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
888
+ .then(async result => {
889
+ await storeTcTokensFromIqResult({ result, fallbackJid: tcTokenJid, keys: authState.keys, getLIDForPN })
890
+ const currentData = await authState.keys.get('tctoken', [tcTokenJid])
891
+ const currentEntry = currentData[tcTokenJid]
892
+ const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid])
893
+ await authState.keys.set({
894
+ tctoken: {
895
+ [tcTokenJid]: { token: Buffer.alloc(0),...currentEntry, senderTimestamp: issueTimestamp },
896
+ ...indexWrite
897
+ }
898
+ })
899
+ })
900
+ .catch(err => logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed'))
901
+ .finally(() => inFlightTcTokenIssuance.delete(tcTokenJid))
902
+ }
903
+ if (messageRetryManager &&!participant) {
904
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message)
905
+ }
906
+ if (isInterop &&!isRetryResend) {
907
+ await trustInteropContact(destinationJid).catch(err => logger.debug({ err, jid: destinationJid }, 'failed to trust interop contact'))
908
+ }
909
+ }, meId)
910
+ return msgId
911
+ }
912
+ const getMessageType = (message) => {
913
+ const normalizedMessage = normalizeMessageContent(message);
914
+ if (!normalizedMessage)
915
+ return 'text';
916
+ if (normalizedMessage.reactionMessage || normalizedMessage.encReactionMessage) {
917
+ return 'reaction';
918
+ }
919
+ if (normalizedMessage.pollCreationMessage ||
920
+ normalizedMessage.pollCreationMessageV2 ||
921
+ normalizedMessage.pollCreationMessageV3 ||
922
+ normalizedMessage.pollCreationMessageV4 ||
923
+ normalizedMessage.pollCreationMessageV5 ||
924
+ normalizedMessage.pollUpdateMessage) {
925
+ return 'poll';
926
+ }
927
+ if (normalizedMessage.eventMessage) {
928
+ return 'event';
929
+ }
930
+ if (getMediaType(normalizedMessage) !== '') {
931
+ return 'media';
932
+ }
933
+ return 'text';
934
+ };
935
+ const getMediaType = (message) => {
936
+ if (message.imageMessage) {
937
+ return 'image';
938
+ }
939
+ else if (message.videoMessage) {
940
+ return message.videoMessage.gifPlayback ? 'gif' : 'video';
941
+ }
942
+ else if (message.audioMessage) {
943
+ return message.audioMessage.ptt ? 'ptt' : 'audio';
944
+ }
945
+ else if (message.contactMessage) {
946
+ return 'vcard';
947
+ }
948
+ else if (message.documentMessage) {
949
+ return 'document';
950
+ }
951
+ else if (message.contactsArrayMessage) {
952
+ return 'contact_array';
953
+ }
954
+ else if (message.liveLocationMessage) {
955
+ return 'livelocation';
956
+ }
957
+ else if (message.stickerMessage) {
958
+ return 'sticker';
959
+ }
960
+ else if (message.listMessage) {
961
+ return 'list';
962
+ }
963
+ else if (message.listResponseMessage) {
964
+ return 'list_response';
965
+ }
966
+ else if (message.buttonsResponseMessage) {
967
+ return 'buttons_response';
968
+ }
969
+ else if (message.orderMessage) {
970
+ return 'order';
971
+ }
972
+ else if (message.productMessage) {
973
+ return 'product';
974
+ }
975
+ else if (message.interactiveResponseMessage) {
976
+ return 'native_flow_response';
977
+ }
978
+ else if (message.groupInviteMessage) {
979
+ return 'url';
980
+ }
981
+ return '';
982
+ };
983
+ const getButtonType = (message) => {
984
+ if (message.listMessage) {
985
+ return 'list'
986
+ }
987
+ else if (message.buttonsMessage) {
988
+ return 'buttons'
989
+ }
990
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_and_pay') {
991
+ return 'review_and_pay'
992
+ }
993
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'review_order') {
994
+ return 'review_order'
995
+ }
996
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_info') {
997
+ return 'payment_info'
998
+ } else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_key_info') {
999
+ return 'payment_key_info'
1000
+ } else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_status') {
1001
+ return 'payment_status'
1002
+ }
1003
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'payment_method') {
1004
+ return 'payment_method'
1005
+ }
1006
+ else if (message.interactiveMessage?.nativeFlowMessage?.buttons?.[0]?.name === 'catalog_message') {
1007
+ return 'catalog_message'
1008
+ }
1009
+ else if (message.interactiveMessage && message.interactiveMessage?.nativeFlowMessage) {
1010
+ return 'interactive'
1011
+ }
1012
+ else if (message.interactiveMessage?.nativeFlowMessage) {
1013
+ return 'native_flow'
1014
+ }
1015
+ };
1016
+ const getButtonArgs = (message) => {
1017
+ const nativeFlow = message.interactiveMessage?.nativeFlowMessage
1018
+ const firstButtonName = nativeFlow?.buttons?.[0]?.name
1019
+ const nativeFlowSpecials = [
1020
+ 'mpm',
1021
+ 'cta_catalog',
1022
+ 'send_location',
1023
+ 'call_permission_request',
1024
+ 'wa_payment_transaction_details',
1025
+ 'automated_greeting_message_view_catalog'
1026
+ ]
1027
+
1028
+ if (nativeFlow && (firstButtonName === 'review_and_pay' || firstButtonName === 'payment_info')) {
1029
+ return {
1030
+ tag: 'biz',
1031
+ attrs: {
1032
+ native_flow_name: firstButtonName === 'review_and_pay' ? 'order_details' : firstButtonName
1033
+ }
1034
+ }
1035
+ } else if (nativeFlow && nativeFlowSpecials.includes(firstButtonName)) {
1036
+ // Only works for WhatsApp Original, not WhatsApp Business
1037
+ return {
1038
+ tag: 'biz',
1039
+ attrs: {
1040
+ actual_actors: '2',
1041
+ host_storage: '2',
1042
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1043
+ },
1044
+ content: [
1045
+ {
1046
+ tag: 'interactive',
1047
+ attrs: {
1048
+ type: 'native_flow',
1049
+ v: '1'
1050
+ },
1051
+ content: [
1052
+ {
1053
+ tag: 'native_flow',
1054
+ attrs: {
1055
+ v: '2',
1056
+ name: firstButtonName
1057
+ }
1058
+ }
1059
+ ]
1060
+ },
1061
+ {
1062
+ tag: 'quality_control',
1063
+ attrs: {
1064
+ source_type: 'third_party'
1065
+ }
1066
+ }
1067
+ ]
1068
+ }
1069
+ } else if (nativeFlow || message.buttonsMessage) {
1070
+ // It works for whatsapp original and whatsapp business
1071
+ return {
1072
+ tag: 'biz',
1073
+ attrs: {
1074
+ actual_actors: '2',
1075
+ host_storage: '2',
1076
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1077
+ },
1078
+ content: [
1079
+ {
1080
+ tag: 'interactive',
1081
+ attrs: {
1082
+ type: 'native_flow',
1083
+ v: '1'
1084
+ },
1085
+ content: [
1086
+ {
1087
+ tag: 'native_flow',
1088
+ attrs: {
1089
+ v: '9',
1090
+ name: 'mixed'
1091
+ }
1092
+ }
1093
+ ]
1094
+ },
1095
+ {
1096
+ tag: 'quality_control',
1097
+ attrs: {
1098
+ source_type: 'third_party'
1099
+ }
1100
+ }
1101
+ ]
1102
+ }
1103
+ } else if (message.listMessage) {
1104
+ return {
1105
+ tag: 'biz',
1106
+ attrs: {
1107
+ actual_actors: '2',
1108
+ host_storage: '2',
1109
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1110
+ },
1111
+ content: [
1112
+ {
1113
+ tag: 'list',
1114
+ attrs: {
1115
+ v: '2',
1116
+ type: 'product_list'
1117
+ }
1118
+ },
1119
+ {
1120
+ tag: 'quality_control',
1121
+ attrs: {
1122
+ source_type: 'third_party'
1123
+ }
1124
+ }
1125
+ ]
1126
+ }
1127
+ } else {
1128
+ return {
1129
+ tag: 'biz',
1130
+ attrs: {
1131
+ actual_actors: '2',
1132
+ host_storage: '2',
1133
+ privacy_mode_ts: Utils_1.unixTimestampSeconds().toString()
1134
+ }
1135
+ }
1136
+ }
1137
+ }
1138
+ const issuePrivacyTokens = async (jids, timestamp) => {
1139
+ const t = (timestamp ?? unixTimestampSeconds()).toString();
1140
+ const result = await query({
1141
+ tag: 'iq',
1142
+ attrs: {
1143
+ to: S_WHATSAPP_NET,
1144
+ type: 'set',
1145
+ xmlns: 'privacy'
1146
+ },
1147
+ content: [
1148
+ {
1149
+ tag: 'tokens',
1150
+ attrs: {},
1151
+ content: jids.map(jid => ({
1152
+ tag: 'token',
1153
+ attrs: {
1154
+ jid: jidNormalizedUser(jid),
1155
+ t,
1156
+ type: 'trusted_contact'
1157
+ }
1158
+ }))
1159
+ }
1160
+ ]
1161
+ });
1162
+ return result;
1163
+ };
1164
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1165
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1166
+ registerSocketEndHandler(() => {
1167
+ if (!config.userDevicesCache && userDevicesCache.close) {
1168
+ userDevicesCache.close();
1169
+ }
1170
+ mediaConn = undefined;
1171
+ if (messageRetryManager) {
1172
+ messageRetryManager.clear();
1173
+ }
1174
+ });
1175
+ return {
1176
+ ...sock,
1177
+ userDevicesCache,
1178
+ devicesMutex,
1179
+ issuePrivacyTokens,
1180
+ assertSessions,
1181
+ relayMessage,
1182
+ sendReceipt,
1183
+ sendReceipts,
1184
+ readMessages,
1185
+ refreshMediaConn,
1186
+ // Function (not getter) so the spread in chats.ts preserves the live closure binding.
1187
+ getMediaHost: () => mediaHost,
1188
+ waUploadToServer,
1189
+ fetchPrivacySettings,
1190
+ sendPeerDataOperationMessage,
1191
+ createParticipantNodes,
1192
+ getUSyncDevices,
1193
+ messageRetryManager,
1194
+ updateMemberLabel,
1195
+ updateMediaMessage: async (message) => {
1196
+ const content = assertMediaContent(message.message);
1197
+ const mediaKey = content.mediaKey;
1198
+ const meId = authState.creds.me.id;
1199
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1200
+ let error = undefined;
1201
+ await Promise.all([
1202
+ sendNode(node),
1203
+ waitForMsgMediaUpdate(async (update) => {
1204
+ const result = update.find(c => c.key.id === message.key.id);
1205
+ if (result) {
1206
+ if (result.error) {
1207
+ error = result.error;
1208
+ }
1209
+ else {
1210
+ try {
1211
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1212
+ if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1213
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1214
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1215
+ data: media,
1216
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404
1217
+ });
1218
+ }
1219
+ content.directPath = media.directPath;
1220
+ content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1221
+ logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1222
+ }
1223
+ catch (err) {
1224
+ error = err;
1225
+ }
1226
+ }
1227
+ return true;
1228
+ }
1229
+ })
1230
+ ]);
1231
+ if (error) {
1232
+ throw error;
1233
+ }
1234
+ ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1235
+ return message;
1236
+ },
1237
+ sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1238
+ const { message, messageId } = Utils_1.generateTableContent(title, headers, rows, quoted, options)
1239
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1240
+ return { message, messageId }
1241
+ },
1242
+ sendList: async (jid, title, items, quoted, options = {}) => {
1243
+ const { message, messageId } = Utils_1.generateListContent(title, items, quoted, options)
1244
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1245
+ return { message, messageId }
1246
+ },
1247
+ sendCodeBlock: async (jid, code, quoted, options = {}) => {
1248
+ const { message, messageId } = Utils_1.generateCodeBlockContent(code, quoted, options)
1249
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1250
+ return { message, messageId }
1251
+ },
1252
+ sendLatex: async (jid, quoted, options) => {
1253
+ const { message, messageId } = Utils_1.generateLatexContent(quoted, options)
1254
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1255
+ return { message, messageId }
1256
+ },
1257
+ sendLatexImage: async (jid, quoted, options, renderLatexToPng, uploadFn) => {
1258
+ const { message, messageId } = await Utils_1.generateLatexImageContent(
1259
+ quoted,
1260
+ options,
1261
+ uploadFn,
1262
+ renderLatexToPng
1263
+ )
1264
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1265
+ return { message, messageId }
1266
+ },
1267
+ sendLatexInlineImage: async (jid, quoted, options, renderLatexToPng, uploadFn) => {
1268
+ const { message, messageId } = await Utils_1.generateLatexInlineImageContent(
1269
+ quoted,
1270
+ options,
1271
+ uploadFn,
1272
+ renderLatexToPng
1273
+ )
1274
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1275
+ return { message, messageId }
1276
+ },
1277
+ captureUnifiedResponse: Utils_1.captureUnifiedResponse,
1278
+ sendUnifiedResponse: async (jid, quoted, captured, options = {}) => {
1279
+ const { message, messageId } = Utils_1.generateUnifiedResponseContent(quoted, captured)
1280
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1281
+ return { message, messageId }
1282
+ },
1283
+ sendRichMessage: async (jid, submessages, quoted, options = {}) => {
1284
+ const { message, messageId } = Utils_1.generateRichMessageContent(submessages, quoted, options)
1285
+ await relayMessage(jid, message, { messageId, noSelfSync: options.noSelfSync })
1286
+ return { message, messageId }
1287
+ },
1288
+ sendMessage: async (jid, content, options = {}) => {
1289
+ const userJid = authState.creds.me.id;
1290
+ const luki = new imup(Utils_1, waUploadToServer, relayMessage, options.brand)
1291
+ const { quoted, participant = false } = options;
1292
+ const messageType = luki.detectType(content);
1293
+ if (typeof content === 'object' &&
1294
+ 'disappearingMessagesInChat' in content &&
1295
+ typeof content['disappearingMessagesInChat'] !== 'undefined' &&
1296
+ isJidGroup(jid)) {
1297
+ const { disappearingMessagesInChat } = content;
1298
+ const value = typeof disappearingMessagesInChat === 'boolean'
1299
+ ? disappearingMessagesInChat
1300
+ ? WA_DEFAULT_EPHEMERAL
1301
+ : 0
1302
+ : disappearingMessagesInChat;
1303
+ await groupToggleEphemeral(jid, value);
1304
+ }
1305
+ else {
1306
+ if (messageType) {
1307
+ switch(messageType) {
1308
+ case 'PAYMENT':
1309
+ const paymentContent = await luki.handlePayment(content, quoted);
1310
+ return await relayMessage(jid, paymentContent, {
1311
+ messageId: Utils_1.generateMessageID(),
1312
+ noSelfSync: options.noSelfSync
1313
+ });
1314
+ case 'PRODUCT':
1315
+ const productContent = await luki.handleProduct(content, jid, quoted);
1316
+ const productMsg = await Utils_1.generateWAMessageFromContent(jid, productContent, { quoted });
1317
+ return await relayMessage(jid, productMsg.message, {
1318
+ messageId: productMsg.key.id,
1319
+ noSelfSync: options.noSelfSync
1320
+ });
1321
+
1322
+ case 'ALBUM_V2':
1323
+ return await luki.handleAlbumV2(content, jid, userJid, options)
1324
+ case 'ALBUM':
1325
+ return await luki.handleAlbum(content, jid, quoted)
1326
+ case 'EVENT':
1327
+ return await luki.handleEvent(content, jid, quoted)
1328
+ case 'POLL_RESULT':
1329
+ return await luki.handlePollResult(content, jid, quoted)
1330
+ case 'ORDER':
1331
+ return await luki.handleOrderMessage(content, jid, quoted)
1332
+ case 'GROUP_STATUS':
1333
+ return await luki.handleGroupStory(content, jid, quoted)
1334
+ case 'GROUP_LABEL':
1335
+ return await luki.handleGbLabel(content, jid)
1336
+ }
1337
+ }
1338
+ const fullMsg = await generateWAMessage(jid, content, {
1339
+ logger,
1340
+ userJid,
1341
+ getUrlInfo: text => getUrlInfo(text, {
1342
+ thumbnailWidth: linkPreviewImageThumbnailWidth,
1343
+ fetchOpts: {
1344
+ timeout: 3000,
1345
+ ...(httpRequestOptions || {})
1346
+ },
1347
+ logger,
1348
+ uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
1349
+ }),
1350
+ //TODO: CACHE
1351
+ getProfilePicUrl: sock.profilePictureUrl,
1352
+ getCallLink: sock.createCallLink,
1353
+ upload: waUploadToServer,
1354
+ mediaCache: config.mediaCache,
1355
+ options: config.options,
1356
+ messageId: generateMessageIDV2(sock.user?.id),
1357
+ ...options
1358
+ });
1359
+ const isEventMsg = 'event' in content && !!content.event;
1360
+ const isDeleteMsg = 'delete' in content && !!content.delete;
1361
+ const isEditMsg = 'edit' in content && !!content.edit;
1362
+ const isPinMsg = 'pin' in content && !!content.pin;
1363
+ const isPollMessage = 'poll' in content && !!content.poll;
1364
+ const additionalAttributes = {};
1365
+ const additionalNodes = [];
1366
+ // required for delete
1367
+ if (isDeleteMsg) {
1368
+ // if the chat is a group, and I am not the author, then delete the message as an admin
1369
+ if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
1370
+ additionalAttributes.edit = '8';
1371
+ }
1372
+ else {
1373
+ additionalAttributes.edit = '7';
1374
+ }
1375
+ }
1376
+ else if (isEditMsg) {
1377
+ additionalAttributes.edit = '1';
1378
+ }
1379
+ else if (isPinMsg) {
1380
+ additionalAttributes.edit = '2';
1381
+ }
1382
+ else if (isPollMessage) {
1383
+ additionalNodes.push({
1384
+ tag: 'meta',
1385
+ attrs: {
1386
+ polltype: 'creation'
1387
+ }
1388
+ });
1389
+ }
1390
+ else if (isEventMsg) {
1391
+ additionalNodes.push({
1392
+ tag: 'meta',
1393
+ attrs: {
1394
+ event_type: 'creation'
1395
+ }
1396
+ });
1397
+ }
1398
+ await relayMessage(jid, fullMsg.message, {
1399
+ messageId: fullMsg.key.id,
1400
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1401
+ additionalAttributes,
1402
+ statusJidList: options.statusJidList,
1403
+ additionalNodes: aiLabel ? additionalNodes : options.additionalNodes,
1404
+ participant,
1405
+ noSelfSync: options.noSelfSync
1406
+ });
1407
+ if (config.emitOwnEvents) {
1408
+ process.nextTick(() => {
1409
+ messageMutex.mutex(() => upsertMessage(fullMsg, 'append'))
1410
+ .catch(err => logger.error({ err }, 'failed to upsert own message'));
1411
+ });
1412
+ }
1413
+ return fullMsg;
1414
+ }
1415
+ },
1416
+ sendMessageMembers: async (jid, message, options = {}) => {
1417
+ const {
1418
+ messageId: idm,
1419
+ quoted,
1420
+ delayMs = 1500,
1421
+ useUserDevicesCache = true,
1422
+ cachedGroupMetadata,
1423
+ onlyMember = true
1424
+ } = options;
1425
+ const { server } = jidDecode(jid);
1426
+ if (server !== "g.us") throw new Error("@g.us server required");
1427
+ const meId = authState.creds.me.id;
1428
+ const messages = Utils_1.normalizeMessageContent(message);
1429
+ const groupData = cachedGroupMetadata? await cachedGroupMetadata(jid) : await groupMetadata(jid);
1430
+ const isLid = groupData.addressingMode === "lid";
1431
+ const adminJids = groupData.participants.filter((x) => x.admin !== null).map((y) => y.id)
1432
+ let participantJids = groupData.participants.map(z => z.id);
1433
+ if (onlyMember) {
1434
+ // Fix: array selalu truthy di JS meski kosong ([] ? true).
1435
+ // Cek .length supaya fallback ke semua member beneran jalan
1436
+ // kalau data admin kosong, bukan diam-diam kirim ke 0 orang.
1437
+ participantJids = adminJids.length ? adminJids : participantJids;
1438
+ }
1439
+ logger.info(`Sending message to ${participantJids.length} members from ${jid}`);
1440
+ for (let i = 0; i < participantJids.length; i++) {
1441
+ const jid = participantJids[i];
1442
+ if (areJidsSameUser(jid, meId)) continue;
1443
+ try {
1444
+ const msgId = `${idm || Utils_1.generateMessageID()}_${i}`;
1445
+ const fullMsg = await Utils_1.generateWAMessageFromContent(jid, message, {
1446
+ messageId: msgId,
1447
+ quoted
1448
+ })
1449
+ await relayMessage(jid, fullMsg.message, {
1450
+ messageId: fullMsg.key.id,
1451
+ useUserDevicesCache,
1452
+ noSelfSync: options.noSelfSync
1453
+ });
1454
+ logger.debug(`Message successfully sent to ${jid}`);
1455
+ if (delayMs && i < participantJids.length - 1) {
1456
+ await new Promise(z => setTimeout(z, delayMs));
1457
+ }
1458
+ } catch (e) {
1459
+ logger.error({ jid, e }, "Error sending message to");
1460
+ }
1461
+ }
1462
+ return JSON.stringify({
1463
+ members_total: participantJids.length,
1464
+ message
1465
+ }, null, 4);
1466
+ }
1467
+ };
1468
+ };
1469
+ //# sourceMappingURL=messages-send.js.map