@hiroosy/baileys-lite 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +25 -0
  2. package/WAProto/index.d.ts +15932 -0
  3. package/WAProto/index.js +115856 -0
  4. package/engine-requirements.js +11 -0
  5. package/package.json +27 -0
  6. package/src/binary/wa-binary-constants.js +1300 -0
  7. package/src/binary/wa-binary.js +649 -0
  8. package/src/constants.js +143 -0
  9. package/src/defaults.js +102 -0
  10. package/src/foundation/audio-duration.js +530 -0
  11. package/src/foundation/audio-samples.js +268 -0
  12. package/src/foundation/boom.js +46 -0
  13. package/src/foundation/cache.js +142 -0
  14. package/src/foundation/concurrency.js +87 -0
  15. package/src/foundation/curve25519.js +221 -0
  16. package/src/foundation/link-preview.js +320 -0
  17. package/src/foundation/logger.js +69 -0
  18. package/src/foundation/long.js +140 -0
  19. package/src/foundation/protobuf-minimal.js +619 -0
  20. package/src/foundation/wa-crypto.js +76 -0
  21. package/src/foundation/zip.js +124 -0
  22. package/src/index.js +48 -0
  23. package/src/signal/libsignal.js +1051 -0
  24. package/src/signal/signal-group.js +487 -0
  25. package/src/signal/signal-repository.js +646 -0
  26. package/src/socket/business-communities.js +830 -0
  27. package/src/socket/chats.js +674 -0
  28. package/src/socket/groups-newsletter.js +342 -0
  29. package/src/socket/messages-recv.js +1835 -0
  30. package/src/socket/messages-send.js +1202 -0
  31. package/src/socket/socket-core.js +833 -0
  32. package/src/socket/usync.js +291 -0
  33. package/src/socket-client/websocket-client.js +124 -0
  34. package/src/utils/auth-state-core.js +764 -0
  35. package/src/utils/auth-state-storage.js +316 -0
  36. package/src/utils/chat-sync.js +1045 -0
  37. package/src/utils/media.js +841 -0
  38. package/src/utils/message-compose.js +1609 -0
  39. package/src/utils/message-processing.js +958 -0
  40. package/src/utils/wa-protocol-core.js +1283 -0
  41. package/src/vendor/jpeg-js/LICENSE +25 -0
  42. package/src/vendor/jpeg-js/decoder.js +1152 -0
  43. package/src/vendor/jpeg-js/encoder.js +824 -0
  44. package/src/vendor/pngjs/LICENSE +20 -0
  45. package/src/vendor/pngjs/bitmapper.js +273 -0
  46. package/src/vendor/pngjs/bitpacker.js +167 -0
  47. package/src/vendor/pngjs/constants.js +38 -0
  48. package/src/vendor/pngjs/crc.js +47 -0
  49. package/src/vendor/pngjs/filter-pack.js +179 -0
  50. package/src/vendor/pngjs/filter-parse-sync.js +27 -0
  51. package/src/vendor/pngjs/filter-parse.js +185 -0
  52. package/src/vendor/pngjs/format-normaliser.js +101 -0
  53. package/src/vendor/pngjs/interlace.js +101 -0
  54. package/src/vendor/pngjs/packer-sync.js +65 -0
  55. package/src/vendor/pngjs/packer.js +138 -0
  56. package/src/vendor/pngjs/paeth-predictor.js +22 -0
  57. package/src/vendor/pngjs/parser-sync.js +121 -0
  58. package/src/vendor/pngjs/parser.js +299 -0
  59. package/src/vendor/pngjs/png-sync.js +19 -0
  60. package/src/vendor/pngjs/sync-inflate.js +174 -0
  61. package/src/vendor/pngjs/sync-reader.js +54 -0
  62. package/src/wam/wam-constants.js +22853 -0
  63. package/src/wam/wam.js +151 -0
