@badzz88/baileys 8.4.7 → 8.4.9

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