@x4r1s3/baileys 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1245 -2
  3. package/SECURITY.md +47 -0
  4. package/WAProto/V +1 -0
  5. package/WAProto/WAProto.proto +8892 -0
  6. package/WAProto/index.d.ts +104128 -0
  7. package/WAProto/index.js +334920 -0
  8. package/assets/rolling-circle.svg +133 -0
  9. package/assets/x4r1s3-banner.svg +32 -0
  10. package/engine-requirements.js +27 -0
  11. package/lib/Builders/A2UI.js +245 -0
  12. package/lib/Builders/AIRich.js +179 -0
  13. package/lib/Builders/Button.js +108 -0
  14. package/lib/Builders/CFC.js +284 -0
  15. package/lib/Builders/Carousel.js +81 -0
  16. package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
  17. package/lib/Call/astralena-v3.mjs +96 -0
  18. package/lib/Call/audio-feeder.mjs +201 -0
  19. package/lib/Call/audio-recorder.mjs +250 -0
  20. package/lib/Call/fetch-wasm-resources.mjs +104 -0
  21. package/lib/Call/index.mjs +707 -0
  22. package/lib/Call/relay-transport.mjs +563 -0
  23. package/lib/Call/signaling.mjs +660 -0
  24. package/lib/Call/types.mjs +17 -0
  25. package/lib/Call/video-feeder.mjs +94 -0
  26. package/lib/Call/voip-resources.mjs +259 -0
  27. package/lib/Call/wasm-engine.mjs +1372 -0
  28. package/lib/Call/worker-bootstrap.mjs +1042 -0
  29. package/lib/Defaults/ban-checker.js +56 -0
  30. package/lib/Defaults/index.js +170 -0
  31. package/lib/Signal/Group/ciphertext-message.js +23 -0
  32. package/lib/Signal/Group/group-session-builder.js +41 -0
  33. package/lib/Signal/Group/group_cipher.js +93 -0
  34. package/lib/Signal/Group/index.js +23 -0
  35. package/lib/Signal/Group/keyhelper.js +29 -0
  36. package/lib/Signal/Group/sender-chain-key.js +37 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
  38. package/lib/Signal/Group/sender-key-message.js +77 -0
  39. package/lib/Signal/Group/sender-key-name.js +59 -0
  40. package/lib/Signal/Group/sender-key-record.js +52 -0
  41. package/lib/Signal/Group/sender-key-state.js +95 -0
  42. package/lib/Signal/Group/sender-message-key.js +37 -0
  43. package/lib/Signal/libsignal.js +440 -0
  44. package/lib/Signal/lid-mapping.js +292 -0
  45. package/lib/Socket/Client/index.js +14 -0
  46. package/lib/Socket/Client/types.js +22 -0
  47. package/lib/Socket/Client/websocket.js +65 -0
  48. package/lib/Socket/aigroups.js +327 -0
  49. package/lib/Socket/ban-checker.js +165 -0
  50. package/lib/Socket/business.js +419 -0
  51. package/lib/Socket/chats.js +1921 -0
  52. package/lib/Socket/communities.js +443 -0
  53. package/lib/Socket/graphql.js +911 -0
  54. package/lib/Socket/groups.js +561 -0
  55. package/lib/Socket/index.js +49 -0
  56. package/lib/Socket/interactive-handler.js +612 -0
  57. package/lib/Socket/interop.js +575 -0
  58. package/lib/Socket/managed-account.js +220 -0
  59. package/lib/Socket/messages-recv.js +2193 -0
  60. package/lib/Socket/messages-send.js +4141 -0
  61. package/lib/Socket/mex.js +53 -0
  62. package/lib/Socket/newsletter.js +291 -0
  63. package/lib/Socket/privacy.js +458 -0
  64. package/lib/Socket/registration.js +440 -0
  65. package/lib/Socket/socket.js +1042 -0
  66. package/lib/Socket/status-actions.js +287 -0
  67. package/lib/Socket/username.js +241 -0
  68. package/lib/Store/index.js +16 -0
  69. package/lib/Store/make-cache-manager-store.js +101 -0
  70. package/lib/Store/make-in-memory-store.js +432 -0
  71. package/lib/Store/make-ordered-dictionary.js +90 -0
  72. package/lib/Store/object-repository.js +35 -0
  73. package/lib/Types/Auth.js +13 -0
  74. package/lib/Types/Bussines.js +13 -0
  75. package/lib/Types/Call.js +13 -0
  76. package/lib/Types/Chat.js +19 -0
  77. package/lib/Types/Contact.js +13 -0
  78. package/lib/Types/Events.js +13 -0
  79. package/lib/Types/GroupMetadata.js +13 -0
  80. package/lib/Types/Label.js +36 -0
  81. package/lib/Types/LabelAssociation.js +18 -0
  82. package/lib/Types/Message.js +30 -0
  83. package/lib/Types/Mex.js +53 -0
  84. package/lib/Types/Product.js +13 -0
  85. package/lib/Types/RichType.js +34 -0
  86. package/lib/Types/Signal.js +13 -0
  87. package/lib/Types/Socket.js +14 -0
  88. package/lib/Types/State.js +60 -0
  89. package/lib/Types/USync.js +13 -0
  90. package/lib/Types/index.js +37 -0
  91. package/lib/Utils/auth-utils.js +313 -0
  92. package/lib/Utils/ban-checker.js +48 -0
  93. package/lib/Utils/bot-capabilities.js +96 -0
  94. package/lib/Utils/bot-planning-replay.js +177 -0
  95. package/lib/Utils/browser-utils.js +40 -0
  96. package/lib/Utils/business.js +242 -0
  97. package/lib/Utils/c2582.js +147 -0
  98. package/lib/Utils/chat-utils.js +905 -0
  99. package/lib/Utils/companion-reg-client-utils.js +104 -0
  100. package/lib/Utils/consumer-application.js +114 -0
  101. package/lib/Utils/crypto.js +129 -0
  102. package/lib/Utils/decode-wa-message.js +496 -0
  103. package/lib/Utils/direct-chat-theme.js +164 -0
  104. package/lib/Utils/event-buffer.js +601 -0
  105. package/lib/Utils/experimental-proto.js +206 -0
  106. package/lib/Utils/games/miniapp.js +17 -0
  107. package/lib/Utils/games/slot-machine.js +270 -0
  108. package/lib/Utils/games/website-preview.js +306 -0
  109. package/lib/Utils/generics.js +402 -0
  110. package/lib/Utils/group-history.js +68 -0
  111. package/lib/Utils/group-wallpaper.js +168 -0
  112. package/lib/Utils/history.js +162 -0
  113. package/lib/Utils/identity-change-handler.js +60 -0
  114. package/lib/Utils/index.js +61 -0
  115. package/lib/Utils/jid-display-normalization.js +221 -0
  116. package/lib/Utils/link-preview.js +96 -0
  117. package/lib/Utils/logger.js +14 -0
  118. package/lib/Utils/lt-hash.js +19 -0
  119. package/lib/Utils/make-mutex.js +44 -0
  120. package/lib/Utils/message-composer.js +709 -0
  121. package/lib/Utils/message-inspect.js +79 -0
  122. package/lib/Utils/message-retry-manager.js +253 -0
  123. package/lib/Utils/message-security.js +167 -0
  124. package/lib/Utils/messages-media.js +1027 -0
  125. package/lib/Utils/messages.js +2467 -0
  126. package/lib/Utils/meta-ai-msmsg.js +215 -0
  127. package/lib/Utils/meta-compositing.js +239 -0
  128. package/lib/Utils/native-flow.js +158 -0
  129. package/lib/Utils/newsletter-live-update-utils.js +74 -0
  130. package/lib/Utils/newsletter-status-utils.js +152 -0
  131. package/lib/Utils/noise-handler.js +212 -0
  132. package/lib/Utils/offline-node-processor.js +51 -0
  133. package/lib/Utils/poll-manager.js +206 -0
  134. package/lib/Utils/portable-compat.js +12 -0
  135. package/lib/Utils/pre-key-manager.js +117 -0
  136. package/lib/Utils/process-message.js +610 -0
  137. package/lib/Utils/reporting-utils.js +269 -0
  138. package/lib/Utils/rich-message-utils.js +2841 -0
  139. package/lib/Utils/scheduled-message.js +107 -0
  140. package/lib/Utils/signal.js +212 -0
  141. package/lib/Utils/source-grep.js +57 -0
  142. package/lib/Utils/stanza-ack.js +49 -0
  143. package/lib/Utils/sticker-annotation.js +87 -0
  144. package/lib/Utils/sync-action-utils.js +59 -0
  145. package/lib/Utils/tc-token-utils.js +174 -0
  146. package/lib/Utils/use-multi-file-auth-state.js +132 -0
  147. package/lib/Utils/use-single-file-auth-state.js +108 -0
  148. package/lib/Utils/use-sqlite-auth-state.js +120 -0
  149. package/lib/Utils/validate-connection.js +221 -0
  150. package/lib/Utils/view-once-utils.js +218 -0
  151. package/lib/Utils/voip-rekey.js +32 -0
  152. package/lib/Utils/website-preview.js +27 -0
  153. package/lib/Utils/welcome-flow.js +228 -0
  154. package/lib/Utils/x4r1s3.js +144 -0
  155. package/lib/WABinary/constants.js +1475 -0
  156. package/lib/WABinary/decode.js +273 -0
  157. package/lib/WABinary/encode.js +231 -0
  158. package/lib/WABinary/generic-utils.js +242 -0
  159. package/lib/WABinary/index.js +17 -0
  160. package/lib/WABinary/jid-utils.js +107 -0
  161. package/lib/WABinary/types.js +13 -0
  162. package/lib/WAM/BinaryInfo.js +21 -0
  163. package/lib/WAM/constants.js +22864 -0
  164. package/lib/WAM/encode.js +161 -0
  165. package/lib/WAM/index.js +15 -0
  166. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
  167. package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
  168. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  169. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
  170. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
  171. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
  172. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
  173. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  174. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
  175. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
  176. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
  177. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
  178. package/lib/WAUSync/Protocols/index.js +24 -0
  179. package/lib/WAUSync/USyncQuery.js +213 -0
  180. package/lib/WAUSync/USyncUser.js +66 -0
  181. package/lib/WAUSync/index.js +15 -0
  182. package/lib/antiban.cjs +4726 -0
  183. package/lib/index.d.ts +1895 -0
  184. package/lib/index.js +41 -0
  185. package/package.json +125 -4
