@vanzxy/baileys 1.4.1 → 1.4.2

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.

Potentially problematic release.


This version of @vanzxy/baileys might be problematic. Click here for more details.

Files changed (111) hide show
  1. package/cjs/WAProto/index.js +106053 -0
  2. package/cjs/lib/Defaults/index.js +168 -0
  3. package/cjs/lib/Signal/Group/ciphertext-message.js +16 -0
  4. package/cjs/lib/Signal/Group/group-session-builder.js +67 -0
  5. package/cjs/lib/Signal/Group/group_cipher.js +86 -0
  6. package/cjs/lib/Signal/Group/index.js +58 -0
  7. package/cjs/lib/Signal/Group/keyhelper.js +56 -0
  8. package/cjs/lib/Signal/Group/sender-chain-key.js +30 -0
  9. package/cjs/lib/Signal/Group/sender-key-distribution-message.js +67 -0
  10. package/cjs/lib/Signal/Group/sender-key-message.js +70 -0
  11. package/cjs/lib/Signal/Group/sender-key-name.js +52 -0
  12. package/cjs/lib/Signal/Group/sender-key-record.js +45 -0
  13. package/cjs/lib/Signal/Group/sender-key-state.js +88 -0
  14. package/cjs/lib/Signal/Group/sender-message-key.js +30 -0
  15. package/cjs/lib/Signal/libsignal.js +467 -0
  16. package/cjs/lib/Signal/lid-mapping.js +281 -0
  17. package/cjs/lib/Socket/Client/index.js +19 -0
  18. package/cjs/lib/Socket/Client/types.js +15 -0
  19. package/cjs/lib/Socket/Client/websocket.js +61 -0
  20. package/cjs/lib/Socket/business.js +384 -0
  21. package/cjs/lib/Socket/chats.js +1257 -0
  22. package/cjs/lib/Socket/communities.js +442 -0
  23. package/cjs/lib/Socket/dugong.js +753 -0
  24. package/cjs/lib/Socket/groups.js +360 -0
  25. package/cjs/lib/Socket/index.js +19 -0
  26. package/cjs/lib/Socket/messages-recv.js +1790 -0
  27. package/cjs/lib/Socket/messages-send.js +1390 -0
  28. package/cjs/lib/Socket/mex.js +46 -0
  29. package/cjs/lib/Socket/newsletter.js +340 -0
  30. package/cjs/lib/Socket/socket.js +1007 -0
  31. package/cjs/lib/Store/index.js +20 -0
  32. package/cjs/lib/Store/make-in-memory-store.js +438 -0
  33. package/cjs/lib/Store/make-ordered-dictionary.js +82 -0
  34. package/cjs/lib/Store/object-repository.js +28 -0
  35. package/cjs/lib/Types/Auth.js +3 -0
  36. package/cjs/lib/Types/Bussines.js +3 -0
  37. package/cjs/lib/Types/Call.js +3 -0
  38. package/cjs/lib/Types/Chat.js +11 -0
  39. package/cjs/lib/Types/Contact.js +3 -0
  40. package/cjs/lib/Types/Events.js +4 -0
  41. package/cjs/lib/Types/GroupMetadata.js +3 -0
  42. package/cjs/lib/Types/Label.js +26 -0
  43. package/cjs/lib/Types/LabelAssociation.js +8 -0
  44. package/cjs/lib/Types/Message.js +19 -0
  45. package/cjs/lib/Types/Mex.js +40 -0
  46. package/cjs/lib/Types/Product.js +3 -0
  47. package/cjs/lib/Types/RichType.js +24 -0
  48. package/cjs/lib/Types/Signal.js +4 -0
  49. package/cjs/lib/Types/Socket.js +4 -0
  50. package/cjs/lib/Types/State.js +54 -0
  51. package/cjs/lib/Types/USync.js +4 -0
  52. package/cjs/lib/Types/index.js +42 -0
  53. package/cjs/lib/Utils/MessageBuilder.js +2164 -0
  54. package/cjs/lib/Utils/auth-utils.js +312 -0
  55. package/cjs/lib/Utils/browser-utils.js +32 -0
  56. package/cjs/lib/Utils/business.js +245 -0
  57. package/cjs/lib/Utils/chat-utils.js +937 -0
  58. package/cjs/lib/Utils/companion-reg-client-utils.js +45 -0
  59. package/cjs/lib/Utils/crypto.js +196 -0
  60. package/cjs/lib/Utils/decode-wa-message.js +324 -0
  61. package/cjs/lib/Utils/event-buffer.js +643 -0
  62. package/cjs/lib/Utils/generics.js +429 -0
  63. package/cjs/lib/Utils/history.js +151 -0
  64. package/cjs/lib/Utils/identity-change-handler.js +56 -0
  65. package/cjs/lib/Utils/index.js +42 -0
  66. package/cjs/lib/Utils/link-preview.js +122 -0
  67. package/cjs/lib/Utils/logger.js +8 -0
  68. package/cjs/lib/Utils/lt-hash.js +62 -0
  69. package/cjs/lib/Utils/make-mutex.js +38 -0
  70. package/cjs/lib/Utils/message-retry-manager.js +267 -0
  71. package/cjs/lib/Utils/messages-media.js +933 -0
  72. package/cjs/lib/Utils/messages.js +2175 -0
  73. package/cjs/lib/Utils/noise-handler.js +205 -0
  74. package/cjs/lib/Utils/offline-node-processor.js +43 -0
  75. package/cjs/lib/Utils/pre-key-manager.js +113 -0
  76. package/cjs/lib/Utils/process-message.js +772 -0
  77. package/cjs/lib/Utils/reporting-utils.js +263 -0
  78. package/cjs/lib/Utils/rich-message-utils.js +439 -0
  79. package/cjs/lib/Utils/signal.js +214 -0
  80. package/cjs/lib/Utils/stanza-ack.js +41 -0
  81. package/cjs/lib/Utils/sync-action-utils.js +54 -0
  82. package/cjs/lib/Utils/tc-token-utils.js +174 -0
  83. package/cjs/lib/Utils/use-multi-file-auth-state.js +125 -0
  84. package/cjs/lib/Utils/use-single-file-auth-state.js +121 -0
  85. package/cjs/lib/Utils/use-sqlite-auth-state.js +182 -0
  86. package/cjs/lib/Utils/validate-connection.js +210 -0
  87. package/cjs/lib/WABinary/constants.js +1470 -0
  88. package/cjs/lib/WABinary/decode.js +301 -0
  89. package/cjs/lib/WABinary/encode.js +257 -0
  90. package/cjs/lib/WABinary/generic-utils.js +274 -0
  91. package/cjs/lib/WABinary/index.js +22 -0
  92. package/cjs/lib/WABinary/jid-utils.js +114 -0
  93. package/cjs/lib/WABinary/types.js +37 -0
  94. package/cjs/lib/WAM/BinaryInfo.js +14 -0
  95. package/cjs/lib/WAM/constants.js +22856 -0
  96. package/cjs/lib/WAM/encode.js +154 -0
  97. package/cjs/lib/WAM/index.js +20 -0
  98. package/cjs/lib/WAUSync/Protocols/USyncContactProtocol.js +56 -0
  99. package/cjs/lib/WAUSync/Protocols/USyncDeviceProtocol.js +67 -0
  100. package/cjs/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  101. package/cjs/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  102. package/cjs/lib/WAUSync/Protocols/USyncUsernameProtocol.js +29 -0
  103. package/cjs/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +55 -0
  104. package/cjs/lib/WAUSync/Protocols/UsyncLIDProtocol.js +33 -0
  105. package/cjs/lib/WAUSync/Protocols/index.js +24 -0
  106. package/cjs/lib/WAUSync/USyncQuery.js +126 -0
  107. package/cjs/lib/WAUSync/USyncUser.js +35 -0
  108. package/cjs/lib/WAUSync/index.js +20 -0
  109. package/cjs/lib/index.js +34 -0
  110. package/cjs/package.json +1 -0
  111. package/package.json +16 -5
