@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.
@@ -1,18 +1,70 @@
1
+ import type { EventEmitter } from 'events';
2
+
3
+ export { CallState } from './types.js';
4
+ export { ActiveCall, VoipClient as GroupVoipClient, attachVoip } from './group-call.js';
5
+
6
+ export interface WASocketLike {
7
+ ev: { on(event: string, listener: (...args: any[]) => void): any; off?(event: string, listener: (...args: any[]) => void): any };
8
+ rejectCall?(callId: string, callFrom: string): Promise<unknown>;
9
+ createCallLink?(type: 'audio' | 'video', event?: number, timeoutMs?: number): Promise<unknown>;
10
+ updateCallPrivacy?(value: 'all' | 'known'): Promise<unknown>;
11
+ requestPairingCode?(phoneNumber: string, customPairingCode?: string): Promise<string>;
12
+ }
13
+
1
14
  export declare class CallManager {
2
- constructor(sock: WASocket);
15
+ constructor(sock: WASocketLike);
3
16
  on(listener: (calls: unknown[]) => void): () => void;
4
17
  off(listener: (calls: unknown[]) => void): this;
5
18
  reject(call: { id: string; from: string }): Promise<unknown>;
6
19
  createLink(type?: 'audio' | 'video', event?: number, timeoutMs?: number): Promise<unknown>;
7
20
  setPrivacy(value: 'all' | 'known'): Promise<unknown>;
8
21
  createVoipClient(options: VoipClientOptions): VoipClient;
22
+ createGroupVoipClient(options?: import('./group-call.js').VoipClientConfig): import('./group-call.js').VoipClient;
23
+ attachVoip(options?: import('./group-call.js').VoipClientConfig): Promise<import('./group-call.js').VoipClient>;
9
24
  static readonly capabilities: Readonly<Record<string, boolean>>;
10
25
  }
