queenruva-sockets 5.6.23

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 (205) hide show
  1. package/LICENSE +31 -0
  2. package/README.md +1082 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +97691 -0
  8. package/engine-requirements.js +11 -0
  9. package/lib/Defaults/index.d.ts +75 -0
  10. package/lib/Defaults/index.js +129 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  12. package/lib/Signal/Group/ciphertext-message.js +12 -0
  13. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  14. package/lib/Signal/Group/group-session-builder.js +30 -0
  15. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  16. package/lib/Signal/Group/group_cipher.js +82 -0
  17. package/lib/Signal/Group/index.d.ts +12 -0
  18. package/lib/Signal/Group/index.js +12 -0
  19. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  20. package/lib/Signal/Group/keyhelper.js +18 -0
  21. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  22. package/lib/Signal/Group/sender-chain-key.js +26 -0
  23. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  24. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  25. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  26. package/lib/Signal/Group/sender-key-message.js +66 -0
  27. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  28. package/lib/Signal/Group/sender-key-name.js +48 -0
  29. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  30. package/lib/Signal/Group/sender-key-record.js +41 -0
  31. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  32. package/lib/Signal/Group/sender-key-state.js +84 -0
  33. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  34. package/lib/Signal/Group/sender-message-key.js +26 -0
  35. package/lib/Signal/libsignal.d.ts +5 -0
  36. package/lib/Signal/libsignal.js +431 -0
  37. package/lib/Signal/lid-mapping.d.ts +23 -0
  38. package/lib/Signal/lid-mapping.js +277 -0
  39. package/lib/Socket/Client/index.d.ts +3 -0
  40. package/lib/Socket/Client/index.js +3 -0
  41. package/lib/Socket/Client/types.d.ts +16 -0
  42. package/lib/Socket/Client/types.js +11 -0
  43. package/lib/Socket/Client/websocket.d.ts +13 -0
  44. package/lib/Socket/Client/websocket.js +54 -0
  45. package/lib/Socket/business.d.ts +217 -0
  46. package/lib/Socket/business.js +379 -0
  47. package/lib/Socket/chats.d.ts +124 -0
  48. package/lib/Socket/chats.js +1193 -0
  49. package/lib/Socket/communities.d.ts +273 -0
  50. package/lib/Socket/communities.js +431 -0
  51. package/lib/Socket/groups.d.ts +161 -0
  52. package/lib/Socket/groups.js +347 -0
  53. package/lib/Socket/index.d.ts +260 -0
  54. package/lib/Socket/index.js +12 -0
  55. package/lib/Socket/messages-recv.d.ts +203 -0
  56. package/lib/Socket/messages-recv.js +1772 -0
  57. package/lib/Socket/messages-send.d.ts +199 -0
  58. package/lib/Socket/messages-send.js +1160 -0
  59. package/lib/Socket/mex.d.ts +3 -0
  60. package/lib/Socket/mex.js +42 -0
  61. package/lib/Socket/newsletter.d.ts +170 -0
  62. package/lib/Socket/newsletter.js +181 -0
  63. package/lib/Socket/socket.d.ts +59 -0
  64. package/lib/Socket/socket.js +1029 -0
  65. package/lib/Types/Auth.d.ts +117 -0
  66. package/lib/Types/Auth.js +2 -0
  67. package/lib/Types/Bussines.d.ts +25 -0
  68. package/lib/Types/Bussines.js +2 -0
  69. package/lib/Types/Call.d.ts +15 -0
  70. package/lib/Types/Call.js +2 -0
  71. package/lib/Types/Chat.d.ts +124 -0
  72. package/lib/Types/Chat.js +8 -0
  73. package/lib/Types/Contact.d.ts +26 -0
  74. package/lib/Types/Contact.js +2 -0
  75. package/lib/Types/Events.d.ts +256 -0
  76. package/lib/Types/Events.js +2 -0
  77. package/lib/Types/GroupMetadata.d.ts +71 -0
  78. package/lib/Types/GroupMetadata.js +2 -0
  79. package/lib/Types/Label.d.ts +47 -0
  80. package/lib/Types/Label.js +25 -0
  81. package/lib/Types/LabelAssociation.d.ts +30 -0
  82. package/lib/Types/LabelAssociation.js +7 -0
  83. package/lib/Types/Message.d.ts +320 -0
  84. package/lib/Types/Message.js +11 -0
  85. package/lib/Types/Mex.d.ts +141 -0
  86. package/lib/Types/Mex.js +37 -0
  87. package/lib/Types/Product.d.ts +79 -0
  88. package/lib/Types/Product.js +2 -0
  89. package/lib/Types/Signal.d.ts +87 -0
  90. package/lib/Types/Signal.js +2 -0
  91. package/lib/Types/Socket.d.ts +136 -0
  92. package/lib/Types/Socket.js +3 -0
  93. package/lib/Types/State.d.ts +97 -0
  94. package/lib/Types/State.js +56 -0
  95. package/lib/Types/USync.d.ts +26 -0
  96. package/lib/Types/USync.js +2 -0
  97. package/lib/Types/index.d.ts +65 -0
  98. package/lib/Types/index.js +26 -0
  99. package/lib/Utils/auth-utils.d.ts +24 -0
  100. package/lib/Utils/auth-utils.js +302 -0
  101. package/lib/Utils/browser-utils.d.ts +4 -0
  102. package/lib/Utils/browser-utils.js +28 -0
  103. package/lib/Utils/business.d.ts +23 -0
  104. package/lib/Utils/business.js +231 -0
  105. package/lib/Utils/chat-utils.d.ts +100 -0
  106. package/lib/Utils/chat-utils.js +872 -0
  107. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  108. package/lib/Utils/companion-reg-client-utils.js +35 -0
  109. package/lib/Utils/crypto.d.ts +37 -0
  110. package/lib/Utils/crypto.js +118 -0
  111. package/lib/Utils/decode-wa-message.d.ts +66 -0
  112. package/lib/Utils/decode-wa-message.js +311 -0
  113. package/lib/Utils/event-buffer.d.ts +36 -0
  114. package/lib/Utils/event-buffer.js +622 -0
  115. package/lib/Utils/generics.d.ts +91 -0
  116. package/lib/Utils/generics.js +378 -0
  117. package/lib/Utils/history.d.ts +24 -0
  118. package/lib/Utils/history.js +134 -0
  119. package/lib/Utils/identity-change-handler.d.ts +44 -0
  120. package/lib/Utils/identity-change-handler.js +50 -0
  121. package/lib/Utils/index.d.ts +22 -0
  122. package/lib/Utils/index.js +22 -0
  123. package/lib/Utils/link-preview.d.ts +21 -0
  124. package/lib/Utils/link-preview.js +85 -0
  125. package/lib/Utils/logger.d.ts +12 -0
  126. package/lib/Utils/logger.js +3 -0
  127. package/lib/Utils/lt-hash.d.ts +8 -0
  128. package/lib/Utils/lt-hash.js +8 -0
  129. package/lib/Utils/make-mutex.d.ts +9 -0
  130. package/lib/Utils/make-mutex.js +33 -0
  131. package/lib/Utils/message-retry-manager.d.ts +115 -0
  132. package/lib/Utils/message-retry-manager.js +265 -0
  133. package/lib/Utils/messages-media.d.ts +133 -0
  134. package/lib/Utils/messages-media.js +786 -0
  135. package/lib/Utils/messages.d.ts +91 -0
  136. package/lib/Utils/messages.js +893 -0
  137. package/lib/Utils/noise-handler.d.ts +20 -0
  138. package/lib/Utils/noise-handler.js +201 -0
  139. package/lib/Utils/offline-node-processor.d.ts +17 -0
  140. package/lib/Utils/offline-node-processor.js +40 -0
  141. package/lib/Utils/pre-key-manager.d.ts +28 -0
  142. package/lib/Utils/pre-key-manager.js +106 -0
  143. package/lib/Utils/process-message.d.ts +60 -0
  144. package/lib/Utils/process-message.js +597 -0
  145. package/lib/Utils/reporting-utils.d.ts +11 -0
  146. package/lib/Utils/reporting-utils.js +258 -0
  147. package/lib/Utils/signal.d.ts +47 -0
  148. package/lib/Utils/signal.js +201 -0
  149. package/lib/Utils/stanza-ack.d.ts +11 -0
  150. package/lib/Utils/stanza-ack.js +38 -0
  151. package/lib/Utils/sync-action-utils.d.ts +19 -0
  152. package/lib/Utils/sync-action-utils.js +49 -0
  153. package/lib/Utils/tc-token-utils.d.ts +37 -0
  154. package/lib/Utils/tc-token-utils.js +163 -0
  155. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  156. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  157. package/lib/Utils/validate-connection.d.ts +11 -0
  158. package/lib/Utils/validate-connection.js +203 -0
  159. package/lib/WABinary/constants.d.ts +28 -0
  160. package/lib/WABinary/constants.js +1301 -0
  161. package/lib/WABinary/decode.d.ts +7 -0
  162. package/lib/WABinary/decode.js +262 -0
  163. package/lib/WABinary/encode.d.ts +3 -0
  164. package/lib/WABinary/encode.js +220 -0
  165. package/lib/WABinary/generic-utils.d.ts +15 -0
  166. package/lib/WABinary/generic-utils.js +113 -0
  167. package/lib/WABinary/index.d.ts +6 -0
  168. package/lib/WABinary/index.js +6 -0
  169. package/lib/WABinary/jid-utils.d.ts +48 -0
  170. package/lib/WABinary/jid-utils.js +96 -0
  171. package/lib/WABinary/types.d.ts +19 -0
  172. package/lib/WABinary/types.js +2 -0
  173. package/lib/WAM/BinaryInfo.d.ts +9 -0
  174. package/lib/WAM/BinaryInfo.js +10 -0
  175. package/lib/WAM/constants.d.ts +40 -0
  176. package/lib/WAM/constants.js +22853 -0
  177. package/lib/WAM/encode.d.ts +3 -0
  178. package/lib/WAM/encode.js +150 -0
  179. package/lib/WAM/index.d.ts +4 -0
  180. package/lib/WAM/index.js +4 -0
  181. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  182. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  183. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  184. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  185. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  186. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  187. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  188. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  189. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  190. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  191. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  192. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  193. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  194. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  195. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  196. package/lib/WAUSync/Protocols/index.js +6 -0
  197. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  198. package/lib/WAUSync/USyncQuery.js +98 -0
  199. package/lib/WAUSync/USyncUser.d.ts +17 -0
  200. package/lib/WAUSync/USyncUser.js +31 -0
  201. package/lib/WAUSync/index.d.ts +4 -0
  202. package/lib/WAUSync/index.js +4 -0
  203. package/lib/index.d.ts +12 -0
  204. package/lib/index.js +11 -0
  205. package/package.json +160 -0
@@ -0,0 +1,622 @@
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