@@ -0,0 +1,1045 @@
1
+ /**
2
+ * Chat/app-state sync utilities. Combines what used to be chat-utils.js,
3
+ * event-buffer.js, and sync-action-utils.js.
4
+ *
5
+ * expandAppStateKeys comes from ../foundation/wa-crypto.js (native).
6
+ */
7
+ import { EventEmitter } from 'node:events'
8
+ import { proto } from '../../WAProto/index.js'
9
+ import { expandAppStateKeys } from '../foundation/wa-crypto.js'
10
+ import { Boom } from '../foundation/boom.js'
11
+ import { LabelAssociationType, WAMessageStatus } from '../constants.js'
12
+ import { getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, isLidUser, isPnUser, jidNormalizedUser } from '../binary/wa-binary.js'
13
+ import { aesDecrypt, aesEncrypt, hmacSign, toNumber, trimUndefined, LT_HASH_ANTI_TAMPERING } from './wa-protocol-core.js'
14
+ import { downloadContentFromMessage } from './media.js'
15
+ import { updateMessageWithReaction, updateMessageWithReceipt } from './message-compose.js'
16
+ import { isRealMessage, shouldIncrementChatUnread } from './message-processing.js'
17
+
18
+ /* ------------------------------------------------------------------ */
19
+ /* App-state (chat-utils): LTHash / patch encode-decode */
20
+ /* ------------------------------------------------------------------ */
21
+
22
+ const mutationKeys = keydata => {
23
+ const keys = expandAppStateKeys(keydata)
24
+ return { indexKey: keys.indexKey, valueEncryptionKey: keys.valueEncryptionKey, valueMacKey: keys.valueMacKey, snapshotMacKey: keys.snapshotMacKey, patchMacKey: keys.patchMacKey }
25
+ }
26
+
27
+ const generateMac = (operation, data, keyId, key) => {
28
+ const opByte = operation === proto.SyncdMutation.SyncdOperation.SET ? 0x01 : 0x02
29
+ const keyIdBuffer = typeof keyId === 'string' ? Buffer.from(keyId, 'base64') : keyId
30
+ const keyData = new Uint8Array(1 + keyIdBuffer.length)
31
+ keyData[0] = opByte
32
+ keyData.set(keyIdBuffer, 1)
33
+ const last = new Uint8Array(8)
34
+ last[7] = keyData.length
35
+ const total = new Uint8Array(keyData.length + data.length + last.length)
36
+ total.set(keyData, 0)
37
+ total.set(data, keyData.length)
38
+ total.set(last, keyData.length + data.length)
39
+ const hmac = hmacSign(total, key, 'sha512')
40
+ return hmac.subarray(0, 32)
41
+ }
42
+
43
+ const to64BitNetworkOrder = e => {
44
+ const buff = Buffer.alloc(8)
45
+ buff.writeUint32BE(e, 4)
46
+ return buff
47
+ }
48
+
49
+ export const makeLtHashGenerator = ({ indexValueMap, hash }) => {
50
+ indexValueMap = { ...indexValueMap }
51
+ const addBuffs = []
52
+ const subBuffs = []
53
+ return {
54
+ mix: ({ indexMac, valueMac, operation }) => {
55
+ const indexMacBase64 = Buffer.from(indexMac).toString('base64')
56
+ const prevOp = indexValueMap[indexMacBase64]
57
+ if (operation === proto.SyncdMutation.SyncdOperation.REMOVE) {
58
+ if (!prevOp) return // WA Web logs+skips; handled downstream by MAC validation / snapshot recovery
59
+ delete indexValueMap[indexMacBase64]
60
+ } else {
61
+ addBuffs.push(valueMac)
62
+ indexValueMap[indexMacBase64] = { valueMac }
63
+ }
64
+ if (prevOp) subBuffs.push(prevOp.valueMac)
65
+ },
66
+ finish: () => {
67
+ const result = LT_HASH_ANTI_TAMPERING.subtractThenAdd(hash, subBuffs, addBuffs)
68
+ return { hash: Buffer.from(result), indexValueMap }
69
+ }
70
+ }
71
+ }
72
+
73
+ const generateSnapshotMac = (lthash, version, name, key) => hmacSign(Buffer.concat([lthash, to64BitNetworkOrder(version), Buffer.from(name, 'utf-8')]), key, 'sha256')
74
+ const generatePatchMac = (snapshotMac, valueMacs, version, type, key) => hmacSign(Buffer.concat([snapshotMac, ...valueMacs, to64BitNetworkOrder(version), Buffer.from(type, 'utf-8')]), key)
75
+
76
+ export const newLTHashState = () => ({ version: 0, hash: Buffer.alloc(128), indexValueMap: {} })
77
+ export const ensureLTHashStateVersion = state => {
78
+ if (typeof state.version !== 'number' || isNaN(state.version)) state.version = 0
79
+ return state
80
+ }
81
+
82
+ export const MAX_SYNC_ATTEMPTS = 2
83
+
84
+ /** WA Web treats missing app-state sync keys as "Blocked" (waits for key arrival), not fatal. */
85
+ export const isMissingKeyError = error => error?.data?.isMissingKey === true
86
+
87
+ /** TypeError indicates a WASM crash; otherwise give up after MAX_SYNC_ATTEMPTS. Missing keys handled separately. */
88
+ export const isAppStateSyncIrrecoverable = (error, attempts) => attempts >= MAX_SYNC_ATTEMPTS || error?.name === 'TypeError'
89
+
90
+ export const encodeSyncdPatch = async ({ type, index, syncAction, apiVersion, operation }, myAppStateKeyId, state, getAppStateSyncKey) => {
91
+ const key = myAppStateKeyId ? await getAppStateSyncKey(myAppStateKeyId) : undefined
92
+ if (!key) throw new Boom(`myAppStateKey ("${myAppStateKeyId}") not present`, { data: { isMissingKey: true } })
93
+ const encKeyId = Buffer.from(myAppStateKeyId, 'base64')
94
+ state = { ...state, indexValueMap: { ...state.indexValueMap } }
95
+ const indexBuffer = Buffer.from(JSON.stringify(index))
96
+ const dataProto = proto.SyncActionData.fromObject({ index: indexBuffer, value: syncAction, padding: new Uint8Array(0), version: apiVersion })
97
+ const encoded = proto.SyncActionData.encode(dataProto).finish()
98
+ const keyValue = mutationKeys(key.keyData)
99
+ const encValue = aesEncrypt(encoded, keyValue.valueEncryptionKey)
100
+ const valueMac = generateMac(operation, encValue, encKeyId, keyValue.valueMacKey)
101
+ const indexMac = hmacSign(indexBuffer, keyValue.indexKey)
102
+ const generator = makeLtHashGenerator(state)
103
+ generator.mix({ indexMac, valueMac, operation })
104
+ Object.assign(state, generator.finish())
105
+ state.version += 1
106
+ const snapshotMac = generateSnapshotMac(state.hash, state.version, type, keyValue.snapshotMacKey)
107
+ const patch = {
108
+ patchMac: generatePatchMac(snapshotMac, [valueMac], state.version, type, keyValue.patchMacKey),
109
+ snapshotMac,
110
+ keyId: { id: encKeyId },
111
+ mutations: [{ operation, record: { index: { blob: indexMac }, value: { blob: Buffer.concat([encValue, valueMac]) }, keyId: { id: encKeyId } } }]
112
+ }
113
+ state.indexValueMap[indexMac.toString('base64')] = { valueMac }
114
+ return { patch, state }
115
+ }
116
+
117
+ export const decodeSyncdMutations = async (msgMutations, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
118
+ const ltGenerator = makeLtHashGenerator(initialState)
119
+ const derivedKeyCache = new Map()
120
+
121
+ async function getKey(keyId) {
122
+ const base64Key = Buffer.from(keyId).toString('base64')
123
+ const cached = derivedKeyCache.get(base64Key)
124
+ if (cached) return cached
125
+ const keyEnc = await getAppStateSyncKey(base64Key)
126
+ if (!keyEnc) throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true, msgMutations } })
127
+ const keys = mutationKeys(keyEnc.keyData)
128
+ derivedKeyCache.set(base64Key, keys)
129
+ return keys
130
+ }
131
+
132
+ for (const msgMutation of msgMutations) {
133
+ const operation = 'operation' in msgMutation ? msgMutation.operation : proto.SyncdMutation.SyncdOperation.SET
134
+ const record = 'record' in msgMutation && msgMutation.record ? msgMutation.record : msgMutation
135
+ let key
136
+ try {
137
+ key = await getKey(record.keyId.id)
138
+ } catch (err) {
139
+ if (isMissingKeyError(err)) throw err
140
+ continue // other errors -> individual record corruption, skip and keep going
141
+ }
142
+ const content = record.value.blob
143
+ const encContent = content.subarray(0, -32)
144
+ const ogValueMac = content.subarray(-32)
145
+ if (validateMacs) {
146
+ const contentHmac = generateMac(operation, encContent, record.keyId.id, key.valueMacKey)
147
+ if (Buffer.compare(contentHmac, ogValueMac) !== 0) continue
148
+ }
149
+ let result
150
+ try {
151
+ result = aesDecrypt(encContent, key.valueEncryptionKey)
152
+ } catch {
153
+ continue
154
+ }
155
+ const syncAction = proto.SyncActionData.decode(result)
156
+ if (validateMacs) {
157
+ const hmac = hmacSign(syncAction.index, key.indexKey)
158
+ if (Buffer.compare(hmac, record.index.blob) !== 0) throw new Boom('HMAC index verification failed')
159
+ }
160
+ const indexStr = Buffer.from(syncAction.index).toString()
161
+ onMutation({ syncAction, index: JSON.parse(indexStr) })
162
+ ltGenerator.mix({ indexMac: record.index.blob, valueMac: ogValueMac, operation })
163
+ }
164
+ return ltGenerator.finish()
165
+ }
166
+
167
+ export const decodeSyncdPatch = async (msg, name, initialState, getAppStateSyncKey, onMutation, validateMacs) => {
168
+ if (validateMacs) {
169
+ const base64Key = Buffer.from(msg.keyId.id).toString('base64')
170
+ const mainKeyObj = await getAppStateSyncKey(base64Key)
171
+ if (!mainKeyObj) throw new Boom(`failed to find key "${base64Key}" to decode patch`, { data: { isMissingKey: true, msg } })
172
+ const mainKey = mutationKeys(mainKeyObj.keyData)
173
+ const mutationmacs = msg.mutations.map(mutation => mutation.record.value.blob.slice(-32))
174
+ const patchMac = generatePatchMac(msg.snapshotMac, mutationmacs, toNumber(msg.version.version), name, mainKey.patchMacKey)
175
+ if (Buffer.compare(patchMac, msg.patchMac) !== 0) throw new Boom('Invalid patch mac')
176
+ }
177
+ return decodeSyncdMutations(msg.mutations, initialState, getAppStateSyncKey, onMutation, validateMacs)
178
+ }
179
+
180
+ export const extractSyncdPatches = async (result, options) => {
181
+ const syncNode = getBinaryNodeChild(result, 'sync')
182
+ const collectionNodes = getBinaryNodeChildren(syncNode, 'collection')
183
+ const final = {}
184
+ await Promise.all(
185
+ collectionNodes.map(async collectionNode => {
186
+ const patchesNode = getBinaryNodeChild(collectionNode, 'patches')
187
+ const patches = getBinaryNodeChildren(patchesNode || collectionNode, 'patch')
188
+ const snapshotNode = getBinaryNodeChild(collectionNode, 'snapshot')
189
+ const syncds = []
190
+ const name = collectionNode.attrs.name
191
+ const hasMorePatches = collectionNode.attrs.has_more_patches === 'true'
192
+ let snapshot
193
+ if (snapshotNode?.content) {
194
+ if (!Buffer.isBuffer(snapshotNode)) snapshotNode.content = Buffer.from(Object.values(snapshotNode.content))
195
+ const blobRef = proto.ExternalBlobReference.decode(snapshotNode.content)
196
+ const data = await downloadExternalBlob(blobRef, options)
197
+ snapshot = proto.SyncdSnapshot.decode(data)
198
+ }
199
+ for (let { content } of patches) {
200
+ if (content) {
201
+ if (!Buffer.isBuffer(content)) content = Buffer.from(Object.values(content))
202
+ const syncd = proto.SyncdPatch.decode(content)
203
+ if (!syncd.version) syncd.version = { version: +collectionNode.attrs.version + 1 }
204
+ syncds.push(syncd)
205
+ }
206
+ }
207
+ final[name] = { patches: syncds, hasMorePatches, snapshot }
208
+ })
209
+ )
210
+ return final
211
+ }
212
+
213
+ export const downloadExternalBlob = async (blob, options) => {
214
+ const stream = await downloadContentFromMessage(blob, 'md-app-state', { options })
215
+ const bufferArray = []
216
+ for await (const chunk of stream) bufferArray.push(chunk)
217
+ return Buffer.concat(bufferArray)
218
+ }
219
+
220
+ export const downloadExternalPatch = async (blob, options) => {
221
+ const buffer = await downloadExternalBlob(blob, options)
222
+ return proto.SyncdMutations.decode(buffer)
223
+ }
224
+
225
+ export const decodeSyncdSnapshot = async (name, snapshot, getAppStateSyncKey, minimumVersionNumber, validateMacs = true, logger) => {
226
+ const newState = newLTHashState()
227
+ newState.version = toNumber(snapshot.version.version)
228
+ const mutationMap = {}
229
+ const areMutationsRequired = typeof minimumVersionNumber === 'undefined' || newState.version > minimumVersionNumber
230
+ const { hash, indexValueMap } = await decodeSyncdMutations(
231
+ snapshot.records,
232
+ newState,
233
+ getAppStateSyncKey,
234
+ areMutationsRequired
235
+ ? mutation => {
236
+ const index = mutation.syncAction.index?.toString()
237
+ mutationMap[index] = mutation
238
+ }
239
+ : () => {},
240
+ validateMacs
241
+ )
242
+ newState.hash = hash
243
+ newState.indexValueMap = indexValueMap
244
+ if (validateMacs) {
245
+ const base64Key = Buffer.from(snapshot.keyId.id).toString('base64')
246
+ const keyEnc = await getAppStateSyncKey(base64Key)
247
+ if (!keyEnc) throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } })
248
+ const result = mutationKeys(keyEnc.keyData)
249
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey)
250
+ if (Buffer.compare(snapshot.mac, computedSnapshotMac) !== 0) {
251
+ logger?.warn({ name, version: newState.version }, 'LTHash verification failed on snapshot, continuing with partial state')
252
+ }
253
+ }
254
+ return { state: newState, mutationMap }
255
+ }
256
+
257
+ export const decodePatches = async (name, syncds, initial, getAppStateSyncKey, options, minimumVersionNumber, logger, validateMacs = true) => {
258
+ const newState = { ...initial, indexValueMap: { ...initial.indexValueMap } }
259
+ const mutationMap = {}
260
+ for (const syncd of syncds) {
261
+ const { version, keyId, snapshotMac } = syncd
262
+ if (syncd.externalMutations) {
263
+ logger?.trace({ name, version }, 'downloading external patch')
264
+ const ref = await downloadExternalPatch(syncd.externalMutations, options)
265
+ logger?.debug({ name, version, mutations: ref.mutations.length }, 'downloaded external patch')
266
+ syncd.mutations?.push(...ref.mutations)
267
+ }
268
+ const patchVersion = toNumber(version.version)
269
+ newState.version = patchVersion
270
+ const shouldMutate = typeof minimumVersionNumber === 'undefined' || patchVersion > minimumVersionNumber
271
+ let decodeResult
272
+ try {
273
+ decodeResult = await decodeSyncdPatch(
274
+ syncd,
275
+ name,
276
+ newState,
277
+ getAppStateSyncKey,
278
+ shouldMutate
279
+ ? mutation => {
280
+ const index = mutation.syncAction.index?.toString()
281
+ mutationMap[index] = mutation
282
+ }
283
+ : () => {},
284
+ validateMacs
285
+ )
286
+ } catch (err) {
287
+ if (isMissingKeyError(err)) throw err
288
+ logger?.warn({ name, version: patchVersion, error: err.message }, 'failed to decode patch, skipping')
289
+ continue
290
+ }
291
+ newState.hash = decodeResult.hash
292
+ newState.indexValueMap = decodeResult.indexValueMap
293
+ if (validateMacs) {
294
+ const base64Key = Buffer.from(keyId.id).toString('base64')
295
+ const keyEnc = await getAppStateSyncKey(base64Key)
296
+ if (!keyEnc) throw new Boom(`failed to find key "${base64Key}" to decode mutation`, { data: { isMissingKey: true } })
297
+ const result = mutationKeys(keyEnc.keyData)
298
+ const computedSnapshotMac = generateSnapshotMac(newState.hash, newState.version, name, result.snapshotMacKey)
299
+ if (Buffer.compare(snapshotMac, computedSnapshotMac) !== 0) {
300
+ logger?.warn({ name, version: newState.version }, 'LTHash verification failed, skipping remaining patches')
301
+ break
302
+ }
303
+ }
304
+ syncd.mutations = [] // clear memory used up by the mutations
305
+ }
306
+ return { state: newState, mutationMap }
307
+ }
308
+
309
+ export const chatModificationToAppPatch = (mod, jid) => {
310
+ const OP = proto.SyncdMutation.SyncdOperation
311
+ const getMessageRange = lastMessages => {
312
+ if (!Array.isArray(lastMessages)) return lastMessages
313
+ const lastMsg = lastMessages[lastMessages.length - 1]
314
+ return {
315
+ lastMessageTimestamp: lastMsg?.messageTimestamp,
316
+ messages: lastMessages?.length
317
+ ? lastMessages.map(m => {
318
+ if (!m.key?.id || !m.key?.remoteJid) throw new Boom('Incomplete key', { statusCode: 400, data: m })
319
+ if (isJidGroup(m.key.remoteJid) && !m.key.fromMe && !m.key.participant) {
320
+ throw new Boom('Expected not from me message to have participant', { statusCode: 400, data: m })
321
+ }
322
+ if (!m.messageTimestamp || !toNumber(m.messageTimestamp)) throw new Boom('Missing timestamp in last message list', { statusCode: 400, data: m })
323
+ if (m.key.participant) m.key.participant = jidNormalizedUser(m.key.participant)
324
+ return m
325
+ })
326
+ : undefined
327
+ }
328
+ }
329
+ let patch
330
+ if ('mute' in mod) {
331
+ patch = { syncAction: { muteAction: { muted: !!mod.mute, muteEndTimestamp: mod.mute || undefined } }, index: ['mute', jid], type: 'regular_high', apiVersion: 2, operation: OP.SET }
332
+ } else if ('archive' in mod) {
333
+ patch = {
334
+ syncAction: { archiveChatAction: { archived: !!mod.archive, messageRange: getMessageRange(mod.lastMessages) } },
335
+ index: ['archive', jid],
336
+ type: 'regular_low',
337
+ apiVersion: 3,
338
+ operation: OP.SET
339
+ }
340
+ } else if ('markRead' in mod) {
341
+ patch = {
342
+ syncAction: { markChatAsReadAction: { read: mod.markRead, messageRange: getMessageRange(mod.lastMessages) } },
343
+ index: ['markChatAsRead', jid],
344
+ type: 'regular_low',
345
+ apiVersion: 3,
346
+ operation: OP.SET
347
+ }
348
+ } else if ('deleteForMe' in mod) {
349
+ const { timestamp, key, deleteMedia } = mod.deleteForMe
350
+ patch = {
351
+ syncAction: { deleteMessageForMeAction: { deleteMedia, messageTimestamp: timestamp } },
352
+ index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
353
+ type: 'regular_high',
354
+ apiVersion: 3,
355
+ operation: OP.SET
356
+ }
357
+ } else if ('clear' in mod) {
358
+ patch = {
359
+ syncAction: { clearChatAction: { messageRange: getMessageRange(mod.lastMessages) } },
360
+ index: ['clearChat', jid, '1', '0'],
361
+ type: 'regular_high',
362
+ apiVersion: 6,
363
+ operation: OP.SET
364
+ }
365
+ } else if ('pin' in mod) {
366
+ patch = { syncAction: { pinAction: { pinned: !!mod.pin } }, index: ['pin_v1', jid], type: 'regular_low', apiVersion: 5, operation: OP.SET }
367
+ } else if ('contact' in mod) {
368
+ patch = { syncAction: { contactAction: mod.contact || {} }, index: ['contact', jid], type: 'critical_unblock_low', apiVersion: 2, operation: mod.contact ? OP.SET : OP.REMOVE }
369
+ } else if ('disableLinkPreviews' in mod) {
370
+ patch = {
371
+ syncAction: { privacySettingDisableLinkPreviewsAction: mod.disableLinkPreviews || {} },
372
+ index: ['setting_disableLinkPreviews'],
373
+ type: 'regular',
374
+ apiVersion: 8,
375
+ operation: OP.SET
376
+ }
377
+ } else if ('star' in mod) {
378
+ const key = mod.star.messages[0]
379
+ patch = {
380
+ syncAction: { starAction: { starred: !!mod.star.star } },
381
+ index: ['star', jid, key.id, key.fromMe ? '1' : '0', '0'],
382
+ type: 'regular_low',
383
+ apiVersion: 2,
384
+ operation: OP.SET
385
+ }
386
+ } else if ('delete' in mod) {
387
+ patch = { syncAction: { deleteChatAction: { messageRange: getMessageRange(mod.lastMessages) } }, index: ['deleteChat', jid, '1'], type: 'regular_high', apiVersion: 6, operation: OP.SET }
388
+ } else if ('pushNameSetting' in mod) {
389
+ patch = { syncAction: { pushNameSetting: { name: mod.pushNameSetting } }, index: ['setting_pushName'], type: 'critical_block', apiVersion: 1, operation: OP.SET }
390
+ } else if ('quickReply' in mod) {
391
+ patch = {
392
+ syncAction: {
393
+ quickReplyAction: {
394
+ count: 0,
395
+ deleted: mod.quickReply.deleted || false,
396
+ keywords: [],
397
+ message: mod.quickReply.message || '',
398
+ shortcut: mod.quickReply.shortcut || ''
399
+ }
400
+ },
401
+ index: ['quick_reply', mod.quickReply.timestamp || String(Math.floor(Date.now() / 1000))],
402
+ type: 'regular',
403
+ apiVersion: 2,
404
+ operation: OP.SET
405
+ }
406
+ } else if ('addLabel' in mod) {
407
+ patch = {
408
+ syncAction: { labelEditAction: { name: mod.addLabel.name, color: mod.addLabel.color, predefinedId: mod.addLabel.predefinedId, deleted: mod.addLabel.deleted } },
409
+ index: ['label_edit', mod.addLabel.id],
410
+ type: 'regular',
411
+ apiVersion: 3,
412
+ operation: OP.SET
413
+ }
414
+ } else if ('addChatLabel' in mod) {
415
+ patch = {
416
+ syncAction: { labelAssociationAction: { labeled: true } },
417
+ index: [LabelAssociationType.Chat, mod.addChatLabel.labelId, jid],
418
+ type: 'regular',
419
+ apiVersion: 3,
420
+ operation: OP.SET
421
+ }
422
+ } else if ('removeChatLabel' in mod) {
423
+ patch = {
424
+ syncAction: { labelAssociationAction: { labeled: false } },
425
+ index: [LabelAssociationType.Chat, mod.removeChatLabel.labelId, jid],
426
+ type: 'regular',
427
+ apiVersion: 3,
428
+ operation: OP.SET
429
+ }
430
+ } else if ('addMessageLabel' in mod) {
431
+ patch = {
432
+ syncAction: { labelAssociationAction: { labeled: true } },
433
+ index: [LabelAssociationType.Message, mod.addMessageLabel.labelId, jid, mod.addMessageLabel.messageId, '0', '0'],
434
+ type: 'regular',
435
+ apiVersion: 3,
436
+ operation: OP.SET
437
+ }
438
+ } else if ('removeMessageLabel' in mod) {
439
+ patch = {
440
+ syncAction: { labelAssociationAction: { labeled: false } },
441
+ index: [LabelAssociationType.Message, mod.removeMessageLabel.labelId, jid, mod.removeMessageLabel.messageId, '0', '0'],
442
+ type: 'regular',
443
+ apiVersion: 3,
444
+ operation: OP.SET
445
+ }
446
+ } else {
447
+ throw new Boom('not supported')
448
+ }
449
+ patch.syncAction.timestamp = Date.now()
450
+ return patch
451
+ }
452
+
453
+ export const processSyncAction = (syncAction, ev, me, initialSyncOpts, logger) => {
454
+ const isInitialSync = !!initialSyncOpts
455
+ const accountSettings = initialSyncOpts?.accountSettings
456
+ logger?.trace({ syncAction, initialSync: !!initialSyncOpts }, 'processing sync action')
457
+ const {
458
+ syncAction: { value: action },
459
+ index: [type, id, msgId, fromMe]
460
+ } = syncAction
461
+
462
+ const getChatUpdateConditional = (id, msgRange) =>
463
+ isInitialSync
464
+ ? data => {
465
+ const chat = data.historySets.chats[id] || data.chatUpserts[id]
466
+ if (chat) return msgRange ? isValidPatchBasedOnMessageRange(chat, msgRange) : true
467
+ }
468
+ : undefined
469
+ const isValidPatchBasedOnMessageRange = (chat, msgRange) => {
470
+ const lastMsgTimestamp = Number(msgRange?.lastMessageTimestamp || msgRange?.lastSystemMessageTimestamp || 0)
471
+ const chatLastMsgTimestamp = Number(chat?.lastMessageRecvTimestamp || 0)
472
+ return lastMsgTimestamp >= chatLastMsgTimestamp
473
+ }
474
+
475
+ if (action?.muteAction) {
476
+ ev.emit('chats.update', [{ id, muteEndTime: action.muteAction?.muted ? toNumber(action.muteAction.muteEndTimestamp) : null, conditional: getChatUpdateConditional(id, undefined) }])
477
+ } else if (action?.archiveChatAction || type === 'archive' || type === 'unarchive') {
478
+ const archiveAction = action?.archiveChatAction
479
+ const isArchived = archiveAction ? archiveAction.archived : type === 'archive'
480
+ const msgRange = !accountSettings?.unarchiveChats ? undefined : archiveAction?.messageRange
481
+ ev.emit('chats.update', [{ id, archived: isArchived, conditional: getChatUpdateConditional(id, msgRange) }])
482
+ } else if (action?.markChatAsReadAction) {
483
+ const markReadAction = action.markChatAsReadAction
484
+ const isNullUpdate = isInitialSync && markReadAction.read
485
+ ev.emit('chats.update', [
486
+ { id, unreadCount: isNullUpdate ? null : markReadAction?.read ? 0 : -1, conditional: getChatUpdateConditional(id, markReadAction?.messageRange) }
487
+ ])
488
+ } else if (action?.deleteMessageForMeAction || type === 'deleteMessageForMe') {
489
+ ev.emit('messages.delete', { keys: [{ remoteJid: id, id: msgId, fromMe: fromMe === '1' }] })
490
+ } else if (action?.contactAction) {
491
+ emitSyncActionResults(ev, processContactAction(action.contactAction, id, logger))
492
+ } else if (action?.pushNameSetting) {
493
+ const name = action?.pushNameSetting?.name
494
+ if (name && me?.name !== name) ev.emit('creds.update', { me: { ...me, name } })
495
+ } else if (action?.pinAction) {
496
+ ev.emit('chats.update', [{ id, pinned: action.pinAction?.pinned ? toNumber(action.timestamp) : null, conditional: getChatUpdateConditional(id, undefined) }])
497
+ } else if (action?.unarchiveChatsSetting) {
498
+ const unarchiveChats = !!action.unarchiveChatsSetting.unarchiveChats
499
+ ev.emit('creds.update', { accountSettings: { unarchiveChats } })
500
+ logger?.info(`archive setting updated => '${action.unarchiveChatsSetting.unarchiveChats}'`)
501
+ if (accountSettings) accountSettings.unarchiveChats = unarchiveChats
502
+ } else if (action?.starAction || type === 'star') {
503
+ let starred = action?.starAction?.starred
504
+ if (typeof starred !== 'boolean') starred = syncAction.index[syncAction.index.length - 1] === '1'
505
+ ev.emit('messages.update', [{ key: { remoteJid: id, id: msgId, fromMe: fromMe === '1' }, update: { starred } }])
506
+ } else if (action?.deleteChatAction || type === 'deleteChat') {
507
+ if (!isInitialSync) ev.emit('chats.delete', [id])
508
+ } else if (action?.labelEditAction) {
509
+ const { name, color, deleted, predefinedId } = action.labelEditAction
510
+ ev.emit('labels.edit', { id, name, color, deleted, predefinedId: predefinedId ? String(predefinedId) : undefined })
511
+ } else if (action?.labelAssociationAction) {
512
+ ev.emit('labels.association', {
513
+ type: action.labelAssociationAction.labeled ? 'add' : 'remove',
514
+ association:
515
+ type === LabelAssociationType.Chat
516
+ ? { type: LabelAssociationType.Chat, chatId: syncAction.index[2], labelId: syncAction.index[1] }
517
+ : { type: LabelAssociationType.Message, chatId: syncAction.index[2], messageId: syncAction.index[3], labelId: syncAction.index[1] }
518
+ })
519
+ } else if (action?.localeSetting?.locale) {
520
+ ev.emit('settings.update', { setting: 'locale', value: action.localeSetting.locale })
521
+ } else if (action?.timeFormatAction) {
522
+ ev.emit('settings.update', { setting: 'timeFormat', value: action.timeFormatAction })
523
+ } else if (action?.pnForLidChatAction) {
524
+ if (action.pnForLidChatAction.pnJid) ev.emit('lid-mapping.update', { lid: id, pn: action.pnForLidChatAction.pnJid })
525
+ } else if (action?.privacySettingRelayAllCalls) {
526
+ ev.emit('settings.update', { setting: 'privacySettingRelayAllCalls', value: action.privacySettingRelayAllCalls })
527
+ } else if (action?.statusPrivacy) {
528
+ ev.emit('settings.update', { setting: 'statusPrivacy', value: action.statusPrivacy })
529
+ } else if (action?.lockChatAction) {
530
+ ev.emit('chats.lock', { id, locked: !!action.lockChatAction.locked })
531
+ } else if (action?.privacySettingDisableLinkPreviewsAction) {
532
+ ev.emit('settings.update', { setting: 'disableLinkPreviews', value: action.privacySettingDisableLinkPreviewsAction })
533
+ } else if (action?.notificationActivitySettingAction?.notificationActivitySetting) {
534
+ ev.emit('settings.update', { setting: 'notificationActivitySetting', value: action.notificationActivitySettingAction.notificationActivitySetting })
535
+ } else if (action?.lidContactAction) {
536
+ ev.emit('contacts.upsert', [
537
+ {
538
+ id,
539
+ name: action.lidContactAction.fullName || action.lidContactAction.firstName || action.lidContactAction.username || undefined,
540
+ username: action.lidContactAction.username || undefined,
541
+ lid: id,
542
+ phoneNumber: undefined
543
+ }
544
+ ])
545
+ } else if (action?.privacySettingChannelsPersonalisedRecommendationAction) {
546
+ ev.emit('settings.update', { setting: 'channelsPersonalisedRecommendation', value: action.privacySettingChannelsPersonalisedRecommendationAction })
547
+ } else {
548
+ logger?.debug({ syncAction, id }, 'unprocessable update')
549
+ }
550
+ }
551
+
552
+ /* ------------------------------------------------------------------ */
553
+ /* Sync action -> event mapping (pure) */
554
+ /* ------------------------------------------------------------------ */
555
+
556
+ /** Process contactAction and return events to emit. Pure function - no side effects. */
557
+ export const processContactAction = (action, id, logger) => {
558
+ const results = []
559
+ if (!id) {
560
+ logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index')
561
+ return results
562
+ }
563
+ const lidJid = action.lidJid
564
+ const idIsPn = isPnUser(id)
565
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined // PN is in index[1], not usually in contactAction.pnJid
566
+ results.push({
567
+ event: 'contacts.upsert',
568
+ data: [{ id, name: action.fullName || action.firstName || action.username || undefined, username: action.username || undefined, lid: lidJid || undefined, phoneNumber }]
569
+ })
570
+ if (lidJid && isLidUser(lidJid) && idIsPn) results.push({ event: 'lid-mapping.update', data: { lid: lidJid, pn: id } })
571
+ return results
572
+ }
573
+
574
+ export const emitSyncActionResults = (ev, results) => {
575
+ for (const result of results) {
576
+ if (result.event === 'contacts.upsert') ev.emit('contacts.upsert', result.data)
577
+ else ev.emit('lid-mapping.update', result.data)
578
+ }
579
+ }
580
+
581
+ /* ------------------------------------------------------------------ */
582
+ /* Event buffer */
583
+ /* ------------------------------------------------------------------ */
584
+
585
+ const BUFFERABLE_EVENT_SET = new Set([
586
+ 'messaging-history.set',
587
+ 'chats.upsert',
588
+ 'chats.update',
589
+ 'chats.delete',
590
+ 'contacts.upsert',
591
+ 'contacts.update',
592
+ 'messages.upsert',
593
+ 'messages.update',
594
+ 'messages.delete',
595
+ 'messages.reaction',
596
+ 'message-receipt.update',
597
+ 'groups.update'
598
+ ])
599
+
600
+ const makeBufferData = () => ({
601
+ historySets: { chats: {}, messages: {}, contacts: {}, isLatest: false, empty: true },
602
+ chatUpserts: {},
603
+ chatUpdates: {},
604
+ chatDeletes: new Set(),
605
+ contactUpserts: {},
606
+ contactUpdates: {},
607
+ messageUpserts: {},
608
+ messageUpdates: {},
609
+ messageReactions: {},
610
+ messageDeletes: {},
611
+ messageReceipts: {},
612
+ groupUpdates: {}
613
+ })
614
+
615
+ const stringifyMessageKey = key => `${key.remoteJid},${key.id},${key.fromMe ? '1' : '0'}`
616
+
617
+ function concatChats(a, b) {
618
+ if (b.unreadCount === null && a.unreadCount < 0) {
619
+ a.unreadCount = undefined
620
+ b.unreadCount = undefined
621
+ }
622
+ if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {
623
+ b = { ...b }
624
+ if (b.unreadCount >= 0) b.unreadCount = Math.max(b.unreadCount, 0) + Math.max(a.unreadCount, 0)
625
+ }
626
+ return Object.assign(a, b)
627
+ }
628
+
629
+ function consolidateEvents(data) {
630
+ const map = {}
631
+ if (!data.historySets.empty) {
632
+ map['messaging-history.set'] = {
633
+ chats: Object.values(data.historySets.chats),
634
+ messages: Object.values(data.historySets.messages),
635
+ contacts: Object.values(data.historySets.contacts),
636
+ pastParticipants: data.historySets.pastParticipants,
637
+ syncType: data.historySets.syncType,
638
+ progress: data.historySets.progress,
639
+ isLatest: data.historySets.isLatest,
640
+ chunkOrder: data.historySets.chunkOrder,
641
+ peerDataRequestSessionId: data.historySets.peerDataRequestSessionId
642
+ }
643
+ }
644
+ const chatUpsertList = Object.values(data.chatUpserts)
645
+ if (chatUpsertList.length) map['chats.upsert'] = chatUpsertList
646
+ const chatUpdateList = Object.values(data.chatUpdates)
647
+ if (chatUpdateList.length) map['chats.update'] = chatUpdateList
648
+ const chatDeleteList = Array.from(data.chatDeletes)
649
+ if (chatDeleteList.length) map['chats.delete'] = chatDeleteList
650
+ const messageUpsertList = Object.values(data.messageUpserts)
651
+ if (messageUpsertList.length) map['messages.upsert'] = { messages: messageUpsertList.map(m => m.message), type: messageUpsertList[0].type }
652
+ const messageUpdateList = Object.values(data.messageUpdates)
653
+ if (messageUpdateList.length) map['messages.update'] = messageUpdateList
654
+ const messageDeleteList = Object.values(data.messageDeletes)
655
+ if (messageDeleteList.length) map['messages.delete'] = { keys: messageDeleteList }
656
+ const messageReactionList = Object.values(data.messageReactions).flatMap(({ key, reactions }) => reactions.flatMap(reaction => ({ key, reaction })))
657
+ if (messageReactionList.length) map['messages.reaction'] = messageReactionList
658
+ const messageReceiptList = Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) => userReceipt.flatMap(receipt => ({ key, receipt })))
659
+ if (messageReceiptList.length) map['message-receipt.update'] = messageReceiptList
660
+ const contactUpsertList = Object.values(data.contactUpserts)
661
+ if (contactUpsertList.length) map['contacts.upsert'] = contactUpsertList
662
+ const contactUpdateList = Object.values(data.contactUpdates)
663
+ if (contactUpdateList.length) map['contacts.update'] = contactUpdateList
664
+ const groupUpdateList = Object.values(data.groupUpdates)
665
+ if (groupUpdateList.length) map['groups.update'] = groupUpdateList
666
+ return map
667
+ }
668
+
669
+ function append(data, historyCache, event, eventData, logger) {
670
+ switch (event) {
671
+ case 'messaging-history.set': {
672
+ for (const chat of eventData.chats) {
673
+ const id = chat.id || ''
674
+ const existingChat = data.historySets.chats[id]
675
+ if (existingChat) existingChat.endOfHistoryTransferType = chat.endOfHistoryTransferType
676
+ if (!existingChat && !historyCache.has(id)) {
677
+ data.historySets.chats[id] = chat
678
+ historyCache.add(id)
679
+ absorbingChatUpdate(chat)
680
+ }
681
+ }
682
+ for (const contact of eventData.contacts) {
683
+ const existingContact = data.historySets.contacts[contact.id]
684
+ if (existingContact) {
685
+ Object.assign(existingContact, trimUndefined(contact))
686
+ } else {
687
+ const historyContactId = `c:${contact.id}`
688
+ const hasAnyName = contact.notify || contact.name || contact.verifiedName
689
+ if (!historyCache.has(historyContactId) || hasAnyName) {
690
+ data.historySets.contacts[contact.id] = contact
691
+ historyCache.add(historyContactId)
692
+ }
693
+ }
694
+ }
695
+ for (const message of eventData.messages) {
696
+ const key = stringifyMessageKey(message.key)
697
+ const existingMsg = data.historySets.messages[key]
698
+ if (!existingMsg && !historyCache.has(key)) {
699
+ data.historySets.messages[key] = message
700
+ historyCache.add(key)
701
+ }
702
+ }
703
+ data.historySets.empty = false
704
+ data.historySets.syncType = eventData.syncType
705
+ if (eventData.pastParticipants?.length) {
706
+ const merged = new Map()
707
+ const sigOf = p => `${p.userJid || ''}:${p.leaveTs || ''}:${p.leaveReason || ''}`
708
+ const ingest = entry => {
709
+ const key = entry.groupJid ?? JSON.stringify(entry)
710
+ const existing = merged.get(key)
711
+ if (!existing) {
712
+ merged.set(key, { ...entry, pastParticipants: [...(entry.pastParticipants || [])] })
713
+ return
714
+ }
715
+ const seen = new Set((existing.pastParticipants || []).map(sigOf))
716
+ for (const p of entry.pastParticipants || []) {
717
+ const sig = sigOf(p)
718
+ if (!seen.has(sig)) {
719
+ existing.pastParticipants.push(p)
720
+ seen.add(sig)
721
+ }
722
+ }
723
+ }
724
+ for (const entry of data.historySets.pastParticipants || []) ingest(entry)
725
+ for (const entry of eventData.pastParticipants) ingest(entry)
726
+ data.historySets.pastParticipants = [...merged.values()]
727
+ }
728
+ data.historySets.progress = eventData.progress
729
+ data.historySets.chunkOrder = eventData.chunkOrder
730
+ data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId
731
+ data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest
732
+ break
733
+ }
734
+ case 'chats.upsert':
735
+ for (const chat of eventData) {
736
+ const id = chat.id || ''
737
+ let upsert = data.chatUpserts[id]
738
+ if (id && !upsert) {
739
+ upsert = data.historySets.chats[id]
740
+ if (upsert) logger.debug({ chatId: id }, 'absorbed chat upsert in chat set')
741
+ }
742
+ if (upsert) upsert = concatChats(upsert, chat)
743
+ else {
744
+ upsert = chat
745
+ data.chatUpserts[id] = upsert
746
+ }
747
+ absorbingChatUpdate(upsert)
748
+ if (data.chatDeletes.has(id)) data.chatDeletes.delete(id)
749
+ }
750
+ break
751
+ case 'chats.update':
752
+ for (const update of eventData) {
753
+ const chatId = update.id
754
+ const conditionMatches = update.conditional ? update.conditional(data) : true
755
+ if (conditionMatches) {
756
+ delete update.conditional
757
+ const upsert = data.historySets.chats[chatId] || data.chatUpserts[chatId]
758
+ if (upsert) concatChats(upsert, update)
759
+ else {
760
+ const chatUpdate = data.chatUpdates[chatId] || {}
761
+ data.chatUpdates[chatId] = concatChats(chatUpdate, update)
762
+ }
763
+ } else if (conditionMatches === undefined) {
764
+ data.chatUpdates[chatId] = update
765
+ }
766
+ if (data.chatDeletes.has(chatId)) data.chatDeletes.delete(chatId)
767
+ }
768
+ break
769
+ case 'chats.delete':
770
+ for (const chatId of eventData) {
771
+ if (!data.chatDeletes.has(chatId)) data.chatDeletes.add(chatId)
772
+ if (data.chatUpdates[chatId]) delete data.chatUpdates[chatId]
773
+ if (data.chatUpserts[chatId]) delete data.chatUpserts[chatId]
774
+ if (data.historySets.chats[chatId]) delete data.historySets.chats[chatId]
775
+ }
776
+ break
777
+ case 'contacts.upsert':
778
+ for (const contact of eventData) {
779
+ let upsert = data.contactUpserts[contact.id]
780
+ if (!upsert) {
781
+ upsert = data.historySets.contacts[contact.id]
782
+ if (upsert) logger.debug({ contactId: contact.id }, 'absorbed contact upsert in contact set')
783
+ }
784
+ if (upsert) upsert = Object.assign(upsert, trimUndefined(contact))
785
+ else {
786
+ upsert = contact
787
+ data.contactUpserts[contact.id] = upsert
788
+ }
789
+ if (data.contactUpdates[contact.id]) {
790
+ Object.assign(data.contactUpdates[contact.id], trimUndefined(contact))
791
+ delete data.contactUpdates[contact.id]
792
+ }
793
+ }
794
+ break
795
+ case 'contacts.update':
796
+ for (const update of eventData) {
797
+ const id = update.id
798
+ const upsert = data.historySets.contacts[id] || data.contactUpserts[id]
799
+ if (upsert) {
800
+ Object.assign(upsert, update)
801
+ } else {
802
+ const contactUpdate = data.contactUpdates[id] || {}
803
+ data.contactUpdates[id] = Object.assign(contactUpdate, update)
804
+ }
805
+ }
806
+ break
807
+ case 'messages.upsert': {
808
+ const { messages, type } = eventData
809
+ for (const message of messages) {
810
+ const key = stringifyMessageKey(message.key)
811
+ let existing = data.messageUpserts[key]?.message
812
+ if (!existing) {
813
+ existing = data.historySets.messages[key]
814
+ if (existing) logger.debug({ messageId: key }, 'absorbed message upsert in message set')
815
+ }
816
+ if (existing) message.messageTimestamp = existing.messageTimestamp
817
+ if (data.messageUpdates[key]) {
818
+ logger.debug('absorbed prior message update in message upsert')
819
+ Object.assign(message, data.messageUpdates[key].update)
820
+ delete data.messageUpdates[key]
821
+ }
822
+ if (data.historySets.messages[key]) data.historySets.messages[key] = message
823
+ else data.messageUpserts[key] = { message, type: type === 'notify' || data.messageUpserts[key]?.type === 'notify' ? 'notify' : type }
824
+ }
825
+ break
826
+ }
827
+ case 'messages.update':
828
+ for (const { key, update } of eventData) {
829
+ const keyStr = stringifyMessageKey(key)
830
+ const existing = data.historySets.messages[keyStr] || data.messageUpserts[keyStr]?.message
831
+ if (existing) {
832
+ Object.assign(existing, update)
833
+ if (update.status === WAMessageStatus.READ && !key.fromMe) decrementChatReadCounterIfMsgDidUnread(existing)
834
+ } else {
835
+ const msgUpdate = data.messageUpdates[keyStr] || { key, update: {} }
836
+ Object.assign(msgUpdate.update, update)
837
+ data.messageUpdates[keyStr] = msgUpdate
838
+ }
839
+ }
840
+ break
841
+ case 'messages.delete':
842
+ if ('keys' in eventData) {
843
+ for (const key of eventData.keys) {
844
+ const keyStr = stringifyMessageKey(key)
845
+ if (!data.messageDeletes[keyStr]) data.messageDeletes[keyStr] = key
846
+ if (data.messageUpserts[keyStr]) delete data.messageUpserts[keyStr]
847
+ if (data.messageUpdates[keyStr]) delete data.messageUpdates[keyStr]
848
+ }
849
+ }
850
+ break
851
+ case 'messages.reaction':
852
+ for (const { key, reaction } of eventData) {
853
+ const keyStr = stringifyMessageKey(key)
854
+ const existing = data.messageUpserts[keyStr]
855
+ if (existing) {
856
+ updateMessageWithReaction(existing.message, reaction)
857
+ } else {
858
+ data.messageReactions[keyStr] = data.messageReactions[keyStr] || { key, reactions: [] }
859
+ updateMessageWithReaction(data.messageReactions[keyStr], reaction)
860
+ }
861
+ }
862
+ break
863
+ case 'message-receipt.update':
864
+ for (const { key, receipt } of eventData) {
865
+ const keyStr = stringifyMessageKey(key)
866
+ const existing = data.messageUpserts[keyStr]
867
+ if (existing) {
868
+ updateMessageWithReceipt(existing.message, receipt)
869
+ } else {
870
+ data.messageReceipts[keyStr] = data.messageReceipts[keyStr] || { key, userReceipt: [] }
871
+ updateMessageWithReceipt(data.messageReceipts[keyStr], receipt)
872
+ }
873
+ }
874
+ break
875
+ case 'groups.update':
876
+ for (const update of eventData) {
877
+ const id = update.id
878
+ if (!data.groupUpdates[id]) data.groupUpdates[id] = Object.assign({}, update)
879
+ }
880
+ break
881
+ default:
882
+ throw new Error(`"${event}" cannot be buffered`)
883
+ }
884
+
885
+ function absorbingChatUpdate(existing) {
886
+ const chatId = existing.id || ''
887
+ const update = data.chatUpdates[chatId]
888
+ if (update) {
889
+ const conditionMatches = update.conditional ? update.conditional(data) : true
890
+ if (conditionMatches) {
891
+ delete update.conditional
892
+ logger.debug({ chatId }, 'absorbed chat update in existing chat')
893
+ Object.assign(existing, concatChats(update, existing))
894
+ delete data.chatUpdates[chatId]
895
+ } else if (conditionMatches === false) {
896
+ logger.debug({ chatId }, 'chat update condition fail, removing')
897
+ delete data.chatUpdates[chatId]
898
+ }
899
+ }
900
+ }
901
+ function decrementChatReadCounterIfMsgDidUnread(message) {
902
+ const chatId = message.key.remoteJid
903
+ const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId]
904
+ if (isRealMessage(message) && shouldIncrementChatUnread(message) && typeof chat?.unreadCount === 'number' && chat.unreadCount > 0) {
905
+ logger.debug({ chatId: chat.id }, 'decrementing chat counter')
906
+ chat.unreadCount -= 1
907
+ if (chat.unreadCount === 0) delete chat.unreadCount
908
+ }
909
+ }
910
+ }
911
+
912
+ /** The event buffer logically consolidates different events into a single event, making data processing more efficient. */
913
+ export const makeEventBuffer = logger => {
914
+ const ev = new EventEmitter()
915
+ const historyCache = new Set()
916
+ let data = makeBufferData()
917
+ let isBuffering = false
918
+ let bufferTimeout = null
919
+ let flushPendingTimeout = null
920
+ let bufferCount = 0
921
+ const MAX_HISTORY_CACHE_SIZE = 10000
922
+ const BUFFER_TIMEOUT_MS = 30000
923
+
924
+ ev.on('event', map => {
925
+ for (const event in map) ev.emit(event, map[event])
926
+ })
927
+
928
+ function buffer() {
929
+ if (!isBuffering) {
930
+ logger.debug('Event buffer activated')
931
+ isBuffering = true
932
+ bufferCount = 0
933
+ if (bufferTimeout) clearTimeout(bufferTimeout)
934
+ bufferTimeout = setTimeout(() => {
935
+ if (isBuffering) {
936
+ logger.warn('Buffer timeout reached, auto-flushing')
937
+ flush()
938
+ }
939
+ }, BUFFER_TIMEOUT_MS)
940
+ }
941
+ bufferCount++
942
+ }
943
+
944
+ function flush() {
945
+ if (!isBuffering) return false
946
+ logger.debug({ bufferCount }, 'Flushing event buffer')
947
+ isBuffering = false
948
+ bufferCount = 0
949
+ if (bufferTimeout) {
950
+ clearTimeout(bufferTimeout)
951
+ bufferTimeout = null
952
+ }
953
+ if (flushPendingTimeout) {
954
+ clearTimeout(flushPendingTimeout)
955
+ flushPendingTimeout = null
956
+ }
957
+ if (historyCache.size > MAX_HISTORY_CACHE_SIZE) {
958
+ logger.debug({ cacheSize: historyCache.size }, 'Clearing history cache')
959
+ historyCache.clear()
960
+ }
961
+ const newData = makeBufferData()
962
+ const chatUpdates = Object.values(data.chatUpdates)
963
+ let conditionalChatUpdatesLeft = 0
964
+ for (const update of chatUpdates) {
965
+ if (update.conditional) {
966
+ conditionalChatUpdatesLeft += 1
967
+ newData.chatUpdates[update.id] = update
968
+ delete data.chatUpdates[update.id]
969
+ }
970
+ }
971
+ const consolidatedData = consolidateEvents(data)
972
+ if (Object.keys(consolidatedData).length) ev.emit('event', consolidatedData)
973
+ data = newData
974
+ logger.trace({ conditionalChatUpdatesLeft }, 'released buffered events')
975
+ return true
976
+ }
977
+
978
+ return {
979
+ process(handler) {
980
+ const listener = async map => {
981
+ await handler(map)
982
+ }
983
+ ev.on('event', listener)
984
+ return () => ev.off('event', listener)
985
+ },
986
+ emit(event, evData) {
987
+ if (event === 'messages.upsert') {
988
+ const { type } = evData
989
+ const existingUpserts = Object.values(data.messageUpserts)
990
+ if (existingUpserts.length > 0) {
991
+ const bufferedType = existingUpserts[0].type
992
+ if (bufferedType !== type) {
993
+ logger.debug({ bufferedType, newType: type }, 'messages.upsert type mismatch, emitting buffered messages')
994
+ ev.emit('event', { 'messages.upsert': { messages: existingUpserts.map(m => m.message), type: bufferedType } })
995
+ data.messageUpserts = {}
996
+ }
997
+ }
998
+ }
999
+ if (isBuffering && BUFFERABLE_EVENT_SET.has(event)) {
1000
+ append(data, historyCache, event, evData, logger)
1001
+ return true
1002
+ }
1003
+ return ev.emit('event', { [event]: evData })
1004
+ },
1005
+ isBuffering: () => isBuffering,
1006
+ buffer,
1007
+ flush,
1008
+ createBufferedFunction(work) {
1009
+ return async (...args) => {
1010
+ buffer()
1011
+ try {
1012
+ const result = await work(...args)
1013
+ if (bufferCount === 1) {
1014
+ setTimeout(() => {
1015
+ if (isBuffering && bufferCount === 1) flush()
1016
+ }, 100)
1017
+ }
1018
+ return result
1019
+ } finally {
1020
+ bufferCount = Math.max(0, bufferCount - 1)
1021
+ if (bufferCount === 0 && !flushPendingTimeout) flushPendingTimeout = setTimeout(flush, 100)
1022
+ }
1023
+ }
1024
+ },
1025
+ on: (...args) => ev.on(...args),
1026
+ off: (...args) => ev.off(...args),
1027
+ removeAllListeners: (...args) => ev.removeAllListeners(...args),
1028
+ destroy() {
1029
+ if (bufferTimeout) {
1030
+ clearTimeout(bufferTimeout)
1031
+ bufferTimeout = null
1032
+ }
1033
+ if (flushPendingTimeout) {
1034
+ clearTimeout(flushPendingTimeout)
1035
+ flushPendingTimeout = null
1036
+ }
1037
+ historyCache.clear()
1038
+ data = makeBufferData()
1039
+ isBuffering = false
1040
+ bufferCount = 0
1041
+ ev.removeAllListeners()
1042
+ logger.debug('Event buffer destroyed')
1043
+ }
1044
+ }
1045
+ }