@skycodee/baileys 8.0.3 → 8.0.4

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