@x4r1s3/baileys 0.0.0-stage → 1.0.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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1262 -2
  3. package/SECURITY.md +47 -0
  4. package/WAProto/V +1 -0
  5. package/WAProto/WAProto.proto +8892 -0
  6. package/WAProto/index.d.ts +104128 -0
  7. package/WAProto/index.js +334920 -0
  8. package/assets/rolling-circle.svg +133 -0
  9. package/assets/x4r1s3-banner.svg +32 -0
  10. package/engine-requirements.js +27 -0
  11. package/lib/Builders/A2UI.js +245 -0
  12. package/lib/Builders/AIRich.js +179 -0
  13. package/lib/Builders/Button.js +108 -0
  14. package/lib/Builders/CFC.js +284 -0
  15. package/lib/Builders/Carousel.js +81 -0
  16. package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
  17. package/lib/Call/audio-feeder.mjs +179 -0
  18. package/lib/Call/audio-recorder.mjs +250 -0
  19. package/lib/Call/fetch-wasm-resources.mjs +104 -0
  20. package/lib/Call/index.mjs +680 -0
  21. package/lib/Call/relay-transport.mjs +563 -0
  22. package/lib/Call/signaling.mjs +641 -0
  23. package/lib/Call/types.mjs +17 -0
  24. package/lib/Call/video-feeder.mjs +94 -0
  25. package/lib/Call/wasm-engine.mjs +1372 -0
  26. package/lib/Call/worker-bootstrap.mjs +1042 -0
  27. package/lib/Defaults/ban-checker.js +56 -0
  28. package/lib/Defaults/index.js +170 -0
  29. package/lib/Signal/Group/ciphertext-message.js +23 -0
  30. package/lib/Signal/Group/group-session-builder.js +41 -0
  31. package/lib/Signal/Group/group_cipher.js +93 -0
  32. package/lib/Signal/Group/index.js +23 -0
  33. package/lib/Signal/Group/keyhelper.js +29 -0
  34. package/lib/Signal/Group/sender-chain-key.js +37 -0
  35. package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
  36. package/lib/Signal/Group/sender-key-message.js +77 -0
  37. package/lib/Signal/Group/sender-key-name.js +59 -0
  38. package/lib/Signal/Group/sender-key-record.js +52 -0
  39. package/lib/Signal/Group/sender-key-state.js +95 -0
  40. package/lib/Signal/Group/sender-message-key.js +37 -0
  41. package/lib/Signal/libsignal.js +440 -0
  42. package/lib/Signal/lid-mapping.js +292 -0
  43. package/lib/Socket/Client/index.js +14 -0
  44. package/lib/Socket/Client/types.js +22 -0
  45. package/lib/Socket/Client/websocket.js +65 -0
  46. package/lib/Socket/aigroups.js +327 -0
  47. package/lib/Socket/ban-checker.js +165 -0
  48. package/lib/Socket/business.js +419 -0
  49. package/lib/Socket/chats.js +1921 -0
  50. package/lib/Socket/communities.js +443 -0
  51. package/lib/Socket/graphql.js +911 -0
  52. package/lib/Socket/groups.js +561 -0
  53. package/lib/Socket/index.js +49 -0
  54. package/lib/Socket/interactive-handler.js +612 -0
  55. package/lib/Socket/interop.js +575 -0
  56. package/lib/Socket/managed-account.js +220 -0
  57. package/lib/Socket/messages-recv.js +2191 -0
  58. package/lib/Socket/messages-send.js +4104 -0
  59. package/lib/Socket/mex.js +53 -0
  60. package/lib/Socket/newsletter.js +291 -0
  61. package/lib/Socket/privacy.js +458 -0
  62. package/lib/Socket/registration.js +440 -0
  63. package/lib/Socket/socket.js +1029 -0
  64. package/lib/Socket/status-actions.js +287 -0
  65. package/lib/Socket/username.js +241 -0
  66. package/lib/Store/index.js +16 -0
  67. package/lib/Store/make-cache-manager-store.js +101 -0
  68. package/lib/Store/make-in-memory-store.js +432 -0
  69. package/lib/Store/make-ordered-dictionary.js +90 -0
  70. package/lib/Store/object-repository.js +35 -0
  71. package/lib/Types/Auth.js +13 -0
  72. package/lib/Types/Bussines.js +13 -0
  73. package/lib/Types/Call.js +13 -0
  74. package/lib/Types/Chat.js +19 -0
  75. package/lib/Types/Contact.js +13 -0
  76. package/lib/Types/Events.js +13 -0
  77. package/lib/Types/GroupMetadata.js +13 -0
  78. package/lib/Types/Label.js +36 -0
  79. package/lib/Types/LabelAssociation.js +18 -0
  80. package/lib/Types/Message.js +30 -0
  81. package/lib/Types/Mex.js +53 -0
  82. package/lib/Types/Product.js +13 -0
  83. package/lib/Types/RichType.js +34 -0
  84. package/lib/Types/Signal.js +13 -0
  85. package/lib/Types/Socket.js +14 -0
  86. package/lib/Types/State.js +60 -0
  87. package/lib/Types/USync.js +13 -0
  88. package/lib/Types/index.js +37 -0
  89. package/lib/Utils/auth-utils.js +313 -0
  90. package/lib/Utils/ban-checker.js +48 -0
  91. package/lib/Utils/bot-capabilities.js +96 -0
  92. package/lib/Utils/bot-planning-replay.js +177 -0
  93. package/lib/Utils/browser-utils.js +40 -0
  94. package/lib/Utils/business.js +242 -0
  95. package/lib/Utils/c2582.js +147 -0
  96. package/lib/Utils/chat-utils.js +905 -0
  97. package/lib/Utils/companion-reg-client-utils.js +44 -0
  98. package/lib/Utils/consumer-application.js +114 -0
  99. package/lib/Utils/crypto.js +129 -0
  100. package/lib/Utils/decode-wa-message.js +496 -0
  101. package/lib/Utils/direct-chat-theme.js +164 -0
  102. package/lib/Utils/event-buffer.js +601 -0
  103. package/lib/Utils/experimental-proto.js +206 -0
  104. package/lib/Utils/games/miniapp.js +17 -0
  105. package/lib/Utils/games/slot-machine.js +270 -0
  106. package/lib/Utils/games/website-preview.js +306 -0
  107. package/lib/Utils/generics.js +402 -0
  108. package/lib/Utils/group-history.js +68 -0
  109. package/lib/Utils/group-wallpaper.js +168 -0
  110. package/lib/Utils/history.js +162 -0
  111. package/lib/Utils/identity-change-handler.js +60 -0
  112. package/lib/Utils/index.js +61 -0
  113. package/lib/Utils/jid-display-normalization.js +221 -0
  114. package/lib/Utils/link-preview.js +96 -0
  115. package/lib/Utils/logger.js +14 -0
  116. package/lib/Utils/lt-hash.js +19 -0
  117. package/lib/Utils/make-mutex.js +44 -0
  118. package/lib/Utils/message-composer.js +709 -0
  119. package/lib/Utils/message-inspect.js +79 -0
  120. package/lib/Utils/message-retry-manager.js +253 -0
  121. package/lib/Utils/message-security.js +167 -0
  122. package/lib/Utils/messages-media.js +1027 -0
  123. package/lib/Utils/messages.js +2467 -0
  124. package/lib/Utils/meta-ai-msmsg.js +215 -0
  125. package/lib/Utils/meta-compositing.js +239 -0
  126. package/lib/Utils/native-flow.js +158 -0
  127. package/lib/Utils/newsletter-live-update-utils.js +74 -0
  128. package/lib/Utils/newsletter-status-utils.js +152 -0
  129. package/lib/Utils/noise-handler.js +212 -0
  130. package/lib/Utils/offline-node-processor.js +51 -0
  131. package/lib/Utils/poll-manager.js +206 -0
  132. package/lib/Utils/portable-compat.js +12 -0
  133. package/lib/Utils/pre-key-manager.js +117 -0
  134. package/lib/Utils/process-message.js +610 -0
  135. package/lib/Utils/reporting-utils.js +269 -0
  136. package/lib/Utils/rich-message-utils.js +2841 -0
  137. package/lib/Utils/scheduled-message.js +107 -0
  138. package/lib/Utils/signal.js +212 -0
  139. package/lib/Utils/source-grep.js +57 -0
  140. package/lib/Utils/stanza-ack.js +49 -0
  141. package/lib/Utils/sticker-annotation.js +87 -0
  142. package/lib/Utils/sync-action-utils.js +59 -0
  143. package/lib/Utils/tc-token-utils.js +174 -0
  144. package/lib/Utils/use-multi-file-auth-state.js +132 -0
  145. package/lib/Utils/use-single-file-auth-state.js +108 -0
  146. package/lib/Utils/use-sqlite-auth-state.js +120 -0
  147. package/lib/Utils/validate-connection.js +220 -0
  148. package/lib/Utils/view-once-utils.js +218 -0
  149. package/lib/Utils/voip-rekey.js +32 -0
  150. package/lib/Utils/website-preview.js +27 -0
  151. package/lib/Utils/welcome-flow.js +228 -0
  152. package/lib/Utils/x4r1s3.js +144 -0
  153. package/lib/WABinary/constants.js +1475 -0
  154. package/lib/WABinary/decode.js +273 -0
  155. package/lib/WABinary/encode.js +231 -0
  156. package/lib/WABinary/generic-utils.js +242 -0
  157. package/lib/WABinary/index.js +17 -0
  158. package/lib/WABinary/jid-utils.js +107 -0
  159. package/lib/WABinary/types.js +13 -0
  160. package/lib/WAM/BinaryInfo.js +21 -0
  161. package/lib/WAM/constants.js +22864 -0
  162. package/lib/WAM/encode.js +161 -0
  163. package/lib/WAM/index.js +15 -0
  164. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
  165. package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
  166. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  167. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
  168. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
  169. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
  170. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
  171. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  172. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
  173. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
  174. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
  175. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
  176. package/lib/WAUSync/Protocols/index.js +24 -0
  177. package/lib/WAUSync/USyncQuery.js +213 -0
  178. package/lib/WAUSync/USyncUser.js +66 -0
  179. package/lib/WAUSync/index.js +15 -0
  180. package/lib/antiban.cjs +4726 -0
  181. package/lib/index.d.ts +1285 -0
  182. package/lib/index.js +30 -0
  183. package/package.json +125 -4
