@xbibzlibrary/whatsbibz 1.3.0

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 (260) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/LICENSE +22 -0
  3. package/LICENSE.upstream +21 -0
  4. package/README.md +280 -0
  5. package/VERIFIKASI-IDENTITAS-2026-09-03.md +138 -0
  6. package/WAProto/GenerateStatics.sh +3 -0
  7. package/WAProto/WAProto.proto +6035 -0
  8. package/WAProto/fix-imports.js +81 -0
  9. package/WAProto/index.d.ts +15314 -0
  10. package/WAProto/index.js +132326 -0
  11. package/assets/logo/README.md +21 -0
  12. package/assets/logo/png/banner-1200x360.png +0 -0
  13. package/assets/logo/png/icon-1024.png +0 -0
  14. package/assets/logo/png/icon-128.png +0 -0
  15. package/assets/logo/png/icon-16.png +0 -0
  16. package/assets/logo/png/icon-24.png +0 -0
  17. package/assets/logo/png/icon-256.png +0 -0
  18. package/assets/logo/png/icon-32.png +0 -0
  19. package/assets/logo/png/icon-48.png +0 -0
  20. package/assets/logo/png/icon-512.png +0 -0
  21. package/assets/logo/png/icon-64.png +0 -0
  22. package/assets/logo/png/mark-512.png +0 -0
  23. package/assets/logo/preview.png +0 -0
  24. package/assets/logo/whatsbibz.ico +0 -0
  25. package/lib/BibzWhats/client.d.ts +95 -0
  26. package/lib/BibzWhats/client.js +501 -0
  27. package/lib/BibzWhats/device-identity.d.ts +60 -0
  28. package/lib/BibzWhats/device-identity.js +234 -0
  29. package/lib/BibzWhats/extract.d.ts +29 -0
  30. package/lib/BibzWhats/extract.js +115 -0
  31. package/lib/BibzWhats/index.d.ts +7 -0
  32. package/lib/BibzWhats/index.js +8 -0
  33. package/lib/BibzWhats/jid.d.ts +22 -0
  34. package/lib/BibzWhats/jid.js +98 -0
  35. package/lib/BibzWhats/pairing.d.ts +35 -0
  36. package/lib/BibzWhats/pairing.js +186 -0
  37. package/lib/BibzWhats/send.d.ts +9 -0
  38. package/lib/BibzWhats/send.js +107 -0
  39. package/lib/BibzWhats/version.d.ts +6 -0
  40. package/lib/BibzWhats/version.js +7 -0
  41. package/lib/Defaults/index.d.ts +73 -0
  42. package/lib/Defaults/index.js +141 -0
  43. package/lib/Modded/message_builder.d.ts +15 -0
  44. package/lib/Modded/message_builder.js +2330 -0
  45. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  46. package/lib/Signal/Group/ciphertext-message.js +11 -0
  47. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  48. package/lib/Signal/Group/group-session-builder.js +29 -0
  49. package/lib/Signal/Group/group_cipher.d.ts +16 -0
  50. package/lib/Signal/Group/group_cipher.js +81 -0
  51. package/lib/Signal/Group/index.d.ts +11 -0
  52. package/lib/Signal/Group/index.js +11 -0
  53. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  54. package/lib/Signal/Group/keyhelper.js +17 -0
  55. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  56. package/lib/Signal/Group/sender-chain-key.js +25 -0
  57. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  58. package/lib/Signal/Group/sender-key-distribution-message.js +62 -0
  59. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  60. package/lib/Signal/Group/sender-key-message.js +65 -0
  61. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  62. package/lib/Signal/Group/sender-key-name.js +47 -0
  63. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  64. package/lib/Signal/Group/sender-key-record.js +40 -0
  65. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  66. package/lib/Signal/Group/sender-key-state.js +83 -0
  67. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  68. package/lib/Signal/Group/sender-message-key.js +25 -0
  69. package/lib/Signal/libsignal.d.ts +4 -0
  70. package/lib/Signal/libsignal.js +406 -0
  71. package/lib/Signal/lid-mapping.d.ts +18 -0
  72. package/lib/Signal/lid-mapping.js +276 -0
  73. package/lib/Socket/Client/index.d.ts +2 -0
  74. package/lib/Socket/Client/index.js +2 -0
  75. package/lib/Socket/Client/types.d.ts +15 -0
  76. package/lib/Socket/Client/types.js +10 -0
  77. package/lib/Socket/Client/websocket.d.ts +12 -0
  78. package/lib/Socket/Client/websocket.js +53 -0
  79. package/lib/Socket/business.d.ts +537 -0
  80. package/lib/Socket/business.js +421 -0
  81. package/lib/Socket/chats.d.ts +110 -0
  82. package/lib/Socket/chats.js +1006 -0
  83. package/lib/Socket/communities.d.ts +646 -0
  84. package/lib/Socket/communities.js +430 -0
  85. package/lib/Socket/engine.d.ts +129 -0
  86. package/lib/Socket/engine.js +767 -0
  87. package/lib/Socket/groups.d.ts +149 -0
  88. package/lib/Socket/groups.js +326 -0
  89. package/lib/Socket/index.d.ts +637 -0
  90. package/lib/Socket/index.js +14 -0
  91. package/lib/Socket/messages-recv.d.ts +239 -0
  92. package/lib/Socket/messages-recv.js +1307 -0
  93. package/lib/Socket/messages-send.d.ts +580 -0
  94. package/lib/Socket/messages-send.js +1639 -0
  95. package/lib/Socket/mex.d.ts +2 -0
  96. package/lib/Socket/mex.js +47 -0
  97. package/lib/Socket/newsletter.d.ts +176 -0
  98. package/lib/Socket/newsletter.js +456 -0
  99. package/lib/Socket/socket.d.ts +56 -0
  100. package/lib/Socket/socket.js +998 -0
  101. package/lib/Types/Auth.d.ts +115 -0
  102. package/lib/Types/Auth.js +1 -0
  103. package/lib/Types/Bussines.d.ts +36 -0
  104. package/lib/Types/Bussines.js +1 -0
  105. package/lib/Types/Call.d.ts +14 -0
  106. package/lib/Types/Call.js +1 -0
  107. package/lib/Types/Chat.d.ts +124 -0
  108. package/lib/Types/Chat.js +7 -0
  109. package/lib/Types/Contact.d.ts +23 -0
  110. package/lib/Types/Contact.js +1 -0
  111. package/lib/Types/Events.d.ts +241 -0
  112. package/lib/Types/Events.js +1 -0
  113. package/lib/Types/GroupMetadata.d.ts +67 -0
  114. package/lib/Types/GroupMetadata.js +1 -0
  115. package/lib/Types/Label.d.ts +46 -0
  116. package/lib/Types/Label.js +24 -0
  117. package/lib/Types/LabelAssociation.d.ts +29 -0
  118. package/lib/Types/LabelAssociation.js +6 -0
  119. package/lib/Types/Message.d.ts +427 -0
  120. package/lib/Types/Message.js +10 -0
  121. package/lib/Types/Newsletter.d.ts +134 -0
  122. package/lib/Types/Newsletter.js +30 -0
  123. package/lib/Types/Product.d.ts +78 -0
  124. package/lib/Types/Product.js +1 -0
  125. package/lib/Types/Signal.d.ts +77 -0
  126. package/lib/Types/Signal.js +1 -0
  127. package/lib/Types/Socket.d.ts +173 -0
  128. package/lib/Types/Socket.js +2 -0
  129. package/lib/Types/State.d.ts +38 -0
  130. package/lib/Types/State.js +12 -0
  131. package/lib/Types/USync.d.ts +25 -0
  132. package/lib/Types/USync.js +1 -0
  133. package/lib/Types/index.d.ts +75 -0
  134. package/lib/Types/index.js +32 -0
  135. package/lib/Utils/auth-utils.d.ts +18 -0
  136. package/lib/Utils/auth-utils.js +289 -0
  137. package/lib/Utils/browser-utils.d.ts +3 -0
  138. package/lib/Utils/browser-utils.js +47 -0
  139. package/lib/Utils/business.d.ts +22 -0
  140. package/lib/Utils/business.js +230 -0
  141. package/lib/Utils/chat-utils.d.ts +69 -0
  142. package/lib/Utils/chat-utils.js +811 -0
  143. package/lib/Utils/companion-reg-client-utils.d.ts +20 -0
  144. package/lib/Utils/companion-reg-client-utils.js +66 -0
  145. package/lib/Utils/crypto.d.ts +41 -0
  146. package/lib/Utils/crypto.js +117 -0
  147. package/lib/Utils/decode-wa-message.d.ts +47 -0
  148. package/lib/Utils/decode-wa-message.js +282 -0
  149. package/lib/Utils/event-buffer.d.ts +35 -0
  150. package/lib/Utils/event-buffer.js +590 -0
  151. package/lib/Utils/generics.d.ts +90 -0
  152. package/lib/Utils/generics.js +384 -0
  153. package/lib/Utils/history.d.ts +21 -0
  154. package/lib/Utils/history.js +130 -0
  155. package/lib/Utils/identity-change-handler.d.ts +36 -0
  156. package/lib/Utils/identity-change-handler.js +48 -0
  157. package/lib/Utils/index.d.ts +25 -0
  158. package/lib/Utils/index.js +24 -0
  159. package/lib/Utils/link-preview.d.ts +20 -0
  160. package/lib/Utils/link-preview.js +84 -0
  161. package/lib/Utils/logger.d.ts +12 -0
  162. package/lib/Utils/logger.js +2 -0
  163. package/lib/Utils/lt-hash.d.ts +10 -0
  164. package/lib/Utils/lt-hash.js +7 -0
  165. package/lib/Utils/make-mutex.d.ts +8 -0
  166. package/lib/Utils/make-mutex.js +32 -0
  167. package/lib/Utils/message-retry-manager.d.ts +109 -0
  168. package/lib/Utils/message-retry-manager.js +224 -0
  169. package/lib/Utils/messages-media.d.ts +129 -0
  170. package/lib/Utils/messages-media.js +784 -0
  171. package/lib/Utils/messages.d.ts +90 -0
  172. package/lib/Utils/messages.js +1240 -0
  173. package/lib/Utils/noise-handler.d.ts +19 -0
  174. package/lib/Utils/noise-handler.js +200 -0
  175. package/lib/Utils/offline-node-processor.d.ts +16 -0
  176. package/lib/Utils/offline-node-processor.js +39 -0
  177. package/lib/Utils/platform-identity.d.ts +14 -0
  178. package/lib/Utils/platform-identity.js +148 -0
  179. package/lib/Utils/pre-key-manager.d.ts +27 -0
  180. package/lib/Utils/pre-key-manager.js +105 -0
  181. package/lib/Utils/process-message.d.ts +59 -0
  182. package/lib/Utils/process-message.js +544 -0
  183. package/lib/Utils/reporting-utils.d.ts +10 -0
  184. package/lib/Utils/reporting-utils.js +257 -0
  185. package/lib/Utils/rich-messages.d.ts +276 -0
  186. package/lib/Utils/rich-messages.js +1143 -0
  187. package/lib/Utils/signal.d.ts +33 -0
  188. package/lib/Utils/signal.js +158 -0
  189. package/lib/Utils/stanza-ack.d.ts +10 -0
  190. package/lib/Utils/stanza-ack.js +37 -0
  191. package/lib/Utils/sticker-pack.d.ts +10 -0
  192. package/lib/Utils/sticker-pack.js +111 -0
  193. package/lib/Utils/sync-action-utils.d.ts +18 -0
  194. package/lib/Utils/sync-action-utils.js +47 -0
  195. package/lib/Utils/tc-token-utils.d.ts +8 -0
  196. package/lib/Utils/tc-token-utils.js +45 -0
  197. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  198. package/lib/Utils/use-multi-file-auth-state.js +120 -0
  199. package/lib/Utils/validate-connection.d.ts +10 -0
  200. package/lib/Utils/validate-connection.js +222 -0
  201. package/lib/VoIP/audio-feeder.d.ts +15 -0
  202. package/lib/VoIP/audio-feeder.js +136 -0
  203. package/lib/VoIP/index.d.ts +12 -0
  204. package/lib/VoIP/index.js +282 -0
  205. package/lib/VoIP/relay-transport.d.ts +43 -0
  206. package/lib/VoIP/relay-transport.js +559 -0
  207. package/lib/VoIP/signaling.js +603 -0
  208. package/lib/VoIP/types.d.ts +69 -0
  209. package/lib/VoIP/types.js +17 -0
  210. package/lib/VoIP/wasm-engine.d.ts +103 -0
  211. package/lib/VoIP/wasm-engine.js +1214 -0
  212. package/lib/VoIP/worker-bootstrap.js +1042 -0
  213. package/lib/WABinary/constants.d.ts +27 -0
  214. package/lib/WABinary/constants.js +1300 -0
  215. package/lib/WABinary/decode.d.ts +6 -0
  216. package/lib/WABinary/decode.js +261 -0
  217. package/lib/WABinary/encode.d.ts +2 -0
  218. package/lib/WABinary/encode.js +219 -0
  219. package/lib/WABinary/generic-utils.d.ts +16 -0
  220. package/lib/WABinary/generic-utils.js +190 -0
  221. package/lib/WABinary/index.d.ts +5 -0
  222. package/lib/WABinary/index.js +5 -0
  223. package/lib/WABinary/jid-utils.d.ts +47 -0
  224. package/lib/WABinary/jid-utils.js +95 -0
  225. package/lib/WABinary/types.d.ts +18 -0
  226. package/lib/WABinary/types.js +1 -0
  227. package/lib/WAM/BinaryInfo.d.ts +8 -0
  228. package/lib/WAM/BinaryInfo.js +9 -0
  229. package/lib/WAM/constants.d.ts +39 -0
  230. package/lib/WAM/constants.js +22852 -0
  231. package/lib/WAM/encode.d.ts +2 -0
  232. package/lib/WAM/encode.js +149 -0
  233. package/lib/WAM/index.d.ts +3 -0
  234. package/lib/WAM/index.js +3 -0
  235. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  236. package/lib/WAUSync/Protocols/USyncContactProtocol.js +28 -0
  237. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  238. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +53 -0
  239. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  240. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  241. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  242. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  243. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  244. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +50 -0
  245. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +9 -0
  246. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  247. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  248. package/lib/WAUSync/Protocols/index.js +4 -0
  249. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  250. package/lib/WAUSync/USyncQuery.js +93 -0
  251. package/lib/WAUSync/USyncUser.d.ts +12 -0
  252. package/lib/WAUSync/USyncUser.js +22 -0
  253. package/lib/WAUSync/index.d.ts +3 -0
  254. package/lib/WAUSync/index.js +3 -0
  255. package/lib/assets/wasm/loader.js +5 -0
  256. package/lib/assets/wasm/whatsapp.wasm +0 -0
  257. package/lib/assets/wasm/worker-modules.js +273 -0
  258. package/lib/index.d.ts +21 -0
  259. package/lib/index.js +22 -0
  260. package/package.json +111 -0
