@zelynskybail/baileys 2.6.30 → 2.6.34

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.
@@ -0,0 +1,718 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { randomBytes, createHmac } from "node:crypto";
3
+
4
+ import { WasmEngine } from "./wasm-engine.js";
5
+ import { RelayRtcTransport } from "./relay-transport.js";
6
+ import { SignalingBridge } from "./signaling.js";
7
+ import { AudioFeeder } from "./audio-feeder.js";
8
+ import { CallState } from "./types.js";
9
+ import { createWavRecorder } from "./call-recorder.js";
10
+
11
+ export { CallState } from "./types.js";
12
+ export { createWavRecorder } from "./call-recorder.js"; // JAP@Add
13
+
14
+ const SHA256_LEN = 32;
15
+
16
+ const toBareJid = (jid) => {
17
+ if (!jid) return jid;
18
+ const at = jid.indexOf("@");
19
+ if (at < 0) return jid;
20
+ const user = jid.slice(0, at).split(":")[0];
21
+ return `${user}@${jid.slice(at + 1)}`;
22
+ };
23
+
24
+ const computeHkdf = (key, salt, info, length) => {
25
+ const effectiveSalt = salt && salt.length > 0 ? Buffer.from(salt) : Buffer.alloc(SHA256_LEN, 0);
26
+ const prk = createHmac("sha256", effectiveSalt).update(key).digest();
27
+ const blocks = Math.ceil(length / SHA256_LEN);
28
+ const okm = Buffer.alloc(blocks * SHA256_LEN);
29
+ let prev = Buffer.alloc(0);
30
+ for (let i = 1; i <= blocks; i += 1) {
31
+ prev = createHmac("sha256", prk)
32
+ .update(prev)
33
+ .update(info)
34
+ .update(Buffer.from([i]))
35
+ .digest();
36
+ prev.copy(okm, (i - 1) * SHA256_LEN);
37
+ }
38
+ return new Uint8Array(okm.buffer, okm.byteOffset, length);
39
+ };
40
+
41
+ const computeHmacSha256 = (data, key) => {
42
+ const result = createHmac("sha256", Buffer.from(key)).update(data).digest();
43
+ return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
44
+ };
45
+
46
+ const isCallReceiptNode = (node) => {
47
+ if (node?.tag !== "receipt") return false;
48
+ const child = Array.isArray(node.content) ? node.content[0] : null;
49
+ return !!(child?.attrs?.["call-id"] || child?.attrs?.call_id);
50
+ };
51
+
52
+ export class ActiveCall extends EventEmitter {
53
+ #state = CallState.Idle;
54
+ #endResolver;
55
+ #endPromise;
56
+ #endTimer = null;
57
+ #endGraceTimer = null; // JAP@Fix: fallback if the engine never confirms the end
58
+ #endRequested = false; // JAP@Fix: "end asked for" is NOT "end completed"
59
+ #ended = false;
60
+ _audioSource = "silence";
61
+
62
+ constructor(callId, engine, durationMs, meta = {}) {
63
+ super();
64
+ this.callId = callId;
65
+ this.startedAt = Date.now(); // JAP@Add
66
+ this._recorder = null; // JAP@Add
67
+ this.engine = engine;
68
+ this.direction = meta.direction || 'outbound'; // JAP@Add: outbound|inbound|group-outbound|group-inbound
69
+ this.from = meta.from || null; // JAP@Add: inbound caller
70
+ this.groupJid = meta.groupJid || null; // JAP@Add: group calls
71
+ this.#endPromise = new Promise((res) => { this.#endResolver = res; });
72
+ if (durationMs > 0) {
73
+ this.#endTimer = setTimeout(() => this.end(), durationMs);
74
+ }
75
+ }
76
+
77
+ get state() { return this.#state; }
78
+
79
+ // JAP@Fix (lifecycle): end() used to set #ended=true itself, so when the
80
+ // engine's state callback later ran _updateState(Idle) -> _forceEnd(), the
81
+ // guard saw #ended and returned early — the "ended" event never fired,
82
+ // waitForEnd() hung forever and recordToFile() never finalized the WAV.
83
+ // Now: end() only REQUESTS the end; #ended is owned by _forceEnd(). If the
84
+ // engine throws or never confirms within 5s, we force-complete ourselves.
85
+ end = () => {
86
+ if (this.#ended || this.#endRequested) return;
87
+ this.#endRequested = true;
88
+ if (this.#endTimer) { clearTimeout(this.#endTimer); this.#endTimer = null; }
89
+ try {
90
+ const result = this.engine.endCall(0, true);
91
+ // JAP@Fix: an async engine that REJECTS its endCall promise used to
92
+ // surface as an unhandledRejection while the call hung in limbo —
93
+ // treat it exactly like a synchronous throw.
94
+ if (result && typeof result.then === "function") {
95
+ result.catch(() => this._forceEnd("end_failed"));
96
+ }
97
+ } catch {
98
+ this._forceEnd("end_failed");
99
+ return;
100
+ }
101
+ this.#endGraceTimer = setTimeout(() => this._forceEnd("end_timeout"), 5000);
102
+ if (typeof this.#endGraceTimer.unref === "function") this.#endGraceTimer.unref();
103
+ };
104
+
105
+ mute = (muted) => {
106
+ try { this.engine.setMute(muted); } catch {}
107
+ };
108
+
109
+ /**
110
+ * JAP@Add --- switch what the call is playing WITHOUT hanging up: a file
111
+ * path/URL, `{ data: Buffer, ext }`, a `lavfi:` graph, or `"silence"`.
112
+ * IVR-style flows become one-liners:
113
+ * ```js
114
+ * const call = await voip.call('62812xxxx', { audioSource: './greeting.mp3' })
115
+ * // ...later, mid-call:
116
+ * call.setAudioSource('./menu.mp3')
117
+ * call.setAudioSource('silence') // stop playing, stay on the call
118
+ * ```
119
+ * Returns true when a live decoder was swapped, false when the call is not
120
+ * feeding audio yet (the new source is still remembered for when it does).
121
+ */
122
+ setAudioSource = (source) => {
123
+ this._audioSource = source;
124
+ if (typeof this._switchAudioSource === "function") {
125
+ return this._switchAudioSource(source);
126
+ }
127
+ return false;
128
+ };
129
+
130
+ /** JAP@Add --- group-call participant management (no-op false when unsupported). */
131
+ invite = (pnUserJid, lidUserJid = '', deviceJids = []) => {
132
+ try { this.engine.inviteToCall({ invitedParticipantPnUserJid: pnUserJid, invitedParticipantLidUserJid: lidUserJid, deviceJids }); return true; } catch { return false; }
133
+ };
134
+ removeParticipant = (peerJid) => {
135
+ try { this.engine.removeCallParticipant(peerJid); return true; } catch { return false; }
136
+ };
137
+ requestMute = (peerJid) => {
138
+ try { this.engine.requestPeerMute(peerJid); return true; } catch { return false; }
139
+ };
140
+ react = (reaction) => {
141
+ try { return this.engine.sendReaction(reaction); } catch { return false; }
142
+ };
143
+ setHandRaised = (raised) => {
144
+ try { return this.engine.raiseHand(raised); } catch { return false; }
145
+ };
146
+
147
+ /** JAP@Add --- ms elapsed since this call object was created. */
148
+ getDurationMs = () => Date.now() - (this.startedAt || Date.now());
149
+
150
+ /**
151
+ * JAP@Add --- record the INBOUND (remote peer) audio stream to a .wav file.
152
+ * Returns a stop() function; the file is also finalized automatically on call end.
153
+ */
154
+ recordToFile = (filePath, opts = {}) => {
155
+ if (this._recorder) throw new Error("Already recording this call.");
156
+ this._recorder = createWavRecorder(filePath, opts);
157
+ const onAudio = (pcm) => { try { this._recorder.write(pcm); } catch {} };
158
+ const onEnd = () => { try { this._recorder?.close(); } catch {} this._recorder = null; };
159
+ this.on("audio", onAudio);
160
+ this.once("ended", onEnd);
161
+ return () => {
162
+ this.off("audio", onAudio);
163
+ this.off("ended", onEnd);
164
+ onEnd();
165
+ };
166
+ };
167
+
168
+ waitForEnd = () => this.#endPromise;
169
+
170
+ _updateState = (state) => {
171
+ this.#state = state;
172
+ if (state === CallState.PreacceptReceived) this.emit("ringing");
173
+ else if (state === CallState.Active) this.emit("connected");
174
+ else if (state === CallState.Idle || state === CallState.Ending) {
175
+ this._forceEnd("ended");
176
+ }
177
+ };
178
+
179
+ _emitAudio = (pcm) => { this.emit("audio", pcm); };
180
+
181
+ _forceEnd = (reason) => {
182
+ if (this.#ended) return;
183
+ this.#ended = true;
184
+ if (this.#endTimer) { clearTimeout(this.#endTimer); this.#endTimer = null; }
185
+ if (this.#endGraceTimer) { clearTimeout(this.#endGraceTimer); this.#endGraceTimer = null; } // JAP@Fix
186
+ this.emit("ended", reason);
187
+ this.#endResolver(reason);
188
+ };
189
+ }
190
+
191
+ export class VoipClient extends EventEmitter {
192
+ #config;
193
+ #engine = null;
194
+ #relay = null;
195
+ #signaling = null;
196
+ #sock = null;
197
+ #activeCall = null;
198
+ #lastPeer = null; // JAP@Add: { peerJid, callId } for recovery
199
+ #lastGroupJoin = null; // JAP@Add: params for rejoinGroupCall()
200
+ #watchdogTimer = null; // JAP@Add: relay-health watchdog
201
+ #watchdogMisses = 0;
202
+ #lastReceivedPackets = -1; // JAP@Add: watchdog tracks real media traffic
203
+ #recoveryAttempts = 0; // JAP@Fix: consecutive failed recoveries for the current call
204
+ #capturePtr = 0;
205
+ #captureChunkBytes = 0;
206
+ #captureSampleRate = 16000;
207
+ #captureChannels = 1;
208
+ #captureFramesPerChunk = 320;
209
+ #feeder = null;
210
+
211
+ constructor(config = {}) {
212
+ super(); // JAP@Add --- VoipClient now emits 'incoming-call' / 'outgoing-call' / 'call-ended'
213
+ this.#config = config;
214
+ }
215
+
216
+ connectWithSocket = async (existingSock) => {
217
+ this.#sock = existingSock;
218
+ await this.#initVoipStack();
219
+ };
220
+
221
+ #initVoipStack = async () => {
222
+ this.#signaling = new SignalingBridge({
223
+ sock: this.#sock,
224
+ // JAP@Add --- surface inbound offers as 'incoming-call' events
225
+ onIncomingCall: (info) => this.#handleIncomingCall(info),
226
+ });
227
+ await this.#signaling.init();
228
+
229
+ this.#relay = this.#config.relay ?? new RelayRtcTransport({
230
+ onTransportMessage: (data, ip, port) => this.#engine?.handleOnTransportMessage(data, ip, port),
231
+ onIceRtt: (rttMs, ip, port) => this.#engine?.updateIceRtt(rttMs, ip, port),
232
+ });
233
+
234
+ // JAP@Add --- `config.engine`/`config.relay` injection (tests + custom stacks)
235
+ this.#engine = this.#config.engine ?? new WasmEngine({
236
+ resourcesPath: this.#config.resourcesPath,
237
+ callbacks: {
238
+ onSignalingXmpp: (peerJid, callId, xmlPayload) =>
239
+ this.#signaling.sendSignaling(peerJid, callId, xmlPayload),
240
+ onCallEvent: (eventType, eventData) => this.#handleCallEvent(eventType, eventData),
241
+ sendDataToRelay: (data, ip, port) => this.#relay.send(data, ip, port),
242
+ onAudioCaptureInit: (config) => this.#handleAudioCaptureInit(config),
243
+ onAudioCaptureStart: () => this.#handleAudioCaptureStart(),
244
+ onAudioCaptureStop: () => this.#handleAudioCaptureStop(),
245
+ onAudioPlaybackData: (audioData) => this.#activeCall?._emitAudio(audioData),
246
+ cryptoHkdf: computeHkdf,
247
+ hmacSha256: computeHmacSha256,
248
+ },
249
+ });
250
+
251
+ await this.#engine.initialize();
252
+ this.#signaling.attachEngine(this.#engine);
253
+
254
+ const selfPnJid = this.#sock.authState.creds.me?.id;
255
+ const selfLidJid = this.#sock.authState.creds.me?.lid;
256
+ this.#engine.initVoipStack(selfPnJid, toBareJid(selfPnJid), selfLidJid);
257
+ await this.#engine.waitForVoipStackReady();
258
+ try { this.#engine.updateNetworkMedium(2, 0); } catch {}
259
+
260
+ this.#sock.ws.on("CB:call", (node) => {
261
+ this.#signaling.processIncomingCall(node, this.#engine, this.#activeCall?.callId ?? "");
262
+ });
263
+ this.#sock.ws.on("CB:receipt", (node) => {
264
+ if (!isCallReceiptNode(node)) return;
265
+ this.#signaling.processIncomingReceipt(node, this.#engine, this.#activeCall?.callId ?? "");
266
+ });
267
+ // JAP@Add --- socket-drop recovery: end media cleanly, re-announce on reconnect
268
+ try {
269
+ this.#sock.ev.on("connection.update", ({ connection }) => {
270
+ if (connection === "close" && this.#activeCall) {
271
+ this.#activeCall._forceEnd("socket_closed");
272
+ } else if (connection === "open") {
273
+ this.emit("voip-ready", {});
274
+ }
275
+ });
276
+ } catch {}
277
+ };
278
+
279
+ /** JAP@Add --- true while a call object exists (dialing, ringing or active). */
280
+ /**
281
+ * JAP@Add --- swap the active call's uplink audio source mid-call (see
282
+ * ActiveCall.setAudioSource for the accepted source shapes). Throws when no
283
+ * call is active. Returns true when a live ffmpeg decoder was swapped,
284
+ * false when audio capture has not started yet (the source is stored and
285
+ * used as soon as the engine opens the uplink).
286
+ */
287
+ setAudioSource = (source) => {
288
+ if (!this.#activeCall) throw new Error("setAudioSource: no active call");
289
+ this.#activeCall._audioSource = source;
290
+ if (this.#feeder) return this.#feeder.swapSource(source);
291
+ return false;
292
+ };
293
+
294
+ isBusy = () => !!this.#activeCall;
295
+
296
+ /** JAP@Add --- the current ActiveCall, or null when idle. */
297
+ getActiveCall = () => this.#activeCall;
298
+
299
+ #handleIncomingCall = (info) => {
300
+ this.emit("incoming-call", { ...info, busy: this.isBusy() });
301
+ if (info.busy || info.ignored) return;
302
+ // JAP@Add --- optional auto-reject
303
+ if (this.#config?.autoReject) {
304
+ void this.rejectCall(info.callId, info.from).catch(() => {});
305
+ return;
306
+ }
307
+ // JAP@Add --- optional auto-answer (1:1) / auto-join (group)
308
+ if (this.#config?.autoAnswer && !info.isGroupCall) {
309
+ void this.answerCall(info.callId, { audioSource: this.#config.audioSource }).catch(() => {});
310
+ } else if (this.#config?.autoJoinGroup && info.isGroupCall) {
311
+ void this.joinGroupCall(info.callId, { audioSource: this.#config.audioSource }).catch(() => {});
312
+ }
313
+ };
314
+
315
+ /** JAP@Add --- pending inbound offers (answers must come from here). */
316
+ getPendingCalls = () => this.#signaling?.listPendingOffers?.() ?? [];
317
+
318
+ /**
319
+ * JAP@Add --- decline an inbound call (delegates to the socket's `rejectCall`)
320
+ * and optionally send a text reply to the caller.
321
+ */
322
+ rejectCall = async (callId, callFrom, { text } = {}) => {
323
+ if (!this.#sock) throw new Error("Not connected. Call connectWithSocket() first.");
324
+ await this.#sock.rejectCall(callId, callFrom);
325
+ const replyText = text ?? this.#config?.autoRejectText;
326
+ if (replyText) {
327
+ try { await this.#sock.sendMessage(callFrom, { text: replyText }); } catch {}
328
+ }
329
+ };
330
+
331
+ /**
332
+ * JAP@Add --- answer an inbound 1:1 call. The offer must still be pending
333
+ * (see `getPendingCalls()`); offers expire after `offerTtlMs` (default 45s).
334
+ */
335
+ answerCall = async (callId, { audioSource = "silence", durationMs = 120_000, isMicEnabled = true } = {}) => {
336
+ if (!this.#engine || !this.#signaling) throw new Error("Not connected. Call connectWithSocket() first.");
337
+ if (this.#activeCall) throw new Error("A call is already active.");
338
+ const offer = this.#signaling.takePendingOffer(callId);
339
+ if (!offer) throw new Error(`No pending inbound offer for ${callId} (expired, answered, or unknown)`);
340
+ const ttl = this.#config?.offerTtlMs ?? 45_000;
341
+ if (Date.now() - offer.receivedAt > ttl) throw new Error(`Inbound offer ${callId} expired`);
342
+ if (offer.isGroupCall) throw new Error(`Offer ${callId} is a group call — use joinGroupCall() instead`);
343
+ const call = new ActiveCall(callId, this.#engine, durationMs, { direction: "inbound", from: offer.from });
344
+ call._audioSource = audioSource;
345
+ this.#activeCall = call;
346
+ call._switchAudioSource = (source) => this.setAudioSource(source); // JAP@Add --- mid-call source swap
347
+ this.#lastPeer = { peerJid: offer.from, callId };
348
+ call.once("ended", (reason) => {
349
+ if (this.#activeCall === call) this.#activeCall = null;
350
+ this.#stopWatchdog();
351
+ this.emit("call-ended", { callId, reason });
352
+ });
353
+ this.#engine.acceptCall({ isMicEnabled });
354
+ call._updateState(CallState.AcceptSent);
355
+ this.emit("call-answered", { callId, from: offer.from });
356
+ this.#startWatchdog();
357
+ return call;
358
+ };
359
+
360
+ /**
361
+ * JAP@Add --- join an inbound group call (offer must be pending).
362
+ */
363
+ joinGroupCall = async (callId, { audioSource = "silence", durationMs = 120_000, hasVideo = false, joinAndAccept = true, chatName = "" } = {}) => {
364
+ if (!this.#engine || !this.#signaling) throw new Error("Not connected. Call connectWithSocket() first.");
365
+ if (this.#activeCall) throw new Error("A call is already active.");
366
+ const offer = this.#signaling.takePendingOffer(callId);
367
+ if (!offer) throw new Error(`No pending group offer for ${callId} (expired, joined, or unknown)`);
368
+ const ttl = this.#config?.offerTtlMs ?? 45_000;
369
+ if (Date.now() - offer.receivedAt > ttl) throw new Error(`Group offer ${callId} expired`);
370
+ const call = new ActiveCall(callId, this.#engine, durationMs, { direction: "group-inbound", from: offer.from, groupJid: offer.groupJid });
371
+ call._audioSource = audioSource;
372
+ this.#activeCall = call;
373
+ call._switchAudioSource = (source) => this.setAudioSource(source); // JAP@Add --- mid-call source swap
374
+ this.#lastPeer = { peerJid: offer.from, callId };
375
+ this.#lastGroupJoin = {
376
+ callId, callCreatorJid: offer.callCreator, initialPeerJid: offer.from,
377
+ hasVideo, groupJid: offer.groupJid, joinAndAccept, chatName,
378
+ };
379
+ call.once("ended", (reason) => {
380
+ if (this.#activeCall === call) this.#activeCall = null;
381
+ this.#stopWatchdog();
382
+ this.emit("call-ended", { callId, reason });
383
+ });
384
+ this.#engine.joinOngoingCall({ ...this.#lastGroupJoin });
385
+ this.emit("group-call-joined", { callId, groupJid: offer.groupJid, from: offer.from });
386
+ this.#startWatchdog();
387
+ return call;
388
+ };
389
+
390
+ /**
391
+ * JAP@Add --- start a new outbound group call.
392
+ * `participants`: phone numbers (digits) — LIDs are resolved automatically.
393
+ */
394
+ startGroupCall = async (groupJid, participants = [], { audioSource = "silence", durationMs = 120_000, useVideo = false, chatName = "" } = {}) => {
395
+ if (!this.#engine || !this.#signaling) throw new Error("Not connected. Call connectWithSocket() first.");
396
+ if (this.#activeCall) throw new Error("A call is already active.");
397
+ if (!groupJid || !participants.length) throw new Error("startGroupCall(groupJid, participants) needs a group + at least 1 participant");
398
+ const pnJids = participants.map((p) => `${String(p).replace(/\D/g, "")}@s.whatsapp.net`);
399
+ const lidJids = [];
400
+ for (const pn of pnJids) {
401
+ try { await this.#sock.presenceSubscribe(pn); } catch {}
402
+ try {
403
+ const lid = await this.#signaling.resolveLid(pn);
404
+ if (lid) lidJids.push(lid);
405
+ } catch {}
406
+ }
407
+ const deviceJids = [];
408
+ for (const lid of lidJids.length ? lidJids : pnJids) {
409
+ try {
410
+ const devs = await this.#signaling.discoverPeerDevices(lid);
411
+ deviceJids.push(...devs);
412
+ } catch {}
413
+ }
414
+ await this.#signaling.ensureSessionsForPeers(deviceJids.length ? deviceJids : pnJids);
415
+ const callId = ("00" + randomBytes(16).toString("hex").slice(2)).toUpperCase();
416
+ const call = new ActiveCall(callId, this.#engine, durationMs, { direction: "group-outbound", groupJid });
417
+ call._audioSource = audioSource;
418
+ this.#activeCall = call;
419
+ call._switchAudioSource = (source) => this.setAudioSource(source); // JAP@Add --- mid-call source swap
420
+ this.#lastPeer = { peerJid: groupJid, callId };
421
+ call.once("ended", (reason) => {
422
+ if (this.#activeCall === call) this.#activeCall = null;
423
+ this.#stopWatchdog();
424
+ this.emit("call-ended", { callId, reason });
425
+ });
426
+ this.emit("group-call-started", { callId, groupJid });
427
+ this.#engine.startGroupCall({ pnUserJids: pnJids, lidUserJids: lidJids, deviceJidsCsv: deviceJids.slice(0, 32), callId, useVideo, groupJid, chatName });
428
+ this.#startWatchdog();
429
+ return call;
430
+ };
431
+
432
+ /** JAP@Add --- rejoin the last group call (recovery after a drop). */
433
+ rejoinGroupCall = async (overrides = {}) => {
434
+ if (!this.#engine) throw new Error("Not connected. Call connectWithSocket() first.");
435
+ if (this.#activeCall) throw new Error("A call is already active.");
436
+ if (!this.#lastGroupJoin) throw new Error("No previous group call to rejoin");
437
+ const params = { ...this.#lastGroupJoin, ...overrides };
438
+ const call = new ActiveCall(params.callId, this.#engine, overrides.durationMs ?? 120_000, { direction: "group-inbound", groupJid: params.groupJid });
439
+ call._audioSource = overrides.audioSource ?? "silence";
440
+ this.#activeCall = call;
441
+ call._switchAudioSource = (source) => this.setAudioSource(source); // JAP@Add --- mid-call source swap
442
+ call.once("ended", (reason) => {
443
+ if (this.#activeCall === call) this.#activeCall = null;
444
+ this.#stopWatchdog();
445
+ this.emit("call-ended", { callId: params.callId, reason });
446
+ });
447
+ this.#engine.joinOngoingCall(params);
448
+ this.emit("group-call-rejoined", { callId: params.callId, groupJid: params.groupJid });
449
+ this.#startWatchdog();
450
+ return call;
451
+ };
452
+
453
+ /** JAP@Add --- invite a participant into the active group call. */
454
+ inviteToGroupCall = async (phoneNumber, deviceJids = []) => {
455
+ if (!this.#activeCall) throw new Error("No active call");
456
+ const targetNumber = String(phoneNumber).replace(/\D/g, "");
457
+ const lid = await this.#signaling.resolveLid(`${targetNumber}@s.whatsapp.net`).catch(() => "");
458
+ return this.#activeCall.invite(`${targetNumber}@s.whatsapp.net`, lid || "", deviceJids);
459
+ };
460
+
461
+ /** JAP@Add --- kick a participant from the active group call. */
462
+ removeGroupParticipant = async (peerJid) => {
463
+ if (!this.#activeCall) throw new Error("No active call");
464
+ return this.#activeCall.removeParticipant(peerJid);
465
+ };
466
+
467
+ /** JAP@Add --- call-link preview/join (scheduled / lobby calls). */
468
+ previewCallLink = (token, opts = {}) => {
469
+ if (!this.#engine) throw new Error("Not connected. Call connectWithSocket() first.");
470
+ return this.#engine.previewCallLink({ token, ...opts });
471
+ };
472
+ joinCallLink = () => {
473
+ if (!this.#engine) throw new Error("Not connected. Call connectWithSocket() first.");
474
+ return this.#engine.joinCallLink();
475
+ };
476
+
477
+ /** JAP@Add --- combined engine + relay stats snapshot. */
478
+ getStats = () => {
479
+ let call = null;
480
+ try { call = this.#engine?.getCallInfo?.() ?? null; } catch {}
481
+ let relay = null;
482
+ try { relay = this.#relay?.getStats?.() ?? null; } catch {}
483
+ return { busy: this.isBusy(), callId: this.#activeCall?.callId ?? null, call, relay };
484
+ };
485
+
486
+ /**
487
+ * JAP@Add --- media-path recovery: re-send the crypto rekey + the call offer.
488
+ * Called automatically by the watchdog; safe to call manually too.
489
+ */
490
+ recoverCall = async ({ peerJid, callId, retryCount = 1 } = {}) => {
491
+ const target = peerJid || this.#lastPeer?.peerJid;
492
+ const id = callId || this.#lastPeer?.callId || this.#activeCall?.callId;
493
+ if (!target || !id) throw new Error("recoverCall needs a peer (no call on record)");
494
+ // JAP@Fix (recovery): fail loudly when there is no engine at all — the old
495
+ // silent catch made a fully-disconnected client report a "recovery" that
496
+ // did nothing, so watchdog loops looked healthy while sending zero bytes.
497
+ if (!this.#engine) throw new Error("recoverCall: engine not connected (connectWithSocket() first)");
498
+ const out = { rekey: false, offer: false };
499
+ try { this.#engine.resendEncRekeyRetry(target, retryCount); out.rekey = true; } catch {}
500
+ try { this.#engine.resendOfferOnDecryptionFailure(target, id); out.offer = true; } catch {}
501
+ this.emit("call-recovery", { peerJid: target, callId: id, ...out });
502
+ return out;
503
+ };
504
+
505
+ call = async (phoneNumber, opts = {}) => {
506
+ if (!this.#engine || !this.#signaling) throw new Error("Not connected. Call connectWithSocket() first.");
507
+ if (this.#activeCall) throw new Error("A call is already active.");
508
+
509
+ const targetNumber = phoneNumber.replace(/\D/g, "");
510
+ const targetPnJid = `${targetNumber}@s.whatsapp.net`;
511
+ const durationMs = opts.durationMs ?? 120_000;
512
+ const audioSource = opts.audioSource ?? "silence";
513
+
514
+ const peerLid = await this.#signaling.resolveLid(targetPnJid);
515
+ if (!peerLid) throw new Error(`Could not resolve LID for ${targetPnJid}`);
516
+
517
+ for (const jid of [targetPnJid, peerLid]) {
518
+ try { await this.#sock.presenceSubscribe(jid); } catch {}
519
+ }
520
+ await new Promise((r) => setTimeout(r, 750));
521
+
522
+ const peerDeviceJids = await this.#signaling.discoverPeerDevices(peerLid);
523
+ const deviceList = peerDeviceJids.length ? peerDeviceJids : [toBareJid(peerLid)];
524
+
525
+ await this.#signaling.ensureSessionsForPeers(deviceList);
526
+
527
+ await new Promise((r) => setTimeout(r, 500));
528
+ await this.#signaling.issueTcToken(peerLid);
529
+ const tcToken = await this.#signaling.ensureTcToken(peerLid, targetPnJid);
530
+
531
+ const callId = ("00" + randomBytes(16).toString("hex").slice(2)).toUpperCase();
532
+
533
+ const call = new ActiveCall(callId, this.#engine, durationMs);
534
+ call._audioSource = audioSource;
535
+ this.#activeCall = call;
536
+ call._switchAudioSource = (source) => this.setAudioSource(source); // JAP@Add --- mid-call source swap
537
+ // JAP@Fix: release the slot when the call ends (was never cleared → isBusy stuck true)
538
+ call.once("ended", (reason) => {
539
+ if (this.#activeCall === call) this.#activeCall = null;
540
+ this.#stopWatchdog();
541
+ this.emit("call-ended", { callId, reason });
542
+ });
543
+ this.emit("outgoing-call", { callId, to: targetPnJid });
544
+ this.#lastPeer = { peerJid: peerLid, callId };
545
+ this.#startWatchdog();
546
+
547
+ this.#engine.startCall({
548
+ peerJid: peerLid,
549
+ peerPn: targetPnJid,
550
+ peerList: deviceList,
551
+ callId,
552
+ isVideo: false,
553
+ isLidCall: true,
554
+ isFromDialer: false,
555
+ extraData: tcToken,
556
+ });
557
+
558
+ return call;
559
+ };
560
+
561
+ #startWatchdog = () => {
562
+ this.#stopWatchdog();
563
+ const intervalMs = this.#config?.watchdogIntervalMs ?? 5000;
564
+ const maxSilent = this.#config?.watchdogMaxSilent ?? 3;
565
+ if (!intervalMs || !maxSilent) return;
566
+ this.#watchdogMisses = 0;
567
+ this.#lastReceivedPackets = -1;
568
+ this.#watchdogTimer = setInterval(() => {
569
+ if (!this.#activeCall) { this.#stopWatchdog(); return; }
570
+ // JAP@Fix (watchdog on real media traffic): "openConnections > 0" only
571
+ // proves a transport EXISTS, not that media flows — a relay can sit in
572
+ // the open state receiving zero RTP for the entire call (NAT drop,
573
+ // relay-side eviction) and the old check called that healthy. Health is
574
+ // now defined as receivedPackets INCREASING between ticks once the call
575
+ // is active. Before the first packet ever arrives (dialing/ringing) we
576
+ // fall back to the transport-existence check so we don't kill call setup.
577
+ let stats = null;
578
+ try { stats = this.#relay?.getStats?.() ?? null; } catch {}
579
+ const open = stats?.openConnections ?? -1;
580
+ const received = stats?.receivedPackets ?? -1;
581
+ const callIsActive = this.#activeCall.state === CallState.Active;
582
+ const sawFirstPacket = received > 0;
583
+ let healthy;
584
+ if (callIsActive && sawFirstPacket && received >= 0 && this.#lastReceivedPackets >= 0) {
585
+ healthy = received > this.#lastReceivedPackets; // real media moved
586
+ } else {
587
+ healthy = open !== 0; // setup phase: transport existing is enough
588
+ }
589
+ this.#lastReceivedPackets = received;
590
+ if (!healthy) {
591
+ this.#watchdogMisses += 1;
592
+ } else {
593
+ this.#watchdogMisses = 0;
594
+ this.#recoveryAttempts = 0; // healthy again — reset the recovery budget
595
+ }
596
+ if (this.#watchdogMisses >= maxSilent) {
597
+ this.#watchdogMisses = 0;
598
+ // JAP@Fix (recovery): the old loop retried forever with no memory —
599
+ // a dead relay meant rekey+offer spam every N*interval for the whole
600
+ // call, and the caller never learned recovery had failed. Now each
601
+ // call gets a bounded budget (default 3); when it runs out we emit
602
+ // 'call-unrecoverable' and force-end so upper layers can redial.
603
+ const maxRecoveries = this.#config?.watchdogMaxRecoveries ?? 3;
604
+ this.#recoveryAttempts += 1;
605
+ this.emit("call-degraded", {
606
+ callId: this.#activeCall.callId,
607
+ attempt: this.#recoveryAttempts,
608
+ maxRecoveries,
609
+ });
610
+ if (this.#recoveryAttempts > maxRecoveries) {
611
+ const dyingCallId = this.#activeCall.callId;
612
+ this.#recoveryAttempts = 0;
613
+ this.emit("call-unrecoverable", { callId: dyingCallId });
614
+ this.#activeCall._forceEnd("unrecoverable");
615
+ return;
616
+ }
617
+ void this.recoverCall({}).catch(() => {});
618
+ }
619
+ }, intervalMs);
620
+ this.#watchdogTimer.unref?.();
621
+ };
622
+
623
+ #stopWatchdog = () => {
624
+ if (this.#watchdogTimer) { clearInterval(this.#watchdogTimer); this.#watchdogTimer = null; }
625
+ this.#watchdogMisses = 0;
626
+ this.#recoveryAttempts = 0;
627
+ };
628
+
629
+ disconnect = () => {
630
+ this.#stopWatchdog();
631
+ this.#activeCall?._forceEnd("disconnect");
632
+ this.#activeCall = null;
633
+ this.#relay?.closeAll();
634
+ this.#engine?.destroy();
635
+ this.#engine = null;
636
+ this.#relay = null;
637
+ this.#signaling = null;
638
+ this.#sock = null;
639
+ };
640
+
641
+ #handleCallEvent = (eventType, eventData) => {
642
+ if (eventType === 16 && eventData) {
643
+ try {
644
+ const parsed = JSON.parse(eventData);
645
+ const info = parsed.call_info ?? parsed.callInfo ?? {};
646
+ const callState = Number(info.call_state ?? info.callState ?? 0);
647
+ this.#activeCall?._updateState(callState);
648
+ } catch {}
649
+ } else if (eventType === 156 && eventData) {
650
+ try {
651
+ const update = JSON.parse(eventData);
652
+ this.#relay?.updateRelayList(update);
653
+ } catch {}
654
+ } else if (eventType === 2) {
655
+ this.#activeCall?._forceEnd("remote_end");
656
+ }
657
+ };
658
+
659
+ #handleAudioCaptureInit = (config) => {
660
+ if (!this.#engine) return;
661
+ this.#captureSampleRate = config.sampleRate || 16000;
662
+ this.#captureChannels = config.channels || 1;
663
+ this.#captureFramesPerChunk = config.framesPerChunk || 320;
664
+ const chunkSamples = this.#captureFramesPerChunk * this.#captureChannels;
665
+ this.#captureChunkBytes = chunkSamples * Float32Array.BYTES_PER_ELEMENT;
666
+ this.#capturePtr = this.#engine.malloc(this.#captureChunkBytes);
667
+ };
668
+
669
+ #handleAudioCaptureStart = () => {
670
+ if (!this.#engine || !this.#capturePtr) return;
671
+ const audioSource = this.#activeCall?._audioSource ?? "silence";
672
+ this.#feeder = new AudioFeeder(
673
+ this.#captureSampleRate,
674
+ this.#captureChannels,
675
+ this.#captureFramesPerChunk,
676
+ (chunk) => {
677
+ if (this.#engine && this.#capturePtr) this.#engine.sendAudioData(chunk, this.#capturePtr);
678
+ },
679
+ audioSource,
680
+ );
681
+ this.#feeder.start();
682
+ };
683
+
684
+ #handleAudioCaptureStop = () => {
685
+ this.#feeder?.stop();
686
+ this.#feeder = null;
687
+ if (this.#engine && this.#capturePtr) {
688
+ try { this.#engine.free(this.#capturePtr); } catch {}
689
+ this.#capturePtr = 0;
690
+ }
691
+ };
692
+ }
693
+
694
+
695
+ /**
696
+ * JAP@Add --- one-liner VoIP setup: creates a VoipClient, binds it to an active
697
+ * Baileys socket, stores it as `sock.voip`, and returns it.
698
+ *
699
+ * ```js
700
+ * import { attachVoip } from '@japofc/baileys'
701
+ * const voip = await attachVoip(sock, {
702
+ * autoReject: true, // decline inbound calls automatically
703
+ * autoRejectText: 'Bot cannot take calls, please type your message 🙏',
704
+ * // autoAnswer: true, // ...or answer them instead
705
+ * // autoJoinGroup: true, // ...or auto-join group calls
706
+ * })
707
+ * voip.on('incoming-call', ({ from }) => console.log('ringing from', from))
708
+ * const call = await voip.call('62812xxxx', { audioSource: './greeting.mp3' })
709
+ * await call.waitForEnd()
710
+ * ```
711
+ */
712
+ export const attachVoip = async (sock, config = {}) => {
713
+ if (!sock?.ws) throw new Error("attachVoip(sock) requires an active Baileys socket.");
714
+ const client = new VoipClient(config);
715
+ await client.connectWithSocket(sock);
716
+ try { sock.voip = client; } catch {}
717
+ return client;
718
+ };