kage-baileys 25.3.18 → 25.3.19

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.
@@ -3,10 +3,30 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.LIDMappingStore = void 0;
4
4
  const index_js_1 = require("../Addon/index.js");
5
5
  const index_js_2 = require("../WABinary/index.js");
6
+
7
+ /** True for @lid and @hosted.lid */
8
+ function isAnyLidUser(jid) {
9
+ return (0, index_js_2.isLidUser)(jid) || (0, index_js_2.isHostedLidUser)(jid);
10
+ }
11
+
12
+ /** True for @s.whatsapp.net and @hosted */
13
+ function isAnyPnUser(jid) {
14
+ return (0, index_js_2.isPnUser)(jid) || (0, index_js_2.isHostedPnUser)(jid);
15
+ }
16
+
17
+ /** Build device-aware JID without ":0" for primary device */
18
+ function encodeDeviceJid(user, server, device) {
19
+ const d = device !== undefined && device !== null ? Number(device) : 0;
20
+ if (!d) {
21
+ return `${user}@${server}`;
22
+ }
23
+ return `${user}:${d}@${server}`;
24
+ }
25
+
6
26
  class LIDMappingStore {
7
27
  constructor(keys, logger, pnToLIDFunc) {
8
28
  this.mappingCache = (0, index_js_1.createCache)({
9
- ttl: 3 * 24 * 60 * 60
29
+ ttl: 14 * 24 * 60 * 60
10
30
  });
11
31
  this.inflightLIDLookups = new Map();
12
32
  this.inflightPNLookups = new Map();
@@ -14,23 +34,31 @@ class LIDMappingStore {
14
34
  this.pnToLIDFunc = pnToLIDFunc;
15
35
  this.logger = logger;
16
36
  }
37
+
17
38
  async storeLIDPNMappings(pairs) {
18
- if (pairs.length === 0)
39
+ if (!pairs || pairs.length === 0)
19
40
  return;
20
41
  const validatedPairs = [];
21
42
  for (const { lid, pn } of pairs) {
22
- if (!(((0, index_js_2.isLidUser)(lid) && (0, index_js_2.isPnUser)(pn)) || ((0, index_js_2.isPnUser)(lid) && (0, index_js_2.isLidUser)(pn)))) {
43
+ const lidIsLid = isAnyLidUser(lid);
44
+ const pnIsPn = isAnyPnUser(pn);
45
+ const lidIsPn = isAnyPnUser(lid);
46
+ const pnIsLid = isAnyLidUser(pn);
47
+ if (!((lidIsLid && pnIsPn) || (lidIsPn && pnIsLid))) {
23
48
  this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`);
24
49
  continue;
25
50
  }
26
- const lidDecoded = (0, index_js_2.jidDecode)(lid);
27
- const pnDecoded = (0, index_js_2.jidDecode)(pn);
28
- if (!lidDecoded || !pnDecoded)
51
+ let lidJid = lidIsLid ? lid : pn;
52
+ let pnJid = pnIsPn ? pn : lid;
53
+ const lidDecoded = (0, index_js_2.jidDecode)(lidJid);
54
+ const pnDecoded = (0, index_js_2.jidDecode)(pnJid);
55
+ if (!lidDecoded || !pnDecoded || !lidDecoded.user || !pnDecoded.user)
29
56
  continue;
30
57
  validatedPairs.push({ pnUser: pnDecoded.user, lidUser: lidDecoded.user });
31
58
  }
32
59
  if (validatedPairs.length === 0)
33
60
  return;
61
+
34
62
  const cacheMissSet = new Set();
35
63
  const existingMappings = new Map();
36
64
  for (const { pnUser } of validatedPairs) {
@@ -55,17 +83,21 @@ class LIDMappingStore {
55
83
  }
56
84
  }
57
85
  }
86
+
58
87
  const pairMap = {};
59
88
  for (const { pnUser, lidUser } of validatedPairs) {
60
89
  const existingLidUser = existingMappings.get(pnUser);
61
90
  if (existingLidUser === lidUser) {
62
91
  this.logger.debug({ pnUser, lidUser }, 'LID mapping already exists, skipping');
92
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
93
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
63
94
  continue;
64
95
  }
65
96
  pairMap[pnUser] = lidUser;
66
97
  }
67
98
  if (Object.keys(pairMap).length === 0)
68
99
  return;
100
+
69
101
  this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`);
70
102
  const batchData = {};
71
103
  for (const [pnUser, lidUser] of Object.entries(pairMap)) {
@@ -75,17 +107,19 @@ class LIDMappingStore {
75
107
  await this.keys.transaction(async () => {
76
108
  await this.keys.set({ 'lid-mapping': batchData });
77
109
  }, 'lid-mapping');
78
-
110
+
79
111
  for (const [pnUser, lidUser] of Object.entries(pairMap)) {
80
112
  this.mappingCache.set(`pn:${pnUser}`, lidUser);
81
113
  this.mappingCache.set(`lid:${lidUser}`, pnUser);
82
114
  }
83
115
  }
116
+
84
117
  async getLIDForPN(pn) {
85
118
  return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null;
86
119
  }
120
+
87
121
  async getLIDsForPNs(pns) {
88
- if (pns.length === 0)
122
+ if (!pns || pns.length === 0)
89
123
  return null;
90
124
  const sortedPns = [...new Set(pns)].sort();
91
125
  const cacheKey = sortedPns.join(',');
@@ -103,6 +137,7 @@ class LIDMappingStore {
103
137
  this.inflightLIDLookups.delete(cacheKey);
104
138
  }
105
139
  }
140
+
106
141
  async _getLIDsForPNsImpl(pns) {
107
142
  const usyncFetch = {};
108
143
  const successfulPairs = {};
@@ -113,15 +148,16 @@ class LIDMappingStore {
113
148
  this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`);
114
149
  return false;
115
150
  }
116
-
117
151
  const pnDevice = decoded.device !== undefined ? decoded.device : 0;
118
- const deviceSpecificLid = `${normalizedLidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === 'hosted' ? 'hosted.lid' : 'lid'}`;
152
+ const lidServer = decoded.server === 'hosted' ? 'hosted.lid' : 'lid';
153
+ const deviceSpecificLid = encodeDeviceJid(normalizedLidUser, lidServer, pnDevice);
119
154
  this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`);
120
155
  successfulPairs[pn] = { lid: deviceSpecificLid, pn };
121
156
  return true;
122
157
  };
158
+
123
159
  for (const pn of pns) {
124
- if (!(0, index_js_2.isPnUser)(pn) && !(0, index_js_2.isHostedPnUser)(pn))
160
+ if (!isAnyPnUser(pn))
125
161
  continue;
126
162
  const decoded = (0, index_js_2.jidDecode)(pn);
127
163
  if (!decoded)
@@ -137,6 +173,7 @@ class LIDMappingStore {
137
173
  }
138
174
  pending.push({ pn, pnUser, decoded });
139
175
  }
176
+
140
177
  if (pending.length) {
141
178
  const pnUsers = [...new Set(pending.map(item => item.pnUser))];
142
179
  const stored = await this.keys.get('lid-mapping', pnUsers);
@@ -171,8 +208,9 @@ class LIDMappingStore {
171
208
  }
172
209
  }
173
210
  }
211
+
174
212
  if (Object.keys(usyncFetch).length > 0) {
175
- const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch));
213
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch));
176
214
  if (result && result.length > 0) {
177
215
  await this.storeLIDPNMappings(result);
178
216
  for (const pair of result) {
@@ -183,10 +221,12 @@ class LIDMappingStore {
183
221
  const lidUser = (0, index_js_2.jidDecode)(pair.lid)?.user;
184
222
  if (!lidUser)
185
223
  continue;
186
- for (const device of usyncFetch[pair.pn]) {
187
- const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted.lid' : 'lid'}`;
188
- this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`);
189
- const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted' : 's.whatsapp.net'}`;
224
+ for (const device of usyncFetch[pair.pn] || [0]) {
225
+ const lidServer = device === 99 ? 'hosted.lid' : 'lid';
226
+ const deviceSpecificLid = encodeDeviceJid(lidUser, lidServer, device === 99 ? 0 : device);
227
+ this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid}`);
228
+ const pnServer = device === 99 ? 'hosted' : 's.whatsapp.net';
229
+ const deviceSpecificPn = encodeDeviceJid(pnUser, pnServer, device === 99 ? 0 : device);
190
230
  successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn };
191
231
  }
192
232
  }
@@ -197,11 +237,13 @@ class LIDMappingStore {
197
237
  }
198
238
  return Object.values(successfulPairs).length > 0 ? Object.values(successfulPairs) : null;
199
239
  }
240
+
200
241
  async getPNForLID(lid) {
201
242
  return (await this.getPNsForLIDs([lid]))?.[0]?.pn || null;
202
243
  }
244
+
203
245
  async getPNsForLIDs(lids) {
204
- if (lids.length === 0)
246
+ if (!lids || lids.length === 0)
205
247
  return null;
206
248
  const sortedLids = [...new Set(lids)].sort();
207
249
  const cacheKey = sortedLids.join(',');
@@ -219,21 +261,26 @@ class LIDMappingStore {
219
261
  this.inflightPNLookups.delete(cacheKey);
220
262
  }
221
263
  }
264
+
222
265
  async _getPNsForLIDsImpl(lids) {
223
266
  const successfulPairs = {};
224
267
  const pending = [];
268
+
225
269
  const addResolvedPair = (lid, decoded, pnUser) => {
226
270
  if (!pnUser || typeof pnUser !== 'string') {
227
271
  return false;
228
272
  }
229
- const lidDevice = decoded.device !== undefined ? decoded.device : 0;
230
- const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === index_js_2.WAJIDDomains.HOSTED_LID ? 'hosted' : 's.whatsapp.net'}`;
273
+ const lidDevice = decoded.device !== undefined && decoded.device !== null ? decoded.device : 0;
274
+ const isHosted = decoded.domainType === index_js_2.WAJIDDomains.HOSTED_LID || decoded.server === 'hosted.lid';
275
+ const pnServer = isHosted ? 'hosted' : 's.whatsapp.net';
276
+ const pnJid = encodeDeviceJid(pnUser, pnServer, lidDevice);
231
277
  this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`);
232
278
  successfulPairs[lid] = { lid, pn: pnJid };
233
279
  return true;
234
280
  };
281
+
235
282
  for (const lid of lids) {
236
- if (!(0, index_js_2.isLidUser)(lid))
283
+ if (!isAnyLidUser(lid))
237
284
  continue;
238
285
  const decoded = (0, index_js_2.jidDecode)(lid);
239
286
  if (!decoded)
@@ -246,6 +293,7 @@ class LIDMappingStore {
246
293
  }
247
294
  pending.push({ lid, lidUser, decoded });
248
295
  }
296
+
249
297
  if (pending.length) {
250
298
  const reverseKeys = [...new Set(pending.map(item => `${item.lidUser}_reverse`))];
251
299
  const stored = await this.keys.get('lid-mapping', reverseKeys);
@@ -268,8 +316,6 @@ class LIDMappingStore {
268
316
  }
269
317
  return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null;
270
318
  }
271
-
272
-
273
319
 
274
320
  close() {
275
321
  this.mappingCache.flushAll();
@@ -0,0 +1,278 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LIDMappingStore = void 0;
4
+ const index_js_1 = require("../Addon/index.js");
5
+ const index_js_2 = require("../WABinary/index.js");
6
+ class LIDMappingStore {
7
+ constructor(keys, logger, pnToLIDFunc) {
8
+ this.mappingCache = (0, index_js_1.createCache)({
9
+ ttl: 3 * 24 * 60 * 60
10
+ });
11
+ this.inflightLIDLookups = new Map();
12
+ this.inflightPNLookups = new Map();
13
+ this.keys = keys;
14
+ this.pnToLIDFunc = pnToLIDFunc;
15
+ this.logger = logger;
16
+ }
17
+ async storeLIDPNMappings(pairs) {
18
+ if (pairs.length === 0)
19
+ return;
20
+ const validatedPairs = [];
21
+ for (const { lid, pn } of pairs) {
22
+ if (!(((0, index_js_2.isLidUser)(lid) && (0, index_js_2.isPnUser)(pn)) || ((0, index_js_2.isPnUser)(lid) && (0, index_js_2.isLidUser)(pn)))) {
23
+ this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`);
24
+ continue;
25
+ }
26
+ const lidDecoded = (0, index_js_2.jidDecode)(lid);
27
+ const pnDecoded = (0, index_js_2.jidDecode)(pn);
28
+ if (!lidDecoded || !pnDecoded)
29
+ continue;
30
+ validatedPairs.push({ pnUser: pnDecoded.user, lidUser: lidDecoded.user });
31
+ }
32
+ if (validatedPairs.length === 0)
33
+ return;
34
+ const cacheMissSet = new Set();
35
+ const existingMappings = new Map();
36
+ for (const { pnUser } of validatedPairs) {
37
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
38
+ if (cached) {
39
+ existingMappings.set(pnUser, cached);
40
+ }
41
+ else {
42
+ cacheMissSet.add(pnUser);
43
+ }
44
+ }
45
+ if (cacheMissSet.size > 0) {
46
+ const cacheMisses = [...cacheMissSet];
47
+ this.logger.trace(`Batch fetching ${cacheMisses.length} LID mappings from database`);
48
+ const stored = await this.keys.get('lid-mapping', cacheMisses);
49
+ for (const pnUser of cacheMisses) {
50
+ const existingLidUser = stored[pnUser];
51
+ if (existingLidUser) {
52
+ existingMappings.set(pnUser, existingLidUser);
53
+ this.mappingCache.set(`pn:${pnUser}`, existingLidUser);
54
+ this.mappingCache.set(`lid:${existingLidUser}`, pnUser);
55
+ }
56
+ }
57
+ }
58
+ const pairMap = {};
59
+ for (const { pnUser, lidUser } of validatedPairs) {
60
+ const existingLidUser = existingMappings.get(pnUser);
61
+ if (existingLidUser === lidUser) {
62
+ this.logger.debug({ pnUser, lidUser }, 'LID mapping already exists, skipping');
63
+ continue;
64
+ }
65
+ pairMap[pnUser] = lidUser;
66
+ }
67
+ if (Object.keys(pairMap).length === 0)
68
+ return;
69
+ this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`);
70
+ const batchData = {};
71
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
72
+ batchData[pnUser] = lidUser;
73
+ batchData[`${lidUser}_reverse`] = pnUser;
74
+ }
75
+ await this.keys.transaction(async () => {
76
+ await this.keys.set({ 'lid-mapping': batchData });
77
+ }, 'lid-mapping');
78
+
79
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
80
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
81
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
82
+ }
83
+ }
84
+ async getLIDForPN(pn) {
85
+ return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null;
86
+ }
87
+ async getLIDsForPNs(pns) {
88
+ if (pns.length === 0)
89
+ return null;
90
+ const sortedPns = [...new Set(pns)].sort();
91
+ const cacheKey = sortedPns.join(',');
92
+ const inflight = this.inflightLIDLookups.get(cacheKey);
93
+ if (inflight) {
94
+ this.logger.trace(`Coalescing getLIDsForPNs request for ${sortedPns.length} PNs`);
95
+ return inflight;
96
+ }
97
+ const promise = this._getLIDsForPNsImpl(pns);
98
+ this.inflightLIDLookups.set(cacheKey, promise);
99
+ try {
100
+ return await promise;
101
+ }
102
+ finally {
103
+ this.inflightLIDLookups.delete(cacheKey);
104
+ }
105
+ }
106
+ async _getLIDsForPNsImpl(pns) {
107
+ const usyncFetch = {};
108
+ const successfulPairs = {};
109
+ const pending = [];
110
+ const addResolvedPair = (pn, decoded, lidUser) => {
111
+ const normalizedLidUser = lidUser.toString();
112
+ if (!normalizedLidUser) {
113
+ this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`);
114
+ return false;
115
+ }
116
+
117
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0;
118
+ const deviceSpecificLid = `${normalizedLidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === 'hosted' ? 'hosted.lid' : 'lid'}`;
119
+ this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`);
120
+ successfulPairs[pn] = { lid: deviceSpecificLid, pn };
121
+ return true;
122
+ };
123
+ for (const pn of pns) {
124
+ if (!(0, index_js_2.isPnUser)(pn) && !(0, index_js_2.isHostedPnUser)(pn))
125
+ continue;
126
+ const decoded = (0, index_js_2.jidDecode)(pn);
127
+ if (!decoded)
128
+ continue;
129
+ const pnUser = decoded.user;
130
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
131
+ if (cached && typeof cached === 'string') {
132
+ if (!addResolvedPair(pn, decoded, cached)) {
133
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
134
+ continue;
135
+ }
136
+ continue;
137
+ }
138
+ pending.push({ pn, pnUser, decoded });
139
+ }
140
+ if (pending.length) {
141
+ const pnUsers = [...new Set(pending.map(item => item.pnUser))];
142
+ const stored = await this.keys.get('lid-mapping', pnUsers);
143
+ for (const pnUser of pnUsers) {
144
+ const lidUser = stored[pnUser];
145
+ if (lidUser && typeof lidUser === 'string') {
146
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
147
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
148
+ }
149
+ }
150
+ for (const { pn, pnUser, decoded } of pending) {
151
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
152
+ if (cached && typeof cached === 'string') {
153
+ if (!addResolvedPair(pn, decoded, cached)) {
154
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
155
+ continue;
156
+ }
157
+ }
158
+ else {
159
+ this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`);
160
+ const device = decoded.device || 0;
161
+ let normalizedPn = (0, index_js_2.jidNormalizedUser)(pn);
162
+ if ((0, index_js_2.isHostedPnUser)(normalizedPn)) {
163
+ normalizedPn = `${pnUser}@s.whatsapp.net`;
164
+ }
165
+ if (!usyncFetch[normalizedPn]) {
166
+ usyncFetch[normalizedPn] = [device];
167
+ }
168
+ else {
169
+ usyncFetch[normalizedPn]?.push(device);
170
+ }
171
+ }
172
+ }
173
+ }
174
+ if (Object.keys(usyncFetch).length > 0) {
175
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch));
176
+ if (result && result.length > 0) {
177
+ await this.storeLIDPNMappings(result);
178
+ for (const pair of result) {
179
+ const pnDecoded = (0, index_js_2.jidDecode)(pair.pn);
180
+ const pnUser = pnDecoded?.user;
181
+ if (!pnUser)
182
+ continue;
183
+ const lidUser = (0, index_js_2.jidDecode)(pair.lid)?.user;
184
+ if (!lidUser)
185
+ continue;
186
+ for (const device of usyncFetch[pair.pn]) {
187
+ const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted.lid' : 'lid'}`;
188
+ this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`);
189
+ const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted' : 's.whatsapp.net'}`;
190
+ successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn };
191
+ }
192
+ }
193
+ }
194
+ else {
195
+ this.logger.warn('USync fetch yielded no results for pending PNs');
196
+ }
197
+ }
198
+ return Object.values(successfulPairs).length > 0 ? Object.values(successfulPairs) : null;
199
+ }
200
+ async getPNForLID(lid) {
201
+ return (await this.getPNsForLIDs([lid]))?.[0]?.pn || null;
202
+ }
203
+ async getPNsForLIDs(lids) {
204
+ if (lids.length === 0)
205
+ return null;
206
+ const sortedLids = [...new Set(lids)].sort();
207
+ const cacheKey = sortedLids.join(',');
208
+ const inflight = this.inflightPNLookups.get(cacheKey);
209
+ if (inflight) {
210
+ this.logger.trace(`Coalescing getPNsForLIDs request for ${sortedLids.length} LIDs`);
211
+ return inflight;
212
+ }
213
+ const promise = this._getPNsForLIDsImpl(lids);
214
+ this.inflightPNLookups.set(cacheKey, promise);
215
+ try {
216
+ return await promise;
217
+ }
218
+ finally {
219
+ this.inflightPNLookups.delete(cacheKey);
220
+ }
221
+ }
222
+ async _getPNsForLIDsImpl(lids) {
223
+ const successfulPairs = {};
224
+ const pending = [];
225
+ const addResolvedPair = (lid, decoded, pnUser) => {
226
+ if (!pnUser || typeof pnUser !== 'string') {
227
+ return false;
228
+ }
229
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0;
230
+ const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === index_js_2.WAJIDDomains.HOSTED_LID ? 'hosted' : 's.whatsapp.net'}`;
231
+ this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`);
232
+ successfulPairs[lid] = { lid, pn: pnJid };
233
+ return true;
234
+ };
235
+ for (const lid of lids) {
236
+ if (!(0, index_js_2.isLidUser)(lid))
237
+ continue;
238
+ const decoded = (0, index_js_2.jidDecode)(lid);
239
+ if (!decoded)
240
+ continue;
241
+ const lidUser = decoded.user;
242
+ const cached = this.mappingCache.get(`lid:${lidUser}`);
243
+ if (cached && typeof cached === 'string') {
244
+ addResolvedPair(lid, decoded, cached);
245
+ continue;
246
+ }
247
+ pending.push({ lid, lidUser, decoded });
248
+ }
249
+ if (pending.length) {
250
+ const reverseKeys = [...new Set(pending.map(item => `${item.lidUser}_reverse`))];
251
+ const stored = await this.keys.get('lid-mapping', reverseKeys);
252
+ for (const { lid, lidUser, decoded } of pending) {
253
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`);
254
+ if (!pnUser || typeof pnUser !== 'string') {
255
+ pnUser = stored[`${lidUser}_reverse`];
256
+ if (pnUser && typeof pnUser === 'string') {
257
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
258
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
259
+ }
260
+ }
261
+ if (pnUser && typeof pnUser === 'string') {
262
+ addResolvedPair(lid, decoded, pnUser);
263
+ }
264
+ else {
265
+ this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`);
266
+ }
267
+ }
268
+ }
269
+ return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null;
270
+ }
271
+
272
+
273
+
274
+ close() {
275
+ this.mappingCache.flushAll();
276
+ }
277
+ }
278
+ exports.LIDMappingStore = LIDMappingStore;
@@ -19,9 +19,31 @@ const makeGroupsSocket = (config) => {
19
19
  },
