@itznomo/baileys 0.0.0-stage → 0.0.3

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