amiudmodz 6.2.7 → 6.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/lib/Socket/business.d.ts +6 -1
  2. package/lib/Socket/business.d.ts.map +1 -1
  3. package/lib/Socket/communities.d.ts +6 -1
  4. package/lib/Socket/communities.d.ts.map +1 -1
  5. package/lib/Socket/index.d.ts.map +1 -1
  6. package/lib/Socket/index.js +17 -4
  7. package/lib/Socket/index.js.map +1 -1
  8. package/lib/Socket/messages-recv.d.ts +6 -1
  9. package/lib/Socket/messages-recv.d.ts.map +1 -1
  10. package/lib/Socket/messages-send.d.ts +6 -1
  11. package/lib/Socket/messages-send.d.ts.map +1 -1
  12. package/lib/Socket/messages-send.js +85 -21
  13. package/lib/Socket/messages-send.js.map +1 -1
  14. package/lib/Socket/newsletter.d.ts.map +1 -1
  15. package/lib/Socket/newsletter.js +4 -5
  16. package/lib/Socket/newsletter.js.map +1 -1
  17. package/lib/Utils/baileys-event-stream.js +0 -0
  18. package/lib/Utils/crypto.d.ts.map +1 -1
  19. package/lib/Utils/crypto.js +6 -7
  20. package/lib/Utils/crypto.js.map +1 -1
  21. package/lib/VoIP/audio-feeder.d.ts +42 -4
  22. package/lib/VoIP/audio-feeder.d.ts.map +1 -1
  23. package/lib/VoIP/audio-feeder.js +252 -128
  24. package/lib/VoIP/audio-feeder.js.map +1 -1
  25. package/lib/VoIP/index.d.ts +91 -8
  26. package/lib/VoIP/index.d.ts.map +1 -1
  27. package/lib/VoIP/index.js +834 -184
  28. package/lib/VoIP/index.js.map +1 -1
  29. package/lib/VoIP/relay-transport.d.ts +26 -1
  30. package/lib/VoIP/relay-transport.d.ts.map +1 -1
  31. package/lib/VoIP/relay-transport.js +257 -181
  32. package/lib/VoIP/relay-transport.js.map +1 -1
  33. package/lib/VoIP/signaling.d.ts +57 -3
  34. package/lib/VoIP/signaling.d.ts.map +1 -1
  35. package/lib/VoIP/signaling.js +791 -328
  36. package/lib/VoIP/signaling.js.map +1 -1
  37. package/lib/VoIP/types.d.ts +12 -11
  38. package/lib/VoIP/types.d.ts.map +1 -1
  39. package/lib/VoIP/types.js +4 -9
  40. package/lib/VoIP/types.js.map +1 -1
  41. package/lib/VoIP/video-feeder.d.ts +53 -0
  42. package/lib/VoIP/video-feeder.d.ts.map +1 -0
  43. package/lib/VoIP/video-feeder.js +269 -0
  44. package/lib/VoIP/video-feeder.js.map +1 -0
  45. package/lib/VoIP/wasm-engine.d.ts +10 -2
  46. package/lib/VoIP/wasm-engine.d.ts.map +1 -1
  47. package/lib/VoIP/wasm-engine.js +179 -71
  48. package/lib/VoIP/wasm-engine.js.map +1 -1
  49. package/lib/VoIP/worker-bootstrap.js +29 -51
  50. package/lib/VoIP/worker-bootstrap.js.map +1 -1
  51. package/lib/WABinary/decode.d.ts.map +1 -1
  52. package/lib/WABinary/decode.js +10 -0
  53. package/lib/WABinary/decode.js.map +1 -1
  54. package/lib/WABinary/encode.d.ts.map +1 -1
  55. package/lib/WABinary/encode.js +10 -0
  56. package/lib/WABinary/encode.js.map +1 -1
  57. package/lib/WABinary/jid-utils.d.ts.map +1 -1
  58. package/lib/WABinary/jid-utils.js +18 -17
  59. package/lib/WABinary/jid-utils.js.map +1 -1
  60. package/lib/assets/wasm/README.md +76 -0
  61. package/lib/assets/wasm/loader.js +0 -1
  62. package/lib/assets/wasm/loader.js.map +1 -1
  63. package/lib/assets/wasm/worker-modules.js +0 -1
  64. package/lib/assets/wasm/worker-modules.js.map +1 -1
  65. package/lib/index.d.ts +1 -0
  66. package/lib/index.d.ts.map +1 -1
  67. package/lib/index.js +1 -0
  68. package/lib/index.js.map +1 -1
  69. package/package.json +146 -142
@@ -1,34 +1,57 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _SignalingBridge_sock, _SignalingBridge_voip, _SignalingBridge_observedTcTokens, _SignalingBridge_pendingTcTokenWaiters, _SignalingBridge_ensuredSignalSessions, _SignalingBridge_remoteDevicePeerByCallId, _SignalingBridge_remoteObfuscatedPeerByCallId, _SignalingBridge_remoteXmppRoutePeerByCallId, _SignalingBridge_incomingCallPeerById, _SignalingBridge_outgoingSignalingQueue, _SignalingBridge_incomingSignalingQueue, _SignalingBridge_doSendSignaling, _SignalingBridge_sendCallStanza, _SignalingBridge_doProcessIncomingCall, _SignalingBridge_doProcessIncomingReceipt, _SignalingBridge_maybeDecryptEnc, _SignalingBridge_encryptCallKey, _SignalingBridge_ensureSignalSessions, _SignalingBridge_appendDeviceIdentity, _SignalingBridge_toBareJid, _SignalingBridge_toCallDeviceJid, _SignalingBridge_toPrimaryDeviceJid, _SignalingBridge_hasConcreteDevice, _SignalingBridge_preferDeviceRouteJid, _SignalingBridge_preferOrderedRouteJid, _SignalingBridge_pickConcreteRouteHint, _SignalingBridge_resolveOutboundPeerJid, _SignalingBridge_expandSignalSessionTargets, _SignalingBridge_normalizeStartCallPeerList, _SignalingBridge_rememberTcToken, _SignalingBridge_getTcToken;
13
- import { decodeBinaryNode } from '../WABinary/decode.js';
14
- import { encodeBinaryNode } from '../WABinary/encode.js';
15
- import { getBinaryNodeChild, getAllBinaryNodeChildren } from '../WABinary/generic-utils.js';
16
- import { jidDecode, jidEncode, jidNormalizedUser } from '../WABinary/jid-utils.js';
17
- import { encodeWAMessage, unpadRandomMax16 } from '../Utils/generics.js';
18
- import { parseAndInjectE2ESessions } from '../Utils/signal.js';
19
- import { encodeSignedDeviceIdentity } from '../Utils/validate-connection.js';
20
- import { proto } from '../../WAProto/index.js';
21
1
  const S_WHATSAPP_NET = "@s.whatsapp.net";
22
- const TC_TOKEN_REQUEST_TIMEOUT_MS = 3500;
2
+ const TC_TOKEN_REQUEST_TIMEOUT_MS = 15000;
23
3
  const SESSION_CACHE_TTL_MS = 5 * 60000;
24
4
  const ACK_TIMEOUT_MS = 15000;
25
- const getNodeChildren = (node) => Array.isArray(node.content) ? node.content : [];
5
+ let _baileysModule = null;
6
+ const loadBaileys = async () => {
7
+ if (_baileysModule)
8
+ return _baileysModule;
9
+ try {
10
+ _baileysModule = await import("../index.js");
11
+ return _baileysModule;
12
+ }
13
+ catch {
14
+ try {
15
+ _baileysModule = await import("../index.js");
16
+ return _baileysModule;
17
+ }
18
+ catch {
19
+ try {
20
+ const binaryDecode = await import('../WABinary/decode.js');
21
+ const binaryEncode = await import('../WABinary/encode.js');
22
+ const binaryGeneric = await import('../WABinary/generic-utils.js');
23
+ const binaryJid = await import('../WABinary/jid-utils.js');
24
+ const utilsGenerics = await import('../Utils/generics.js');
25
+ const utilsSignal = await import('../Utils/signal.js');
26
+ const utilsValidate = await import('../Utils/validate-connection.js');
27
+ const waProto = await import('../../WAProto/index.js');
28
+ const waSync = await import('../WAUSync/index.js');
29
+ _baileysModule = {
30
+ ...binaryDecode,
31
+ ...binaryEncode,
32
+ ...binaryGeneric,
33
+ ...binaryJid,
34
+ ...utilsGenerics,
35
+ ...utilsSignal,
36
+ ...utilsValidate,
37
+ ...waProto,
38
+ ...waSync,
39
+ };
40
+ return _baileysModule;
41
+ }
42
+ catch (err) {
43
+ throw new Error("Could not import internal Baileys module: " + (err?.message || err));
44
+ }
45
+ }
46
+ }
47
+ };
48
+ const getNodeChildren = node => Array.isArray(node.content) ? node.content : [];
26
49
  const setNodeChildren = (node, children) => {
27
50
  node.content = children.length ? children : undefined;
28
51
  };