@@ -0,0 +1,601 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/event-buffer.js
5
+ * About: Event buffer module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: makeEventBuffer
7
+ * Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
8
+ *
9
+ * Copyright and attribution notice.
10
+ * Do not copy, reproduce, redistribute, modify, or create derivative works
11
+ * from this source without explicit written permission.
12
+ */
13
+ import EventEmitter from 'events';
14
+ import { WAMessageStatus } from '../Types/index.js';
15
+ import { trimUndefined } from './generics.js';
16
+ import { updateMessageWithReaction, updateMessageWithReceipt } from './messages.js';
17
+ import { isRealMessage, shouldIncrementChatUnread } from './process-message.js';
18
+ const BUFFERABLE_EVENT = [
19
+ 'messaging-history.set',
20
+ 'chats.upsert',
21
+ 'chats.update',
22
+ 'chats.delete',
23
+ 'contacts.upsert',
24
+ 'contacts.update',
25
+ 'messages.upsert',
26
+ 'messages.update',
27
+ 'messages.delete',
28
+ 'messages.reaction',
29
+ 'message-receipt.update',
30
+ 'groups.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
+ export const makeEventBuffer = (logger) => {
38
+ const ev = new EventEmitter();
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 = 30000; // 30 seconds
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
+ // Clear history cache
192
+ historyCache.clear();
193
+ // Reset buffer data
194
+ data = makeBufferData();
195
+ isBuffering = false;
196
+ bufferCount = 0;
197
+ // Remove all listeners
198
+ ev.removeAllListeners();
199
+ logger.debug('Event buffer destroyed');
200
+ }
201
+ };
202
+ };
203
+ const makeBufferData = () => {
204
+ return {
205
+ historySets: {
206
+ chats: {},
207
+ messages: {},
208
+ contacts: {},
209
+ isLatest: false,
210
+ empty: true
211
+ },
212
+ chatUpserts: {},
213
+ chatUpdates: {},
214
+ chatDeletes: new Set(),
215
+ contactUpserts: {},
216
+ contactUpdates: {},
217
+ messageUpserts: {},
218
+ messageUpdates: {},
219
+ messageReactions: {},
220
+ messageDeletes: {},
221
+ messageReceipts: {},
222
+ groupUpdates: {}
223
+ };
224
+ };
225
+ function append(data, historyCache, event,
226
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
227
+ eventData, logger) {
228
+ switch (event) {
229
+ case 'messaging-history.set':
230
+ for (const chat of eventData.chats) {
231
+ const id = chat.id || '';
232
+ const existingChat = data.historySets.chats[id];
233
+ if (existingChat) {
234
+ existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType;
235
+ }
236
+ if (!existingChat && !historyCache.has(id)) {
237
+ data.historySets.chats[id] = chat;
238
+ historyCache.add(id);
239
+ absorbingChatUpdate(chat);
240
+ }
241
+ }
242
+ for (const contact of eventData.contacts) {
243
+ const existingContact = data.historySets.contacts[contact.id];
244
+ if (existingContact) {
245
+ Object.assign(existingContact, trimUndefined(contact));
246
+ }
247
+ else {
248
+ const historyContactId = `c:${contact.id}`;
249
+ const hasAnyName = contact.notify || contact.name || contact.verifiedName;
250
+ if (!historyCache.has(historyContactId) || hasAnyName) {
251
+ data.historySets.contacts[contact.id] = contact;
252
+ historyCache.add(historyContactId);
253
+ }
254
+ }
255
+ }
256
+ for (const message of eventData.messages) {
257
+ const key = stringifyMessageKey(message.key);
258
+ const existingMsg = data.historySets.messages[key];
259
+ if (!existingMsg && !historyCache.has(key)) {
260
+ data.historySets.messages[key] = message;
261
+ historyCache.add(key);
262
+ }
263
+ }
264
+ data.historySets.empty = false;
265
+ data.historySets.syncType = eventData.syncType;
266
+ data.historySets.progress = eventData.progress;
267
+ data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId;
268
+ data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest;
269
+ break;
270
+ case 'chats.upsert':
271
+ for (const chat of eventData) {
272
+ const id = chat.id || '';
273
+ let upsert = data.chatUpserts[id];
274
+ if (id && !upsert) {
275
+ upsert = data.historySets.chats[id];
276
+ if (upsert) {
277
+ logger.debug({ chatId: id }, 'absorbed chat upsert in chat set');
278
+ }
279
+ }
280
+ if (upsert) {
281
+ upsert = concatChats(upsert, chat);
282
+ }
283
+ else {
284
+ upsert = chat;
285
+ data.chatUpserts[id] = upsert;
286
+ }
287
+ absorbingChatUpdate(upsert);
288
+ if (data.chatDeletes.has(id)) {
289
+ data.chatDeletes.delete(id);
290
+ }
291
+ }
292
+ break;
293
+ case 'chats.update':
294
+ for (const update of eventData) {
295
+ const chatId = update.id;
296
+ const conditionMatches = update.conditional ? update.conditional(data) : true;
297
+ if (conditionMatches) {
298
+ delete update.conditional;
299
+ // if there is an existing upsert, merge the update into it
300
+ const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId];
301
+ if (upsert) {
302
+ concatChats(upsert, update);
303
+ }
304
+ else {
305
+ // merge the update into the existing update
306
+ const chatUpdate = data.chatUpdates[chatId] || {};
307
+ data.chatUpdates[chatId] = concatChats(chatUpdate, update);
308
+ }
309
+ }
310
+ else if (conditionMatches === undefined) {
311
+ // condition yet to be fulfilled
312
+ data.chatUpdates[chatId] = update;
313
+ }
314
+ // otherwise -- condition not met, update is invalid
315
+ // if the chat has been updated
316
+ // ignore any existing chat delete
317
+ if (data.chatDeletes.has(chatId)) {
318
+ data.chatDeletes.delete(chatId);
319
+ }
320
+ }
321
+ break;
322
+ case 'chats.delete':
323
+ for (const chatId of eventData) {
324
+ if (!data.chatDeletes.has(chatId)) {
325
+ data.chatDeletes.add(chatId);
326
+ }
327
+ // remove any prior updates & upserts
328
+ if (data.chatUpdates[chatId]) {
329
+ delete data.chatUpdates[chatId];
330
+ }
331
+ if (data.chatUpserts[chatId]) {
332
+ delete data.chatUpserts[chatId];
333
+ }
334
+ if (data.historySets.chats[chatId]) {
335
+ delete data.historySets.chats[chatId];
336
+ }
337
+ }
338
+ break;
339
+ case 'contacts.upsert':
340
+ for (const contact of eventData) {
341
+ let upsert = data.contactUpserts[contact.id];
342
+ if (!upsert) {
343
+ upsert = data.historySets.contacts[contact.id];
344
+ if (upsert) {
345
+ logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set');
346
+ }
347
+ }
348
+ if (upsert) {
349
+ upsert = Object.assign(upsert, trimUndefined(contact));
350
+ }
351
+ else {
352
+ upsert = contact;
353
+ data.contactUpserts[contact.id] = upsert;
354
+ }
355
+ if (data.contactUpdates[contact.id]) {
356
+ upsert = Object.assign(data.contactUpdates[contact.id], trimUndefined(contact));
357
+ delete data.contactUpdates[contact.id];
358
+ }
359
+ }
360
+ break;
361
+ case 'contacts.update':
362
+ const contactUpdates = eventData;
363
+ for (const update of contactUpdates) {
364
+ const id = update.id;
365
+ // merge into prior upsert
366
+ const upsert = data.historySets.contacts[id] || data.contactUpserts[id];
367
+ if (upsert) {
368
+ Object.assign(upsert, update);
369
+ }
370
+ else {
371
+ // merge into prior update
372
+ const contactUpdate = data.contactUpdates[id] || {};
373
+ data.contactUpdates[id] = Object.assign(contactUpdate, update);
374
+ }
375
+ }
376
+ break;
377
+ case 'messages.upsert':
378
+ const { messages, type } = eventData;
379
+ for (const message of messages) {
380
+ const key = stringifyMessageKey(message.key);
381
+ let existing = data.messageUpserts[key]?.message;
382
+ if (!existing) {
383
+ existing = data.historySets.messages[key];
384
+ if (existing) {
385
+ logger.debug({ messageId: key }, 'absorbed message upsert in message set');
386
+ }
387
+ }
388
+ if (existing) {
389
+ message.messageTimestamp = existing.messageTimestamp;
390
+ }
391
+ if (data.messageUpdates[key]) {
392
+ logger.debug('absorbed prior message update in message upsert');
393
+ Object.assign(message, data.messageUpdates[key].update);
394
+ delete data.messageUpdates[key];
395
+ }
396
+ if (data.historySets.messages[key]) {
397
+ data.historySets.messages[key] = message;
398
+ }
399
+ else {
400
+ data.messageUpserts[key] = {
401
+ message,
402
+ type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type
403
+ };
404
+ }
405
+ }
406
+ break;
407
+ case 'messages.update':
408
+ const msgUpdates = eventData;
409
+ for (const { key, update } of msgUpdates) {
410
+ const keyStr = stringifyMessageKey(key);
411
+ const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message;
412
+ if (existing) {
413
+ Object.assign(existing, update);
414
+ // if the message was received & read by us
415
+ // the chat counter must have been incremented
416
+ // so we need to decrement it
417
+ if (update.status === WAMessageStatus.READ && !key.fromMe) {
418
+ decrementChatReadCounterIfMsgDidUnread(existing);
419
+ }
420
+ }
421
+ else {
422
+ const msgUpdate = data.messageUpdates[keyStr] || { key, update: {} };
423
+ Object.assign(msgUpdate.update, update);
424
+ data.messageUpdates[keyStr] = msgUpdate;
425
+ }
426
+ }
427
+ break;
428
+ case 'messages.delete':
429
+ const deleteData = eventData;
430
+ if ('keys' in deleteData) {
431
+ const { keys } = deleteData;
432
+ for (const key of keys) {
433
+ const keyStr = stringifyMessageKey(key);
434
+ if (!data.messageDeletes[keyStr]) {
435
+ data.messageDeletes[keyStr] = key;
436
+ }
437
+ if (data.messageUpserts[keyStr]) {
438
+ delete data.messageUpserts[keyStr];
439
+ }
440
+ if (data.messageUpdates[keyStr]) {
441
+ delete data.messageUpdates[keyStr];
442
+ }
443
+ }
444
+ }
445
+ else {
446
+ // TODO: add support
447
+ }
448
+ break;
449
+ case 'messages.reaction':
450
+ const reactions = eventData;
451
+ for (const { key, reaction } of reactions) {
452
+ const keyStr = stringifyMessageKey(key);
453
+ const existing = data.messageUpserts[keyStr];
454
+ if (existing) {
455
+ updateMessageWithReaction(existing.message, reaction);
456
+ }
457
+ else {
458
+ data.messageReactions[keyStr] = data.messageReactions[keyStr] || { key, reactions: [] };
459
+ updateMessageWithReaction(data.messageReactions[keyStr], reaction);
460
+ }
461
+ }
462
+ break;
463
+ case 'message-receipt.update':
464
+ const receipts = eventData;
465
+ for (const { key, receipt } of receipts) {
466
+ const keyStr = stringifyMessageKey(key);
467
+ const existing = data.messageUpserts[keyStr];
468
+ if (existing) {
469
+ updateMessageWithReceipt(existing.message, receipt);
470
+ }
471
+ else {
472
+ data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || { key, userReceipt: [] };
473
+ updateMessageWithReceipt(data.messageReceipts[keyStr], receipt);
474
+ }
475
+ }
476
+ break;
477
+ case 'groups.update':
478
+ const groupUpdates = eventData;
479
+ for (const update of groupUpdates) {
480
+ const id = update.id;
481
+ const groupUpdate = data.groupUpdates[id] || {};
482
+ if (!data.groupUpdates[id]) {
483
+ data.groupUpdates[id] = Object.assign(groupUpdate, update);
484
+ }
485
+ }
486
+ break;
487
+ default:
488
+ throw new Error(`"${event}" cannot be buffered`);
489
+ }
490
+ function absorbingChatUpdate(existing) {
491
+ const chatId = existing.id || '';
492
+ const update = data.chatUpdates[chatId];
493
+ if (update) {
494
+ const conditionMatches = update.conditional ? update.conditional(data) : true;
495
+ if (conditionMatches) {
496
+ delete update.conditional;
497
+ logger.debug({ chatId }, 'absorbed chat update in existing chat');
498
+ Object.assign(existing, concatChats(update, existing));
499
+ delete data.chatUpdates[chatId];
500
+ }
501
+ else if (conditionMatches === false) {
502
+ logger.debug({ chatId }, 'chat update condition fail, removing');
503
+ delete data.chatUpdates[chatId];
504
+ }
505
+ }
506
+ }
507
+ function decrementChatReadCounterIfMsgDidUnread(message) {
508
+ // decrement chat unread counter
509
+ // if the message has already been marked read by us
510
+ const chatId = message.key.remoteJid;
511
+ const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId];
512
+ if (isRealMessage(message) &&
513
+ shouldIncrementChatUnread(message) &&
514
+ typeof chat?.unreadCount === 'number' &&
515
+ chat.unreadCount > 0) {
516
+ logger.debug({ chatId: chat.id }, 'decrementing chat counter');
517
+ chat.unreadCount -= 1;
518
+ if (chat.unreadCount === 0) {
519
+ delete chat.unreadCount;
520
+ }
521
+ }
522
+ }
523
+ }
524
+ function consolidateEvents(data) {
525
+ const map = {};
526
+ if (!data.historySets.empty) {
527
+ map['messaging-history.set'] = {
528
+ chats: Object.values(data.historySets.chats),
529
+ messages: Object.values(data.historySets.messages),
530
+ contacts: Object.values(data.historySets.contacts),
531
+ syncType: data.historySets.syncType,
532
+ progress: data.historySets.progress,
533
+ isLatest: data.historySets.isLatest,
534
+ peerDataRequestSessionId: data.historySets.peerDataRequestSessionId
535
+ };
536
+ }
537
+ const chatUpsertList = Object.values(data.chatUpserts);
538
+ if (chatUpsertList.length) {
539
+ map['chats.upsert'] = chatUpsertList;
540
+ }
541
+ const chatUpdateList = Object.values(data.chatUpdates);
542
+ if (chatUpdateList.length) {
543
+ map['chats.update'] = chatUpdateList;
544
+ }
545
+ const chatDeleteList = Array.from(data.chatDeletes);
546
+ if (chatDeleteList.length) {
547
+ map['chats.delete'] = chatDeleteList;
548
+ }
549
+ const messageUpsertList = Object.values(data.messageUpserts);
550
+ if (messageUpsertList.length) {
551
+ const type = messageUpsertList[0].type;
552
+ map['messages.upsert'] = {
553
+ messages: messageUpsertList.map(m => m.message),
554
+ type
555
+ };
556
+ }
557
+ const messageUpdateList = Object.values(data.messageUpdates);
558
+ if (messageUpdateList.length) {
559
+ map['messages.update'] = messageUpdateList;
560
+ }
561
+ const messageDeleteList = Object.values(data.messageDeletes);
562
+ if (messageDeleteList.length) {
563
+ map['messages.delete'] = { keys: messageDeleteList };
564
+ }
565
+ const messageReactionList = Object.values(data.messageReactions).flatMap(({ key, reactions }) => reactions.flatMap(reaction => ({ key, reaction })));
566
+ if (messageReactionList.length) {
567
+ map['messages.reaction'] = messageReactionList;
568
+ }
569
+ const messageReceiptList = Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) => userReceipt.flatMap(receipt => ({ key, receipt })));
570
+ if (messageReceiptList.length) {
571
+ map['message-receipt.update'] = messageReceiptList;
572
+ }
573
+ const contactUpsertList = Object.values(data.contactUpserts);
574
+ if (contactUpsertList.length) {
575
+ map['contacts.upsert'] = contactUpsertList;
576
+ }
577
+ const contactUpdateList = Object.values(data.contactUpdates);
578
+ if (contactUpdateList.length) {
579
+ map['contacts.update'] = contactUpdateList;
580
+ }
581
+ const groupUpdateList = Object.values(data.groupUpdates);
582
+ if (groupUpdateList.length) {
583
+ map['groups.update'] = groupUpdateList;
584
+ }
585
+ return map;
586
+ }
587
+ function concatChats(a, b) {
588
+ if (b.unreadCount === null && // neutralize unread counter
589
+ a.unreadCount < 0) {
590
+ a.unreadCount = undefined;
591
+ b.unreadCount = undefined;
592
+ }
593
+ if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
594
+ b = { ...b };
595
+ if (b.unreadCount >= 0) {
596
+ b.unreadCount = Math.max(b.unreadCount, 0) + Math.max(a.unreadCount, 0);
597
+ }
598
+ }
599
+ return Object.assign(a, b);
600
+ }
601
+ const stringifyMessageKey = (key) => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`;