@zervonexx/baileys 5.0.0 → 5.0.2

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 (127) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +4124 -4112
  3. package/WAProto/WAProto.json +1 -0
  4. package/WAProto/WAProto.proto +7160 -0
  5. package/WAProto/WAProtoCompile.js +264 -322
  6. package/WAProto/index.js +55 -95
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +249 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +17 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +195 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +3 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +944 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. package/package.json +187 -192
  126. package/WAProto/fetcher.js +0 -68
  127. package/WAProto/parser.js +0 -334
@@ -1,283 +1,283 @@
1
- import { LRUCache } from 'lru-cache'
2
- import { isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, WAJIDDomains } from '../WABinary/index.js'
3
-
4
- export class LIDMappingStore {
5
- constructor(keys, logger, pnToLIDFunc) {
6
- this.mappingCache = new LRUCache({ max: 10000, ttl: 3 * 24 * 60 * 60 * 1000, ttlAutopurge: true, updateAgeOnGet: true })
7
- this.inflightLIDLookups = new Map()
8
- this.inflightPNLookups = new Map()
9
- this.keys = keys
10
- this.logger = logger
11
- this.pnToLIDFunc = pnToLIDFunc
12
- }
13
-
14
- async storeLIDPNMappings(pairs) {
15
- if (!pairs.length) return
16
-
17
- const validatedPairs = []
18
- for (const { lid, pn } of pairs) {
19
- if (!((isLidUser(lid) && isPnUser(pn)) || (isPnUser(lid) && isLidUser(pn)))) {
20
- this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`)
21
- continue
22
- }
23
- const lidDecoded = jidDecode(lid)
24
- const pnDecoded = jidDecode(pn)
25
- if (!lidDecoded || !pnDecoded) continue // fixed: was `return`, skips only this pair
26
- validatedPairs.push({ pnUser: pnDecoded.user, lidUser: lidDecoded.user })
27
- }
28
-
29
- if (!validatedPairs.length) return
30
-
31
- // Batch check all cache misses in one DB call (forward AND reverse)
32
- const cacheMissSet = new Set()
33
- const existingMappings = new Map()
34
- const existingReverse = new Map()
35
-
36
- for (const { pnUser } of validatedPairs) {
37
- const cached = this.mappingCache.get(`pn:${pnUser}`)
38
- if (cached) existingMappings.set(pnUser, cached)
39
- else cacheMissSet.add(pnUser)
40
- }
41
-
42
- if (cacheMissSet.size > 0) {
43
- this.logger.trace(`Batch fetching ${cacheMissSet.size} LID mappings from database`)
44
- const stored = await this.keys.get('lid-mapping', [...cacheMissSet])
45
- for (const pnUser of cacheMissSet) {
46
- const lidUser = stored[pnUser]
47
- if (lidUser) {
48
- existingMappings.set(pnUser, lidUser)
49
- this.mappingCache.set(`pn:${pnUser}`, lidUser)
50
- this.mappingCache.set(`lid:${lidUser}`, pnUser)
51
- }
52
- }
53
- }
54
-
55
- // Separately verify the reverse entry actually exists on disk for every
56
- // pair whose forward mapping we found — a forward file existing does NOT
57
- // guarantee its `_reverse` sibling was ever written (e.g. when only the
58
- // recipient side of a fromMe message was resolved, never the sender side).
59
- const reverseKeysToCheck = []
60
- for (const { pnUser, lidUser } of validatedPairs) {
61
- if (existingMappings.get(pnUser) === lidUser) reverseKeysToCheck.push(`${lidUser}_reverse`)
62
- }
63
- if (reverseKeysToCheck.length) {
64
- const storedReverse = await this.keys.get('lid-mapping', reverseKeysToCheck)
65
- for (const key of reverseKeysToCheck) {
66
- if (storedReverse[key]) existingReverse.set(key, storedReverse[key])
67
- }
68
- }
69
-
70
- const pairMap = {}
71
- for (const { pnUser, lidUser } of validatedPairs) {
72
- const forwardExists = existingMappings.get(pnUser) === lidUser
73
- const reverseExists = existingReverse.has(`${lidUser}_reverse`)
74
- if (forwardExists && reverseExists) {
75
- continue
76
- }
77
- if (forwardExists && !reverseExists) {
78
- this.logger.debug({ pnUser, lidUser }, 'forward mapping exists but reverse is missing, repairing')
79
- }
80
- pairMap[pnUser] = lidUser
81
- }
82
- if (!Object.keys(pairMap).length) return
83
-
84
- this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`)
85
-
86
- // Single batched keys.set inside transaction
87
- const batchData = {}
88
- for (const [pnUser, lidUser] of Object.entries(pairMap)) {
89
- batchData[pnUser] = lidUser
90
- batchData[`${lidUser}_reverse`] = pnUser
91
- }
92
-
93
- await this.keys.transaction(async () => {
94
- await this.keys.set({ 'lid-mapping': batchData })
95
- }, 'lid-mapping')
96
-
97
- // Update cache only after successful DB write
98
- for (const [pnUser, lidUser] of Object.entries(pairMap)) {
99
- this.mappingCache.set(`pn:${pnUser}`, lidUser)
100
- this.mappingCache.set(`lid:${lidUser}`, pnUser)
101
- }
102
- }
103
-
104
- async getLIDForPN(pn) {
105
- return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null
106
- }
107
-
108
- async getLIDsForPNs(pns) {
109
- if (!pns.length) return null
110
- const sortedPns = [...new Set(pns)].sort()
111
- const cacheKey = sortedPns.join(',')
112
-
113
- const inflight = this.inflightLIDLookups.get(cacheKey)
114
- if (inflight) {
115
- this.logger.trace(`Coalescing getLIDsForPNs for ${sortedPns.length} PNs`)
116
- return inflight
117
- }
118
-
119
- const promise = this._getLIDsForPNsImpl(pns)
120
- this.inflightLIDLookups.set(cacheKey, promise)
121
- try {
122
- return await promise
123
- } finally {
124
- this.inflightLIDLookups.delete(cacheKey)
125
- }
126
- }
127
-
128
- async _getLIDsForPNsImpl(pns) {
129
- const usyncFetch = {}
130
- const successfulPairs = {}
131
- const pending = []
132
-
133
- const addResolvedPair = (pn, decoded, lidUser) => {
134
- const normalizedLidUser = lidUser.toString()
135
- if (!normalizedLidUser) {
136
- this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`)
137
- return false
138
- }
139
- const pnDevice = decoded.device !== undefined ? decoded.device : 0
140
- const deviceSpecificLid = `${normalizedLidUser}${pnDevice ? `:${pnDevice}` : ''}@${decoded.server === 'hosted' ? 'hosted.lid' : 'lid'}`
141
- this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`)
142
- successfulPairs[pn] = { lid: deviceSpecificLid, pn }
143
- return true
144
- }
145
-
146
- for (const pn of pns) {
147
- if (!isPnUser(pn) && !isHostedPnUser(pn)) continue
148
- const decoded = jidDecode(pn)
149
- if (!decoded) continue
150
- const pnUser = decoded.user
151
- const cached = this.mappingCache.get(`pn:${pnUser}`)
152
- if (cached) {
153
- addResolvedPair(pn, decoded, cached)
154
- } else {
155
- pending.push({ pn, pnUser, decoded })
156
- }
157
- }
158
-
159
- if (pending.length) {
160
- // Single batched DB fetch for all cache misses
161
- const pnUsers = [...new Set(pending.map(p => p.pnUser))]
162
- const stored = await this.keys.get('lid-mapping', pnUsers)
163
-
164
- for (const pnUser of pnUsers) {
165
- const lidUser = stored[pnUser]
166
- if (lidUser) {
167
- this.mappingCache.set(`pn:${pnUser}`, lidUser)
168
- this.mappingCache.set(`lid:${lidUser}`, pnUser)
169
- }
170
- }
171
-
172
- for (const { pn, pnUser, decoded } of pending) {
173
- const cached = this.mappingCache.get(`pn:${pnUser}`)
174
- if (cached) {
175
- addResolvedPair(pn, decoded, cached)
176
- } else {
177
- this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`)
178
- const device = decoded.device || 0
179
- let normalizedPn = jidNormalizedUser(pn)
180
- if (isHostedPnUser(normalizedPn)) normalizedPn = `${pnUser}@s.whatsapp.net`
181
- if (!usyncFetch[normalizedPn]) usyncFetch[normalizedPn] = [device]
182
- else usyncFetch[normalizedPn].push(device)
183
- }
184
- }
185
- }
186
-
187
- if (Object.keys(usyncFetch).length > 0) {
188
- const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch))
189
- if (result?.length > 0) {
190
- await this.storeLIDPNMappings(result) // fixed: was fire-and-forget
191
- for (const pair of result) {
192
- const pnDecoded = jidDecode(pair.pn)
193
- const pnUser = pnDecoded?.user
194
- if (!pnUser) continue
195
- const lidUser = jidDecode(pair.lid)?.user
196
- if (!lidUser) continue
197
- for (const device of usyncFetch[pair.pn] || []) {
198
- const deviceSpecificLid = `${lidUser}${device ? `:${device}` : ''}@${device === 99 ? 'hosted.lid' : 'lid'}`
199
- const deviceSpecificPn = `${pnUser}${device ? `:${device}` : ''}@${device === 99 ? 'hosted' : 's.whatsapp.net'}`
200
- this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`)
201
- successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn }
202
- }
203
- }
204
- } else {
205
- return null
206
- }
207
- }
208
-
209
- return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null
210
- }
211
-
212
- async getPNForLID(lid) {
213
- return (await this.getPNsForLIDs([lid]))?.[0]?.pn || null
214
- }
215
-
216
- async getPNsForLIDs(lids) {
217
- if (!lids.length) return null
218
- const sortedLids = [...new Set(lids)].sort()
219
- const cacheKey = sortedLids.join(',')
220
-
221
- const inflight = this.inflightPNLookups.get(cacheKey)
222
- if (inflight) {
223
- this.logger.trace(`Coalescing getPNsForLIDs for ${sortedLids.length} LIDs`)
224
- return inflight
225
- }
226
-
227
- const promise = this._getPNsForLIDsImpl(lids)
228
- this.inflightPNLookups.set(cacheKey, promise)
229
- try {
230
- return await promise
231
- } finally {
232
- this.inflightPNLookups.delete(cacheKey)
233
- }
234
- }
235
-
236
- async _getPNsForLIDsImpl(lids) {
237
- const successfulPairs = {}
238
- const pending = []
239
-
240
- const addResolvedPair = (lid, decoded, pnUser) => {
241
- if (!pnUser || typeof pnUser !== 'string') return false
242
- const lidDevice = decoded.device !== undefined ? decoded.device : 0
243
- const pnJid = `${pnUser}${lidDevice ? `:${lidDevice}` : ''}@${decoded.domainType === WAJIDDomains.HOSTED_LID ? 'hosted' : 's.whatsapp.net'}`
244
- this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`)
245
- successfulPairs[lid] = { lid, pn: pnJid }
246
- return true
247
- }
248
-
249
- for (const lid of lids) {
250
- if (!isLidUser(lid)) continue
251
- const decoded = jidDecode(lid)
252
- if (!decoded) continue
253
- const lidUser = decoded.user
254
- const cached = this.mappingCache.get(`lid:${lidUser}`)
255
- if (cached) {
256
- addResolvedPair(lid, decoded, cached)
257
- } else {
258
- pending.push({ lid, lidUser, decoded })
259
- }
260
- }
261
-
262
- if (pending.length) {
263
- // Single batched DB fetch for all cache misses
264
- const reverseKeys = [...new Set(pending.map(p => `${p.lidUser}_reverse`))]
265
- const stored = await this.keys.get('lid-mapping', reverseKeys)
266
-
267
- for (const { lid, lidUser, decoded } of pending) {
268
- let pnUser = this.mappingCache.get(`lid:${lidUser}`)
269
- if (!pnUser || typeof pnUser !== 'string') {
270
- pnUser = stored[`${lidUser}_reverse`]
271
- if (pnUser && typeof pnUser === 'string') {
272
- this.mappingCache.set(`lid:${lidUser}`, pnUser)
273
- this.mappingCache.set(`pn:${pnUser}`, lidUser)
274
- }
275
- }
276
- if (pnUser) addResolvedPair(lid, decoded, pnUser)
277
- else this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`)
278
- }
279
- }
280
-
281
- return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null
282
- }
1
+ import { LRUCache } from 'lru-cache'
2
+ import { isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, WAJIDDomains } from '../WABinary/index.js'
3
+
4
+ export class LIDMappingStore {
5
+ constructor(keys, logger, pnToLIDFunc) {
6
+ this.mappingCache = new LRUCache({ max: 10000, ttl: 3 * 24 * 60 * 60 * 1000, ttlAutopurge: true, updateAgeOnGet: true })
7
+ this.inflightLIDLookups = new Map()
8
+ this.inflightPNLookups = new Map()
9
+ this.keys = keys
10
+ this.logger = logger
11
+ this.pnToLIDFunc = pnToLIDFunc
12
+ }
13
+
14
+ async storeLIDPNMappings(pairs) {
15
+ if (!pairs.length) return
16
+
17
+ const validatedPairs = []
18
+ for (const { lid, pn } of pairs) {
19
+ if (!((isLidUser(lid) && isPnUser(pn)) || (isPnUser(lid) && isLidUser(pn)))) {
20
+ this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`)
21
+ continue
22
+ }
23
+ const lidDecoded = jidDecode(lid)
24
+ const pnDecoded = jidDecode(pn)
25
+ if (!lidDecoded || !pnDecoded) continue // fixed: was `return`, skips only this pair
26
+ validatedPairs.push({ pnUser: pnDecoded.user, lidUser: lidDecoded.user })
27
+ }
28
+
29
+ if (!validatedPairs.length) return
30
+
31
+ // Batch check all cache misses in one DB call (forward AND reverse)
32
+ const cacheMissSet = new Set()
33
+ const existingMappings = new Map()
34
+ const existingReverse = new Map()
35
+
36
+ for (const { pnUser } of validatedPairs) {
37
+ const cached = this.mappingCache.get(`pn:${pnUser}`)
38
+ if (cached) existingMappings.set(pnUser, cached)
39
+ else cacheMissSet.add(pnUser)
40
+ }
41
+
42
+ if (cacheMissSet.size > 0) {
43
+ this.logger.trace(`Batch fetching ${cacheMissSet.size} LID mappings from database`)
44
+ const stored = await this.keys.get('lid-mapping', [...cacheMissSet])
45
+ for (const pnUser of cacheMissSet) {
46
+ const lidUser = stored[pnUser]
47
+ if (lidUser) {
48
+ existingMappings.set(pnUser, lidUser)
49
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
50
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
51
+ }
52
+ }
53
+ }
54
+
55
+ // Separately verify the reverse entry actually exists on disk for every
56
+ // pair whose forward mapping we found — a forward file existing does NOT
57
+ // guarantee its `_reverse` sibling was ever written (e.g. when only the
58
+ // recipient side of a fromMe message was resolved, never the sender side).
59
+ const reverseKeysToCheck = []
60
+ for (const { pnUser, lidUser } of validatedPairs) {
61
+ if (existingMappings.get(pnUser) === lidUser) reverseKeysToCheck.push(`${lidUser}_reverse`)
62
+ }
63
+ if (reverseKeysToCheck.length) {
64
+ const storedReverse = await this.keys.get('lid-mapping', reverseKeysToCheck)
65
+ for (const key of reverseKeysToCheck) {
66
+ if (storedReverse[key]) existingReverse.set(key, storedReverse[key])
67
+ }
68
+ }
69
+
70
+ const pairMap = {}
71
+ for (const { pnUser, lidUser } of validatedPairs) {
72
+ const forwardExists = existingMappings.get(pnUser) === lidUser
73
+ const reverseExists = existingReverse.has(`${lidUser}_reverse`)
74
+ if (forwardExists && reverseExists) {
75
+ continue
76
+ }
77
+ if (forwardExists && !reverseExists) {
78
+ this.logger.debug({ pnUser, lidUser }, 'forward mapping exists but reverse is missing, repairing')
79
+ }
80
+ pairMap[pnUser] = lidUser
81
+ }
82
+ if (!Object.keys(pairMap).length) return
83
+
84
+ this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`)
85
+
86
+ // Single batched keys.set inside transaction
87
+ const batchData = {}
88
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
89
+ batchData[pnUser] = lidUser
90
+ batchData[`${lidUser}_reverse`] = pnUser
91
+ }
92
+
93
+ await this.keys.transaction(async () => {
94
+ await this.keys.set({ 'lid-mapping': batchData })
95
+ }, 'lid-mapping')
96
+
97
+ // Update cache only after successful DB write
98
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
99
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
100
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
101
+ }
102
+ }
103
+
104
+ async getLIDForPN(pn) {
105
+ return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null
106
+ }
107
+
108
+ async getLIDsForPNs(pns) {
109
+ if (!pns.length) return null
110
+ const sortedPns = [...new Set(pns)].sort()
111
+ const cacheKey = sortedPns.join(',')
112
+
113
+ const inflight = this.inflightLIDLookups.get(cacheKey)
114
+ if (inflight) {
115
+ this.logger.trace(`Coalescing getLIDsForPNs for ${sortedPns.length} PNs`)
116
+ return inflight
117
+ }
118
+
119
+ const promise = this._getLIDsForPNsImpl(pns)
120
+ this.inflightLIDLookups.set(cacheKey, promise)
121
+ try {
122
+ return await promise
123
+ } finally {
124
+ this.inflightLIDLookups.delete(cacheKey)
125
+ }
126
+ }
127
+
128
+ async _getLIDsForPNsImpl(pns) {
129
+ const usyncFetch = {}
130
+ const successfulPairs = {}
131
+ const pending = []
132
+
133
+ const addResolvedPair = (pn, decoded, lidUser) => {
134
+ const normalizedLidUser = lidUser.toString()
135
+ if (!normalizedLidUser) {
136
+ this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`)
137
+ return false
138
+ }
139
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0
140
+ const deviceSpecificLid = `${normalizedLidUser}${pnDevice ? `:${pnDevice}` : ''}@${decoded.server === 'hosted' ? 'hosted.lid' : 'lid'}`
141
+ this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`)
142
+ successfulPairs[pn] = { lid: deviceSpecificLid, pn }
143
+ return true
144
+ }
145
+
146
+ for (const pn of pns) {
147
+ if (!isPnUser(pn) && !isHostedPnUser(pn)) continue
148
+ const decoded = jidDecode(pn)
149
+ if (!decoded) continue
150
+ const pnUser = decoded.user
151
+ const cached = this.mappingCache.get(`pn:${pnUser}`)
152
+ if (cached) {
153
+ addResolvedPair(pn, decoded, cached)
154
+ } else {
155
+ pending.push({ pn, pnUser, decoded })
156
+ }
157
+ }
158
+
159
+ if (pending.length) {
160
+ // Single batched DB fetch for all cache misses
161
+ const pnUsers = [...new Set(pending.map(p => p.pnUser))]
162
+ const stored = await this.keys.get('lid-mapping', pnUsers)
163
+
164
+ for (const pnUser of pnUsers) {
165
+ const lidUser = stored[pnUser]
166
+ if (lidUser) {
167
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
168
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
169
+ }
170
+ }
171
+
172
+ for (const { pn, pnUser, decoded } of pending) {
173
+ const cached = this.mappingCache.get(`pn:${pnUser}`)
174
+ if (cached) {
175
+ addResolvedPair(pn, decoded, cached)
176
+ } else {
177
+ this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`)
178
+ const device = decoded.device || 0
179
+ let normalizedPn = jidNormalizedUser(pn)
180
+ if (isHostedPnUser(normalizedPn)) normalizedPn = `${pnUser}@s.whatsapp.net`
181
+ if (!usyncFetch[normalizedPn]) usyncFetch[normalizedPn] = [device]
182
+ else usyncFetch[normalizedPn].push(device)
183
+ }
184
+ }
185
+ }
186
+
187
+ if (Object.keys(usyncFetch).length > 0) {
188
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch))
189
+ if (result?.length > 0) {
190
+ await this.storeLIDPNMappings(result) // fixed: was fire-and-forget
191
+ for (const pair of result) {
192
+ const pnDecoded = jidDecode(pair.pn)
193
+ const pnUser = pnDecoded?.user
194
+ if (!pnUser) continue
195
+ const lidUser = jidDecode(pair.lid)?.user
196
+ if (!lidUser) continue
197
+ for (const device of usyncFetch[pair.pn] || []) {
198
+ const deviceSpecificLid = `${lidUser}${device ? `:${device}` : ''}@${device === 99 ? 'hosted.lid' : 'lid'}`
199
+ const deviceSpecificPn = `${pnUser}${device ? `:${device}` : ''}@${device === 99 ? 'hosted' : 's.whatsapp.net'}`
200
+ this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`)
201
+ successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn }
202
+ }
203
+ }
204
+ } else {
205
+ return null
206
+ }
207
+ }
208
+
209
+ return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null
210
+ }
211
+
212
+ async getPNForLID(lid) {
213
+ return (await this.getPNsForLIDs([lid]))?.[0]?.pn || null
214
+ }
215
+
216
+ async getPNsForLIDs(lids) {
217
+ if (!lids.length) return null
218
+ const sortedLids = [...new Set(lids)].sort()
219
+ const cacheKey = sortedLids.join(',')
220
+
221
+ const inflight = this.inflightPNLookups.get(cacheKey)
222
+ if (inflight) {
223
+ this.logger.trace(`Coalescing getPNsForLIDs for ${sortedLids.length} LIDs`)
224
+ return inflight
225
+ }
226
+
227
+ const promise = this._getPNsForLIDsImpl(lids)
228
+ this.inflightPNLookups.set(cacheKey, promise)
229
+ try {
230
+ return await promise
231
+ } finally {
232
+ this.inflightPNLookups.delete(cacheKey)
233
+ }
234
+ }
235
+
236
+ async _getPNsForLIDsImpl(lids) {
237
+ const successfulPairs = {}
238
+ const pending = []
239
+
240
+ const addResolvedPair = (lid, decoded, pnUser) => {
241
+ if (!pnUser || typeof pnUser !== 'string') return false
242
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0
243
+ const pnJid = `${pnUser}${lidDevice ? `:${lidDevice}` : ''}@${decoded.domainType === WAJIDDomains.HOSTED_LID ? 'hosted' : 's.whatsapp.net'}`
244
+ this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`)
245
+ successfulPairs[lid] = { lid, pn: pnJid }
246
+ return true
247
+ }
248
+
249
+ for (const lid of lids) {
250
+ if (!isLidUser(lid)) continue
251
+ const decoded = jidDecode(lid)
252
+ if (!decoded) continue
253
+ const lidUser = decoded.user
254
+ const cached = this.mappingCache.get(`lid:${lidUser}`)
255
+ if (cached) {
256
+ addResolvedPair(lid, decoded, cached)
257
+ } else {
258
+ pending.push({ lid, lidUser, decoded })
259
+ }
260
+ }
261
+
262
+ if (pending.length) {
263
+ // Single batched DB fetch for all cache misses
264
+ const reverseKeys = [...new Set(pending.map(p => `${p.lidUser}_reverse`))]
265
+ const stored = await this.keys.get('lid-mapping', reverseKeys)
266
+
267
+ for (const { lid, lidUser, decoded } of pending) {
268
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`)
269
+ if (!pnUser || typeof pnUser !== 'string') {
270
+ pnUser = stored[`${lidUser}_reverse`]
271
+ if (pnUser && typeof pnUser === 'string') {
272
+ this.mappingCache.set(`lid:${lidUser}`, pnUser)
273
+ this.mappingCache.set(`pn:${pnUser}`, lidUser)
274
+ }
275
+ }
276
+ if (pnUser) addResolvedPair(lid, decoded, pnUser)
277
+ else this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`)
278
+ }
279
+ }
280
+
281
+ return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null
282
+ }
283
283
  }
@@ -1,2 +1,2 @@
1
- export * from './types.js'
1
+ export * from './types.js'
2
2
  export * from './websocket.js'
@@ -1,10 +1,10 @@
1
- import { EventEmitter } from 'events'
2
-
3
- export class AbstractSocketClient extends EventEmitter {
4
- constructor(url, config) {
5
- super()
6
- this.url = url
7
- this.config = config
8
- this.setMaxListeners(0)
9
- }
1
+ import { EventEmitter } from 'events'
2
+
3
+ export class AbstractSocketClient extends EventEmitter {
4
+ constructor(url, config) {
5
+ super()
6
+ this.url = url
7
+ this.config = config
8
+ this.setMaxListeners(0)
9
+ }
10
10
  }