20
20
  content
21
21
  });
22
+
23
+ const storeParticipantLidMappings = async (meta) => {
24
+ try {
25
+ const pairs = [];
26
+ for (const part of meta?.participants || []) {
27
+ if (part.id && part.phoneNumber) {
28
+ pairs.push({ lid: part.id, pn: part.phoneNumber });
29
+ }
30
+ else if (part.id && part.lid) {
31
+ pairs.push({ lid: part.lid, pn: part.id });
32
+ }
33
+ }
34
+ if (pairs.length && sock.signalRepository?.lidMapping?.storeLIDPNMappings) {
35
+ await sock.signalRepository.lidMapping.storeLIDPNMappings(pairs);
36
+ }
37
+ }
38
+ catch (err) {
39
+ // non-fatal
40
+ }
41
+ };
22
42
  const groupMetadata = async (jid) => {
23
43
  const result = await groupQuery(jid, 'get', [{ tag: 'query', attrs: { request: 'interactive' } }]);
24
- return (0, exports.extractGroupMetadata)(result);
44
+ const meta = (0, exports.extractGroupMetadata)(result);
45
+ await storeParticipantLidMappings(meta);
46
+ return meta;
25
47
  };
26
48
  const groupFetchAllParticipating = async () => {
27
49
  const result = await query({
@@ -53,6 +75,7 @@ const makeGroupsSocket = (config) => {
53
75
  content: [groupNode]
54
76
  });
55
77
  data[meta.id] = meta;
78
+ await storeParticipantLidMappings(meta);
56
79
  }
57
80
  }