11
- export interface VoipClientOptions { authDir: string; usePairingCode?: boolean; phoneNumber?: string }
12
- export declare class VoipClient {
26
+
27
+ export interface VoipClientOptions {
28
+ /** Folder session VoIP — HARUS terpisah dari session bot */
29
+ authDir: string;
30
+ /** Pakai pairing code (disarankan) instead of QR */
31
+ usePairingCode?: boolean;
32
+ /** Wajib jika usePairingCode — nomor dengan country code, digits */
33
+ phoneNumber?: string;
34
+ /** Default false. true = izinkan QR (tidak disarankan di bot) */
35
+ printQR?: boolean;
36
+ /** Callback saat pairing code tersedia */
37
+ onPairingCode?: (code: string) => void;
38
+ /** Optional parent bot socket */
39
+ sock?: WASocketLike;
40
+ socket?: WASocketLike;
41
+ }
42
+
43
+ export interface VoipCallOptions {
44
+ audioSource?: string | 'silence';
45
+ durationMs?: number;
46
+ repeatAudio?: boolean;
47
+ [key: string]: unknown;
48
+ }
49
+
50
+ export declare class VoipClient extends EventEmitter {
13
51
  constructor(options: VoipClientOptions);
52
+ readonly isRegistered: boolean;
53
+ readonly isConnected: boolean;
54
+ /** Bind parent bot socket — tidak buka session / QR */
55
+ attach(sock: WASocketLike): this;
56
+ /** Connect media engine (reuse creds di authDir jika ada) */
14
57
  connect(): Promise<this>;
15
- call(phoneNumber: string, options?: { audioSource?: string | 'silence'; durationMs?: number }): Promise<unknown>;
58
+ call(phoneNumber: string, options?: VoipCallOptions): Promise<unknown>;
16
59
  disconnect(): void;
60
+ getCallManager(): CallManager | null;
17
61
  static readonly capabilities: Readonly<Record<string, boolean>>;
62
+ on(event: 'pairing-code' | 'qr' | 'connected' | 'disconnected' | 'attached', listener: (...args: any[]) => void): this;
18
63
  }
64
+
65
+ export declare function createBotVoipClient(
66
+ sock: WASocketLike | null | undefined,
67
+ options?: Partial<VoipClientOptions> & { botAuthDir?: string },
68
+ ): VoipClient;
69
+
70
+ export declare function attachCalling(sock: WASocketLike): CallManager;
package/lib/VoIP/index.js CHANGED
@@ -1,81 +1,396 @@
1
1
  /**
2
- * Call-control APIs on the primary Baileys socket plus an optional outbound
3
- * VoIP media client adapter. Incoming media, video and group RTC are not
4
- * provided by the current upstream caller engine.
2
+ * Call-control on the primary Baileys socket + optional outbound VoIP media client.
3
+ *
4
+ * Design (matang untuk bot seperti KuzeMD):
5
+ * 1) CallManager(sock) → event/reject/link di SOCKET BOT yang sudah login (tanpa session baru)
6
+ * 2) VoipClient → media call 1:1 via engine @paiavaliable/baileys-caller
7
+ * - Session TERPISAH (multi-device linked device), folder authDir sendiri
8
+ * - Setelah sekali pair, creds tersimpan → connect() berikutnya TANPA QR
9
+ * - usePairingCode + phoneNumber → pairing code (bukan QR)
10
+ * - attach(sock) menyimpan parent sock untuk koordinasi (bukan hijack)
11
+ *
12
+ * Incoming RTC media / video / group call: belum didukung engine upstream.
5
13
  */
14
+
15
+ import fs from 'fs';
16
+ import path from 'path';
17
+ import { EventEmitter } from 'events';
18
+ import { VoipClient as GroupVoipClient } from './group-call.js';
19
+
20
+ function hasCreds(authDir) {
21
+ try {
22
+ const p = path.join(authDir, 'creds.json');
23
+ if (!fs.existsSync(p)) return false;
24
+ const j = JSON.parse(fs.readFileSync(p, 'utf8'));
25
+ return Boolean(j?.me?.id || j?.me);
26
+ } catch {
27
+ return false;
28
+ }
29
+ }
30
+
31
+ function ensureDir(dir) {
32
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
33
+ }
34
+
35
+ /* ─────────────────────────────────────────────
36
+ * CallManager — pakai socket bot yang sudah open
37
+ * ───────────────────────────────────────────── */
6
38
  export class CallManager {
7
39
  constructor(sock) {
8
40
  if (!sock || !sock.ev) throw new TypeError('A Baileys socket is required.');
9
41
  this.sock = sock;
10
42
  }
43
+
11
44
  on(listener) {
12
45
  if (typeof listener !== 'function') throw new TypeError('Call listener must be a function.');
13
46
  this.sock.ev.on('call', listener);
14
47
  return () => this.off(listener);
15
48
  }
16
- off(listener) { this.sock.ev.off?.('call', listener); return this; }
49
+
50
+ off(listener) {
51
+ this.sock.ev.off?.('call', listener);
52
+ return this;
53
+ }
54
+
17
55
  async reject(call) {
18
56
  const callId = call?.id;
19
57
  const callFrom = call?.from;
20
58
  if (!callId || !callFrom) throw new TypeError('Call event must contain id and from.');
21
- if (typeof this.sock.rejectCall !== 'function') throw new Error('rejectCall is not supported by this socket.');
59
+ if (typeof this.sock.rejectCall !== 'function') {
60
+ throw new Error('rejectCall is not supported by this socket.');
61
+ }
22
62
  return this.sock.rejectCall(callId, callFrom);
23
63
  }
64
+
24
65
  async createLink(type = 'audio', event, timeoutMs) {
25
- if (type !== 'audio' && type !== 'video') throw new TypeError('Call link type must be audio or video.');
26
- if (typeof this.sock.createCallLink !== 'function') throw new Error('createCallLink is not supported by this socket.');
66
+ if (type !== 'audio' && type !== 'video') {
67
+ throw new TypeError('Call link type must be audio or video.');
68
+ }
69
+ if (typeof this.sock.createCallLink !== 'function') {
70
+ throw new Error('createCallLink is not supported by this socket.');
71
+ }
27
72
  return this.sock.createCallLink(type, event, timeoutMs);
28
73
  }
74
+
29
75
  async setPrivacy(value) {
30
- if (value !== 'all' && value !== 'known') throw new TypeError('Call privacy must be all or known.');
31
- if (typeof this.sock.updateCallPrivacy !== 'function') throw new Error('updateCallPrivacy is not supported by this socket.');
76
+ if (value !== 'all' && value !== 'known') {
77
+ throw new TypeError('Call privacy must be all or known.');
78
+ }
79
+ if (typeof this.sock.updateCallPrivacy !== 'function') {
80
+ throw new Error('updateCallPrivacy is not supported by this socket.');
81
+ }
32
82
  return this.sock.updateCallPrivacy(value);
33
83
  }
34
- createVoipClient(options = {}) { return new VoipClient(options); }
84
+
85
+ /** Create the experimental shared-socket group-call engine (JAPofc VoIP port). */
86
+ createGroupVoipClient(options = {}) {
87
+ return new GroupVoipClient(options);
88
+ }
89
+
90
+ /** Attach the group-call engine to this existing socket. */
91
+ async attachVoip(options = {}) {
92
+ const client = new GroupVoipClient(options);
93
+ await client.connectWithSocket(this.sock);
94
+ try { this.sock.voip = client; } catch {}
95
+ return client;
96
+ }
97
+
98
+ /** Factory VoipClient (session media terpisah) */
99
+ createVoipClient(options = {}) {
100
+ return new VoipClient(options);
101
+ }
102
+
35
103
  static get capabilities() {
36
- return Object.freeze({ incomingCallEvents: true, rejectIncomingCall: true, createAudioVideoCallLink: true, outboundVoiceClientAvailable: true, inboundRtcMedia: false, videoRtc: false, groupRtc: false, voiceClientUsesSeparateSession: true });
104
+ return Object.freeze({
105
+ incomingCallEvents: true,
106
+ rejectIncomingCall: true,
107
+ createAudioVideoCallLink: true,
108
+ outboundVoiceClientAvailable: true,
109
+ inboundRtcMedia: false,
110
+ videoRtc: false,
111
+ groupRtc: false,
112
+ /** media outbound tetap session linked-device terpisah */
113
+ voiceClientUsesSeparateSession: true,
114
+ parentSocketAttach: true,
115
+ pairingCode: true,
116
+ });
37
117
  }
38
118
  }
39
119
 
40
- /** Lazy adapter for the MIT-licensed baileys-caller engine. It owns a separate
41
- * linked-device session using authDir; it does not hijack the parent socket. */
42
- export class VoipClient {
120
+ /* ─────────────────────────────────────────────
121
+ * VoipClient — outbound media (session sendiri)
122
+ * ───────────────────────────────────────────── */
123
+ export class VoipClient extends EventEmitter {
124
+ /**
125
+ * @param {object} options
126
+ * @param {string} options.authDir - folder session VoIP (PISAH dari session bot)
127
+ * @param {boolean} [options.usePairingCode] - pakai pairing code, bukan QR
128
+ * @param {string} [options.phoneNumber] - wajib jika usePairingCode (digits, country code)
129
+ * @param {import('events').EventEmitter} [options.sock] - optional parent bot socket (attach)
130
+ * @param {boolean} [options.printQR] - default false (bot-friendly)
131
+ * @param {(code: string) => void} [options.onPairingCode] - callback saat dapat pairing code
132
+ */
43
133
  constructor(options = {}) {
44
- if (!options || typeof options !== 'object') throw new TypeError('VoipClient options must be an object.');
45
- if (typeof options.authDir !== 'string' || !options.authDir.trim()) throw new TypeError('VoipClient requires a non-empty authDir for its separate linked-device session.');
46
- this.options = { authDir: options.authDir, ...(options.usePairingCode !== undefined ? { usePairingCode: Boolean(options.usePairingCode) } : {}), ...(options.phoneNumber ? { phoneNumber: String(options.phoneNumber).replace(/\D/g, '') } : {}) };
47
- if (this.options.usePairingCode && !this.options.phoneNumber) throw new TypeError('phoneNumber is required when usePairingCode is enabled.');
134
+ super();
135
+ if (!options || typeof options !== 'object') {
136
+ throw new TypeError('VoipClient options must be an object.');
137
+ }
138
+ if (typeof options.authDir !== 'string' || !options.authDir.trim()) {
139
+ throw new TypeError(
140
+ 'VoipClient requires authDir (folder session VoIP TERPISAH dari session bot).',
141
+ );
142
+ }
143
+
144
+ const authDir = path.resolve(options.authDir.trim());
145
+ const usePairingCode = Boolean(options.usePairingCode);
146
+ const phoneNumber = options.phoneNumber
147
+ ? String(options.phoneNumber).replace(/\D/g, '')
148
+ : '';
149
+
150
+ if (usePairingCode && !phoneNumber) {
151
+ throw new TypeError('phoneNumber is required when usePairingCode is enabled.');
152
+ }
153
+
154
+ this.options = {
155
+ authDir,
156
+ usePairingCode,
157
+ phoneNumber,
158
+ printQR: options.printQR === true, // default OFF — jangan spam QR di bot
159
+ onPairingCode:
160
+ typeof options.onPairingCode === 'function' ? options.onPairingCode : null,
161
+ };
162
+
48
163
  this.client = null;
164
+ this.parentSock = options.sock || options.socket || null;
165
+ this._connecting = null;
166
+ }
167
+
168
+ /** Apakah session VoIP sudah pernah login (creds ada) */
169
+ get isRegistered() {
170
+ return hasCreds(this.options.authDir);
171
+ }
172
+
173
+ get isConnected() {
174
+ return Boolean(this.client);
175
+ }
176
+
177
+ /**
178
+ * Simpan referensi socket bot (untuk CallManager / koordinasi).
179
+ * TIDAK membuka session baru. TIDAK memicu QR.
180
+ */
181
+ attach(sock) {
182
+ if (!sock || !sock.ev) {
183
+ throw new TypeError('attach(sock) requires a live Baileys socket.');
184
+ }
185
+ this.parentSock = sock;
186
+ this.emit('attached', sock);
187
+ return this;
49
188
  }
189
+
190
+ /**
191
+ * Connect engine media.
192
+ * - Jika creds sudah ada di authDir → silent reconnect (tanpa QR / pairing)
193
+ * - Jika belum & usePairingCode → minta pairing code
194
+ * - Jika belum & printQR true → engine boleh emit QR
195
+ * - Default printQR false → error jelas jika belum registered tanpa pairing mode
196
+ */
50
197
  async connect() {
51
198
  if (this.client) return this;
199
+ if (this._connecting) return this._connecting;
200
+
201
+ this._connecting = this._doConnect().finally(() => {
202
+ this._connecting = null;
203
+ });
204
+ return this._connecting;
205
+ }
206
+
207
+ async _doConnect() {
208
+ ensureDir(this.options.authDir);
209
+
210
+ const registered = hasCreds(this.options.authDir);
211
+
212
+ // Belum login & user tidak minta pairing & QR dimatikan → jangan bikin QR diam-diam
213
+ if (!registered && !this.options.usePairingCode && !this.options.printQR) {
214
+ throw new Error(
215
+ 'VoIP session belum terdaftar di authDir.\n' +
216
+ ` authDir: ${this.options.authDir}\n` +
217
+ 'Gunakan salah satu:\n' +
218
+ ' • new VoipClient({ authDir, usePairingCode: true, phoneNumber: "62..." })\n' +
219
+ ' • atau { printQR: true } untuk scan QR sekali, lalu creds tersimpan.',
220
+ );
221
+ }
222
+
52
223
  let mod;
53
224
  try {
54
225
  mod = await import('@paiavaliable/baileys-caller');
55
226
  } catch (error) {
56
- throw new Error('VoIP engine is unavailable. Install @paiavaliable/baileys-caller or reinstall @zelynskybail/baileys with optional dependencies enabled.', { cause: error });
227
+ throw new Error(
228
+ 'VoIP engine unavailable. Install optional dependency:\n' +
229
+ ' npm i @paiavaliable/baileys-caller\n' +
230
+ 'Then reinstall / use @zelynskybail/baileys with optional deps.',
231
+ { cause: error },
232
+ );
57
233
  }
234
+
58
235
  const Client = mod.VoipClient ?? mod.default?.VoipClient;
59
- if (typeof Client !== 'function') throw new Error('The installed VoIP engine does not export VoipClient.');
60
- const client = new Client(this.options);
236
+ if (typeof Client !== 'function') {
237
+ throw new Error('Installed VoIP engine does not export VoipClient.');
238
+ }
239
+
240
+ // Opsi diteruskan ke engine; printQR default false biar bot tidak kebanjiran QR
241
+ const engineOpts = {
242
+ authDir: this.options.authDir,
243
+ printQR: this.options.printQR && !this.options.usePairingCode,
244
+ };
245
+ if (this.options.usePairingCode) {
246
+ engineOpts.usePairingCode = true;
247
+ engineOpts.phoneNumber = this.options.phoneNumber;
248
+ engineOpts.printQR = false;
249
+ }
250
+
251
+ const client = new Client(engineOpts);
252
+
253
+ // Hook pairing code / qr dari engine jika emit event
254
+ const forwardPairing = (code) => {
255
+ if (!code) return;
256
+ this.emit('pairing-code', code);
257
+ try {
258
+ this.options.onPairingCode?.(code);
259
+ } catch {}
260
+ };
261
+
262
+ if (typeof client.on === 'function') {
263
+ client.on('pairing-code', forwardPairing);
264
+ client.on('pairingCode', forwardPairing);
265
+ client.on('qr', (qr) => {
266
+ // Jika user tidak minta QR, jangan biarkan tanpa peringatan
267
+ this.emit('qr', qr);
268
+ if (!this.options.printQR) {
269
+ console.warn(
270
+ '[VoipClient] Engine emitted QR but printQR=false. Prefer usePairingCode.',
271
+ );
272
+ }
273
+ });
274
+ }
275
+
276
+ // Beberapa engine expose requestPairingCode di client.sock setelah partial init
61
277
  try {
62
278
  await client.connect();
63
- this.client = client;
64
- return this;
65
279
  } catch (error) {
66
- try { client.disconnect?.(); } catch {}
280
+ try {
281
+ client.disconnect?.();
282
+ } catch {}
67
283
  throw error;
68
284
  }
285
+
286
+ // Coba request pairing code jika mode pairing & engine punya method
287
+ if (this.options.usePairingCode && !registered) {
288
+ try {
289
+ const sock = client.sock || client.socket || client.wa || null;
290
+ if (sock && typeof sock.requestPairingCode === 'function') {
291
+ const code = await sock.requestPairingCode(this.options.phoneNumber);
292
+ forwardPairing(code);
293
+ }
294
+ } catch (e) {
295
+ console.warn('[VoipClient] requestPairingCode:', e?.message || e);
296
+ }
297
+ }
298
+
299
+ this.client = client;
300
+ this.emit('connected');
301
+ return this;
69
302
  }
303
+
304
+ /**
305
+ * Outbound 1:1 voice call + stream audio file.
306
+ * @param {string} phoneNumber digits only
307
+ * @param {{ audioSource?: string, durationMs?: number, repeatAudio?: boolean }} options
308
+ */
70
309
  async call(phoneNumber, options = {}) {
71
- if (!this.client) throw new Error('Call connect() before starting a call.');
72
- return this.client.call(phoneNumber, options);
310
+ if (!this.client) {
311
+ throw new Error('Call connect() before starting a call.');
312
+ }
313
+ const number = String(phoneNumber || '').replace(/\D/g, '');
314
+ if (!number) throw new TypeError('phoneNumber is required');
315
+
316
+ const opts = {
317
+ audioSource: options.audioSource ?? 'silence',
318
+ durationMs: options.durationMs,
319
+ // default jangan loop — bot music play
320
+ repeatAudio: options.repeatAudio === true,
321
+ ...options,
322
+ };
323
+
324
+ return this.client.call(number, opts);
73
325
  }
326
+
74
327
  disconnect() {
75
- this.client?.disconnect?.();
328
+ try {
329
+ this.client?.disconnect?.();
330
+ } catch {}
76
331
  this.client = null;
332
+ this.emit('disconnected');
77
333
  }
334
+
335
+ /** CallManager dari parent sock (jika attach) */
336
+ getCallManager() {
337
+ if (!this.parentSock) return null;
338
+ return new CallManager(this.parentSock);
339
+ }
340
+
78
341
  static get capabilities() {
79
- return Object.freeze({ outboundVoice1to1: true, audioStreaming: true, receivePcm: true, inboundCalls: false, videoCalls: false, groupCalls: false, sharedParentSocket: false });
342
+ return Object.freeze({
343
+ outboundVoice1to1: true,
344
+ audioStreaming: true,
345
+ receivePcm: true,
346
+ inboundCalls: false,
347
+ videoCalls: false,
348
+ groupCalls: false,
349
+ sharedParentSocket: false,
350
+ attachParentSocket: true,
351
+ pairingCode: true,
352
+ persistentAuthDir: true,
353
+ });
80
354
  }
81
355
  }
356
+
357
+ /**
358
+ * Helper bot-friendly: VoipClient dengan authDir di samping session bot.
359
+ * Contoh: session bot = ./sessions → voip = ./sessions-voip
360
+ *
361
+ * @param {object} sock - WASocket bot (optional, untuk attach)
362
+ * @param {object} [options]
363
+ * @param {string} [options.botAuthDir='sessions']
364
+ * @param {string} [options.phoneNumber] - untuk pairing code first-run
365
+ * @param {boolean} [options.usePairingCode]
366
+ */
367
+ export function createBotVoipClient(sock, options = {}) {
368
+ const botAuthDir = options.botAuthDir
369
+ ? path.resolve(options.botAuthDir)
370
+ : path.resolve(process.cwd(), 'sessions');
371
+ const authDir =
372
+ options.authDir ||
373
+ path.join(path.dirname(botAuthDir), `${path.basename(botAuthDir)}-voip`);
374
+
375
+ const client = new VoipClient({
376
+ authDir,
377
+ usePairingCode: Boolean(options.usePairingCode),
378
+ phoneNumber: options.phoneNumber,
379
+ printQR: options.printQR === true,
380
+ onPairingCode: options.onPairingCode,
381
+ sock,
382
+ });
383
+
384
+ if (sock) client.attach(sock);
385
+ return client;
386
+ }
387
+
388
+ /** Alias dokumentasi */
389
+ export function attachCalling(sock) {
390
+ if (!sock || !sock.ev) throw new TypeError('attachCalling requires sock');
391
+ return new CallManager(sock);
392
+ }
393
+
394
+ // Experimental group-call engine ported from @japofc/baileys 2.4.7-new.
395
+ export { VoipClient as GroupVoipClient, ActiveCall, attachVoip } from './group-call.js';
396
+ export { CallState } from './types.js';
@@ -0,0 +1,43 @@
1
+ type RelayAddress = {
2
+ protocol: number;
3
+ ipv4?: string;
4
+ ipv6?: string;
5
+ port?: number;
6
+ port_v6?: number;
7
+ };
8
+ type RelayDescriptor = {
9
+ relay_id: number;
10
+ relay_name: string;
11
+ token_id: number;
12
+ auth_token_id?: number;
13
+ addresses: RelayAddress[];
14
+ };
15
+ export type RelayListUpdatePayload = {
16
+ relay_key: string;
17
+ relay_tokens: string[];
18
+ auth_tokens?: string[];
19
+ enable_edgeray_dtls_active_mode?: boolean;
20
+ relays: RelayDescriptor[];
21
+ };
22
+ export type RelayTransportStats = {
23
+ sentPackets: number;
24
+ receivedPackets: number;
25
+ sentBytes: number;
26
+ receivedBytes: number;
27
+ droppedPackets: number;
28
+ openConnections: number;
29
+ };
30
+ export type RelayTransportConfig = {
31
+ onTransportMessage: (data: Uint8Array, ip: string, port: number) => void;
32
+ onIceRtt?: (rttMs: number, ip: string, port: number) => void;
33
+ };
34
+ export declare class RelayRtcTransport {
35
+ #private;
36
+ private readonly config;
37
+ constructor(config: RelayTransportConfig);
38
+ updateRelayList: (update: RelayListUpdatePayload) => void;
39
+ send: (packet: Uint8Array | Buffer, ip: string, port: number) => number;
40
+ getStats: () => RelayTransportStats;
41
+ closeAll: () => Promise<void>;
42
+ }
43
+ export {};