@@ -0,0 +1,680 @@
1
+ /**
2
+ * baileys-caller — WhatsApp voice calling for Node.js.
3
+ *
4
+ * Wraps WhatsApp Web's official VoIP WASM stack and routes signaling through
5
+ * Baileys. Public surface:
6
+ *
7
+ * const client = new VoipClient({ authDir })
8
+ * await client.connect()
9
+ * const call = await client.call("12345678901", { audioSource: "./hi.mp3" })
10
+ *
11
+ * @author ShellTear
12
+ */
13
+ import { EventEmitter } from "node:events";
14
+ import { randomBytes, createHmac } from "node:crypto";
15
+ import { existsSync } from "node:fs";
16
+ import { join, resolve } from "node:path";
17
+ import { WasmEngine } from "./wasm-engine.mjs";
18
+ import { RelayRtcTransport } from "./relay-transport.mjs";
19
+ import { SignalingBridge } from "./signaling.mjs";
20
+ import { AudioFeeder } from "./audio-feeder.mjs";
21
+ import { VideoFeeder } from "./video-feeder.mjs";
22
+ import { CallRecorder } from "./audio-recorder.mjs";
23
+ import { CallState } from "./types.mjs";
24
+ export { CallState } from "./types.mjs";
25
+ const SHA256_LEN = 32;
26
+ const loadBaileys = async () => {
27
+ try {
28
+ return await import("../index.js");
29
+ }
30
+ catch (error) {
31
+ throw new Error("Could not load the local Baileys implementation for VoIP.", { cause: error });
32
+ }
33
+ };
34
+ const toBareJid = (jid) => {
35
+ if (!jid)
36
+ return jid;
37
+ const at = jid.indexOf("@");
38
+ if (at < 0)
39
+ return jid;
40
+ const user = jid.slice(0, at).split(":")[0];
41
+ return `${user}@${jid.slice(at + 1)}`;
42
+ };
43
+ const computeHkdf = (key, salt, info, length) => {
44
+ const effectiveSalt = salt && salt.length > 0 ? Buffer.from(salt) : Buffer.alloc(SHA256_LEN, 0);
45
+ const prk = createHmac("sha256", effectiveSalt).update(key).digest();
46
+ const blocks = Math.ceil(length / SHA256_LEN);
47
+ const okm = Buffer.alloc(blocks * SHA256_LEN);
48
+ let prev = Buffer.alloc(0);
49
+ for (let i = 1; i <= blocks; i += 1) {
50
+ prev = createHmac("sha256", prk)
51
+ .update(prev)
52
+ .update(info)
53
+ .update(Buffer.from([i]))
54
+ .digest();
55
+ prev.copy(okm, (i - 1) * SHA256_LEN);
56
+ }
57
+ return new Uint8Array(okm.buffer, okm.byteOffset, length);
58
+ };
59
+ const computeHmacSha256 = (data, key) => {
60
+ const result = createHmac("sha256", Buffer.from(key)).update(data).digest();
61
+ return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
62
+ };
63
+ const isCallReceiptNode = (node) => {
64
+ if (node?.tag !== "receipt")
65
+ return false;
66
+ const child = Array.isArray(node.content) ? node.content[0] : null;
67
+ return !!(child?.attrs?.["call-id"] || child?.attrs?.call_id);
68
+ };
69
+ const isVideoSource = (source) => !!source && typeof source[Symbol.asyncIterator] === "function";
70
+ const VIDEO_UPGRADE_TIMEOUT_MS = 5000;
71
+ /** A live or recently-ended call. */
72
+ export class ActiveCall extends EventEmitter {
73
+ callId;
74
+ engine;
75
+ #state = CallState.Idle;
76
+ #endResolver;
77
+ #endPromise;
78
+ #endTimer = null;
79
+ #ended = false;
80
+ #recorder = null;
81
+ #recordingDone = Promise.resolve(undefined);
82
+ #videoUpgradeHandler = null;
83
+ direction;
84
+ peerJid;
85
+ isVideo = false;
86
+ /** @internal mirrors the source path for the audio feeder */
87
+ _audioSource = "silence";
88
+ /** @internal async iterable of raw NV12 frames */
89
+ _videoSource = null;
90
+ constructor(callId, engine, durationMs, { direction = "outgoing", peerJid = "" } = {}) {
91
+ super();
92
+ this.callId = callId;
93
+ this.engine = engine;
94
+ this.direction = direction;
95
+ this.peerJid = peerJid;
96
+ this.#endPromise = new Promise((res) => { this.#endResolver = res; });
97
+ if (durationMs > 0) {
98
+ this.#endTimer = setTimeout(() => this.end(), durationMs);
99
+ }
100
+ }
101
+ get state() { return this.#state; }
102
+ get recordingDone() { return this.#recordingDone; }
103
+ /** @internal */
104
+ _startDurationTimer = (durationMs) => {
105
+ if (durationMs > 0 && !this.#ended && !this.#endTimer) {
106
+ this.#endTimer = setTimeout(() => this.end(), durationMs);
107
+ }
108
+ };
109
+ end = () => {
110
+ if (this.#ended)
111
+ return;
112
+ if (this.#endTimer) {
113
+ clearTimeout(this.#endTimer);
114
+ this.#endTimer = null;
115
+ }
116
+ try {
117
+ this.engine.endCall(0, true);
118
+ }
119
+ catch { }
120
+ this._forceEnd("hangup");
121
+ };
122
+ mute = (muted) => {
123
+ try {
124
+ this.engine.setMute(muted);
125
+ }
126
+ catch { }
127
+ };
128
+ /** Request enabling local video on this active audio call. */
129
+ requestVideoUpgrade = (videoSource) => {
130
+ if (!this.#videoUpgradeHandler)
131
+ return Promise.reject(new Error("Video upgrade is not available for this call."));
132
+ return this.#videoUpgradeHandler(videoSource);
133
+ };
134
+ /** @internal */
135
+ _setVideoUpgradeHandler = (handler) => { this.#videoUpgradeHandler = handler; };
136
+ waitForEnd = () => this.#endPromise;
137
+ waitForRecording = () => this.#recordingDone;
138
+ /** @internal — called by VoipClient on WASM call-state change */
139
+ _updateState = (state) => {
140
+ this.#state = state;
141
+ if (state === CallState.PreacceptReceived)
142
+ this.emit("ringing");
143
+ else if (state === CallState.Active)
144
+ this.emit("connected");
145
+ else if (state === CallState.Idle || state === CallState.Ending) {
146
+ this._forceEnd("ended");
147
+ }
148
+ };
149
+ /** @internal */
150
+ _emitAudio = (pcm) => { this.emit("audio", pcm); };
151
+ /** @internal */
152
+ _emitVideoFrame = (frame) => { this.emit("videoFrame", frame); };
153
+ /** @internal */
154
+ _emitVideoError = (error) => { this.emit("videoError", error); };
155
+ /** @internal */
156
+ _attachRecorder = (recorder) => { this.#recorder = recorder; };
157
+ /** @internal */
158
+ _recordAudio = (direction, pcm) => { this.#recorder?.write(direction, pcm); };
159
+ /** @internal */
160
+ _emitRecordingError = (direction, error) => { this.emit("recordingError", { callId: this.callId, direction, error }); };
161
+ /** @internal */
162
+ _forceEnd = (reason) => {
163
+ if (this.#ended)
164
+ return;
165
+ this.#ended = true;
166
+ this.#state = CallState.Ending;
167
+ if (this.#endTimer) {
168
+ clearTimeout(this.#endTimer);
169
+ this.#endTimer = null;
170
+ }
171
+ const recorder = this.#recorder;
172
+ this.#recorder = null;
173
+ this._videoSource = null;
174
+ this.#recordingDone = recorder?.close?.() ?? Promise.resolve(undefined);
175
+ this.#recordingDone.then((result) => {
176
+ if (result) this.emit("recordingComplete", result);
177
+ }).catch((error) => this._emitRecordingError("both", error));
178
+ this.emit("ended", reason);
179
+ this.#endResolver(reason);
180
+ };
181
+ }
182
+ /** Top-level client. Connects to WhatsApp, places calls, and can answer incoming voice calls. */
183
+ export class VoipClient extends EventEmitter {
184
+ #config;
185
+ #engine = null;
186
+ #relay = null;
187
+ #signaling = null;
188
+ #sock = null;
189
+ #activeCall = null;
190
+ #incomingCalls = new Map();
191
+ #pendingVideoUpgrade = null;
192
+ #recordingFinalizers = new Set();
193
+ #creatingCall = false;
194
+ #baileys = null;
195
+ #ownsSocket = true;
196
+ #callNodeHandler = null;
197
+ #receiptNodeHandler = null;
198
+ // Capture state populated when WASM negotiates audio params
199
+ #capturePtr = 0;
200
+ #captureChunkBytes = 0;
201
+ #captureSampleRate = 16000;
202
+ #captureChannels = 1;
203
+ #captureFramesPerChunk = 320;
204
+ #playbackSampleRate = 16000;
205
+ #playbackChannels = 1;
206
+ #feeder = null;
207
+ #videoFeeder = null;
208
+ constructor(config) {
209
+ super();
210
+ this.#config = config;
211
+ this.#ownsSocket = !config.sock;
212
+ }
213
+ /** Connect to WhatsApp and bring up the WASM VoIP stack. */
214
+ connect = async () => {
215
+ const resourcesPath = this.#config.resourcesPath ?? process.env.X4R1S3_VOIP_RESOURCES;
216
+ const wasmPath = this.#config.wasmPath ? resolve(this.#config.wasmPath) : resourcesPath ? join(resolve(resourcesPath), "assets", "wasm", "whatsapp.wasm") : undefined;
217
+ const workerPath = resourcesPath ? join(resolve(resourcesPath), "assets", "wasm", "worker-modules.js") : undefined;
218
+ if (!this.#config.wasmBinary && (!wasmPath || !existsSync(wasmPath))) {
219
+ throw new Error("VoIP WASM is not available. Set resourcesPath or X4R1S3_VOIP_RESOURCES to a directory containing assets/wasm/whatsapp.wasm.");
220
+ }
221
+ if (!this.#config.workerModulesCode && (!workerPath || !existsSync(workerPath))) {
222
+ throw new Error("VoIP worker-modules.js is not available. Set resourcesPath or pass workerModulesCode.");
223
+ }
224
+ if (this.#config.recording && (typeof this.#config.recording !== "object" || !this.#config.recording.directory)) {
225
+ throw new Error("Automatic recording requires recording.directory; omit recording to keep recording disabled.");
226
+ }
227
+ try {
228
+ await import("@roamhq/wrtc");
229
+ }
230
+ catch (error) {
231
+ throw new Error("VoIP media requires the optional @roamhq/wrtc peer dependency (install @roamhq/wrtc@^0.10.0).", { cause: error });
232
+ }
233
+ this.#baileys = await loadBaileys();
234
+ if (this.#config.sock) {
235
+ if (!this.#config.sock.authState?.creds?.me || !this.#config.sock.ws) {
236
+ throw new Error("Pass a connected Baileys socket with authState and ws available.");
237
+ }
238
+ this.#sock = this.#config.sock;
239
+ }
240
+ else {
241
+ const { useMultiFileAuthState, default: makeWASocket, DisconnectReason } = this.#baileys;
242
+ const makeSocket = makeWASocket ?? this.#baileys.makeWASocket ?? this.#baileys;
243
+ if (!this.#config.authDir) {
244
+ throw new Error("authDir is required when no existing sock is provided.");
245
+ }
246
+ const authDir = resolve(this.#config.authDir);
247
+ const { state, saveCreds } = await useMultiFileAuthState(authDir);
248
+ const silentLogger = {
249
+ level: "silent",
250
+ child: () => silentLogger,
251
+ trace: () => { },
252
+ debug: () => { },
253
+ info: () => { },
254
+ warn: () => { },
255
+ error: () => { },
256
+ fatal: () => { },
257
+ };
258
+ const createSocket = () => makeSocket({ auth: state, emitOwnEvents: true, logger: silentLogger });
259
+ await new Promise((resolveOpen, rejectOpen) => {
260
+ let opened = false;
261
+ let retries = 0;
262
+ const maxRetries = 5;
263
+ const connectSocket = () => {
264
+ this.#sock = createSocket();
265
+ this.#sock.ev.on("creds.update", saveCreds);
266
+ this.#sock.ev.on("connection.update", (update) => {
267
+ if (update.qr) {
268
+ void import("qrcode-terminal")
269
+ .then((qrt) => (qrt.default ?? qrt).generate(update.qr, { small: true }))
270
+ .catch(() => {
271
+ console.log("Scan this QR code in WhatsApp > Linked Devices:");
272
+ console.log(update.qr);
273
+ });
274
+ }
275
+ if (update.connection === "open") {
276
+ opened = true;
277
+ resolveOpen();
278
+ return;
279
+ }
280
+ if (update.connection === "close" && !opened) {
281
+ const statusCode = update.lastDisconnect?.error?.output?.statusCode;
282
+ const shouldReconnect = statusCode === 515 || statusCode === DisconnectReason?.restartRequired;
283
+ if (shouldReconnect && retries < maxRetries) {
284
+ retries += 1;
285
+ this.#sock?.end?.();
286
+ setTimeout(connectSocket, 1000);
287
+ }
288
+ else {
289
+ rejectOpen(update.lastDisconnect?.error ?? new Error("socket closed before open"));
290
+ }
291
+ }
292
+ });
293
+ };
294
+ connectSocket();
295
+ });
296
+ }
297
+ this.#signaling = new SignalingBridge({
298
+ sock: this.#sock,
299
+ onIncomingOffer: (info) => this.#handleIncomingOffer(info),
300
+ onIncomingEnded: (callId, reason) => this.#handleIncomingEnded(callId, reason),
301
+ onVideoState: (info) => this.#handleVideoState(info),
302
+ });
303
+ await this.#signaling.init();
304
+ this.#relay = new RelayRtcTransport({
305
+ onTransportMessage: (data, ip, port) => this.#engine?.handleOnTransportMessage(data, ip, port),
306
+ onIceRtt: (rttMs, ip, port) => this.#engine?.updateIceRtt(rttMs, ip, port),
307
+ });
308
+ this.#engine = new WasmEngine({
309
+ resourcesPath,
310
+ wasmPath: this.#config.wasmPath,
311
+ wasmBinary: this.#config.wasmBinary,
312
+ workerModulesCode: this.#config.workerModulesCode,
313
+ loaderCode: this.#config.loaderCode,
314
+ callbacks: {
315
+ onSignalingXmpp: (peerJid, callId, xmlPayload) => this.#signaling.sendSignaling(peerJid, callId, xmlPayload),
316
+ onCallEvent: (eventType, eventData) => this.#handleCallEvent(eventType, eventData),
317
+ sendDataToRelay: (data, ip, port) => this.#relay.send(data, ip, port),
318
+ onAudioCaptureInit: (config) => this.#handleAudioCaptureInit(config),
319
+ onAudioCaptureStart: () => this.#handleAudioCaptureStart(),
320
+ onAudioCaptureStop: () => this.#handleAudioCaptureStop(),
321
+ onAudioPlaybackInit: (config) => this.#handleAudioPlaybackInit(config),
322
+ onAudioPlaybackData: (audioData) => {
323
+ const pcm = new Float32Array(audioData);
324
+ this.#activeCall?._recordAudio("inbound", pcm);
325
+ this.#activeCall?._emitAudio(pcm);
326
+ },
327
+ onVideoCaptureStart: () => this.#handleVideoCaptureStart(),
328
+ onVideoCaptureStop: () => this.#handleVideoCaptureStop(),
329
+ onVideoFrame: (frame) => this.#activeCall?._emitVideoFrame(frame),
330
+ cryptoHkdf: computeHkdf,
331
+ hmacSha256: computeHmacSha256,
332
+ },
333
+ });
334
+ await this.#engine.initialize();
335
+ this.#signaling.attachEngine(this.#engine);
336
+ const selfPnJid = this.#sock.authState.creds.me?.id;
337
+ const selfLidJid = this.#sock.authState.creds.me?.lid;
338
+ this.#engine.initVoipStack(selfPnJid, toBareJid(selfPnJid), selfLidJid);
339
+ await this.#engine.waitForVoipStackReady();
340
+ try {
341
+ this.#engine.updateNetworkMedium(2, 0);
342
+ }
343
+ catch { }
344
+ this.#callNodeHandler = (node) => {
345
+ this.#signaling.processIncomingCall(node, this.#engine, this.#activeCall?.callId ?? "");
346
+ };
347
+ this.#receiptNodeHandler = (node) => {
348
+ if (!isCallReceiptNode(node))
349
+ return;
350
+ this.#signaling.processIncomingReceipt(node, this.#engine, this.#activeCall?.callId ?? "");
351
+ };
352
+ this.#sock.ws.on("CB:call", this.#callNodeHandler);
353
+ this.#sock.ws.on("CB:receipt", this.#receiptNodeHandler);
354
+ };
355
+ /** Place an outbound audio or video call. */
356
+ call = async (phoneNumber, opts = {}) => {
357
+ if (!this.#engine || !this.#signaling)
358
+ throw new Error("Not connected. Call connect() first.");
359
+ if (this.#activeCall)
360
+ throw new Error("A call is already active.");
361
+ const targetNumber = phoneNumber.replace(/\D/g, "");
362
+ const isVideo = Boolean(opts.isVideo || opts.videoSource);
363
+ if (isVideo && !isVideoSource(opts.videoSource))
364
+ throw new Error("Outgoing video calls require videoSource, an async iterable of raw NV12 frames.");
365
+ const targetPnJid = `${targetNumber}@s.whatsapp.net`;
366
+ const durationMs = opts.durationMs ?? 120_000;
367
+ const audioSource = opts.audioSource ?? "silence";
368
+ const peerLid = await this.#signaling.resolveLid(targetPnJid);
369
+ if (!peerLid)
370
+ throw new Error(`Could not resolve LID for ${targetPnJid}`);
371
+ for (const jid of [targetPnJid, peerLid]) {
372
+ try {
373
+ await this.#sock.presenceSubscribe(jid);
374
+ }
375
+ catch { }
376
+ }
377
+ await new Promise((r) => setTimeout(r, 750));
378
+ const peerDeviceJids = await this.#signaling.discoverPeerDevices(peerLid);
379
+ const deviceList = peerDeviceJids.length ? peerDeviceJids : [toBareJid(peerLid)];
380
+ await this.#signaling.ensureSessionsForPeers(deviceList);
381
+ await new Promise((r) => setTimeout(r, 500));
382
+ await this.#signaling.issueTcToken(peerLid);
383
+ const tcToken = await this.#signaling.ensureTcToken(peerLid, targetPnJid);
384
+ const callId = ("00" + randomBytes(16).toString("hex").slice(2)).toUpperCase();
385
+ const call = await this.#createActiveCall(callId, peerLid, "outgoing", { ...opts, audioSource, durationMs });
386
+ try {
387
+ this.#engine.startCall({
388
+ peerJid: peerLid,
389
+ peerPn: targetPnJid,
390
+ peerList: deviceList,
391
+ callId,
392
+ isVideo,
393
+ isLidCall: true,
394
+ isFromDialer: false,
395
+ extraData: tcToken,
396
+ });
397
+ }
398
+ catch (error) {
399
+ call._forceEnd("call_start_failed");
400
+ throw error;
401
+ }
402
+ return call;
403
+ };
404
+ /** Answer a pending incoming audio or video call after receiving the `incomingCall` event. */
405
+ answerIncomingCall = async (callId, opts = {}) => {
406
+ if (!this.#engine || !this.#signaling)
407
+ throw new Error("Not connected. Call connect() first.");
408
+ if (this.#activeCall || this.#creatingCall)
409
+ throw new Error("A call is already active or being prepared.");
410
+ const incoming = this.#incomingCalls.get(callId);
411
+ if (!incoming)
412
+ throw new Error(`No pending incoming call with ID ${callId}`);
413
+ if (opts.videoSource && !isVideoSource(opts.videoSource))
414
+ throw new Error("videoSource must be an async iterable of raw NV12 frames.");
415
+ if (!incoming.isVideo && (opts.isVideo || opts.videoSource))
416
+ throw new Error("Video cannot be added to an incoming audio call; WhatsApp requires a separate video-upgrade signaling handshake.");
417
+ if (opts.isVideo && !isVideoSource(opts.videoSource))
418
+ throw new Error("Enabling local video requires videoSource, an async iterable of raw NV12 frames.");
419
+ const call = await this.#createActiveCall(callId, incoming.peerJid, "incoming", { ...opts, isVideo: incoming.isVideo });
420
+ if (!this.#incomingCalls.has(callId)) {
421
+ call._forceEnd("incoming_call_ended");
422
+ throw new Error("The incoming call ended before it could be answered.");
423
+ }
424
+ call._updateState(CallState.ReceivedCall);
425
+ try {
426
+ this.#engine.acceptCall(true, Boolean(incoming.isVideo && opts.videoSource));
427
+ this.#incomingCalls.delete(callId);
428
+ if (call.state === CallState.ReceivedCall)
429
+ call._updateState(CallState.AcceptSent);
430
+ return call;
431
+ }
432
+ catch (error) {
433
+ call._forceEnd("answer_failed");
434
+ throw error;
435
+ }
436
+ };
437
+ /** Reject a pending incoming call. */
438
+ rejectIncomingCall = (callId) => {
439
+ if (!this.#engine || !this.#signaling)
440
+ throw new Error("Not connected. Call connect() first.");
441
+ if (!this.#incomingCalls.has(callId))
442
+ throw new Error(`No pending incoming call with ID ${callId}`);
443
+ this.#engine.rejectCall();
444
+ this.#incomingCalls.delete(callId);
445
+ };
446
+ /** Tear down the WhatsApp socket and release resources. */
447
+ disconnect = async () => {
448
+ const activeCall = this.#activeCall;
449
+ activeCall?._forceEnd("disconnect");
450
+ if (activeCall)
451
+ await activeCall.waitForRecording();
452
+ await Promise.allSettled([...this.#recordingFinalizers]);
453
+ this.#activeCall = null;
454
+ this.#incomingCalls.clear();
455
+ if (this.#callNodeHandler)
456
+ this.#sock?.ws?.off?.("CB:call", this.#callNodeHandler);
457
+ if (this.#receiptNodeHandler)
458
+ this.#sock?.ws?.off?.("CB:receipt", this.#receiptNodeHandler);
459
+ this.#signaling?.dispose?.();
460
+ await this.#relay?.closeAll();
461
+ await this.#engine?.destroy();
462
+ if (this.#ownsSocket)
463
+ this.#sock?.end?.();
464
+ this.#engine = null;
465
+ this.#relay = null;
466
+ this.#signaling = null;
467
+ this.#sock = null;
468
+ this.#callNodeHandler = null;
469
+ this.#receiptNodeHandler = null;
470
+ };
471
+ // ─── private ──────────────────────────────────────────────────────────────
472
+ #handleCallEvent = (eventType, eventData) => {
473
+ if (eventType === 16 && eventData) {
474
+ try {
475
+ const parsed = JSON.parse(eventData);
476
+ const info = parsed.call_info ?? parsed.callInfo ?? {};
477
+ const callState = Number(info.call_state ?? info.callState ?? 0);
478
+ const eventCallId = String(info.call_id ?? info.callId ?? parsed.call_id ?? parsed.callId ?? "");
479
+ if (this.#activeCall && (!eventCallId || eventCallId === this.#activeCall.callId))
480
+ this.#activeCall._updateState(callState);
481
+ }
482
+ catch { }
483
+ }
484
+ else if (eventType === 156 && eventData) {
485
+ try {
486
+ const update = JSON.parse(eventData);
487
+ this.#relay?.updateRelayList(update);
488
+ }
489
+ catch { }
490
+ }
491
+ else if (eventType === 2) {
492
+ this.#activeCall?._forceEnd("remote_end");
493
+ }
494
+ };
495
+ #handleVideoState = (info) => {
496
+ const pending = this.#pendingVideoUpgrade;
497
+ if (this.#activeCall?.callId !== info.callId)
498
+ return;
499
+ const state = Number(info.state);
500
+ if (state === 4) {
501
+ if (pending?.call === this.#activeCall) this.#settleVideoUpgrade("accepted");
502
+ }
503
+ else if (!pending || pending.call.callId !== info.callId) return;
504
+ else if (state === 5) this.#settleVideoUpgrade("rejected");
505
+ else if (state === 7) this.#settleVideoUpgrade("rejected_by_timeout");
506
+ else if (state === 8 || state === 9) this.#settleVideoUpgrade("cancelled");
507
+ else if (state === 20) this.#settleVideoUpgrade("failed");
508
+ };
509
+ #requestVideoUpgrade = (call, videoSource) => {
510
+ if (!this.#engine || this.#activeCall !== call || call.state !== CallState.Active)
511
+ return Promise.reject(new Error("Video upgrade requires an active call."));
512
+ if (call.isVideo)
513
+ return Promise.reject(new Error("This call already has video enabled."));
514
+ if (this.#pendingVideoUpgrade)
515
+ return Promise.reject(new Error("A video upgrade is already pending."));
516
+ if (!isVideoSource(videoSource))
517
+ return Promise.reject(new Error("videoSource must be an async iterable of raw NV12 frames."));
518
+
519
+ call._videoSource = videoSource;
520
+ return new Promise((resolve) => {
521
+ const timer = setTimeout(() => this.#settleVideoUpgrade("timeout"), VIDEO_UPGRADE_TIMEOUT_MS);
522
+ timer.unref?.();
523
+ this.#pendingVideoUpgrade = { call, resolve, timer };
524
+ try {
525
+ const result = this.#engine.requestVideoUpgrade();
526
+ if (result && typeof result.then === "function") {
527
+ result.catch((error) => {
528
+ if (this.#pendingVideoUpgrade?.call !== call) return;
529
+ this.#settleVideoUpgrade("failed");
530
+ call._emitVideoError(error instanceof Error ? error : new Error(String(error)));
531
+ });
532
+ }
533
+ }
534
+ catch (error) {
535
+ this.#settleVideoUpgrade("failed");
536
+ call._emitVideoError(error instanceof Error ? error : new Error(String(error)));
537
+ }
538
+ });
539
+ };
540
+ #settleVideoUpgrade = (result) => {
541
+ const pending = this.#pendingVideoUpgrade;
542
+ if (!pending)
543
+ return;
544
+ this.#pendingVideoUpgrade = null;
545
+ clearTimeout(pending.timer);
546
+ if (result === "accepted") pending.call.isVideo = true;
547
+ else pending.call._videoSource = null;
548
+ pending.resolve(result);
549
+ };
550
+ #handleAudioCaptureInit = (config) => {
551
+ if (!this.#engine)
552
+ return;
553
+ this.#captureSampleRate = config.sampleRate || 16000;
554
+ this.#captureChannels = config.channels || 1;
555
+ this.#captureFramesPerChunk = config.framesPerChunk || 320;
556
+ const chunkSamples = this.#captureFramesPerChunk * this.#captureChannels;
557
+ this.#captureChunkBytes = chunkSamples * Float32Array.BYTES_PER_ELEMENT;
558
+ this.#capturePtr = this.#engine.malloc(this.#captureChunkBytes);
559
+ };
560
+ #handleAudioPlaybackInit = (config) => {
561
+ this.#playbackSampleRate = config.sampleRate || 16000;
562
+ this.#playbackChannels = config.channels || 1;
563
+ };
564
+ #handleAudioCaptureStart = () => {
565
+ if (!this.#engine || !this.#capturePtr)
566
+ return;
567
+ const audioSource = this.#activeCall?._audioSource ?? "silence";
568
+ this.#feeder = new AudioFeeder(this.#captureSampleRate, this.#captureChannels, this.#captureFramesPerChunk, (chunk) => {
569
+ this.#activeCall?._recordAudio("outbound", chunk);
570
+ if (this.#engine && this.#capturePtr)
571
+ this.#engine.sendAudioData(chunk, this.#capturePtr);
572
+ }, audioSource);
573
+ this.#feeder.start();
574
+ };
575
+ #handleAudioCaptureStop = () => {
576
+ this.#feeder?.stop();
577
+ this.#feeder = null;
578
+ if (this.#engine && this.#capturePtr) {
579
+ try {
580
+ this.#engine.free(this.#capturePtr);
581
+ }
582
+ catch { }
583
+ this.#capturePtr = 0;
584
+ }
585
+ };
586
+ #handleVideoCaptureStart = () => {
587
+ this.#handleVideoCaptureStop();
588
+ const call = this.#activeCall;
589
+ if (!call?._videoSource || !this.#engine) {
590
+ const error = new Error("The WASM runtime requested local video capture, but no videoSource is configured.");
591
+ call?._emitVideoError(error);
592
+ this.emit("videoError", { callId: call?.callId ?? "", error });
593
+ return;
594
+ }
595
+ this.#videoFeeder = new VideoFeeder(call._videoSource, (frame) => this.#engine?.sendVideoFrame(frame), (error) => {
596
+ call._emitVideoError(error);
597
+ this.emit("videoError", { callId: call.callId, error });
598
+ });
599
+ this.#videoFeeder.start();
600
+ };
601
+ #handleVideoCaptureStop = () => {
602
+ this.#videoFeeder?.stop();
603
+ this.#videoFeeder = null;
604
+ };
605
+ #handleIncomingOffer = (info) => {
606
+ if (this.#activeCall || !info?.callId || this.#incomingCalls.has(info.callId))
607
+ return;
608
+ const incoming = Object.freeze({
609
+ callId: String(info.callId),
610
+ peerJid: String(info.peerJid ?? ""),
611
+ callerJid: String(info.callerJid ?? info.peerJid ?? ""),
612
+ isVideo: Boolean(info.isVideo),
613
+ });
614
+ this.#incomingCalls.set(incoming.callId, incoming);
615
+ this.emit("incomingCall", incoming);
616
+ };
617
+ #handleIncomingEnded = (callId, reason) => {
618
+ if (!this.#incomingCalls.delete(callId))
619
+ return;
620
+ this.emit("incomingCallEnded", { callId, reason });
621
+ };
622
+ #createActiveCall = async (callId, peerJid, direction, options = {}) => {
623
+ if (this.#activeCall || this.#creatingCall)
624
+ throw new Error("A call is already active or being prepared.");
625
+ this.#creatingCall = true;
626
+ try {
627
+ const durationMs = options.durationMs ?? 120_000;
628
+ const call = new ActiveCall(callId, this.#engine, 0, { direction, peerJid });
629
+ call._setVideoUpgradeHandler((videoSource) => this.#requestVideoUpgrade(call, videoSource));
630
+ call._audioSource = options.audioSource ?? "silence";
631
+ call._videoSource = options.videoSource ?? null;
632
+ call.isVideo = Boolean(options.isVideo || options.videoSource);
633
+ await this.#prepareRecording(call, options);
634
+ call._startDurationTimer(durationMs);
635
+ this.#activeCall = call;
636
+ call.on("recordingComplete", (result) => {
637
+ try { this.emit("recordingComplete", result); }
638
+ catch { }
639
+ });
640
+ call.on("recordingError", (details) => {
641
+ try { this.emit("recordingError", details); }
642
+ catch { }
643
+ });
644
+ call.once("ended", () => {
645
+ if (this.#pendingVideoUpgrade?.call === call)
646
+ this.#settleVideoUpgrade("cancelled");
647
+ this.#handleVideoCaptureStop();
648
+ if (this.#activeCall === call)
649
+ this.#activeCall = null;
650
+ const finalizer = call.waitForRecording();
651
+ this.#recordingFinalizers.add(finalizer);
652
+ void finalizer.finally(() => this.#recordingFinalizers.delete(finalizer)).catch(() => { });
653
+ });
654
+ return call;
655
+ }
656
+ finally {
657
+ this.#creatingCall = false;
658
+ }
659
+ };
660
+ #prepareRecording = async (call, options) => {
661
+ const config = this.#config.recording;
662
+ if (!config || options.recording === false)
663
+ return;
664
+ const recorder = await CallRecorder.create({
665
+ directory: config.directory,
666
+ callId: call.callId,
667
+ sampleRate: this.#captureSampleRate,
668
+ channels: this.#captureChannels,
669
+ outboundSampleRate: this.#captureSampleRate,
670
+ outboundChannels: this.#captureChannels,
671
+ inboundSampleRate: this.#playbackSampleRate,
672
+ inboundChannels: this.#playbackChannels,
673
+ maxQueuedBytes: config.maxQueuedBytes,
674
+ onError: (direction, error) => call._emitRecordingError(direction, error),
675
+ });
676
+ call._attachRecorder(recorder);
677
+ try { this.emit("recordingStarted", { callId: call.callId, files: recorder.paths }); }
678
+ catch { }
679
+ };
680
+ }