58
81
 
@@ -1284,15 +1284,28 @@ const makeMessagesRecvSocket = (config) => {
1284
1284
  if (!!alt) {
1285
1285
  const altServer = (0, index_js_6.jidDecode)(alt)?.server;
1286
1286
  const primaryJid = msg.key.participant || msg.key.remoteJid;
1287
- if (altServer === 'lid') {
1288
- if (!(await signalRepository.lidMapping.getPNForLID(alt))) {
1287
+ const isAltLid = altServer === 'lid' || altServer === 'hosted.lid';
1288
+ const isPrimaryLid = (0, index_js_6.isLidUser)(primaryJid) || (typeof index_js_6.isHostedLidUser === 'function' && (0, index_js_6.isHostedLidUser)(primaryJid));
1289
+ try {
1290
+ if (isAltLid && primaryJid && !(0, index_js_6.isLidUser)(primaryJid) && !(typeof index_js_6.isHostedLidUser === 'function' && (0, index_js_6.isHostedLidUser)(primaryJid))) {
1289
1291
  await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
1290
- await signalRepository.migrateSession(primaryJid, alt);
1292
+ await signalRepository.migrateSession(primaryJid, alt).catch(() => {});
1293
+ try { ev.emit('lid-mapping.update', { lid: alt, pn: primaryJid }); } catch {}
1291
1294
  }
1292
- }
1293
- else {
1294
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
1295
- await signalRepository.migrateSession(alt, primaryJid);
1295
+ else if (!isAltLid && isPrimaryLid) {
1296
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
1297
+ await signalRepository.migrateSession(alt, primaryJid).catch(() => {});
1298
+ try { ev.emit('lid-mapping.update', { lid: primaryJid, pn: alt }); } catch {}
1299
+ }
1300
+ else if (isAltLid) {
1301
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: alt, pn: primaryJid }]);
1302
+ }
1303
+ else {
1304
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid: primaryJid, pn: alt }]);
1305
+ await signalRepository.migrateSession(alt, primaryJid).catch(() => {});
1306
+ }
1307
+ } catch (mapErr) {
1308
+ logger?.debug?.({ mapErr, alt, primaryJid }, 'lid mapping store failed');
1296
1309
  }