@@ -0,0 +1,590 @@
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 BibzWhats 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
+ // BibzWhats (upstream #2191): bersihkan timer, cache & listener saat socket ditutup
175
+ if (bufferTimeout) {
176
+ clearTimeout(bufferTimeout);
177
+ bufferTimeout = null;
178
+ }
179
+ if (flushPendingTimeout) {
180
+ clearTimeout(flushPendingTimeout);
181
+ flushPendingTimeout = null;
182
+ }
183
+ historyCache.clear();
184
+ data = makeBufferData();
185
+ isBuffering = false;
186
+ bufferCount = 0;
187
+ ev.removeAllListeners();
188
+ logger.debug('Event buffer destroyed');
189
+ }
190
+ };
191
+ };
192
+ const makeBufferData = () => {
193
+ return {
194
+ historySets: {
195
+ chats: {},
196
+ messages: {},
197
+ contacts: {},
198
+ isLatest: false,
199
+ empty: true
200
+ },
201
+ chatUpserts: {},
202
+ chatUpdates: {},
203
+ chatDeletes: new Set(),
204
+ contactUpserts: {},
205
+ contactUpdates: {},
206
+ messageUpserts: {},
207
+ messageUpdates: {},
208
+ messageReactions: {},
209
+ messageDeletes: {},
210
+ messageReceipts: {},
211
+ groupUpdates: {}
212
+ };
213
+ };
214
+ function append(data, historyCache, event,
215
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
216
+ eventData, logger) {
217
+ switch (event) {
218
+ case 'messaging-history.set':
219
+ for (const chat of eventData.chats) {
220
+ const id = chat.id || '';
221
+ const existingChat = data.historySets.chats[id];
222
+ if (existingChat) {
223
+ existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType;
224
+ }
225
+ if (!existingChat && !historyCache.has(id)) {
226
+ data.historySets.chats[id] = chat;
227
+ historyCache.add(id);
228
+ absorbingChatUpdate(chat);
229
+ }
230
+ }
231
+ for (const contact of eventData.contacts) {
232
+ const existingContact = data.historySets.contacts[contact.id];
233
+ if (existingContact) {
234
+ Object.assign(existingContact, trimUndefined(contact));
235
+ }
236
+ else {
237
+ const historyContactId = `c:${contact.id}`;
238
+ const hasAnyName = contact.notify || contact.name || contact.verifiedName;
239
+ if (!historyCache.has(historyContactId) || hasAnyName) {
240
+ data.historySets.contacts[contact.id] = contact;
241
+ historyCache.add(historyContactId);
242
+ }
243
+ }
244
+ }
245
+ for (const message of eventData.messages) {
246
+ const key = stringifyMessageKey(message.key);
247
+ const existingMsg = data.historySets.messages[key];
248
+ if (!existingMsg && !historyCache.has(key)) {
249
+ data.historySets.messages[key] = message;
250
+ historyCache.add(key);
251
+ }
252
+ }
253
+ data.historySets.empty = false;
254
+ data.historySets.syncType = eventData.syncType;
255
+ data.historySets.progress = eventData.progress;
256
+ data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId;
257
+ data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest;
258
+ break;
259
+ case 'chats.upsert':
260
+ for (const chat of eventData) {
261
+ const id = chat.id || '';
262
+ let upsert = data.chatUpserts[id];
263
+ if (id && !upsert) {
264
+ upsert = data.historySets.chats[id];
265
+ if (upsert) {
266
+ logger.debug({ chatId: id }, 'absorbed chat upsert in chat set');
267
+ }
268
+ }
269
+ if (upsert) {
270
+ upsert = concatChats(upsert, chat);
271
+ }
272
+ else {
273
+ upsert = chat;
274
+ data.chatUpserts[id] = upsert;
275
+ }
276
+ absorbingChatUpdate(upsert);
277
+ if (data.chatDeletes.has(id)) {
278
+ data.chatDeletes.delete(id);
279
+ }
280
+ }
281
+ break;
282
+ case 'chats.update':
283
+ for (const update of eventData) {
284
+ const chatId = update.id;
285
+ const conditionMatches = update.conditional ? update.conditional(data) : true;
286
+ if (conditionMatches) {
287
+ delete update.conditional;
288
+ // if there is an existing upsert, merge the update into it
289
+ const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId];
290
+ if (upsert) {
291
+ concatChats(upsert, update);
292
+ }
293
+ else {
294
+ // merge the update into the existing update
295
+ const chatUpdate = data.chatUpdates[chatId] || {};
296
+ data.chatUpdates[chatId] = concatChats(chatUpdate, update);
297
+ }
298
+ }
299
+ else if (conditionMatches === undefined) {
300
+ // condition yet to be fulfilled
301
+ data.chatUpdates[chatId] = update;
302
+ }
303
+ // otherwise -- condition not met, update is invalid
304
+ // if the chat has been updated
305
+ // ignore any existing chat delete
306
+ if (data.chatDeletes.has(chatId)) {
307
+ data.chatDeletes.delete(chatId);
308
+ }
309
+ }
310
+ break;
311
+ case 'chats.delete':
312
+ for (const chatId of eventData) {
313
+ if (!data.chatDeletes.has(chatId)) {
314
+ data.chatDeletes.add(chatId);
315
+ }
316
+ // remove any prior updates & upserts
317
+ if (data.chatUpdates[chatId]) {
318
+ delete data.chatUpdates[chatId];
319
+ }
320
+ if (data.chatUpserts[chatId]) {
321
+ delete data.chatUpserts[chatId];
322
+ }
323
+ if (data.historySets.chats[chatId]) {
324
+ delete data.historySets.chats[chatId];
325
+ }
326
+ }
327
+ break;
328
+ case 'contacts.upsert':
329
+ for (const contact of eventData) {
330
+ let upsert = data.contactUpserts[contact.id];
331
+ if (!upsert) {
332
+ upsert = data.historySets.contacts[contact.id];
333
+ if (upsert) {
334
+ logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set');
335
+ }
336
+ }
337
+ if (upsert) {
338
+ upsert = Object.assign(upsert, trimUndefined(contact));
339
+ }
340
+ else {
341
+ upsert = contact;
342
+ data.contactUpserts[contact.id] = upsert;
343
+ }
344
+ if (data.contactUpdates[contact.id]) {
345
+ upsert = Object.assign(data.contactUpdates[contact.id], trimUndefined(contact));
346
+ delete data.contactUpdates[contact.id];
347
+ }
348
+ }
349
+ break;
350
+ case 'contacts.update':
351
+ const contactUpdates = eventData;
352
+ for (const update of contactUpdates) {
353
+ const id = update.id;
354
+ // merge into prior upsert
355
+ const upsert = data.historySets.contacts[id] || data.contactUpserts[id];
356
+ if (upsert) {
357
+ Object.assign(upsert, update);
358
+ }
359
+ else {
360
+ // merge into prior update
361
+ const contactUpdate = data.contactUpdates[id] || {};
362
+ data.contactUpdates[id] = Object.assign(contactUpdate, update);
363
+ }
364
+ }
365
+ break;
366
+ case 'messages.upsert':
367
+ const { messages, type } = eventData;
368
+ for (const message of messages) {
369
+ const key = stringifyMessageKey(message.key);
370
+ let existing = data.messageUpserts[key]?.message;
371
+ if (!existing) {
372
+ existing = data.historySets.messages[key];
373
+ if (existing) {
374
+ logger.debug({ messageId: key }, 'absorbed message upsert in message set');
375
+ }
376
+ }
377
+ if (existing) {
378
+ message.messageTimestamp = existing.messageTimestamp;
379
+ }
380
+ if (data.messageUpdates[key]) {
381
+ logger.debug('absorbed prior message update in message upsert');
382
+ Object.assign(message, data.messageUpdates[key].update);
383
+ delete data.messageUpdates[key];
384
+ }
385
+ if (data.historySets.messages[key]) {
386
+ data.historySets.messages[key] = message;
387
+ }
388
+ else {
389
+ data.messageUpserts[key] = {
390
+ message,
391
+ type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type
392
+ };
393
+ }
394
+ }
395
+ break;
396
+ case 'messages.update':
397
+ const msgUpdates = eventData;
398
+ for (const { key, update } of msgUpdates) {
399
+ const keyStr = stringifyMessageKey(key);
400
+ const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message;
401
+ if (existing) {
402
+ Object.assign(existing, update);
403
+ // if the message was received & read by us
404
+ // the chat counter must have been incremented
405
+ // so we need to decrement it
406
+ if (update.status === WAMessageStatus.READ && !key.fromMe) {
407
+ decrementChatReadCounterIfMsgDidUnread(existing);
408
+ }
409
+ }
410
+ else {
411
+ const msgUpdate = data.messageUpdates[keyStr] || { key, update: {} };
412
+ Object.assign(msgUpdate.update, update);
413
+ data.messageUpdates[keyStr] = msgUpdate;
414
+ }
415
+ }
416
+ break;
417
+ case 'messages.delete':
418
+ const deleteData = eventData;
419
+ if ('keys' in deleteData) {
420
+ const { keys } = deleteData;
421
+ for (const key of keys) {
422
+ const keyStr = stringifyMessageKey(key);
423
+ if (!data.messageDeletes[keyStr]) {
424
+ data.messageDeletes[keyStr] = key;
425
+ }
426
+ if (data.messageUpserts[keyStr]) {
427
+ delete data.messageUpserts[keyStr];
428
+ }
429
+ if (data.messageUpdates[keyStr]) {
430
+ delete data.messageUpdates[keyStr];
431
+ }
432
+ }
433
+ }
434
+ else {
435
+ // TODO: add support
436
+ }
437
+ break;
438
+ case 'messages.reaction':
439
+ const reactions = eventData;
440
+ for (const { key, reaction } of reactions) {
441
+ const keyStr = stringifyMessageKey(key);
442
+ const existing = data.messageUpserts[keyStr];
443
+ if (existing) {
444
+ updateMessageWithReaction(existing.message, reaction);
445
+ }
446
+ else {
447
+ data.messageReactions[keyStr] = data.messageReactions[keyStr] || { key, reactions: [] };
448
+ updateMessageWithReaction(data.messageReactions[keyStr], reaction);
449
+ }
450
+ }
451
+ break;
452
+ case 'message-receipt.update':
453
+ const receipts = eventData;
454
+ for (const { key, receipt } of receipts) {
455
+ const keyStr = stringifyMessageKey(key);
456
+ const existing = data.messageUpserts[keyStr];
457
+ if (existing) {
458
+ updateMessageWithReceipt(existing.message, receipt);
459
+ }
460
+ else {
461
+ data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || { key, userReceipt: [] };
462
+ updateMessageWithReceipt(data.messageReceipts[keyStr], receipt);
463
+ }
464
+ }
465
+ break;
466
+ case 'groups.update':
467
+ const groupUpdates = eventData;
468
+ for (const update of groupUpdates) {
469
+ const id = update.id;
470
+ const groupUpdate = data.groupUpdates[id] || {};
471
+ if (!data.groupUpdates[id]) {
472
+ data.groupUpdates[id] = Object.assign(groupUpdate, update);
473
+ }
474
+ }
475
+ break;
476
+ default:
477
+ throw new Error(`"${event}" cannot be buffered`);
478
+ }
479
+ function absorbingChatUpdate(existing) {
480
+ const chatId = existing.id || '';
481
+ const update = data.chatUpdates[chatId];
482
+ if (update) {
483
+ const conditionMatches = update.conditional ? update.conditional(data) : true;
484
+ if (conditionMatches) {
485
+ delete update.conditional;
486
+ logger.debug({ chatId }, 'absorbed chat update in existing chat');
487
+ Object.assign(existing, concatChats(update, existing));
488
+ delete data.chatUpdates[chatId];
489
+ }
490
+ else if (conditionMatches === false) {
491
+ logger.debug({ chatId }, 'chat update condition fail, removing');
492
+ delete data.chatUpdates[chatId];
493
+ }
494
+ }
495
+ }
496
+ function decrementChatReadCounterIfMsgDidUnread(message) {
497
+ // decrement chat unread counter
498
+ // if the message has already been marked read by us
499
+ const chatId = message.key.remoteJid;
500
+ const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId];
501
+ if (isRealMessage(message) &&
502
+ shouldIncrementChatUnread(message) &&
503
+ typeof chat?.unreadCount === 'number' &&
504
+ chat.unreadCount > 0) {
505
+ logger.debug({ chatId: chat.id }, 'decrementing chat counter');
506
+ chat.unreadCount -= 1;
507
+ if (chat.unreadCount === 0) {
508
+ delete chat.unreadCount;
509
+ }
510
+ }
511
+ }
512
+ }
513
+ function consolidateEvents(data) {
514
+ const map = {};
515
+ if (!data.historySets.empty) {
516
+ map['messaging-history.set'] = {
517
+ chats: Object.values(data.historySets.chats),
518
+ messages: Object.values(data.historySets.messages),
519
+ contacts: Object.values(data.historySets.contacts),
520
+ syncType: data.historySets.syncType,
521
+ progress: data.historySets.progress,
522
+ isLatest: data.historySets.isLatest,
523
+ peerDataRequestSessionId: data.historySets.peerDataRequestSessionId
524
+ };
525
+ }
526
+ const chatUpsertList = Object.values(data.chatUpserts);
527
+ if (chatUpsertList.length) {
528
+ map['chats.upsert'] = chatUpsertList;
529
+ }
530
+ const chatUpdateList = Object.values(data.chatUpdates);
531
+ if (chatUpdateList.length) {
532
+ map['chats.update'] = chatUpdateList;
533
+ }
534
+ const chatDeleteList = Array.from(data.chatDeletes);
535
+ if (chatDeleteList.length) {
536
+ map['chats.delete'] = chatDeleteList;
537
+ }
538
+ const messageUpsertList = Object.values(data.messageUpserts);
539
+ if (messageUpsertList.length) {
540
+ const type = messageUpsertList[0].type;
541
+ map['messages.upsert'] = {
542
+ messages: messageUpsertList.map(m => m.message),
543
+ type
544
+ };
545
+ }
546
+ const messageUpdateList = Object.values(data.messageUpdates);
547
+ if (messageUpdateList.length) {
548
+ map['messages.update'] = messageUpdateList;
549
+ }
550
+ const messageDeleteList = Object.values(data.messageDeletes);
551
+ if (messageDeleteList.length) {
552
+ map['messages.delete'] = { keys: messageDeleteList };
553
+ }
554
+ const messageReactionList = Object.values(data.messageReactions).flatMap(({ key, reactions }) => reactions.flatMap(reaction => ({ key, reaction })));
555
+ if (messageReactionList.length) {
556
+ map['messages.reaction'] = messageReactionList;
557
+ }
558
+ const messageReceiptList = Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) => userReceipt.flatMap(receipt => ({ key, receipt })));
559
+ if (messageReceiptList.length) {
560
+ map['message-receipt.update'] = messageReceiptList;
561
+ }
562
+ const contactUpsertList = Object.values(data.contactUpserts);
563
+ if (contactUpsertList.length) {
564
+ map['contacts.upsert'] = contactUpsertList;
565
+ }
566
+ const contactUpdateList = Object.values(data.contactUpdates);
567
+ if (contactUpdateList.length) {
568
+ map['contacts.update'] = contactUpdateList;
569
+ }
570
+ const groupUpdateList = Object.values(data.groupUpdates);
571
+ if (groupUpdateList.length) {
572
+ map['groups.update'] = groupUpdateList;
573
+ }
574
+ return map;
575
+ }
576
+ function concatChats(a, b) {
577
+ if (b.unreadCount === null && // neutralize unread counter
578
+ a.unreadCount < 0) {
579
+ a.unreadCount = undefined;
580
+ b.unreadCount = undefined;
581
+ }
582
+ if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
583
+ b = { ...b };
584
+ if (b.unreadCount >= 0) {
585
+ b.unreadCount = Math.max(b.unreadCount, 0) + Math.max(a.unreadCount, 0);
586
+ }
587
+ }
588
+ return Object.assign(a, b);
589
+ }
590
+ const stringifyMessageKey = (key) => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`;
@@ -0,0 +1,90 @@
1
+ import { proto } from '../../WAProto/index.js';
2
+ import type { BaileysEventEmitter, BaileysEventMap, ConnectionState, WACallUpdateType, WAMessageKey, WAVersion } from '../Types/index.js';
3
+ import { type BinaryNode } from '../WABinary/index.js';
4
+ export declare const BufferJSON: {
5
+ replacer: (k: any, value: any) => any;
6
+ reviver: (_: any, value: any) => any;
7
+ };
8
+ export declare const getKeyAuthor: (key: WAMessageKey | undefined | null, meId?: string) => string;
9
+ export declare const isStringNullOrEmpty: (value: string | null | undefined) => value is null | undefined | "";
10
+ export declare const writeRandomPadMax16: (msg: Uint8Array) => Buffer;
11
+ export declare const unpadRandomMax16: (e: Uint8Array | Buffer) => Uint8Array<ArrayBuffer>;
12
+ export declare const generateParticipantHashV2: (participants: string[]) => string;
13
+ export declare const encodeWAMessage: (message: proto.IMessage) => Buffer;
14
+ export declare const generateRegistrationId: () => number;
15
+ export declare const encodeBigEndian: (e: number, t?: number) => Uint8Array<ArrayBuffer>;
16
+ export declare const toNumber: (t: Long | number | null | undefined) => number;
17
+ /** unix timestamp of a date in seconds */
18
+ export declare const unixTimestampSeconds: (date?: Date) => number;
19
+ export type DebouncedTimeout = ReturnType<typeof debouncedTimeout>;
20
+ export declare const debouncedTimeout: (intervalMs?: number, task?: () => void) => {
21
+ start: (newIntervalMs?: number, newTask?: () => void) => void;
22
+ cancel: () => void;
23
+ setTask: (newTask: () => void) => () => void;
24
+ setInterval: (newInterval: number) => number;
25
+ };
26
+ export declare const delay: (ms: number) => Promise<void>;
27
+ export declare const delayCancellable: (ms: number) => {
28
+ delay: Promise<void>;
29
+ cancel: () => void;
30
+ };
31
+ export declare function promiseTimeout<T>(ms: number | undefined, promise: (resolve: (v: T) => void, reject: (error: any) => void) => void): Promise<T>;
32
+ export declare const generateMessageIDV2: (userId?: string) => string;
33
+ export declare const generateMessageID: () => string;
34
+ export declare function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T): (check: (u: BaileysEventMap[T]) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
35
+ export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
36
+ /**
37
+ * utility that fetches latest baileys version from the master branch.
38
+ * Use to ensure your WA connection is always on the latest version
39
+ */
40
+ export declare const fetchLatestBaileysVersion: (options?: RequestInit) => Promise<{
41
+ version: WAVersion;
42
+ isLatest: boolean;
43
+ error?: undefined;
44
+ } | {
45
+ version: WAVersion;
46
+ isLatest: boolean;
47
+ error: unknown;
48
+ }>;
49
+ /**
50
+ * A utility that fetches the latest web version of whatsapp.
51
+ * Use to ensure your WA connection is always on the latest version
52
+ */
53
+ export declare const fetchLatestWaWebVersion: (options?: RequestInit) => Promise<{
54
+ version: WAVersion;
55
+ isLatest: boolean;
56
+ error?: undefined;
57
+ } | {
58
+ version: WAVersion;
59
+ isLatest: boolean;
60
+ error: unknown;
61
+ }>;
62
+ /** unique message tag prefix for MD clients */
63
+ export declare const generateMdTagPrefix: () => string;
64
+ /**
65
+ * Given a type of receipt, returns what the new status of the message should be
66
+ * @param type type from receipt
67
+ */
68
+ export declare const getStatusFromReceiptType: (type: string | undefined) => proto.WebMessageInfo.Status | undefined;
69
+ /**
70
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
71
+ * @param reason the string reason given, eg. "conflict"
72
+ */
73
+ export declare const getErrorCodeFromStreamError: (node: BinaryNode) => {
74
+ reason: string;
75
+ statusCode: number;
76
+ };
77
+ export declare const getCallStatusFromNode: ({ tag, attrs }: BinaryNode) => WACallUpdateType;
78
+ export declare const getCodeFromWSError: (error: Error) => number;
79
+ /**
80
+ * Is the given platform WA business
81
+ * @param platform AuthenticationCreds.platform
82
+ */
83
+ export declare const isWABusinessPlatform: (platform: string) => platform is "smba" | "smbi";
84
+ export declare function trimUndefined(obj: {
85
+ [_: string]: any;
86
+ }): {
87
+ [_: string]: any;
88
+ };
89
+ export declare function bytesToCrockford(buffer: Buffer): string;
90
+ export declare function encodeNewsletterMessage(message: proto.IMessage): Uint8Array;