29
52
  const replaceNodeChild = (node, tag, nextChild) => {
30
53
  const children = getNodeChildren(node);
31
- const index = children.findIndex((c) => c.tag === tag);
54
+ const index = children.findIndex(child => child.tag === tag);
32
55
  if (index >= 0)
33
56
  children[index] = nextChild;
34
57
  else
@@ -36,7 +59,7 @@ const replaceNodeChild = (node, tag, nextChild) => {
36
59
  setNodeChildren(node, children);
37
60
  };
38
61
  const removeNodeChildrenByTag = (node, tag) => {
39
- setNodeChildren(node, getNodeChildren(node).filter((c) => c.tag !== tag));
62
+ setNodeChildren(node, getNodeChildren(node).filter(child => child.tag !== tag));
40
63
  };
41
64
  const parseCountAttr = (value, fallback = 0) => {
42
65
  const parsed = Number(value);
@@ -44,131 +67,417 @@ const parseCountAttr = (value, fallback = 0) => {
44
67
  };
45
68
  export class SignalingBridge {
46
69
  constructor(config) {
47
- _SignalingBridge_sock.set(this, void 0);
48
- _SignalingBridge_voip.set(this, null);
49
- _SignalingBridge_observedTcTokens.set(this, new Map());
50
- _SignalingBridge_pendingTcTokenWaiters.set(this, new Map());
51
- _SignalingBridge_ensuredSignalSessions.set(this, new Map());
52
- _SignalingBridge_remoteDevicePeerByCallId.set(this, new Map());
53
- _SignalingBridge_remoteObfuscatedPeerByCallId.set(this, new Map());
54
- _SignalingBridge_remoteXmppRoutePeerByCallId.set(this, new Map());
55
- _SignalingBridge_incomingCallPeerById.set(this, new Map());
56
- _SignalingBridge_outgoingSignalingQueue.set(this, Promise.resolve(undefined));
57
- _SignalingBridge_incomingSignalingQueue.set(this, Promise.resolve(undefined));
58
- this.attachEngine = (voip) => {
59
- __classPrivateFieldSet(this, _SignalingBridge_voip, voip, "f");
70
+ this._sock = config.sock;
71
+ this._log = typeof config.logger === 'function'
72
+ ? config.logger
73
+ : config.debug ? (...args) => console.log(...args) : () => { };
74
+ this.setSocket = socket => {
75
+ this._sock = socket;
76
+ };
77
+ this._baileys = null;
78
+ this._voip = null;
79
+ this._observedTcTokens = new Map();
80
+ this._pendingTcTokenWaiters = new Map();
81
+ this._ensuredSignalSessions = new Map();
82
+ this._remoteDevicePeerByCallId = new Map();
83
+ this._remoteObfuscatedPeerByCallId = new Map();
84
+ this._remoteXmppRoutePeerByCallId = new Map();
85
+ this._incomingCallPeerById = new Map();
86
+ this._outgoingSignalingQueue = Promise.resolve(undefined);
87
+ this._incomingSignalingQueue = Promise.resolve(undefined);
88
+ this.attachEngine = voip => {
89
+ this._voip = voip;
60
90
  };
61
91
  this.init = async () => {
62
- const originalKeysSet = __classPrivateFieldGet(this, _SignalingBridge_sock, "f").authState.keys.set.bind(__classPrivateFieldGet(this, _SignalingBridge_sock, "f").authState.keys);
63
- __classPrivateFieldGet(this, _SignalingBridge_sock, "f").authState.keys.set = async (data) => {
64
- const result = await originalKeysSet(data);
65
- for (const [jid, entry] of Object.entries(data?.tctoken ?? {})) {
66
- if (entry?.token instanceof Uint8Array && entry.token.length > 0) {
67
- __classPrivateFieldGet(this, _SignalingBridge_rememberTcToken, "f").call(this, jid, entry.token, entry.timestamp);
92
+ this._baileys = await loadBaileys();
93
+ if (this._sock.authState?.keys?.set) {
94
+ const originalKeysSet = this._sock.authState.keys.set.bind(this._sock.authState.keys);
95
+ this._sock.authState.keys.set = async (data) => {
96
+ const result = await originalKeysSet(data);
97
+ for (const [jid, entry] of Object.entries(data?.tctoken ?? {})) {
98
+ if (entry?.token instanceof Uint8Array && entry.token.length > 0) {
99
+ this._rememberTcToken(jid, entry.token, entry.timestamp);
100
+ }
68
101
  }
69
- }
70
- return result;
71
- };
102
+ return result;
103
+ };
104
+ }
105
+ if (this._sock.ev?.on) {
106
+ this._sock.ev.on("chats.update", updates => {
107
+ for (const update of updates || []) {
108
+ if (update?.id && update?.tcToken instanceof Uint8Array && update.tcToken.length > 0) {
109
+ this._log("[RTC TC TOKEN FROM CHATS.UPDATE]", {
110
+ jid: update.id,
111
+ length: update.tcToken.length
112
+ });
113
+ this._rememberTcToken(update.id, update.tcToken, String(Math.floor(Date.now() / 1000)));
114
+ }
115
+ }
116
+ });
117
+ }
118
+ if (this._sock.ws?.on) {
119
+ const handlePrivacyNotification = node => {
120
+ try {
121
+ if (node?.attrs?.type !== "privacy_token")
122
+ return;
123
+ this._processPrivacyTokenNotification(node);
124
+ }
125
+ catch (err) {
126
+ this._log("[RTC RAW PRIVACY TOKEN ERROR]", err?.message || err);
127
+ }
128
+ };
129
+ this._sock.ws.on("CB:notification,type:privacy_token", handlePrivacyNotification);
130
+ this._sock.ws.on("CB:notification", handlePrivacyNotification);
131
+ }
72
132
  };
73
133
  this.sendSignaling = (peerJid, callId, xmlPayload) => {
74
- __classPrivateFieldSet(this, _SignalingBridge_outgoingSignalingQueue, __classPrivateFieldGet(this, _SignalingBridge_outgoingSignalingQueue, "f")
75
- .then(() => __classPrivateFieldGet(this, _SignalingBridge_doSendSignaling, "f").call(this, peerJid, callId, xmlPayload))
76
- .catch(() => { }), "f");
134
+ this._outgoingSignalingQueue = this._outgoingSignalingQueue
135
+ .then(() => this._doSendSignaling(peerJid, callId, xmlPayload))
136
+ .catch(err => {
137
+ this._log("[RTC SIGNALING ERROR]", err?.stack || err?.message || err);
138
+ });
77
139
  };
78
140
  this.processIncomingCall = (node, voip, activeCallId) => {
79
- __classPrivateFieldSet(this, _SignalingBridge_incomingSignalingQueue, __classPrivateFieldGet(this, _SignalingBridge_incomingSignalingQueue, "f")
80
- .then(() => __classPrivateFieldGet(this, _SignalingBridge_doProcessIncomingCall, "f").call(this, node, voip, activeCallId))
81
- .catch(() => { }), "f");
141
+ this._incomingSignalingQueue = this._incomingSignalingQueue
142
+ .then(() => {
143
+ if (!voip || (typeof voip.isInitialized === "function" && !voip.isInitialized()))
144
+ return;
145
+ return this._doProcessIncomingCall(node, voip, activeCallId);
146
+ })
147
+ .catch(err => {
148
+ this._log("[RTC INCOMING CALL ERROR]", err?.stack || err?.message || err);
149
+ });
82
150
  };
83
151
  this.processIncomingReceipt = (node, voip, activeCallId) => {
84
- __classPrivateFieldSet(this, _SignalingBridge_incomingSignalingQueue, __classPrivateFieldGet(this, _SignalingBridge_incomingSignalingQueue, "f")
85
- .then(() => __classPrivateFieldGet(this, _SignalingBridge_doProcessIncomingReceipt, "f").call(this, node, voip, activeCallId))
86
- .catch(() => { }), "f");
152
+ this._incomingSignalingQueue = this._incomingSignalingQueue
153
+ .then(() => {
154
+ if (!voip || (typeof voip.isInitialized === "function" && !voip.isInitialized()))
155
+ return;
156
+ return this._doProcessIncomingReceipt(node, voip, activeCallId);
157
+ })
158
+ .catch(err => {
159
+ this._log("[RTC INCOMING RECEIPT ERROR]", err?.stack || err?.message || err);
160
+ });
87
161
  };
88
162
  this.requestTcToken = async (jid) => {
89
- const userJid = __classPrivateFieldGet(this, _SignalingBridge_toBareJid, "f").call(this, jid);
90
- const cached = await __classPrivateFieldGet(this, _SignalingBridge_getTcToken, "f").call(this, userJid);
163
+ const userJid = this._toBareJid(jid);
164
+ const cached = await this._getTcToken(userJid);
91
165
  if (cached?.length)
92
166
  return cached;
93
- try {
94
- const response = await __classPrivateFieldGet(this, _SignalingBridge_sock, "f").getPrivacyTokens([userJid]);
95
- const tokensNode = getBinaryNodeChild(response, "tokens") ??
96
- getBinaryNodeChild(getBinaryNodeChild(response, "iq"), "tokens");
97
- const tokenNodes = tokensNode
98
- ? getAllBinaryNodeChildren(tokensNode).filter((c) => c.tag === "token")
99
- : [];
167
+ const waiter = this._waitForTcToken(userJid, TC_TOKEN_REQUEST_TIMEOUT_MS);
168
+ const logResponse = (label, response) => {
169
+ this._log(`[RTC TC TOKEN RESPONSE:${label}]`, JSON.stringify(response, (key, value) => {
170
+ if (value instanceof Uint8Array || Buffer.isBuffer(value)) {
171
+ return `<buffer:${value.length}>`;
172
+ }
173
+ return value;
174
+ }, 2));
175
+ };
176
+ const tryReadResponse = async (label, response) => {
177
+ logResponse(label, response);
178
+ const tokenNodes = this._findTcTokenNodes(response);
100
179
  for (const tokenNode of tokenNodes) {
101
- const tokenJid = String(tokenNode.attrs.jid ?? "");
102
- if (jidNormalizedUser(tokenJid) !== jidNormalizedUser(userJid))
103
- continue;
104
- const content = tokenNode.content;
180
+ const content = tokenNode?.content;
105
181
  if (content instanceof Uint8Array && content.length > 0) {
106
182
  const token = Buffer.from(content);
107
- await __classPrivateFieldGet(this, _SignalingBridge_sock, "f").authState.keys.set({
108
- tctoken: { [userJid]: { token, timestamp: String(tokenNode.attrs.t ?? "") } },
109
- });
183
+ const timestamp = String(tokenNode.attrs?.t ?? Math.floor(Date.now() / 1000));
184
+ await this._storeTcToken(userJid, token, timestamp);
110
185
  return token;
111
186
  }
112
187
  }
188
+ return null;
189
+ };
190
+ const attempts = [];
191
+ if (typeof this._sock.getPrivacyTokens === "function") {
192
+ attempts.push({
193
+ label: "getPrivacyTokens",
194
+ run: () => this._sock.getPrivacyTokens([userJid])
195
+ });
113
196
  }
114
- catch { }
115
- return __classPrivateFieldGet(this, _SignalingBridge_getTcToken, "f").call(this, userJid);
197
+ attempts.push({
198
+ label: "privacy-set-with-t",
199
+ run: () => this._sock.query({
200
+ tag: "iq",
201
+ attrs: {
202
+ to: S_WHATSAPP_NET,
203
+ type: "set",
204
+ xmlns: "privacy",
205
+ id: this._sock.generateMessageTag()
206
+ },
207
+ content: [
208
+ {
209
+ tag: "tokens",
210
+ attrs: {},
211
+ content: [
212
+ {
213
+ tag: "token",
214
+ attrs: {
215
+ jid: userJid,
216
+ t: String(Math.floor(Date.now() / 1000)),
217
+ type: "trusted_contact"
218
+ }
219
+ }
220
+ ]
221
+ }
222
+ ]
223
+ })
224
+ });
225
+ attempts.push({
226
+ label: "privacy-set-no-t",
227
+ run: () => this._sock.query({
228
+ tag: "iq",
229
+ attrs: {
230
+ to: S_WHATSAPP_NET,
231
+ type: "set",
232
+ xmlns: "privacy",
233
+ id: this._sock.generateMessageTag()
234
+ },
235
+ content: [
236
+ {
237
+ tag: "tokens",
238
+ attrs: {},
239
+ content: [
240
+ {
241
+ tag: "token",
242
+ attrs: {
243
+ jid: userJid,
244
+ type: "trusted_contact"
245
+ }
246
+ }
247
+ ]
248
+ }
249
+ ]
250
+ })
251
+ });
252
+ for (const attempt of attempts) {
253
+ try {
254
+ const response = await attempt.run();
255
+ const token = await tryReadResponse(attempt.label, response);
256
+ if (token?.length)
257
+ return token;
258
+ }
259
+ catch (err) {
260
+ this._log(`[RTC TC TOKEN REQUEST ERROR:${attempt.label}]`, err?.stack || err?.message || err);
261
+ }
262
+ const stored = await this._getTcToken(userJid);
263
+ if (stored?.length)
264
+ return stored;
265
+ const waited = await Promise.race([
266
+ waiter,
267
+ new Promise(resolve => setTimeout(() => resolve(undefined), 2500))
268
+ ]);
269
+ if (waited?.length)
270
+ return waited;
271
+ }
272
+ const waited = await waiter;
273
+ if (waited?.length)
274
+ return waited;
275
+ return this._getTcToken(userJid);
116
276
  };
117
277
  this.ensureTcToken = async (...jids) => {
118
278
  const uniqueJids = [
119
- ...new Set(jids.map((j) => __classPrivateFieldGet(this, _SignalingBridge_toBareJid, "f").call(this, String(j ?? "").trim())).filter(Boolean)),
279
+ ...new Set(jids.map(jid => this._toBareJid(String(jid ?? "").trim())).filter(Boolean))
120
280
  ];
121
281
  for (const jid of uniqueJids) {
122
- const cached = await __classPrivateFieldGet(this, _SignalingBridge_getTcToken, "f").call(this, jid);
282
+ const cached = await this._getTcToken(jid);
123
283
  if (cached?.length)
124
284
  return cached;
125
285
  }
126
286
  for (const jid of uniqueJids) {
127
- const fetched = await Promise.race([
128
- this.requestTcToken(jid),
129
- new Promise((r) => setTimeout(() => r(undefined), TC_TOKEN_REQUEST_TIMEOUT_MS)),
130
- ]);
287
+ const fetched = await this.requestTcToken(jid);
131
288
  if (fetched?.length)
132
289
  return fetched;
133
290
  }
134
291
  return undefined;
135
292
  };
136
- this.discoverPeerDevices = async (peerLidJid) => {
137
- const devices = await __classPrivateFieldGet(this, _SignalingBridge_sock, "f").getUSyncDevices([peerLidJid], true, false);
138
- return __classPrivateFieldGet(this, _SignalingBridge_normalizeStartCallPeerList, "f").call(this, devices.map((d) => d.jid).filter(Boolean));
293
+ this.discoverPeerDevices = async (peerJid) => {
294
+ const bareJid = this._toBareJid(peerJid);
295
+ const { jidDecode } = this._baileys;
296
+ const decoded = jidDecode(bareJid);
297
+ if (!decoded?.user)
298
+ return [bareJid];
299
+ const server = bareJid.endsWith("@lid") ? "lid" : "s.whatsapp.net";
300
+ const attempts = [
301
+ [bareJid, false, false],
302
+ [bareJid, true, false],
303
+ [bareJid, false, true],
304
+ [bareJid, true, true]
305
+ ];
306
+ for (const [jid, useCache, ignoreZeroDevices] of attempts) {
307
+ try {
308
+ const devices = await this._sock.getUSyncDevices?.([jid], useCache, ignoreZeroDevices);
309
+ const jids = [];
310
+ for (const device of devices || []) {
311
+ if (!device)
312
+ continue;
313
+ if (typeof device === "string") {
314
+ jids.push(device);
315
+ continue;
316
+ }
317
+ if (device.jid) {
318
+ jids.push(device.jid);
319
+ continue;
320
+ }
321
+ const user = device.user || decoded.user;
322
+ const dev = device.device;
323
+ if (user && dev !== undefined && dev !== null) {
324
+ jids.push(`${user}:${dev}@${server}`);
325
+ }
326
+ }
327
+ const list = this._normalizeStartCallPeerList(jids);
328
+ if (list.length) {
329
+ this._log("[RTC DEVICES]", { peerJid: bareJid, list });
330
+ return list;
331
+ }
332
+ }
333
+ catch (err) {
334
+ this._log("[RTC DEVICES ERROR]", err?.message || err);
335
+ }
336
+ }
337
+ const fallback = [`${decoded.user}:0@${server}`];
338
+ this._log("[RTC DEVICES FALLBACK]", { peerJid: bareJid, fallback });
339
+ return fallback;
139
340
  };
140
341
  this.ensureSessionsForPeers = async (jids) => {
141
- const targets = __classPrivateFieldGet(this, _SignalingBridge_expandSignalSessionTargets, "f").call(this, jids);
342
+ const targets = this._expandSignalSessionTargets(jids);
142
343
  if (targets.length)
143
- await __classPrivateFieldGet(this, _SignalingBridge_ensureSignalSessions, "f").call(this, targets, true);
344
+ await this._ensureSignalSessions(targets, true);
345
+ };
346
+ this.resolveLid = async (jid) => {
347
+ const bare = this._toBareJid(String(jid || "").trim());
348
+ if (!bare)
349
+ return undefined;
350
+ if (bare.endsWith("@lid"))
351
+ return bare;
352
+ try {
353
+ const mapped = await this._sock.signalRepository?.lidMapping?.getLIDForPN?.(bare);
354
+ if (mapped)
355
+ return this._toBareJid(mapped);
356
+ }
357
+ catch { }
358
+ try {
359
+ const stored = await this._getStoredLidForPn(bare);
360
+ if (stored)
361
+ return stored;
362
+ }
363
+ catch { }
364
+ const resolved = await this._resolveLidViaUSync(bare);
365
+ if (resolved) {
366
+ await this._storeLidPnMapping(resolved, bare);
367
+ return resolved;
368
+ }
369
+ return undefined;
144
370
  };
145
- this.resolveLid = async (pnJid) => __classPrivateFieldGet(this, _SignalingBridge_sock, "f").signalRepository.lidMapping?.getLIDForPN(pnJid);
146
371
  this.issueTcToken = async (jid) => {
147
- const userJid = __classPrivateFieldGet(this, _SignalingBridge_toBareJid, "f").call(this, jid);
372
+ const userJid = this._toBareJid(jid);
148
373
  const issuedAt = Math.floor(Date.now() / 1000);
149
374
  try {
150
- await __classPrivateFieldGet(this, _SignalingBridge_sock, "f").query({
375
+ await this._sock.query({
151
376
  tag: "iq",
152
377
  attrs: {
153
- to: S_WHATSAPP_NET, type: "set", xmlns: "privacy",
154
- id: __classPrivateFieldGet(this, _SignalingBridge_sock, "f").generateMessageTag(),
378
+ to: S_WHATSAPP_NET,
379
+ type: "set",
380
+ xmlns: "privacy",
381
+ id: this._sock.generateMessageTag()
155
382
  },
156
- content: [{
157
- tag: "tokens", attrs: {},
158
- content: [{
383
+ content: [
384
+ {
385
+ tag: "tokens",
386
+ attrs: {},
387
+ content: [
388
+ {
159
389
  tag: "token",
160
- attrs: { jid: userJid, t: String(issuedAt), type: "trusted_contact" },
161
- }],
162
- }],
390
+ attrs: {
391
+ jid: userJid,
392
+ t: String(issuedAt),
393
+ type: "trusted_contact"
394
+ }
395
+ }
396
+ ]
397
+ }
398
+ ]
163
399
  });
164
400
  return true;
165
401
  }
166
- catch {
402
+ catch (err) {
403
+ this._log("[RTC ISSUE TC TOKEN ERROR]", err?.message || err);
167
404
  return false;
168
405
  }
169
406
  };
170
- this.getRemoteDeviceJid = (callId) => __classPrivateFieldGet(this, _SignalingBridge_remoteDevicePeerByCallId, "f").get(callId);
171
- _SignalingBridge_doSendSignaling.set(this, async (peerJid, callId, xmlPayload) => {
407
+ this.getRemoteDeviceJid = callId => this._remoteDevicePeerByCallId.get(callId);
408
+ this._resolveLidViaUSync = async (pnJid) => {
409
+ if (typeof this._sock.executeUSyncQuery !== "function")
410
+ return undefined;
411
+ const { USyncQuery, USyncUser } = this._baileys;
412
+ if (!USyncQuery || !USyncUser)
413
+ return undefined;
414
+ const query = new USyncQuery()
415
+ .withContext("message")
416
+ .withLIDProtocol();
417
+ query.withUser(new USyncUser().withId(pnJid));
418
+ try {
419
+ const result = await this._sock.executeUSyncQuery(query);
420
+ const row = (result?.list || []).find(item => item?.id === pnJid || item?.lid);
421
+ const lid = this._normalizeLid(row?.lid);
422
+ if (lid) {
423
+ this._log("[RTC LID RESOLVED]", { pn: pnJid, lid });
424
+ return lid;
425
+ }
426
+ }
427
+ catch (err) {
428
+ this._log("[RTC RESOLVE LID USYNC ERROR]", err?.message || err);
429
+ }
430
+ return undefined;
431
+ };
432
+ this._normalizeLid = value => {
433
+ const raw = String(value || "").trim();
434
+ if (!raw)
435
+ return undefined;
436
+ if (raw.endsWith("@lid"))
437
+ return this._toBareJid(raw);
438
+ if (raw.endsWith("@hosted.lid"))
439
+ return this._toBareJid(raw);
440
+ if (/^\d+$/.test(raw))
441
+ return `${raw}@lid`;
442
+ return raw.includes("@") ? this._toBareJid(raw) : `${raw}@lid`;
443
+ };
444
+ this._getStoredLidForPn = async (pnJid) => {
445
+ const decoded = this._baileys.jidDecode(pnJid);
446
+ if (!decoded?.user || !this._sock.authState?.keys?.get)
447
+ return undefined;
448
+ const stored = await this._sock.authState.keys.get("lid-mapping", [decoded.user]);
449
+ const lidUser = stored?.[decoded.user];
450
+ if (!lidUser)
451
+ return undefined;
452
+ return this._normalizeLid(String(lidUser));
453
+ };
454
+ this._storeLidPnMapping = async (lidJid, pnJid) => {
455
+ const normalizedLid = this._normalizeLid(lidJid);
456
+ const normalizedPn = this._toBareJid(pnJid);
457
+ if (!normalizedLid || !normalizedPn)
458
+ return;
459
+ try {
460
+ await this._sock.signalRepository?.lidMapping?.storeLIDPNMappings?.([
461
+ { lid: normalizedLid, pn: normalizedPn }
462
+ ]);
463
+ }
464
+ catch { }
465
+ const pnDecoded = this._baileys.jidDecode(normalizedPn);
466
+ const lidDecoded = this._baileys.jidDecode(normalizedLid);
467
+ if (!pnDecoded?.user || !lidDecoded?.user || !this._sock.authState?.keys?.set)
468
+ return;
469
+ try {
470
+ await this._sock.authState.keys.set({
471
+ "lid-mapping": {
472
+ [pnDecoded.user]: lidDecoded.user,
473
+ [`${lidDecoded.user}_reverse`]: pnDecoded.user
474
+ }
475
+ });
476
+ }
477
+ catch { }
478
+ };
479
+ this._doSendSignaling = async (peerJid, callId, xmlPayload) => {
480
+ const { decodeBinaryNode, getBinaryNodeChild } = this._baileys;
172
481
  const rawPayload = Buffer.from(xmlPayload);
173
482
  let voipNode;
174
483
  try {
@@ -178,21 +487,25 @@ export class SignalingBridge {
178
487
  voipNode = await decodeBinaryNode(rawPayload);
179
488
  }
180
489
  const signalingTag = String(voipNode.tag);
181
- const effectivePeerJid = __classPrivateFieldGet(this, _SignalingBridge_resolveOutboundPeerJid, "f").call(this, callId, peerJid);
490
+ const effectivePeerJid = this._resolveOutboundPeerJid(callId, peerJid);
182
491
  if (signalingTag === "offer" && !voipNode.attrs["call-creator"]) {
183
- const selfLid = __classPrivateFieldGet(this, _SignalingBridge_sock, "f").authState.creds.me?.lid;
184
- if (selfLid)
185
- voipNode.attrs["call-creator"] = selfLid;
492
+ const selfCreator = this._sock.authState?.creds?.me?.lid ||
493
+ this._sock.authState?.creds?.me?.lidJid ||
494
+ this._sock.authState?.creds?.me?.id ||
495
+ this._sock.user?.lid ||
496
+ this._sock.user?.id ||
497
+ this._sock.user?.jid;
498
+ if (selfCreator)
499
+ voipNode.attrs["call-creator"] = this._toBareJid(selfCreator);
186
500
  }
187
501
  const destination = getBinaryNodeChild(voipNode, "destination");
188
502
  if (destination) {
189
503
  const destinations = getNodeChildren(destination);
190
- const destinationJids = destinations
191
- .map((n) => String(n.attrs.jid ?? "").trim())
192
- .filter(Boolean);
193
- const sessionTargets = __classPrivateFieldGet(this, _SignalingBridge_expandSignalSessionTargets, "f").call(this, destinationJids);
194
- if (sessionTargets.length)
195
- await __classPrivateFieldGet(this, _SignalingBridge_ensureSignalSessions, "f").call(this, sessionTargets, signalingTag === "offer");
504
+ const destinationJids = destinations.map(node => String(node.attrs.jid ?? "").trim()).filter(Boolean);
505
+ const sessionTargets = this._expandSignalSessionTargets(destinationJids);
506
+ if (sessionTargets.length) {
507
+ await this._ensureSignalSessions(sessionTargets, signalingTag === "offer");
508
+ }
196
509
  const rootEnc = getBinaryNodeChild(voipNode, "enc");
197
510
  const encCount = parseCountAttr(rootEnc?.attrs.count);
198
511
  let includeDeviceIdentity = false;
@@ -202,80 +515,90 @@ export class SignalingBridge {
202
515
  if (!targetJid || !destEnc || !(destEnc.content instanceof Uint8Array))
203
516
  continue;
204
517
  try {
205
- const encrypted = await __classPrivateFieldGet(this, _SignalingBridge_encryptCallKey, "f").call(this, targetJid, destEnc.content, encCount);
518
+ const encrypted = await this._encryptCallKey(targetJid, destEnc.content, encCount);
206
519
  includeDeviceIdentity = includeDeviceIdentity || encrypted.shouldIncludeDeviceIdentity;
207
520
  setNodeChildren(destNode, [encrypted.encNode]);
208
521
  }
209
- catch {
210
- for (const d of destinations)
211
- removeNodeChildrenByTag(d, "enc");
522
+ catch (err) {
523
+ this._log("[RTC ENCRYPT DEST ERROR]", err?.message || err);
524
+ for (const destinationNode of destinations)
525
+ removeNodeChildrenByTag(destinationNode, "enc");
212
526
  break;
213
527
  }
214
528
  }
215
529
  if (includeDeviceIdentity)
216
- __classPrivateFieldGet(this, _SignalingBridge_appendDeviceIdentity, "f").call(this, voipNode);
217
- await __classPrivateFieldGet(this, _SignalingBridge_sendCallStanza, "f").call(this, __classPrivateFieldGet(this, _SignalingBridge_toBareJid, "f").call(this, peerJid), voipNode, signalingTag, effectivePeerJid, peerJid);
530
+ this._appendDeviceIdentity(voipNode);
531
+ await this._sendCallStanza(this._toBareJid(peerJid), voipNode, signalingTag, effectivePeerJid, peerJid);
218
532
  return;
219
533
  }
220
534
  if (signalingTag === "offer" || signalingTag === "enc_rekey") {
221
535
  const enc = getBinaryNodeChild(voipNode, "enc");
222
536
  if (enc && enc.content instanceof Uint8Array) {
223
- const targetJid = __classPrivateFieldGet(this, _SignalingBridge_toCallDeviceJid, "f").call(this, effectivePeerJid);
224
- const encrypted = await __classPrivateFieldGet(this, _SignalingBridge_encryptCallKey, "f").call(this, targetJid, enc.content, parseCountAttr(enc.attrs.count));
537
+ const targetJid = this._toCallDeviceJid(effectivePeerJid);
538
+ const encrypted = await this._encryptCallKey(targetJid, enc.content, parseCountAttr(enc.attrs.count));
225
539
  replaceNodeChild(voipNode, "enc", encrypted.encNode);
226
540
  if (encrypted.shouldIncludeDeviceIdentity)
227
- __classPrivateFieldGet(this, _SignalingBridge_appendDeviceIdentity, "f").call(this, voipNode);
228
- await __classPrivateFieldGet(this, _SignalingBridge_sendCallStanza, "f").call(this, targetJid, voipNode, signalingTag, effectivePeerJid, peerJid);
541
+ this._appendDeviceIdentity(voipNode);
542
+ await this._sendCallStanza(targetJid, voipNode, signalingTag, effectivePeerJid, peerJid);
229
543
  return;
230
544
  }
231
545
  }
232
546
  const routeTo = signalingTag !== "offer" && signalingTag !== "enc_rekey"
233
- ? __classPrivateFieldGet(this, _SignalingBridge_toBareJid, "f").call(this, effectivePeerJid)
234
- : __classPrivateFieldGet(this, _SignalingBridge_toCallDeviceJid, "f").call(this, effectivePeerJid);
235
- await __classPrivateFieldGet(this, _SignalingBridge_sendCallStanza, "f").call(this, routeTo, voipNode, signalingTag, effectivePeerJid, peerJid);
236
- });
237
- _SignalingBridge_sendCallStanza.set(this, async (routeTo, voipNode, signalingTag, effectivePeerJid, callbackPeerJid) => {
238
- const stanzaId = __classPrivateFieldGet(this, _SignalingBridge_sock, "f").generateMessageTag();
239
- await __classPrivateFieldGet(this, _SignalingBridge_sock, "f").sendNode({
547
+ ? this._toBareJid(effectivePeerJid)
548
+ : this._toCallDeviceJid(effectivePeerJid);
549
+ await this._sendCallStanza(routeTo, voipNode, signalingTag, effectivePeerJid, peerJid);
550
+ };
551
+ this._sendCallStanza = async (routeTo, voipNode, signalingTag, effectivePeerJid, callbackPeerJid) => {
552
+ const stanzaId = this._sock.generateMessageTag();
553
+ this._log("[RTC SEND CALL STANZA]", { to: routeTo, id: stanzaId, tag: signalingTag, peer: effectivePeerJid });
554
+ await this._sock.sendNode({
240
555
  tag: "call",
241
556
  attrs: { to: routeTo, id: stanzaId },
242
- content: [voipNode],
557
+ content: [voipNode]
243
558
  });
244
559
  void (async () => {
245
560
  try {
246
- const ackNode = await __classPrivateFieldGet(this, _SignalingBridge_sock, "f").waitForMessage(stanzaId, ACK_TIMEOUT_MS);
247
- if (!ackNode || !__classPrivateFieldGet(this, _SignalingBridge_voip, "f"))
561
+ if (typeof this._sock.waitForMessage !== "function") {
562
+ this._log("[RTC CALL ACK] waitForMessage not available");
563
+ return;
564
+ }
565
+ const ackNode = await this._sock.waitForMessage(stanzaId, ACK_TIMEOUT_MS);
566
+ this._log("[RTC CALL ACK]", ackNode?.attrs || null);
567
+ if (!ackNode || !this._voip)
568
+ return;
569
+ if (typeof this._voip.isInitialized === "function" && !this._voip.isInitialized())
248
570
  return;
571
+ const { encodeBinaryNode } = this._baileys;
249
572
  const ackPayload = Buffer.from(encodeBinaryNode(ackNode)).toString("base64");
250
573
  const tcToken = await this.ensureTcToken(effectivePeerJid, callbackPeerJid);
251
574
  try {
252
- __classPrivateFieldGet(this, _SignalingBridge_voip, "f").handleSignalingAck({
575
+ this._voip.handleSignalingAck({
253
576
  payload: ackPayload,
254
577
  ackError: ackNode.attrs?.error ?? "0",
255
578
  msgType: ackNode.attrs?.type ?? signalingTag,
256
579
  peerJid: effectivePeerJid,
257
- extraData: tcToken,
580
+ extraData: tcToken
258
581
  });
259
582
  }
260
- catch { }
583
+ catch (err) {
584
+ this._log("[RTC HANDLE ACK ERROR]", err?.message || err);
585
+ }
586
+ }
587
+ catch (err) {
588
+ this._log("[RTC WAIT ACK ERROR]", err?.message || err);
261
589
  }
262
- catch { }
263
590
  })();
264
- });
265
- _SignalingBridge_doProcessIncomingCall.set(this, async (node, voip, activeCallId) => {
591
+ };
592
+ this._doProcessIncomingCall = async (node, voip, activeCallId) => {
593
+ const { getAllBinaryNodeChildren, getBinaryNodeChild, encodeBinaryNode } = this._baileys;
266
594
  const voipChild = getAllBinaryNodeChildren(node)[0];
267
595
  if (!voipChild)
268
596
  return;
269
597
  const incomingCallId = String(voipChild.attrs["call-id"] ?? voipChild.attrs.call_id ?? "");
270
- const normalizedIncomingId = incomingCallId.toUpperCase();
271
- const normalizedActiveId = String(activeCallId ?? "").toUpperCase();
272
- const callIdForRouting = normalizedIncomingId || normalizedActiveId;
273
- if (normalizedActiveId && normalizedIncomingId && normalizedIncomingId !== normalizedActiveId)
598
+ const callIdForRouting = incomingCallId || activeCallId;
599
+ if (activeCallId && incomingCallId && incomingCallId !== activeCallId)
274
600
  return;
275
- const senderDeviceJid = String(voipChild.attrs.participant ?? "") ||
276
- String(node.attrs.participant ?? "") ||
277
- String(node.attrs.from ?? "") ||
278
- String(voipChild.attrs["call-creator"] ?? "");
601
+ const senderDeviceJid = String(voipChild.attrs.participant ?? "") || String(node.attrs.participant ?? "") || String(node.attrs.from ?? "") || String(voipChild.attrs["call-creator"] ?? "");
279
602
  const callbackPeerJid = String(node.attrs.from ?? "") || senderDeviceJid;
280
603
  const platform = voipChild.attrs.platform ?? node.attrs.platform ?? "";
281
604
  const appVersion = voipChild.attrs.version ?? node.attrs.version ?? "";
@@ -284,111 +607,81 @@ export class SignalingBridge {
284
607
  const offline = !!(voipChild.attrs.offline ?? node.attrs.offline);
285
608
  let usableNode = voipChild;
286
609
  if (getBinaryNodeChild(voipChild, "enc")) {
287
- usableNode = await __classPrivateFieldGet(this, _SignalingBridge_maybeDecryptEnc, "f").call(this, voipChild, senderDeviceJid);
610
+ usableNode = await this._maybeDecryptEnc(voipChild, senderDeviceJid);
288
611
  }
289
612
  const b64 = Buffer.from(encodeBinaryNode(usableNode)).toString("base64");
290
- const storedPeerJid = callIdForRouting ? __classPrivateFieldGet(this, _SignalingBridge_incomingCallPeerById, "f").get(callIdForRouting) : undefined;
291
- let mappedRemoteDeviceJid = callIdForRouting ? __classPrivateFieldGet(this, _SignalingBridge_remoteDevicePeerByCallId, "f").get(callIdForRouting) : undefined;
613
+ const storedPeerJid = callIdForRouting ? this._incomingCallPeerById.get(callIdForRouting) : undefined;
614
+ let mappedRemoteDeviceJid = callIdForRouting ? this._remoteDevicePeerByCallId.get(callIdForRouting) : undefined;
292
615
  if (callIdForRouting && (callbackPeerJid || senderDeviceJid)) {
293
- __classPrivateFieldGet(this, _SignalingBridge_remoteXmppRoutePeerByCallId, "f").set(callIdForRouting, callbackPeerJid || senderDeviceJid);
294
- const hinted = __classPrivateFieldGet(this, _SignalingBridge_pickConcreteRouteHint, "f").call(this, senderDeviceJid, callbackPeerJid);
616
+ this._remoteXmppRoutePeerByCallId.set(callIdForRouting, callbackPeerJid || senderDeviceJid);
617
+ const hinted = this._pickConcreteRouteHint(senderDeviceJid, callbackPeerJid);
295
618
  if (hinted && hinted !== mappedRemoteDeviceJid) {
296
619
  mappedRemoteDeviceJid = hinted;
297
- __classPrivateFieldGet(this, _SignalingBridge_remoteDevicePeerByCallId, "f").set(callIdForRouting, hinted);
620
+ this._remoteDevicePeerByCallId.set(callIdForRouting, hinted);
298
621
  }
299
622
  }
300
623
  const routedPeerJid = usableNode.tag === "offer"
301
- ? __classPrivateFieldGet(this, _SignalingBridge_preferDeviceRouteJid, "f").call(this, senderDeviceJid, callbackPeerJid, storedPeerJid)
302
- : __classPrivateFieldGet(this, _SignalingBridge_preferOrderedRouteJid, "f").call(this, mappedRemoteDeviceJid, storedPeerJid, senderDeviceJid, callbackPeerJid);
303
- if (callIdForRouting && routedPeerJid) {
304
- __classPrivateFieldGet(this, _SignalingBridge_incomingCallPeerById, "f").set(callIdForRouting, routedPeerJid);
305
- }
624
+ ? this._preferDeviceRouteJid(senderDeviceJid, callbackPeerJid, storedPeerJid)
625
+ : this._preferOrderedRouteJid(mappedRemoteDeviceJid, storedPeerJid, senderDeviceJid, callbackPeerJid);
626
+ if (callIdForRouting && routedPeerJid)
627
+ this._incomingCallPeerById.set(callIdForRouting, routedPeerJid);
306
628
  const tcToken = await this.ensureTcToken(routedPeerJid, callbackPeerJid);
629
+ if (!voip || (typeof voip.isInitialized === "function" && !voip.isInitialized()))
630
+ return;
307
631
  switch (usableNode.tag) {
308
632
  case "offer":
309
- voip.handleSignalingOffer({
310
- payload: b64,
311
- peerPlatform: Number(platform || 0),
312
- peerAppVersion: appVersion,
313
- epochId, timestamp,
314
- isOffline: offline,
315
- isOfferNotContact: false,
316
- peerJid: routedPeerJid,
317
- tcToken,
318
- });
633
+ voip.handleSignalingOffer({ payload: b64, peerPlatform: Number(platform || 0), peerAppVersion: appVersion, epochId, timestamp, isOffline: offline, isOfferNotContact: false, peerJid: routedPeerJid, tcToken });
319
634
  break;
320
635
  case "ack":
321
- voip.handleSignalingAck({
322
- payload: b64,
323
- ackError: usableNode.attrs.error ?? "0",
324
- msgType: usableNode.attrs.type ?? "",
325
- peerJid: routedPeerJid,
326
- extraData: tcToken,
327
- });
636
+ voip.handleSignalingAck({ payload: b64, ackError: usableNode.attrs.error ?? "0", msgType: usableNode.attrs.type ?? "", peerJid: routedPeerJid, extraData: tcToken });
328
637
  break;
329
638
  default:
330
- voip.handleSignalingMessage({
331
- payload: b64,
332
- peerPlatform: platform,
333
- peerAppVersion: appVersion,
334
- epochId, timestamp,
335
- isOffline: offline,
336
- peerJid: routedPeerJid,
337
- tcToken,
338
- });
639
+ voip.handleSignalingMessage({ payload: b64, peerPlatform: platform, peerAppVersion: appVersion, epochId, timestamp, isOffline: offline, peerJid: routedPeerJid, tcToken });
339
640
  if (callIdForRouting && (usableNode.tag === "terminate" || usableNode.tag === "reject")) {
340
- __classPrivateFieldGet(this, _SignalingBridge_incomingCallPeerById, "f").delete(callIdForRouting);
341
- __classPrivateFieldGet(this, _SignalingBridge_remoteDevicePeerByCallId, "f").delete(callIdForRouting);
342
- __classPrivateFieldGet(this, _SignalingBridge_remoteObfuscatedPeerByCallId, "f").delete(callIdForRouting);
343
- __classPrivateFieldGet(this, _SignalingBridge_remoteXmppRoutePeerByCallId, "f").delete(callIdForRouting);
641
+ this._incomingCallPeerById.delete(callIdForRouting);
642
+ this._remoteDevicePeerByCallId.delete(callIdForRouting);
643
+ this._remoteObfuscatedPeerByCallId.delete(callIdForRouting);
644
+ this._remoteXmppRoutePeerByCallId.delete(callIdForRouting);
344
645
  }
345
646
  break;
346
647
  }
347
- });
348
- _SignalingBridge_doProcessIncomingReceipt.set(this, async (node, voip, activeCallId) => {
648
+ };
649
+ this._doProcessIncomingReceipt = async (node, voip, activeCallId) => {
650
+ const { getAllBinaryNodeChildren, encodeBinaryNode } = this._baileys;
349
651
  const receiptChild = getAllBinaryNodeChildren(node)[0];
350
652
  if (!receiptChild)
351
653
  return;
352
654
  const incomingCallId = String(receiptChild.attrs["call-id"] ?? receiptChild.attrs.call_id ?? "");
353
- const normalizedIncomingId = incomingCallId.toUpperCase();
354
- const normalizedActiveId = String(activeCallId ?? "").toUpperCase();
355
- const callIdForRouting = normalizedIncomingId || normalizedActiveId;
356
- if (normalizedActiveId && normalizedIncomingId && normalizedIncomingId !== normalizedActiveId)
655
+ const callIdForRouting = incomingCallId || activeCallId;
656
+ if (activeCallId && incomingCallId && incomingCallId !== activeCallId)
357
657
  return;
358
658
  const callbackPeerJid = String(node.attrs.from ?? receiptChild.attrs["call-creator"] ?? "");
359
- const storedPeerJid = callIdForRouting ? __classPrivateFieldGet(this, _SignalingBridge_incomingCallPeerById, "f").get(callIdForRouting) : undefined;
360
- const routedPeerJid = __classPrivateFieldGet(this, _SignalingBridge_preferOrderedRouteJid, "f").call(this, storedPeerJid, callbackPeerJid);
659
+ const storedPeerJid = callIdForRouting ? this._incomingCallPeerById.get(callIdForRouting) : undefined;
660
+ const routedPeerJid = this._preferOrderedRouteJid(storedPeerJid, callbackPeerJid);
361
661
  if (callIdForRouting && routedPeerJid)
362
- __classPrivateFieldGet(this, _SignalingBridge_incomingCallPeerById, "f").set(callIdForRouting, routedPeerJid);
662
+ this._incomingCallPeerById.set(callIdForRouting, routedPeerJid);
363
663
  const tcToken = await this.ensureTcToken(routedPeerJid, callbackPeerJid);
364
- voip.handleSignalingReceipt({
365
- payload: Buffer.from(encodeBinaryNode(node)).toString("base64"),
366
- peerJid: routedPeerJid,
367
- tcToken,
368
- });
369
- });
370
- _SignalingBridge_maybeDecryptEnc.set(this, async (voipNode, peerJid) => {
664
+ if (!voip || (typeof voip.isInitialized === "function" && !voip.isInitialized()))
665
+ return;
666
+ voip.handleSignalingReceipt({ payload: Buffer.from(encodeBinaryNode(node)).toString("base64"), peerJid: routedPeerJid, tcToken });
667
+ };
668
+ this._maybeDecryptEnc = async (voipNode, peerJid) => {
669
+ const { getBinaryNodeChild, unpadRandomMax16, proto } = this._baileys;
371
670
  const enc = getBinaryNodeChild(voipNode, "enc");
372
671
  if (!enc || !(enc.content instanceof Uint8Array))
373
672
  return voipNode;
374
673
  const type = enc.attrs.type;
375
674
  if (type !== "pkmsg" && type !== "msg")
376
675
  return voipNode;
377
- const candidates = [...new Set([
378
- peerJid,
379
- __classPrivateFieldGet(this, _SignalingBridge_toCallDeviceJid, "f").call(this, peerJid),
380
- ].filter(Boolean))];
676
+ const candidates = [...new Set([peerJid, this._toCallDeviceJid(peerJid)])].filter(Boolean);
381
677
  let lastErr;
382
678
  for (const jid of candidates) {
383
679
  try {
384
- const decrypted = await __classPrivateFieldGet(this, _SignalingBridge_sock, "f").signalRepository.decryptMessage({
385
- jid, type, ciphertext: enc.content,
386
- });
680
+ const decrypted = await this._sock.signalRepository.decryptMessage({ jid, type, ciphertext: enc.content });
387
681
  const parsed = proto.Message.decode(unpadRandomMax16(decrypted));
388
682
  const callKey = parsed.call?.callKey;
389
- if (!callKey || callKey.length === 0) {
683
+ if (!callKey || callKey.length === 0)
390
684
  throw new Error("decrypted signaling has no call.callKey");
391
- }
392
685
  enc.content = callKey;
393
686
  return voipNode;
394
687
  }
@@ -397,187 +690,357 @@ export class SignalingBridge {
397
690
  }
398
691
  }
399
692
  throw lastErr;
400
- });
401
- _SignalingBridge_encryptCallKey.set(this, async (targetJid, rawCallKey, count) => {
402
- const primaryDeviceJid = __classPrivateFieldGet(this, _SignalingBridge_toPrimaryDeviceJid, "f").call(this, targetJid);
403
- const sessionTargets = primaryDeviceJid && primaryDeviceJid !== targetJid
404
- ? [primaryDeviceJid, targetJid]
405
- : [targetJid];
406
- await __classPrivateFieldGet(this, _SignalingBridge_ensureSignalSessions, "f").call(this, sessionTargets, false);
407
- const { type, ciphertext } = await __classPrivateFieldGet(this, _SignalingBridge_sock, "f").signalRepository.encryptMessage({
693
+ };
694
+ this._encryptCallKey = async (targetJid, rawCallKey, count) => {
695
+ const { encodeWAMessage } = this._baileys;
696
+ const primaryDeviceJid = this._toPrimaryDeviceJid(targetJid);
697
+ const sessionTargets = primaryDeviceJid && primaryDeviceJid !== targetJid ? [primaryDeviceJid, targetJid] : [targetJid];
698
+ await this._ensureSignalSessions(sessionTargets, false);
699
+ const { type, ciphertext } = await this._sock.signalRepository.encryptMessage({
408
700
  jid: targetJid,
409
- data: encodeWAMessage({ call: { callKey: Buffer.from(rawCallKey) } }),
701
+ data: encodeWAMessage({ call: { callKey: Buffer.from(rawCallKey) } })
410
702
  });
411
703
  return {
412
- encNode: {
413
- tag: "enc",
414
- attrs: { v: "2", type, count: String(count) },
415
- content: Buffer.from(ciphertext),
416
- },
417
- shouldIncludeDeviceIdentity: type === "pkmsg",
704
+ encNode: { tag: "enc", attrs: { v: "2", type, count: String(count) }, content: Buffer.from(ciphertext) },
705
+ shouldIncludeDeviceIdentity: type === "pkmsg"
418
706
  };
419
- });
420
- _SignalingBridge_ensureSignalSessions.set(this, async (jids, refresh) => {
707
+ };
708
+ this._ensureSignalSessions = async (jids, refresh) => {
709
+ const targets = [...new Set(jids.filter(Boolean).map(jid => this._toCallDeviceJid(jid)))];
710
+ if (!targets.length) {
711
+ return;
712
+ }
713
+ if (typeof this._sock.assertSessions === "function") {
714
+ try {
715
+ await this._sock.assertSessions(targets, refresh);
716
+ return;
717
+ }
718
+ catch (err) {
719
+ this._log("[RTC ASSERT SESSIONS ERROR]", err?.message || err);
720
+ }
721
+ }
722
+ const { parseAndInjectE2ESessions } = this._baileys;
421
723
  const missing = [];
422
- for (const jid of [...new Set(jids.filter(Boolean))]) {
423
- const signalId = __classPrivateFieldGet(this, _SignalingBridge_sock, "f").signalRepository.jidToSignalProtocolAddress(jid);
424
- const cachedAt = __classPrivateFieldGet(this, _SignalingBridge_ensuredSignalSessions, "f").get(signalId);
425
- if (!refresh && cachedAt && Date.now() - cachedAt < SESSION_CACHE_TTL_MS)
426
- continue;
427
- if (!refresh) {
428
- const validation = await __classPrivateFieldGet(this, _SignalingBridge_sock, "f").signalRepository.validateSession(jid);
429
- if (validation.exists) {
430
- __classPrivateFieldGet(this, _SignalingBridge_ensuredSignalSessions, "f").set(signalId, Date.now());
724
+ for (const jid of targets) {
725
+ try {
726
+ const signalId = this._sock.signalRepository.jidToSignalProtocolAddress(jid);
727
+ const cachedAt = this._ensuredSignalSessions.get(signalId);
728
+ if (!refresh && cachedAt && Date.now() - cachedAt < SESSION_CACHE_TTL_MS) {
431
729
  continue;
432
730
  }
731
+ if (!refresh) {
732
+ const validation = await this._sock.signalRepository.validateSession(jid);
733
+ if (validation.exists) {
734
+ this._ensuredSignalSessions.set(signalId, Date.now());
735
+ continue;
736
+ }
737
+ }
738
+ missing.push(jid);
739
+ }
740
+ catch {
741
+ missing.push(jid);
433
742
  }
434
- missing.push(jid);
435
743
  }
436
- if (!missing.length)
744
+ if (!missing.length) {
437
745
  return;
438
- const sessionNode = await __classPrivateFieldGet(this, _SignalingBridge_sock, "f").query({
439
- tag: "iq",
440
- attrs: { xmlns: "encrypt", type: "get", to: S_WHATSAPP_NET },
441
- content: [{
442
- tag: "key", attrs: {},
443
- content: missing.map((jid) => ({ tag: "user", attrs: { jid } })),
444
- }],
445
- });
446
- await parseAndInjectE2ESessions(sessionNode, __classPrivateFieldGet(this, _SignalingBridge_sock, "f").signalRepository);
447
- for (const jid of missing) {
448
- __classPrivateFieldGet(this, _SignalingBridge_ensuredSignalSessions, "f").set(__classPrivateFieldGet(this, _SignalingBridge_sock, "f").signalRepository.jidToSignalProtocolAddress(jid), Date.now());
449
746
  }
450
- });
451
- _SignalingBridge_appendDeviceIdentity.set(this, (voipNode) => {
747
+ try {
748
+ const sessionNode = await this._sock.query({
749
+ tag: "iq",
750
+ attrs: {
751
+ xmlns: "encrypt",
752
+ type: "get",
753
+ to: S_WHATSAPP_NET,
754
+ id: this._sock.generateMessageTag()
755
+ },
756
+ content: [
757
+ {
758
+ tag: "key",
759
+ attrs: {},
760
+ content: missing.map(jid => ({
761
+ tag: "user",
762
+ attrs: { jid }
763
+ }))
764
+ }
765
+ ]
766
+ });
767
+ await parseAndInjectE2ESessions(sessionNode, this._sock.signalRepository);
768
+ for (const jid of missing) {
769
+ try {
770
+ this._ensuredSignalSessions.set(this._sock.signalRepository.jidToSignalProtocolAddress(jid), Date.now());
771
+ }
772
+ catch { }
773
+ }
774
+ }
775
+ catch (err) {
776
+ this._log("[RTC ENSURE SIGNAL SESSION ERROR]", {
777
+ message: err?.message || String(err),
778
+ targets: missing
779
+ });
780
+ if (String(err?.message || err).toLowerCase().includes("connection closed") ||
781
+ String(err?.message || err).toLowerCase().includes("socket")) {
782
+ return;
783
+ }
784
+ throw err;
785
+ }
786
+ };
787
+ this._appendDeviceIdentity = voipNode => {
788
+ const { getBinaryNodeChild, encodeSignedDeviceIdentity } = this._baileys;
452
789
  if (getBinaryNodeChild(voipNode, "device-identity"))
453
790
  return;
454
- const account = __classPrivateFieldGet(this, _SignalingBridge_sock, "f").authState.creds.account;
791
+ const account = this._sock.authState.creds.account;
455
792
  if (!account)
456
793
  return;
457
794
  const children = getNodeChildren(voipNode);
458
- children.push({
459
- tag: "device-identity",
460
- attrs: {},
461
- content: encodeSignedDeviceIdentity(account, true),
462
- });
795
+ children.push({ tag: "device-identity", attrs: {}, content: encodeSignedDeviceIdentity(account, true) });
463
796
  setNodeChildren(voipNode, children);
464
- });
465
- _SignalingBridge_toBareJid.set(this, (jid) => {
797
+ };
798
+ this._toBareJid = jid => {
799
+ const { jidDecode, jidEncode } = this._baileys;
466
800
  const decoded = jidDecode(jid);
467
801
  if (!decoded?.user)
468
802
  return jid;
469
- const server = jid.endsWith("@lid") ? "lid" : "s.whatsapp.net";
803
+ const server = String(jid).endsWith("@lid") ? "lid" : "s.whatsapp.net";
470
804
  return jidEncode(decoded.user, server);
471
- });
472
- _SignalingBridge_toCallDeviceJid.set(this, (jid) => {
805
+ };
806
+ this._toCallDeviceJid = jid => {
807
+ const { jidDecode } = this._baileys;
473
808
  const decoded = jidDecode(jid);
474
809
  if (!decoded?.user)
475
810
  return jid;
476
- const server = jid.endsWith("@lid") ? "lid" : "s.whatsapp.net";
477
- if (decoded.device == null)
478
- return jidEncode(decoded.user, server);
811
+ const server = String(jid).endsWith("@lid") ? "lid" : "s.whatsapp.net";
812
+ if (decoded.device === undefined || decoded.device === null)
813
+ return `${decoded.user}:0@${server}`;
479
814
  return `${decoded.user}:${decoded.device}@${server}`;
480
- });
481
- _SignalingBridge_toPrimaryDeviceJid.set(this, (jid) => {
815
+ };
816
+ this._toPrimaryDeviceJid = jid => {
817
+ const { jidDecode } = this._baileys;
482
818
  const decoded = jidDecode(jid);
483
819
  if (!decoded?.user)
484
820
  return undefined;
485
821
  const device = decoded.device;
486
822
  if (device == null || device === 0)
487
823
  return undefined;
488
- const server = jid.endsWith("@lid") ? "lid" : "s.whatsapp.net";
489
- return jidEncode(decoded.user, server);
490
- });
491
- _SignalingBridge_hasConcreteDevice.set(this, (jid) => {
492
- const decoded = jidDecode(jid);
824
+ const server = String(jid).endsWith("@lid") ? "lid" : "s.whatsapp.net";
825
+ return `${decoded.user}:0@${server}`;
826
+ };
827
+ this._hasConcreteDevice = jid => {
828
+ const decoded = this._baileys.jidDecode(jid);
493
829
  return !!decoded?.user && decoded.device != null;
494
- });
495
- _SignalingBridge_preferDeviceRouteJid.set(this, (...candidates) => {
496
- for (const c of candidates) {
497
- const jid = String(c ?? "").trim();
498
- if (jid && __classPrivateFieldGet(this, _SignalingBridge_hasConcreteDevice, "f").call(this, jid))
830
+ };
831
+ this._preferDeviceRouteJid = (...candidates) => {
832
+ for (const candidate of candidates) {
833
+ const jid = String(candidate ?? "").trim();
834
+ if (jid && this._hasConcreteDevice(jid))
499
835
  return jid;
500
836
  }
501
- for (const c of candidates) {
502
- const jid = String(c ?? "").trim();
837
+ for (const candidate of candidates) {
838
+ const jid = String(candidate ?? "").trim();
503
839
  if (jid)
504
- return __classPrivateFieldGet(this, _SignalingBridge_toCallDeviceJid, "f").call(this, jid);
840
+ return this._toCallDeviceJid(jid);
505
841
  }
506
842
  return "";
507
- });
508
- _SignalingBridge_preferOrderedRouteJid.set(this, (...candidates) => {
509
- for (const c of candidates) {
510
- const jid = String(c ?? "").trim();
843
+ };
844
+ this._preferOrderedRouteJid = (...candidates) => {
845
+ for (const candidate of candidates) {
846
+ const jid = String(candidate ?? "").trim();
511
847
  if (jid)
512
- return __classPrivateFieldGet(this, _SignalingBridge_toCallDeviceJid, "f").call(this, jid);
848
+ return this._toCallDeviceJid(jid);
513
849
  }
514
850
  return "";
515
- });
516
- _SignalingBridge_pickConcreteRouteHint.set(this, (...candidates) => {
517
- for (const c of candidates) {
518
- const jid = String(c ?? "").trim();
519
- if (jid && __classPrivateFieldGet(this, _SignalingBridge_hasConcreteDevice, "f").call(this, jid))
851
+ };
852
+ this._pickConcreteRouteHint = (...candidates) => {
853
+ for (const candidate of candidates) {
854
+ const jid = String(candidate ?? "").trim();
855
+ if (jid && this._hasConcreteDevice(jid))
520
856
  return jid;
521
857
  }
522
858
  return "";
523
- });
524
- _SignalingBridge_resolveOutboundPeerJid.set(this, (callId, wasmPeerJid) => {
859
+ };
860
+ this._resolveOutboundPeerJid = (callId, wasmPeerJid) => {
525
861
  const peerJid = String(wasmPeerJid ?? "").trim();
526
862
  if (!peerJid || !callId)
527
863
  return peerJid;
528
- const normalizedCallId = String(callId).toUpperCase();
529
- return __classPrivateFieldGet(this, _SignalingBridge_remoteDevicePeerByCallId, "f").get(normalizedCallId) ?? __classPrivateFieldGet(this, _SignalingBridge_remoteDevicePeerByCallId, "f").get(callId) ?? peerJid;
530
- });
531
- _SignalingBridge_expandSignalSessionTargets.set(this, (jids) => [...new Set(jids.flatMap((jid) => {
532
- const primary = __classPrivateFieldGet(this, _SignalingBridge_toPrimaryDeviceJid, "f").call(this, jid);
864
+ return this._remoteDevicePeerByCallId.get(callId) ?? peerJid;
865
+ };
866
+ this._expandSignalSessionTargets = jids => [
867
+ ...new Set(jids.flatMap(jid => {
868
+ const primary = this._toPrimaryDeviceJid(jid);
533
869
  return primary && primary !== jid ? [primary, jid] : [jid];
534
- }))]);
535
- _SignalingBridge_normalizeStartCallPeerList.set(this, (jids) => {
870
+ }))
871
+ ];
872
+ this._normalizeStartCallPeerList = jids => {
873
+ const { jidDecode } = this._baileys;
536
874
  const result = new Set();
537
875
  for (const jid of jids) {
538
- const decoded = jidDecode(jid);
876
+ const value = String(jid || "").trim();
877
+ if (!value)
878
+ continue;
879
+ const decoded = jidDecode(value);
539
880
  if (!decoded?.user) {
540
- result.add(jid);
881
+ result.add(value);
541
882
  continue;
542
883
  }
543
- const server = jid.endsWith("@lid") ? "lid" : "s.whatsapp.net";
544
- result.add(jidEncode(decoded.user, server));
545
- if (decoded.device != null) {
884
+ const server = value.endsWith("@lid") ? "lid" : "s.whatsapp.net";
885
+ result.add(`${decoded.user}:0@${server}`);
886
+ if (decoded.device !== undefined && decoded.device !== null)
546
887
  result.add(`${decoded.user}:${decoded.device}@${server}`);
547
- }
548
888
  }
549
889
  return [...result].slice(0, 5);
550
- });
551
- _SignalingBridge_rememberTcToken.set(this, (jid, token, timestamp = "") => {
552
- const bareJid = __classPrivateFieldGet(this, _SignalingBridge_toBareJid, "f").call(this, jid);
553
- if (!token.length)
890
+ };
891
+ this._findTcTokenNodes = node => {
892
+ const result = [];
893
+ const walk = item => {
894
+ if (!item)
895
+ return;
896
+ if (Array.isArray(item)) {
897
+ for (const child of item)
898
+ walk(child);
899
+ return;
900
+ }
901
+ if (typeof item !== "object")
902
+ return;
903
+ if (item.tag === "token" &&
904
+ (item.attrs?.type === "trusted_contact" || item.attrs?.type === undefined) &&
905
+ item.content instanceof Uint8Array &&
906
+ item.content.length > 0) {
907
+ result.push(item);
908
+ }
909
+ if (Array.isArray(item.content)) {
910
+ for (const child of item.content)
911
+ walk(child);
912
+ }
913
+ };
914
+ walk(node);
915
+ return result;
916
+ };
917
+ this._processPrivacyTokenNotification = node => {
918
+ const { getAllBinaryNodeChildren, getBinaryNodeChildren } = this._baileys;
919
+ const child = getAllBinaryNodeChildren(node)[0];
920
+ const tokenNodes = child ? getBinaryNodeChildren(child, "token") : [];
921
+ for (const tokenNode of tokenNodes) {
922
+ const jid = String(tokenNode.attrs?.jid || node.attrs?.from || "");
923
+ const content = tokenNode.content;
924
+ if (jid && content instanceof Uint8Array && content.length > 0) {
925
+ this._log("[RTC TC TOKEN FROM RAW NOTIFICATION]", {
926
+ jid,
927
+ length: content.length
928
+ });
929
+ this._storeTcToken(jid, Buffer.from(content), String(tokenNode.attrs?.t ?? Math.floor(Date.now() / 1000))).catch(() => { });
930
+ }
931
+ }
932
+ };
933
+ this._getTcTokenCandidateJids = async (jid) => {
934
+ const result = new Set();
935
+ const bare = this._toBareJid(jid);
936
+ if (bare)
937
+ result.add(bare);
938
+ try {
939
+ const lid = await this._sock.signalRepository?.lidMapping?.getLIDForPN?.(bare);
940
+ if (lid)
941
+ result.add(this._toBareJid(lid));
942
+ }
943
+ catch { }
944
+ try {
945
+ const pn = await this._sock.signalRepository?.lidMapping?.getPNForLID?.(bare);
946
+ if (pn)
947
+ result.add(this._toBareJid(pn));
948
+ }
949
+ catch { }
950
+ return [...result].filter(Boolean);
951
+ };
952
+ this._storeTcToken = async (jid, token, timestamp = "") => {
953
+ const candidates = await this._getTcTokenCandidateJids(jid);
954
+ if (!candidates.length)
955
+ candidates.push(this._toBareJid(jid));
956
+ const write = {};
957
+ for (const storageJid of candidates) {
958
+ if (!storageJid)
959
+ continue;
960
+ write[storageJid] = {
961
+ token: Buffer.from(token),
962
+ timestamp: String(timestamp || Math.floor(Date.now() / 1000))
963
+ };
964
+ this._rememberTcToken(storageJid, token, timestamp);
965
+ }
966
+ try {
967
+ if (Object.keys(write).length) {
968
+ await this._sock.authState.keys.set({ tctoken: write });
969
+ }
970
+ }
971
+ catch { }
972
+ return Buffer.from(token);
973
+ };
974
+ this._waitForTcToken = async (jid, timeoutMs = TC_TOKEN_REQUEST_TIMEOUT_MS) => {
975
+ const candidates = await this._getTcTokenCandidateJids(jid);
976
+ return new Promise(resolve => {
977
+ const timer = setTimeout(() => {
978
+ for (const candidate of candidates) {
979
+ const waiters = this._pendingTcTokenWaiters.get(candidate);
980
+ if (!waiters)
981
+ continue;
982
+ this._pendingTcTokenWaiters.set(candidate, waiters.filter(fn => fn !== done));
983
+ }
984
+ const anyWaiters = this._pendingTcTokenWaiters.get("*");
985
+ if (anyWaiters) {
986
+ this._pendingTcTokenWaiters.set("*", anyWaiters.filter(fn => fn !== done));
987
+ }
988
+ resolve(undefined);
989
+ }, timeoutMs);
990
+ const done = token => {
991
+ clearTimeout(timer);
992
+ resolve(Buffer.from(token));
993
+ };
994
+ for (const candidate of candidates) {
995
+ const waiters = this._pendingTcTokenWaiters.get(candidate) || [];
996
+ waiters.push(done);
997
+ this._pendingTcTokenWaiters.set(candidate, waiters);
998
+ }
999
+ const anyWaiters = this._pendingTcTokenWaiters.get("*") || [];
1000
+ anyWaiters.push(done);
1001
+ this._pendingTcTokenWaiters.set("*", anyWaiters);
1002
+ });
1003
+ };
1004
+ this._rememberTcToken = (jid, token, timestamp = "") => {
1005
+ const bareJid = this._toBareJid(jid);
1006
+ if (!token?.length)
554
1007
  return;
555
- __classPrivateFieldGet(this, _SignalingBridge_observedTcTokens, "f").set(bareJid, { token: Buffer.from(token), timestamp });
556
- const waiters = __classPrivateFieldGet(this, _SignalingBridge_pendingTcTokenWaiters, "f").get(bareJid);
557
- if (waiters?.length) {
558
- __classPrivateFieldGet(this, _SignalingBridge_pendingTcTokenWaiters, "f").delete(bareJid);
559
- for (const w of waiters)
560
- w(Buffer.from(token));
561
- }
562
- });
563
- _SignalingBridge_getTcToken.set(this, async (jid) => {
564
- const userJid = __classPrivateFieldGet(this, _SignalingBridge_toBareJid, "f").call(this, jid);
565
- const observed = __classPrivateFieldGet(this, _SignalingBridge_observedTcTokens, "f").get(userJid)?.token;
566
- if (observed?.length)
567
- return Buffer.from(observed);
1008
+ this._observedTcTokens.set(bareJid, {
1009
+ token: Buffer.from(token),
1010
+ timestamp
1011
+ });
1012
+ const notify = key => {
1013
+ const waiters = this._pendingTcTokenWaiters.get(key);
1014
+ if (waiters?.length) {
1015
+ this._pendingTcTokenWaiters.delete(key);
1016
+ for (const waiter of waiters)
1017
+ waiter(Buffer.from(token));
1018
+ }
1019
+ };
1020
+ notify(bareJid);
1021
+ notify("*");
1022
+ };
1023
+ this._getTcToken = async (jid) => {
1024
+ const candidates = await this._getTcTokenCandidateJids(jid);
1025
+ for (const candidate of candidates) {
1026
+ const observed = this._observedTcTokens.get(candidate)?.token;
1027
+ if (observed?.length)
1028
+ return Buffer.from(observed);
1029
+ }
568
1030
  try {
569
- const data = await __classPrivateFieldGet(this, _SignalingBridge_sock, "f").authState.keys.get("tctoken", [userJid]);
570
- const token = data[userJid]?.token;
571
- if (token && token.length > 0) {
572
- __classPrivateFieldGet(this, _SignalingBridge_rememberTcToken, "f").call(this, userJid, token, data[userJid]?.timestamp);
573
- return token;
1031
+ const data = await this._sock.authState.keys.get("tctoken", candidates);
1032
+ for (const candidate of candidates) {
1033
+ const token = data[candidate]?.token;
1034
+ if (token && token.length > 0) {
1035
+ this._rememberTcToken(candidate, token, data[candidate]?.timestamp);
1036
+ return Buffer.from(token);
1037
+ }
574
1038
  }
575
1039
  }
576
1040
  catch { }
577
1041
  return undefined;
578
- });
579
- __classPrivateFieldSet(this, _SignalingBridge_sock, config.sock, "f");
1042
+ };
580
1043
  }
581
1044
  }
582
- _SignalingBridge_sock = new WeakMap(), _SignalingBridge_voip = new WeakMap(), _SignalingBridge_observedTcTokens = new WeakMap(), _SignalingBridge_pendingTcTokenWaiters = new WeakMap(), _SignalingBridge_ensuredSignalSessions = new WeakMap(), _SignalingBridge_remoteDevicePeerByCallId = new WeakMap(), _SignalingBridge_remoteObfuscatedPeerByCallId = new WeakMap(), _SignalingBridge_remoteXmppRoutePeerByCallId = new WeakMap(), _SignalingBridge_incomingCallPeerById = new WeakMap(), _SignalingBridge_outgoingSignalingQueue = new WeakMap(), _SignalingBridge_incomingSignalingQueue = new WeakMap(), _SignalingBridge_doSendSignaling = new WeakMap(), _SignalingBridge_sendCallStanza = new WeakMap(), _SignalingBridge_doProcessIncomingCall = new WeakMap(), _SignalingBridge_doProcessIncomingReceipt = new WeakMap(), _SignalingBridge_maybeDecryptEnc = new WeakMap(), _SignalingBridge_encryptCallKey = new WeakMap(), _SignalingBridge_ensureSignalSessions = new WeakMap(), _SignalingBridge_appendDeviceIdentity = new WeakMap(), _SignalingBridge_toBareJid = new WeakMap(), _SignalingBridge_toCallDeviceJid = new WeakMap(), _SignalingBridge_toPrimaryDeviceJid = new WeakMap(), _SignalingBridge_hasConcreteDevice = new WeakMap(), _SignalingBridge_preferDeviceRouteJid = new WeakMap(), _SignalingBridge_preferOrderedRouteJid = new WeakMap(), _SignalingBridge_pickConcreteRouteHint = new WeakMap(), _SignalingBridge_resolveOutboundPeerJid = new WeakMap(), _SignalingBridge_expandSignalSessionTargets = new WeakMap(), _SignalingBridge_normalizeStartCallPeerList = new WeakMap(), _SignalingBridge_rememberTcToken = new WeakMap(), _SignalingBridge_getTcToken = new WeakMap();
1045
+ export default SignalingBridge;
583
1046
  //# sourceMappingURL=signaling.js.map