1297
1310
  }
1298
1311
  await messageMutex.mutex(async () => {
@@ -72,7 +72,7 @@ exports.isJidMetaAI = isJidMetaAI;
72
72
  const isPnUser = (jid) => jid?.endsWith('@s.whatsapp.net');
73
73
  exports.isPnUser = isPnUser;
74
74
 
75
- const isLidUser = (jid) => jid?.endsWith('@lid');
75
+ const isLidUser = (jid) => typeof jid === 'string' && (jid.endsWith('@lid') || jid.endsWith('@hosted.lid'));
76
76
  exports.isLidUser = isLidUser;
77
77
 
78
78
  const isJidBroadcast = (jid) => jid?.endsWith('@broadcast');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kage-baileys",
3
- "version": "25.3.18",
3
+ "version": "25.3.19",
4
4
  "description": "Kage Baileys full merge — Builders + mbuilder + Framework + advanced sticker packs + KAGE pairing + extended WAProto. Multi-device ready. FIXED: all core modules deduplicated, removed third-party libsignal-node fork.",
5
5
  "keywords": [
6
6
  "kage-baileys",
@@ -1,7 +0,0 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "compilerOptions": {
4
- "noEmit": true,
5
- "skipLibCheck": true
6
- }
7
- }
package/tsconfig.json DELETED
@@ -1,28 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2022",
4
- "module": "NodeNext",
5
- "moduleResolution": "NodeNext",
6
- "lib": ["ES2022"],
7
- "strict": false,
8
- "noEmit": true,
9
- "skipLibCheck": true,
10
- "esModuleInterop": true,
11
- "resolveJsonModule": true,
12
- "allowJs": true,
13
- "checkJs": false,
14
- "forceConsistentCasingInFileNames": true,
15
- "types": ["node"]
16
- },
17
- "include": [
18
- "lib/**/*.d.ts",
19
- "lib/index.js",
20
- "test/**/*.ts",
21
- "test/**/*.js"
22
- ],
23
- "exclude": [
24
- "node_modules",
25
- "maintenance",
26
- "Example"
27
- ]
28
- }