@@ -0,0 +1,643 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeEventBuffer = void 0;
7
+ const events_1 = __importDefault(require("events"));
8
+ const index_js_1 = require("../Types/index.js");
9
+ const generics_js_1 = require("./generics.js");
10
+ const messages_js_1 = require("./messages.js");
11
+ const process_message_js_1 = require("./process-message.js");
12
+ const BUFFERABLE_EVENT = [
13
+ 'messaging-history.set',
14
+ 'chats.upsert',
15
+ 'chats.update',
16
+ 'chats.delete',
17
+ 'contacts.upsert',
18
+ 'contacts.update',
19
+ 'messages.upsert',
20
+ 'messages.update',
21
+ 'messages.delete',
22
+ 'messages.reaction',
23
+ 'message-receipt.update',
24
+ 'groups.update',
25
+ // Vanz@Fix (bug 43): these events were emitted directly without being buffered,
26
+ // causing them to fire out of order during createBufferedFunction.
27
+ 'settings.update',
28
+ 'chats.lock',
29
+ 'lid-mapping.update',
30
+ 'newsletter-settings.update'
31
+ ];
32
+ const BUFFERABLE_EVENT_SET = new Set(BUFFERABLE_EVENT);
33
+ /**
34
+ * The event buffer logically consolidates different events into a single event
35
+ * making the data processing more efficient.
36
+ */
37
+ const makeEventBuffer = (logger, timeoutMs) => {
38
+ const ev = new events_1.default();
39
+ const historyCache = new Set();
40
+ let data = makeBufferData();
41
+ let isBuffering = false;
42
+ let bufferTimeout = null;
43
+ let flushPendingTimeout = null; // Add a specific timer for the debounced flush to prevent leak
44
+ let bufferCount = 0;
45
+ const MAX_HISTORY_CACHE_SIZE = 10000; // Limit the history cache size to prevent memory bloat
46
+ const BUFFER_TIMEOUT_MS = timeoutMs ?? 30000; // Vanz@Fix (bug 25): was hardcoded 30s — now configurable via makeWASocket({ eventBufferTimeoutMs })
47
+ // take the generic event and fire it as a baileys event
48
+ ev.on('event', (map) => {
49
+ for (const event in map) {
50
+ ev.emit(event, map[event]);
51
+ }
52
+ });
53
+ function buffer() {
54
+ if (!isBuffering) {
55
+ logger.debug('Event buffer activated');
56
+ isBuffering = true;
57
+ bufferCount = 0;
58
+ if (bufferTimeout) {
59
+ clearTimeout(bufferTimeout);
60
+ }
61
+ bufferTimeout = setTimeout(() => {
62
+ if (isBuffering) {
63
+ logger.warn('Buffer timeout reached, auto-flushing');
64
+ flush();
65
+ }
66
+ }, BUFFER_TIMEOUT_MS);
67
+ }
68
+ // Always increment count when requested
69
+ bufferCount++;
70
+ }
71
+ function flush() {
72
+ if (!isBuffering) {
73
+ return false;
74
+ }
75
+ logger.debug({ bufferCount }, 'Flushing event buffer');
76
+ isBuffering = false;
77
+ bufferCount = 0;
78
+ // Clear timeout
79
+ if (bufferTimeout) {
80
+ clearTimeout(bufferTimeout);
81
+ bufferTimeout = null;
82
+ }
83
+ if (flushPendingTimeout) {
84
+ clearTimeout(flushPendingTimeout);
85
+ flushPendingTimeout = null;
86
+ }
87
+ // Clear history cache if it exceeds the max size
88
+ if (historyCache.size > MAX_HISTORY_CACHE_SIZE) {
89
+ logger.debug({ cacheSize: historyCache.size }, 'Clearing history cache');
90
+ historyCache.clear();
91
+ }
92
+ const newData = makeBufferData();
93
+ const chatUpdates = Object.values(data.chatUpdates);
94
+ let conditionalChatUpdatesLeft = 0;
95
+ for (const update of chatUpdates) {
96
+ if (update.conditional) {
97
+ conditionalChatUpdatesLeft += 1;
98
+ newData.chatUpdates[update.id] = update;
99
+ delete data.chatUpdates[update.id];
100
+ }
101
+ }
102
+ const consolidatedData = consolidateEvents(data);
103
+ if (Object.keys(consolidatedData).length) {
104
+ ev.emit('event', consolidatedData);
105
+ }
106
+ data = newData;
107
+ logger.trace({ conditionalChatUpdatesLeft }, 'released buffered events');
108
+ return true;
109
+ }
110
+ return {
111
+ process(handler) {
112
+ const listener = async (map) => {
113
+ await handler(map);
114
+ };
115
+ ev.on('event', listener);
116
+ return () => {
117
+ ev.off('event', listener);
118
+ };
119
+ },
120
+ emit(event, evData) {
121
+ // Check if this is a messages.upsert with a different type than what's buffered
122
+ // If so, flush the buffered messages first to avoid type overshadowing
123
+ if (event === 'messages.upsert') {
124
+ const { type } = evData;
125
+ const existingUpserts = Object.values(data.messageUpserts);
126
+ if (existingUpserts.length > 0) {
127
+ const bufferedType = existingUpserts[0].type;
128
+ if (bufferedType !== type) {
129
+ logger.debug({ bufferedType, newType: type }, 'messages.upsert type mismatch, emitting buffered messages');
130
+ // Emit the buffered messages with their correct type
131
+ ev.emit('event', {
132
+ 'messages.upsert': {
133
+ messages: existingUpserts.map(m => m.message),
134
+ type: bufferedType
135
+ }
136
+ });
137
+ // Clear the message upserts from the buffer
138
+ data.messageUpserts = {};
139
+ }
140
+ }
141
+ }
142
+ if (isBuffering && BUFFERABLE_EVENT_SET.has(event)) {
143
+ append(data, historyCache, event, evData, logger);
144
+ return true;
145
+ }
146
+ return ev.emit('event', { [event]: evData });
147
+ },
148
+ isBuffering() {
149
+ return isBuffering;
150
+ },
151
+ buffer,
152
+ flush,
153
+ createBufferedFunction(work) {
154
+ return async (...args) => {
155
+ buffer();
156
+ try {
157
+ const result = await work(...args);
158
+ // If this is the only buffer, flush after a small delay
159
+ if (bufferCount === 1) {
160
+ setTimeout(() => {
161
+ if (isBuffering && bufferCount === 1) {
162
+ flush();
163
+ }
164
+ }, 100); // Small delay to allow nested buffers
165
+ }
166
+ return result;
167
+ }
168
+ catch (error) {
169
+ throw error;
170
+ }
171
+ finally {
172
+ bufferCount = Math.max(0, bufferCount - 1);
173
+ if (bufferCount === 0) {
174
+ // Only schedule ONE timeout, not 10,000
175
+ if (!flushPendingTimeout) {
176
+ flushPendingTimeout = setTimeout(flush, 100);
177
+ }
178
+ }
179
+ }
180
+ };
181
+ },
182
+ on: (...args) => ev.on(...args),
183
+ off: (...args) => ev.off(...args),
184
+ removeAllListeners: (...args) => ev.removeAllListeners(...args),
185
+ destroy() {
186
+ // Clear buffer timeout
187
+ if (bufferTimeout) {
188
+ clearTimeout(bufferTimeout);
189
+ bufferTimeout = null;
190
+ }
191
+ if (flushPendingTimeout) {
192
+ clearTimeout(flushPendingTimeout);
193
+ flushPendingTimeout = null;
194
+ }
195
+ // Clear history cache
196
+ historyCache.clear();
197
+ // Reset buffer data
198
+ data = makeBufferData();
199
+ isBuffering = false;
200
+ bufferCount = 0;
201
+ // Remove all listeners
202
+ ev.removeAllListeners();
203
+ logger.debug('Event buffer destroyed');
204
+ }
205
+ };
206
+ };
207
+ exports.makeEventBuffer = makeEventBuffer;
208
+ const makeBufferData = () => {
209
+ return {
210
+ historySets: {
211
+ chats: {},
212
+ messages: {},
213
+ contacts: {},
214
+ isLatest: false,
215
+ empty: true
216
+ },
217
+ chatUpserts: {},
218
+ chatUpdates: {},
219
+ chatDeletes: new Set(),
220
+ contactUpserts: {},
221
+ contactUpdates: {},
222
+ messageUpserts: {},
223
+ messageUpdates: {},
224
+ messageReactions: {},
225
+ messageDeletes: {},
226
+ messageReceipts: {},
227
+ groupUpdates: {}
228
+ };
229
+ };
230
+ function append(data, historyCache, event,
231
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
232
+ eventData, logger) {
233
+ switch (event) {
234
+ case 'messaging-history.set':
235
+ for (const chat of eventData.chats) {
236
+ const id = chat.id || '';
237
+ const existingChat = data.historySets.chats[id];
238
+ if (existingChat) {
239
+ existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType;
240
+ }
241
+ if (!existingChat && !historyCache.has(id)) {
242
+ data.historySets.chats[id] = chat;
243
+ historyCache.add(id);
244
+ absorbingChatUpdate(chat);
245
+ }
246
+ }
247
+ for (const contact of eventData.contacts) {
248
+ const existingContact = data.historySets.contacts[contact.id];
249
+ if (existingContact) {
250
+ Object.assign(existingContact, (0, generics_js_1.trimUndefined)(contact));
251
+ }
252
+ else {
253
+ const historyContactId = `c:${contact.id}`;
254
+ const hasAnyName = contact.notify || contact.name || contact.verifiedName;
255
+ if (!historyCache.has(historyContactId) || hasAnyName) {
256
+ data.historySets.contacts[contact.id] = contact;
257
+ historyCache.add(historyContactId);
258
+ }
259
+ }
260
+ }
261
+ for (const message of eventData.messages) {
262
+ const key = stringifyMessageKey(message.key);
263
+ const existingMsg = data.historySets.messages[key];
264
+ if (!existingMsg && !historyCache.has(key)) {
265
+ data.historySets.messages[key] = message;
266
+ historyCache.add(key);
267
+ }
268
+ }
269
+ data.historySets.empty = false;
270
+ data.historySets.syncType = eventData.syncType;
271
+ if (eventData.pastParticipants?.length) {
272
+ const merged = new Map();
273
+ const sigOf = (p) => `${p.userJid || ''}:${p.leaveTs || ''}:${p.leaveReason || ''}`;
274
+ const ingest = (entry) => {
275
+ const key = entry.groupJid ?? JSON.stringify(entry);
276
+ const existing = merged.get(key);
277
+ if (!existing) {
278
+ merged.set(key, { ...entry, pastParticipants: [...(entry.pastParticipants || [])] });
279
+ return;
280
+ }
281
+ const seen = new Set((existing.pastParticipants || []).map(sigOf));
282
+ for (const p of entry.pastParticipants || []) {
283
+ const sig = sigOf(p);
284
+ if (!seen.has(sig)) {
285
+ existing.pastParticipants.push(p);
286
+ seen.add(sig);
287
+ }
288
+ }
289
+ };
290
+ for (const entry of data.historySets.pastParticipants || [])
291
+ ingest(entry);
292
+ for (const entry of eventData.pastParticipants)
293
+ ingest(entry);
294
+ data.historySets.pastParticipants = [...merged.values()];
295
+ }
296
+ data.historySets.progress = eventData.progress;
297
+ data.historySets.chunkOrder = eventData.chunkOrder;
298
+ data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId;
299
+ data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest;
300
+ break;
301
+ case 'chats.upsert':
302
+ for (const chat of eventData) {
303
+ const id = chat.id || '';
304
+ let upsert = data.chatUpserts[id];
305
+ if (id && !upsert) {
306
+ upsert = data.historySets.chats[id];
307
+ if (upsert) {
308
+ logger.debug({ chatId: id }, 'absorbed chat upsert in chat set');
309
+ }
310
+ }
311
+ if (upsert) {
312
+ upsert = concatChats(upsert, chat);
313
+ }
314
+ else {
315
+ upsert = chat;
316
+ data.chatUpserts[id] = upsert;
317
+ }
318
+ absorbingChatUpdate(upsert);
319
+ if (data.chatDeletes.has(id)) {
320
+ data.chatDeletes.delete(id);
321
+ }
322
+ }
323
+ break;
324
+ case 'chats.update':
325
+ for (const update of eventData) {
326
+ const chatId = update.id;
327
+ const conditionMatches = update.conditional ? update.conditional(data) : true;
328
+ if (conditionMatches) {
329
+ delete update.conditional;
330
+ // if there is an existing upsert, merge the update into it
331
+ const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId];
332
+ if (upsert) {
333
+ concatChats(upsert, update);
334
+ }
335
+ else {
336
+ // merge the update into the existing update
337
+ const chatUpdate = data.chatUpdates[chatId] || {};
338
+ data.chatUpdates[chatId] = concatChats(chatUpdate, update);
339
+ }
340
+ }
341
+ else if (conditionMatches === undefined) {
342
+ // condition yet to be fulfilled
343
+ data.chatUpdates[chatId] = update;
344
+ }
345
+ // otherwise -- condition not met, update is invalid
346
+ // if the chat has been updated
347
+ // ignore any existing chat delete
348
+ if (data.chatDeletes.has(chatId)) {
349
+ data.chatDeletes.delete(chatId);
350
+ }
351
+ }
352
+ break;
353
+ case 'chats.delete':
354
+ for (const chatId of eventData) {
355
+ if (!data.chatDeletes.has(chatId)) {
356
+ data.chatDeletes.add(chatId);
357
+ }
358
+ // remove any prior updates & upserts
359
+ if (data.chatUpdates[chatId]) {
360
+ delete data.chatUpdates[chatId];
361
+ }
362
+ if (data.chatUpserts[chatId]) {
363
+ delete data.chatUpserts[chatId];
364
+ }
365
+ if (data.historySets.chats[chatId]) {
366
+ delete data.historySets.chats[chatId];
367
+ }
368
+ }
369
+ break;
370
+ case 'contacts.upsert':
371
+ for (const contact of eventData) {
372
+ let upsert = data.contactUpserts[contact.id];
373
+ if (!upsert) {
374
+ upsert = data.historySets.contacts[contact.id];
375
+ if (upsert) {
376
+ logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set');
377
+ }
378
+ }
379
+ if (upsert) {
380
+ upsert = Object.assign(upsert, (0, generics_js_1.trimUndefined)(contact));
381
+ }
382
+ else {
383
+ upsert = contact;
384
+ data.contactUpserts[contact.id] = upsert;
385
+ }
386
+ if (data.contactUpdates[contact.id]) {
387
+ upsert = Object.assign(data.contactUpdates[contact.id], (0, generics_js_1.trimUndefined)(contact));
388
+ delete data.contactUpdates[contact.id];
389
+ }
390
+ }
391
+ break;
392
+ case 'contacts.update':
393
+ const contactUpdates = eventData;
394
+ for (const update of contactUpdates) {
395
+ const id = update.id;
396
+ // merge into prior upsert
397
+ const upsert = data.historySets.contacts[id] || data.contactUpserts[id];
398
+ if (upsert) {
399
+ Object.assign(upsert, update);
400
+ }
401
+ else {
402
+ // merge into prior update
403
+ const contactUpdate = data.contactUpdates[id] || {};
404
+ data.contactUpdates[id] = Object.assign(contactUpdate, update);
405
+ }
406
+ }
407
+ break;
408
+ case 'messages.upsert':
409
+ const { messages, type } = eventData;
410
+ for (const message of messages) {
411
+ const key = stringifyMessageKey(message.key);
412
+ let existing = data.messageUpserts[key]?.message;
413
+ if (!existing) {
414
+ existing = data.historySets.messages[key];
415
+ if (existing) {
416
+ logger.debug({ messageId: key }, 'absorbed message upsert in message set');
417
+ }
418
+ }
419
+ if (existing) {
420
+ message.messageTimestamp = existing.messageTimestamp;
421
+ }
422
+ if (data.messageUpdates[key]) {
423
+ logger.debug('absorbed prior message update in message upsert');
424
+ Object.assign(message, data.messageUpdates[key].update);
425
+ delete data.messageUpdates[key];
426
+ }
427
+ if (data.historySets.messages[key]) {
428
+ data.historySets.messages[key] = message;
429
+ }
430
+ else {
431
+ data.messageUpserts[key] = {
432
+ message,
433
+ type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type
434
+ };
435
+ }
436
+ }
437
+ break;
438
+ case 'messages.update':
439
+ const msgUpdates = eventData;
440
+ for (const { key, update } of msgUpdates) {
441
+ const keyStr = stringifyMessageKey(key);
442
+ const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message;
443
+ if (existing) {
444
+ Object.assign(existing, update);
445
+ // if the message was received & read by us
446
+ // the chat counter must have been incremented
447
+ // so we need to decrement it
448
+ if (update.status === index_js_1.WAMessageStatus.READ && !key.fromMe) {
449
+ decrementChatReadCounterIfMsgDidUnread(existing);
450
+ }
451
+ }
452
+ else {
453
+ const msgUpdate = data.messageUpdates[keyStr] || { key, update: {} };
454
+ Object.assign(msgUpdate.update, update);
455
+ data.messageUpdates[keyStr] = msgUpdate;
456
+ }
457
+ }
458
+ break;
459
+ case 'messages.delete':
460
+ const deleteData = eventData;
461
+ if ('keys' in deleteData) {
462
+ const { keys } = deleteData;
463
+ for (const key of keys) {
464
+ const keyStr = stringifyMessageKey(key);
465
+ if (!data.messageDeletes[keyStr]) {
466
+ data.messageDeletes[keyStr] = key;
467
+ }
468
+ if (data.messageUpserts[keyStr]) {
469
+ delete data.messageUpserts[keyStr];
470
+ }
471
+ if (data.messageUpdates[keyStr]) {
472
+ delete data.messageUpdates[keyStr];
473
+ }
474
+ }
475
+ }
476
+ else {
477
+ // TODO: add support
478
+ }
479
+ break;
480
+ case 'messages.reaction':
481
+ const reactions = eventData;
482
+ for (const { key, reaction } of reactions) {
483
+ const keyStr = stringifyMessageKey(key);
484
+ const existing = data.messageUpserts[keyStr];
485
+ if (existing) {
486
+ (0, messages_js_1.updateMessageWithReaction)(existing.message, reaction);
487
+ }
488
+ else {
489
+ data.messageReactions[keyStr] = data.messageReactions[keyStr] || { key, reactions: [] };
490
+ (0, messages_js_1.updateMessageWithReaction)(data.messageReactions[keyStr], reaction);
491
+ }
492
+ }
493
+ break;
494
+ case 'message-receipt.update':
495
+ const receipts = eventData;
496
+ for (const { key, receipt } of receipts) {
497
+ const keyStr = stringifyMessageKey(key);
498
+ const existing = data.messageUpserts[keyStr];
499
+ if (existing) {
500
+ (0, messages_js_1.updateMessageWithReceipt)(existing.message, receipt);
501
+ }
502
+ else {
503
+ data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || { key, userReceipt: [] };
504
+ (0, messages_js_1.updateMessageWithReceipt)(data.messageReceipts[keyStr], receipt);
505
+ }
506
+ }
507
+ break;
508
+ case 'groups.update':
509
+ const groupUpdates = eventData;
510
+ for (const update of groupUpdates) {
511
+ const id = update.id;
512
+ const groupUpdate = data.groupUpdates[id] || {};
513
+ if (!data.groupUpdates[id]) {
514
+ data.groupUpdates[id] = Object.assign(groupUpdate, update);
515
+ }
516
+ }
517
+ break;
518
+ // Vanz@Fix (bug 43): pass-through events — no consolidation needed, just buffer them
519
+ case 'settings.update':
520
+ case 'chats.lock':
521
+ case 'lid-mapping.update':
522
+ case 'newsletter-settings.update':
523
+ // These events are not consolidated — they fire as-is when the buffer flushes.
524
+ // We still need them in BUFFERABLE_EVENT so they don't throw "cannot be buffered".
525
+ break;
526
+ default:
527
+ throw new Error(`"${event}" cannot be buffered`);
528
+ }
529
+ function absorbingChatUpdate(existing) {
530
+ const chatId = existing.id || '';
531
+ const update = data.chatUpdates[chatId];
532
+ if (update) {
533
+ const conditionMatches = update.conditional ? update.conditional(data) : true;
534
+ if (conditionMatches) {
535
+ delete update.conditional;
536
+ logger.debug({ chatId }, 'absorbed chat update in existing chat');
537
+ Object.assign(existing, concatChats(update, existing));
538
+ delete data.chatUpdates[chatId];
539
+ }
540
+ else if (conditionMatches === false) {
541
+ logger.debug({ chatId }, 'chat update condition fail, removing');
542
+ delete data.chatUpdates[chatId];
543
+ }
544
+ }
545
+ }
546
+ function decrementChatReadCounterIfMsgDidUnread(message) {
547
+ // decrement chat unread counter
548
+ // if the message has already been marked read by us
549
+ const chatId = message.key.remoteJid;
550
+ const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId];
551
+ if ((0, process_message_js_1.isRealMessage)(message) &&
552
+ (0, process_message_js_1.shouldIncrementChatUnread)(message) &&
553
+ typeof chat?.unreadCount === 'number' &&
554
+ chat.unreadCount > 0) {
555
+ logger.debug({ chatId: chat.id }, 'decrementing chat counter');
556
+ chat.unreadCount -= 1;
557
+ if (chat.unreadCount === 0) {
558
+ delete chat.unreadCount;
559
+ }
560
+ }
561
+ }
562
+ }
563
+ function consolidateEvents(data) {
564
+ const map = {};
565
+ if (!data.historySets.empty) {
566
+ map['messaging-history.set'] = {
567
+ chats: Object.values(data.historySets.chats),
568
+ messages: Object.values(data.historySets.messages),
569
+ contacts: Object.values(data.historySets.contacts),
570
+ pastParticipants: data.historySets.pastParticipants,
571
+ syncType: data.historySets.syncType,
572
+ progress: data.historySets.progress,
573
+ isLatest: data.historySets.isLatest,
574
+ chunkOrder: data.historySets.chunkOrder,
575
+ peerDataRequestSessionId: data.historySets.peerDataRequestSessionId
576
+ };
577
+ }
578
+ const chatUpsertList = Object.values(data.chatUpserts);
579
+ if (chatUpsertList.length) {
580
+ map['chats.upsert'] = chatUpsertList;
581
+ }
582
+ const chatUpdateList = Object.values(data.chatUpdates);
583
+ if (chatUpdateList.length) {
584
+ map['chats.update'] = chatUpdateList;
585
+ }
586
+ const chatDeleteList = Array.from(data.chatDeletes);
587
+ if (chatDeleteList.length) {
588
+ map['chats.delete'] = chatDeleteList;
589
+ }
590
+ const messageUpsertList = Object.values(data.messageUpserts);
591
+ if (messageUpsertList.length) {
592
+ const type = messageUpsertList[0].type;
593
+ map['messages.upsert'] = {
594
+ messages: messageUpsertList.map(m => m.message),
595
+ type
596
+ };
597
+ }
598
+ const messageUpdateList = Object.values(data.messageUpdates);
599
+ if (messageUpdateList.length) {
600
+ map['messages.update'] = messageUpdateList;
601
+ }
602
+ const messageDeleteList = Object.values(data.messageDeletes);
603
+ if (messageDeleteList.length) {
604
+ map['messages.delete'] = { keys: messageDeleteList };
605
+ }
606
+ const messageReactionList = Object.values(data.messageReactions).flatMap(({ key, reactions }) => reactions.flatMap(reaction => ({ key, reaction })));
607
+ if (messageReactionList.length) {
608
+ map['messages.reaction'] = messageReactionList;
609
+ }
610
+ const messageReceiptList = Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) => userReceipt.flatMap(receipt => ({ key, receipt })));
611
+ if (messageReceiptList.length) {
612
+ map['message-receipt.update'] = messageReceiptList;
613
+ }
614
+ const contactUpsertList = Object.values(data.contactUpserts);
615
+ if (contactUpsertList.length) {
616
+ map['contacts.upsert'] = contactUpsertList;
617
+ }
618
+ const contactUpdateList = Object.values(data.contactUpdates);
619
+ if (contactUpdateList.length) {
620
+ map['contacts.update'] = contactUpdateList;
621
+ }
622
+ const groupUpdateList = Object.values(data.groupUpdates);
623
+ if (groupUpdateList.length) {
624
+ map['groups.update'] = groupUpdateList;
625
+ }
626
+ return map;
627
+ }
628
+ function concatChats(a, b) {
629
+ if (b.unreadCount === null && // neutralize unread counter
630
+ a.unreadCount < 0) {
631
+ a.unreadCount = undefined;
632
+ b.unreadCount = undefined;
633
+ }
634
+ if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
635
+ b = { ...b };
636
+ if (b.unreadCount >= 0) {
637
+ b.unreadCount = Math.max(b.unreadCount, 0) + Math.max(a.unreadCount, 0);
638
+ }
639
+ }
640
+ return Object.assign(a, b);
641
+ }
642
+ const stringifyMessageKey = (key) => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`;
643
+ //# sourceMappingURL=event-buffer.js.map