kage-baileys 3.0.6 → 3.2.3

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 (216) hide show
  1. package/Example/connection.cjs +4 -0
  2. package/README.MD +4726 -48
  3. package/WAProto/WAProto.proto +3395 -415
  4. package/WAProto/compat.cjs +12 -0
  5. package/WAProto/index.d.ts +47104 -19888
  6. package/WAProto/index.js +131979 -57361
  7. package/lib/Addon/http-error.js +43 -0
  8. package/lib/Addon/index.js +32 -0
  9. package/lib/Addon/keyed-db.js +250 -0
  10. package/lib/Addon/link-preview.js +82 -0
  11. package/lib/Defaults/baileys-version.json +3 -0
  12. package/lib/Defaults/connection.js +110 -0
  13. package/lib/Defaults/constants.js +156 -0
  14. package/lib/Defaults/history.js +46 -0
  15. package/lib/Defaults/index.js +230 -0
  16. package/lib/Defaults/media.js +104 -0
  17. package/lib/Defaults/phonenumber-mcc.json +223 -0
  18. package/lib/Defaults/prefix.js +44 -0
  19. package/lib/Extensions/business-advanced.js +382 -0
  20. package/lib/Extensions/business.js +159 -0
  21. package/lib/Extensions/chats-advanced.js +1106 -0
  22. package/lib/Extensions/chats.js +349 -0
  23. package/lib/Extensions/communities-advanced.js +430 -0
  24. package/lib/Extensions/community.js +94 -0
  25. package/lib/Extensions/groups-advanced.js +343 -0
  26. package/lib/Extensions/index.js +30 -0
  27. package/lib/Extensions/messages-recv-advanced.js +1690 -0
  28. package/lib/Extensions/messages-send-advanced.js +622 -0
  29. package/lib/Extensions/messages-send.js +1380 -0
  30. package/lib/Extensions/newsletter-advanced.js +228 -0
  31. package/lib/Extensions/newsletter.js +72 -0
  32. package/lib/Extensions/socket.js +389 -0
  33. package/lib/Modded/message_builder.js +2084 -4
  34. package/lib/Signal/Group/ciphertext-message.js +54 -0
  35. package/lib/Signal/Group/group-session-builder.js +124 -0
  36. package/lib/Signal/Group/group_cipher.js +216 -0
  37. package/lib/Signal/Group/index.js +124 -0
  38. package/lib/Signal/Group/keyhelper.js +108 -0
  39. package/lib/Signal/Group/sender-chain-key.js +83 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js +157 -0
  41. package/lib/Signal/Group/sender-key-message.js +166 -0
  42. package/lib/Signal/Group/sender-key-name.js +130 -0
  43. package/lib/Signal/Group/sender-key-record.js +113 -0
  44. package/lib/Signal/Group/sender-key-state.js +208 -0
  45. package/lib/Signal/Group/sender-message-key.js +82 -0
  46. package/lib/Signal/libsignal.js +935 -0
  47. package/lib/Signal/lid-mapping.js +545 -1
  48. package/lib/Socket/Client/index.js +60 -0
  49. package/lib/Socket/Client/types.js +51 -0
  50. package/lib/Socket/Client/websocket.js +152 -0
  51. package/lib/Socket/business.js +831 -0
  52. package/lib/Socket/chats.js +2535 -49
  53. package/lib/Socket/communities.js +450 -1
  54. package/lib/Socket/community.js +1022 -0
  55. package/lib/Socket/dugong.js +1 -1
  56. package/lib/Socket/groups.js +747 -0
  57. package/lib/Socket/index.js +60 -2
  58. package/lib/Socket/messages-recv.js +3450 -5
  59. package/lib/Socket/messages-send.js +3123 -0
  60. package/lib/Socket/mex.js +126 -1
  61. package/lib/Socket/newsletter.js +465 -0
  62. package/lib/Socket/socket.js +2217 -1
  63. package/lib/Store/index.js +79 -0
  64. package/lib/Store/make-cache-manager-store.js +186 -0
  65. package/lib/Store/make-in-memory-store.js +878 -0
  66. package/lib/Store/make-ordered-dictionary.js +187 -0
  67. package/lib/Store/object-repository.js +78 -0
  68. package/lib/Types/Auth.js +25 -0
  69. package/lib/Types/Bussines.js +25 -1
  70. package/lib/Types/Call.js +25 -0
  71. package/lib/Types/Chat.js +39 -0
  72. package/lib/Types/Contact.js +25 -0
  73. package/lib/Types/Events.js +25 -0
  74. package/lib/Types/GroupMetadata.js +25 -0
  75. package/lib/Types/Label.js +76 -0
  76. package/lib/Types/LabelAssociation.js +40 -0
  77. package/lib/Types/Message.js +57 -0
  78. package/lib/Types/Mex.js +56 -1
  79. package/lib/Types/MexUpdates.js +46 -0
  80. package/lib/Types/Newsletter.js +56 -0
  81. package/lib/Types/Product.js +25 -0
  82. package/lib/Types/RichType.js +23 -0
  83. package/lib/Types/Signal.js +25 -0
  84. package/lib/Types/Socket.js +25 -0
  85. package/lib/Types/State.js +92 -0
  86. package/lib/Types/USync.js +25 -0
  87. package/lib/Types/index.js +133 -0
  88. package/lib/Utils/auth-utils.js +703 -0
  89. package/lib/Utils/automation-tools.js +51 -16
  90. package/lib/Utils/baileys-event-stream.js +146 -0
  91. package/lib/Utils/browser-utils.js +95 -0
  92. package/lib/Utils/business.js +525 -0
  93. package/lib/Utils/chat-utils.js +1861 -0
  94. package/lib/Utils/companion-reg-client-utils.js +55 -1
  95. package/lib/Utils/crypto.js +355 -0
  96. package/lib/Utils/decode-wa-message.js +709 -0
  97. package/lib/Utils/event-buffer.js +1323 -8
  98. package/lib/Utils/generics.js +945 -1
  99. package/lib/Utils/history.js +266 -0
  100. package/lib/Utils/identity-change-handler.js +62 -1
  101. package/lib/Utils/index.js +114 -0
  102. package/lib/Utils/link-preview.js +179 -0
  103. package/lib/Utils/logger.js +42 -0
  104. package/lib/Utils/lt-hash.js +73 -0
  105. package/lib/Utils/make-mutex.js +104 -0
  106. package/lib/Utils/message-inspector.js +110 -0
  107. package/lib/Utils/message-retry-manager.js +507 -2
  108. package/lib/Utils/messages-media.js +1931 -1
  109. package/lib/Utils/messages.js +3748 -0
  110. package/lib/Utils/noise-handler.js +423 -0
  111. package/lib/Utils/offline-node-processor.js +53 -1
  112. package/lib/Utils/pre-key-manager.js +255 -1
  113. package/lib/Utils/process-message.js +1592 -0
  114. package/lib/Utils/reporting-utils.js +272 -1
  115. package/lib/Utils/rich-message-utils.js +377 -0
  116. package/lib/Utils/rich-messages.js +1 -1
  117. package/lib/Utils/signal.js +437 -0
  118. package/lib/Utils/stanza-ack.js +51 -1
  119. package/lib/Utils/status-refresh.js +37 -0
  120. package/lib/Utils/status-tools.js +4 -2
  121. package/lib/Utils/sync-action-utils.js +63 -1
  122. package/lib/Utils/tc-token-utils.js +185 -1
  123. package/lib/Utils/terminal-banner.js +31 -0
  124. package/lib/Utils/use-multi-file-auth-state.js +271 -0
  125. package/lib/Utils/use-single-file-auth-state.js +108 -0
  126. package/lib/Utils/use-sqlite-auth-state.js +142 -0
  127. package/lib/Utils/validate-connection.js +497 -1
  128. package/lib/Utils/view-once-compat.js +13 -5
  129. package/lib/VoIP/audio-feeder.js +150 -0
  130. package/lib/VoIP/index.js +289 -0
  131. package/lib/VoIP/relay-transport.js +608 -0
  132. package/lib/VoIP/signaling.js +583 -0
  133. package/lib/VoIP/types.js +30 -0
  134. package/lib/VoIP/wasm-engine.js +1261 -2
  135. package/lib/VoIP/worker-bootstrap.js +1090 -2
  136. package/lib/WABinary/constants.js +2805 -0
  137. package/lib/WABinary/decode.js +649 -2
  138. package/lib/WABinary/encode.js +564 -2
  139. package/lib/WABinary/generic-utils.js +401 -0
  140. package/lib/WABinary/index.js +82 -0
  141. package/lib/WABinary/jid-utils.js +290 -0
  142. package/lib/WABinary/types.js +25 -0
  143. package/lib/WAM/BinaryInfo.js +50 -0
  144. package/lib/WAM/constants.js +45747 -0
  145. package/lib/WAM/encode.js +393 -0
  146. package/lib/WAM/index.js +78 -0
  147. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +135 -0
  148. package/lib/WAUSync/Protocols/USyncContactProtocol.js +110 -0
  149. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +142 -0
  150. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +85 -0
  151. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +69 -0
  152. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +107 -0
  153. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +38 -1
  154. package/lib/WAUSync/Protocols/index.js +83 -0
  155. package/lib/WAUSync/USyncQuery.js +241 -2
  156. package/lib/WAUSync/USyncUser.js +86 -0
  157. package/lib/WAUSync/index.js +78 -0
  158. package/lib/assets/wasm/loader.js +1875 -1
  159. package/lib/assets/wasm/worker-modules.js +11047 -1
  160. package/lib/index.d.ts +126 -0
  161. package/lib/index.js +53 -21
  162. package/lib/index.mjs +437 -0
  163. package/licenses/upstream-MIT.txt +22 -0
  164. package/maintenance/api-coverage.json +1642 -0
  165. package/maintenance/archivos-sha256.json +207 -0
  166. package/maintenance/consumer-validation.log +3 -0
  167. package/maintenance/dependency-audit.json +4 -4
  168. package/maintenance/extension-inventory.json +57 -0
  169. package/maintenance/protocol-update.json +1101 -0
  170. package/maintenance/protocol-wire-audit.json +4 -0
  171. package/maintenance/reference-socket-surface.json +209 -0
  172. package/maintenance/resumen-validacion.json +50 -0
  173. package/maintenance/validation.log +2725 -0
  174. package/maintenance/verification.json +566 -0
  175. package/package.json +107 -9
  176. package/scripts/check-imports.cjs +10 -0
  177. package/scripts/check-package.cjs +40 -0
  178. package/scripts/check-syntax.cjs +1 -1
  179. package/scripts/generate-protobuf.cjs +6 -1
  180. package/scripts/generate-public-types.cjs +9 -0
  181. package/scripts/kage-base64-fix.cjs +45 -0
  182. package/scripts/maintenance.cjs +10 -0
  183. package/test/advanced.test.cjs +24 -0
  184. package/test/base64-fix.test.cjs +49 -0
  185. package/test/maintenance.test.cjs +1 -1
  186. package/test/npm-publication.test.cjs +141 -0
  187. package/test/recepcion-reparada.test.cjs +98 -0
  188. package/test/resilience-binary.test.cjs +69 -0
  189. package/test/resilience-transport.test.cjs +34 -0
  190. package/test/types.test.ts +5 -0
  191. package/test/upgrade.test.cjs +104 -0
  192. package/tsconfig.json +20 -0
  193. package/WAProto/p.html +0 -1
  194. package/lib/KageExtra/Modded/message_builder.js +0 -2330
  195. package/lib/KageExtra/VoIP/audio-feeder.js +0 -136
  196. package/lib/KageExtra/VoIP/index.js +0 -282
  197. package/lib/KageExtra/VoIP/relay-transport.js +0 -559
  198. package/lib/KageExtra/VoIP/signaling.js +0 -603
  199. package/lib/KageExtra/VoIP/types.js +0 -17
  200. package/lib/KageExtra/VoIP/wasm-engine.js +0 -1214
  201. package/lib/KageExtra/VoIP/worker-bootstrap.js +0 -1042
  202. package/lib/KageExtra/assets/wasm/loader.js +0 -5
  203. package/lib/KageExtra/assets/wasm/whatsapp.wasm +0 -0
  204. package/lib/KageExtra/assets/wasm/worker-modules.js +0 -273
  205. package/lib/KageExtra/index.js +0 -3
  206. package/lib/KageExtra/package.json +0 -1
  207. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -53
  208. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -24
  209. package/maintenance/revision-full-check.txt +0 -1097
  210. package/maintenance/revision-library-tests.tap +0 -1088
  211. package/maintenance/revision-protobuf.txt +0 -5
  212. package/maintenance/revision-syntax.txt +0 -5
  213. package/maintenance/schema-coverage.json +0 -23
  214. package/maintenance/schema-merge.json +0 -30
  215. package/maintenance/validation-node20.txt +0 -191
  216. package/maintenance/validation-node22.txt +0 -237
@@ -134,3 +134,153 @@ const DEFAULT_WARMUP_MS = 500;
134
134
  }
135
135
  };
136
136
  } exports.AudioFeeder = AudioFeeder;
137
+
138
+ // Kage: herramientas de Kage.
139
+ const __kageModule103 = (() => {
140
+ const module = { exports: {} }; const exports = module.exports;
141
+ "use strict";
142
+ Object.defineProperty(exports, "__esModule", { value: true });
143
+ exports.AudioFeeder = void 0;
144
+ /**
145
+ * Audio feeder.
146
+ *
147
+ * Spawns ffmpeg to decode `source` into f32le PCM at the requested rate, then
148
+ * meters frames out at chunk-cadence to the WASM uplink.
149
+ *
150
+ * @author ShellTear
151
+ */
152
+ const node_child_process_1 = require("node:child_process");
153
+ const LOW_WATERMARK_CHUNKS = 16;
154
+ const MAX_QUEUED_CHUNKS = 1024;
155
+ const DEFAULT_WARMUP_MS = 500;
156
+ class AudioFeeder {
157
+ sampleRate;
158
+ channels;
159
+ framesPerChunk;
160
+ onChunk;
161
+ source;
162
+ #proc = null;
163
+ #pending = Buffer.alloc(0);
164
+ #queue = [];
165
+ #emitTimer = null;
166
+ #nextEmitAtMs = 0;
167
+ #warmupUntilMs = 0;
168
+ droppedChunks = 0;
169
+ underflowChunks = 0;
170
+ bytesProduced = 0;
171
+ chunksEmitted = 0;
172
+ constructor(sampleRate, channels, framesPerChunk, onChunk, source = "silence") {
173
+ this.sampleRate = sampleRate;
174
+ this.channels = channels;
175
+ this.framesPerChunk = framesPerChunk;
176
+ this.onChunk = onChunk;
177
+ this.source = source;
178
+ }
179
+ start = () => {
180
+ if (this.#proc)
181
+ return;
182
+ const chunkSamples = this.framesPerChunk * this.channels;
183
+ const chunkBytes = chunkSamples * Float32Array.BYTES_PER_ELEMENT;
184
+ const chunkIntervalMs = (this.framesPerChunk / this.sampleRate) * 1000;
185
+ const inputArgs = this.#resolveInputArgs();
186
+ this.#proc = (0, node_child_process_1.spawn)("ffmpeg", [
187
+ "-hide_banner",
188
+ "-loglevel", "error",
189
+ "-thread_queue_size", "512",
190
+ ...inputArgs,
191
+ "-f", "f32le",
192
+ "-ac", String(this.channels),
193
+ "-ar", String(this.sampleRate),
194
+ "pipe:1",
195
+ ]);
196
+ this.#proc.stdout.on("data", (chunk) => {
197
+ this.#pending = Buffer.concat([this.#pending, chunk]);
198
+ while (this.#pending.length >= chunkBytes) {
199
+ if (this.#queue.length >= MAX_QUEUED_CHUNKS) {
200
+ this.#proc?.stdout.pause();
201
+ break;
202
+ }
203
+ const frame = this.#pending.subarray(0, chunkBytes);
204
+ this.#pending = this.#pending.subarray(chunkBytes);
205
+ const out = new Float32Array(chunkSamples);
206
+ out.set(new Float32Array(frame.buffer, frame.byteOffset, chunkSamples));
207
+ this.bytesProduced += chunkBytes;
208
+ this.#queue.push(out);
209
+ }
210
+ });
211
+ this.#proc.stderr.on("data", (chunk) => {
212
+ process.stderr.write(`[AudioFeeder] ${chunk.toString().trim()}\n`);
213
+ });
214
+ this.#proc.on("error", (err) => {
215
+ process.stderr.write(`[AudioFeeder] ffmpeg process error: ${err.message}\n`);
216
+ this.#proc = null;
217
+ });
218
+ this.#proc.on("exit", (code) => {
219
+ if (code !== 0 && code !== null) {
220
+ process.stderr.write(`[AudioFeeder] ffmpeg exited with code=${code}\n`);
221
+ }
222
+ this.#proc = null;
223
+ });
224
+ this.#nextEmitAtMs = 0;
225
+ this.#warmupUntilMs = Date.now() + DEFAULT_WARMUP_MS;
226
+ this.#scheduleNext(chunkSamples, chunkIntervalMs);
227
+ };
228
+ stop = () => {
229
+ if (this.#emitTimer) {
230
+ clearTimeout(this.#emitTimer);
231
+ this.#emitTimer = null;
232
+ }
233
+ this.#proc?.kill("SIGTERM");
234
+ this.#proc = null;
235
+ this.#pending = Buffer.alloc(0);
236
+ this.#queue = [];
237
+ this.#warmupUntilMs = 0;
238
+ };
239
+ #resolveInputArgs = () => {
240
+ if (!this.source || this.source === "silence") {
241
+ return ["-f", "lavfi", "-i", `aevalsrc=0:d=3600:s=${this.sampleRate}`];
242
+ }
243
+ if (this.source.startsWith("lavfi:")) {
244
+ return ["-f", "lavfi", "-i", this.source.slice("lavfi:".length)];
245
+ }
246
+ return ["-i", this.source];
247
+ };
248
+ #scheduleNext = (chunkSamples, chunkIntervalMs) => {
249
+ if (!this.#proc)
250
+ return;
251
+ const now = Date.now();
252
+ if (this.#nextEmitAtMs === 0)
253
+ this.#nextEmitAtMs = now;
254
+ const delayMs = Math.max(0, this.#nextEmitAtMs - now);
255
+ this.#emitTimer = setTimeout(() => {
256
+ this.#emitTimer = null;
257
+ if (this.#queue.length < LOW_WATERMARK_CHUNKS && Date.now() < this.#warmupUntilMs) {
258
+ this.#nextEmitAtMs = Date.now() + 10;
259
+ this.#scheduleNext(chunkSamples, chunkIntervalMs);
260
+ return;
261
+ }
262
+ this.#flushOne(chunkSamples);
263
+ this.#nextEmitAtMs += chunkIntervalMs;
264
+ this.#scheduleNext(chunkSamples, chunkIntervalMs);
265
+ }, delayMs);
266
+ };
267
+ #flushOne = (chunkSamples) => {
268
+ let nextChunk = this.#queue.shift();
269
+ if (!nextChunk) {
270
+ nextChunk = new Float32Array(chunkSamples);
271
+ this.underflowChunks += 1;
272
+ }
273
+ this.chunksEmitted += 1;
274
+ this.onChunk(nextChunk);
275
+ if (this.#proc?.stdout.isPaused() && this.#queue.length <= MAX_QUEUED_CHUNKS / 4) {
276
+ this.#proc.stdout.resume();
277
+ }
278
+ };
279
+ }
280
+ exports.AudioFeeder = AudioFeeder;
281
+
282
+ return module.exports;
283
+ })();
284
+ for (const key of Object.keys(__kageModule103)) {
285
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule103[key]});
286
+ }
package/lib/VoIP/index.js CHANGED
@@ -280,3 +280,292 @@ const isCallReceiptNode = (node) => {
280
280
  }
281
281
  };
282
282
  } exports.VoipClient = VoipClient;
283
+
284
+ // Kage: herramientas de Kage.
285
+ const __kageModule104 = (() => {
286
+ const module = { exports: {} }; const exports = module.exports;
287
+ "use strict";
288
+ Object.defineProperty(exports, "__esModule", { value: true });
289
+ exports.VoipClient = exports.ActiveCall = exports.CallState = void 0;
290
+ const node_events_1 = require("node:events");
291
+ const node_crypto_1 = require("node:crypto");
292
+ const wasm_engine_js_1 = require("./wasm-engine.js");
293
+ const relay_transport_js_1 = require("./relay-transport.js");
294
+ const signaling_js_1 = require("./signaling.js");
295
+ const audio_feeder_js_1 = require("./audio-feeder.js");
296
+ const types_js_1 = require("./types.js");
297
+ var types_js_2 = require("./types.js");
298
+ Object.defineProperty(exports, "CallState", { enumerable: true, get: function () { return types_js_2.CallState; } });
299
+ const SHA256_LEN = 32;
300
+ const toBareJid = (jid) => {
301
+ if (!jid)
302
+ return jid;
303
+ const at = jid.indexOf("@");
304
+ if (at < 0)
305
+ return jid;
306
+ const user = jid.slice(0, at).split(":")[0];
307
+ return `${user}@${jid.slice(at + 1)}`;
308
+ };
309
+ const computeHkdf = (key, salt, info, length) => {
310
+ const effectiveSalt = salt && salt.length > 0 ? Buffer.from(salt) : Buffer.alloc(SHA256_LEN, 0);
311
+ const prk = (0, node_crypto_1.createHmac)("sha256", effectiveSalt).update(key).digest();
312
+ const blocks = Math.ceil(length / SHA256_LEN);
313
+ const okm = Buffer.alloc(blocks * SHA256_LEN);
314
+ let prev = Buffer.alloc(0);
315
+ for (let i = 1; i <= blocks; i += 1) {
316
+ prev = (0, node_crypto_1.createHmac)("sha256", prk)
317
+ .update(prev)
318
+ .update(info)
319
+ .update(Buffer.from([i]))
320
+ .digest();
321
+ prev.copy(okm, (i - 1) * SHA256_LEN);
322
+ }
323
+ return new Uint8Array(okm.buffer, okm.byteOffset, length);
324
+ };
325
+ const computeHmacSha256 = (data, key) => {
326
+ const result = (0, node_crypto_1.createHmac)("sha256", Buffer.from(key)).update(data).digest();
327
+ return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
328
+ };
329
+ const isCallReceiptNode = (node) => {
330
+ if (node?.tag !== "receipt")
331
+ return false;
332
+ const child = Array.isArray(node.content) ? node.content[0] : null;
333
+ return !!(child?.attrs?.["call-id"] || child?.attrs?.call_id);
334
+ };
335
+ class ActiveCall extends node_events_1.EventEmitter {
336
+ #state = types_js_1.CallState.Idle;
337
+ #endResolver;
338
+ #endPromise;
339
+ #endTimer = null;
340
+ #ended = false;
341
+ #hasBeenActive = false;
342
+ _audioSource = "silence";
343
+ constructor(callId, engine, durationMs) {
344
+ super();
345
+ this.callId = callId;
346
+ this.engine = engine;
347
+ this.#endPromise = new Promise((res) => { this.#endResolver = res; });
348
+ if (durationMs > 0) {
349
+ this.#endTimer = setTimeout(() => this.end(), durationMs);
350
+ }
351
+ }
352
+ get state() { return this.#state; }
353
+ end = () => {
354
+ if (this.#ended)
355
+ return;
356
+ this.#ended = true;
357
+ if (this.#endTimer) {
358
+ clearTimeout(this.#endTimer);
359
+ this.#endTimer = null;
360
+ }
361
+ try {
362
+ this.engine.endCall(0, true);
363
+ }
364
+ catch { }
365
+ };
366
+ mute = (muted) => {
367
+ try {
368
+ this.engine.setMute(muted);
369
+ }
370
+ catch { }
371
+ };
372
+ waitForEnd = () => this.#endPromise;
373
+ _updateState = (state) => {
374
+ this.#state = state;
375
+ if (state === types_js_1.CallState.Calling || state === types_js_1.CallState.PreacceptReceived || state === types_js_1.CallState.Active) {
376
+ this.#hasBeenActive = true;
377
+ }
378
+ if (state === types_js_1.CallState.PreacceptReceived)
379
+ this.emit("ringing");
380
+ else if (state === types_js_1.CallState.Active)
381
+ this.emit("connected");
382
+ else if (this.#hasBeenActive && (state === types_js_1.CallState.Idle || state === types_js_1.CallState.Ending)) {
383
+ this._forceEnd("ended");
384
+ }
385
+ };
386
+ _emitAudio = (pcm) => { this.emit("audio", pcm); };
387
+ _forceEnd = (reason) => {
388
+ if (this.#ended)
389
+ return;
390
+ this.#ended = true;
391
+ if (this.#endTimer) {
392
+ clearTimeout(this.#endTimer);
393
+ this.#endTimer = null;
394
+ }
395
+ this.emit("ended", reason);
396
+ this.#endResolver(reason);
397
+ };
398
+ }
399
+ exports.ActiveCall = ActiveCall;
400
+ class VoipClient {
401
+ #config;
402
+ #engine = null;
403
+ #relay = null;
404
+ #signaling = null;
405
+ #sock = null;
406
+ #activeCall = null;
407
+ #capturePtr = 0;
408
+ #captureChunkBytes = 0;
409
+ #captureSampleRate = 16000;
410
+ #captureChannels = 1;
411
+ #captureFramesPerChunk = 320;
412
+ #feeder = null;
413
+ constructor(config = {}) {
414
+ this.#config = config;
415
+ }
416
+ connectWithSocket = async (existingSock) => {
417
+ this.#sock = existingSock;
418
+ await this.#initVoipStack();
419
+ };
420
+ #initVoipStack = async () => {
421
+ this.#signaling = new signaling_js_1.SignalingBridge({ sock: this.#sock });
422
+ await this.#signaling.init();
423
+ this.#relay = new relay_transport_js_1.RelayRtcTransport({
424
+ onTransportMessage: (data, ip, port) => this.#engine?.handleOnTransportMessage(data, ip, port),
425
+ onIceRtt: (rttMs, ip, port) => this.#engine?.updateIceRtt(rttMs, ip, port),
426
+ });
427
+ this.#engine = new wasm_engine_js_1.WasmEngine({
428
+ resourcesPath: this.#config.resourcesPath,
429
+ callbacks: {
430
+ onSignalingXmpp: (peerJid, callId, xmlPayload) => this.#signaling.sendSignaling(peerJid, callId, xmlPayload),
431
+ onCallEvent: (eventType, eventData) => this.#handleCallEvent(eventType, eventData),
432
+ sendDataToRelay: (data, ip, port) => this.#relay.send(data, ip, port),
433
+ onAudioCaptureInit: (config) => this.#handleAudioCaptureInit(config),
434
+ onAudioCaptureStart: () => this.#handleAudioCaptureStart(),
435
+ onAudioCaptureStop: () => this.#handleAudioCaptureStop(),
436
+ onAudioPlaybackData: (audioData) => this.#activeCall?._emitAudio(audioData),
437
+ cryptoHkdf: computeHkdf,
438
+ hmacSha256: computeHmacSha256,
439
+ },
440
+ });
441
+ await this.#engine.initialize();
442
+ this.#signaling.attachEngine(this.#engine);
443
+ const selfPnJid = this.#sock.authState.creds.me?.id;
444
+ const selfLidJid = this.#sock.authState.creds.me?.lid;
445
+ this.#engine.initVoipStack(selfPnJid, toBareJid(selfPnJid), selfLidJid);
446
+ await this.#engine.waitForVoipStackReady();
447
+ try {
448
+ this.#engine.updateNetworkMedium(2, 0);
449
+ }
450
+ catch { }
451
+ this.#sock.ws.on("CB:call", (node) => {
452
+ this.#signaling.processIncomingCall(node, this.#engine, this.#activeCall?.callId ?? "");
453
+ });
454
+ this.#sock.ws.on("CB:receipt", (node) => {
455
+ if (!isCallReceiptNode(node))
456
+ return;
457
+ this.#signaling.processIncomingReceipt(node, this.#engine, this.#activeCall?.callId ?? "");
458
+ });
459
+ };
460
+ call = async (phoneNumber, opts = {}) => {
461
+ if (!this.#engine || !this.#signaling)
462
+ throw new Error("Not connected. Call connectWithSocket() first.");
463
+ if (this.#activeCall)
464
+ throw new Error("A call is already active.");
465
+ const targetNumber = phoneNumber.replace(/\D/g, "");
466
+ const targetPnJid = `${targetNumber}@s.whatsapp.net`;
467
+ const durationMs = opts.durationMs ?? 120_000;
468
+ const audioSource = opts.audioSource ?? "silence";
469
+ const peerLid = await this.#signaling.resolveLid(targetPnJid);
470
+ if (!peerLid)
471
+ throw new Error(`Could not resolve LID for ${targetPnJid}`);
472
+ for (const jid of [targetPnJid, peerLid]) {
473
+ try {
474
+ await this.#sock.presenceSubscribe(jid);
475
+ }
476
+ catch { }
477
+ }
478
+ await new Promise((r) => setTimeout(r, 750));
479
+ const peerDeviceJids = await this.#signaling.discoverPeerDevices(peerLid);
480
+ const deviceList = peerDeviceJids.length ? peerDeviceJids : [toBareJid(peerLid)];
481
+ const allSessionTargets = [...new Set([...deviceList, peerLid, toBareJid(peerLid), targetPnJid, toBareJid(targetPnJid)])];
482
+ await this.#signaling.ensureSessionsForPeers(allSessionTargets);
483
+ await new Promise((r) => setTimeout(r, 500));
484
+ await this.#signaling.issueTcToken(peerLid);
485
+ const tcToken = await this.#signaling.ensureTcToken(peerLid, targetPnJid);
486
+ const callId = ("00" + (0, node_crypto_1.randomBytes)(16).toString("hex").slice(2)).toUpperCase();
487
+ const call = new ActiveCall(callId, this.#engine, durationMs);
488
+ call._audioSource = audioSource;
489
+ this.#activeCall = call;
490
+ this.#engine.startCall({
491
+ peerJid: peerLid,
492
+ peerPn: targetPnJid,
493
+ peerList: deviceList,
494
+ callId,
495
+ isVideo: false,
496
+ isLidCall: true,
497
+ isFromDialer: false,
498
+ extraData: tcToken,
499
+ });
500
+ return call;
501
+ };
502
+ disconnect = () => {
503
+ this.#activeCall?._forceEnd("disconnect");
504
+ this.#activeCall = null;
505
+ this.#relay?.closeAll();
506
+ this.#engine?.destroy();
507
+ this.#engine = null;
508
+ this.#relay = null;
509
+ this.#signaling = null;
510
+ this.#sock = null;
511
+ };
512
+ #handleCallEvent = (eventType, eventData) => {
513
+ if (eventType === 16 && eventData) {
514
+ try {
515
+ const parsed = JSON.parse(eventData);
516
+ const info = parsed.call_info ?? parsed.callInfo ?? {};
517
+ const callState = Number(info.call_state ?? info.callState ?? 0);
518
+ this.#activeCall?._updateState(callState);
519
+ }
520
+ catch { }
521
+ }
522
+ else if (eventType === 156 && eventData) {
523
+ try {
524
+ const update = JSON.parse(eventData);
525
+ this.#relay?.updateRelayList(update);
526
+ }
527
+ catch { }
528
+ }
529
+ else if (eventType === 2) {
530
+ this.#activeCall?._forceEnd("remote_end");
531
+ }
532
+ };
533
+ #handleAudioCaptureInit = (config) => {
534
+ if (!this.#engine)
535
+ return;
536
+ this.#captureSampleRate = config.sampleRate || 16000;
537
+ this.#captureChannels = config.channels || 1;
538
+ this.#captureFramesPerChunk = config.framesPerChunk || 320;
539
+ const chunkSamples = this.#captureFramesPerChunk * this.#captureChannels;
540
+ this.#captureChunkBytes = chunkSamples * Float32Array.BYTES_PER_ELEMENT;
541
+ this.#capturePtr = this.#engine.malloc(this.#captureChunkBytes);
542
+ };
543
+ #handleAudioCaptureStart = () => {
544
+ if (!this.#engine || !this.#capturePtr)
545
+ return;
546
+ const audioSource = this.#activeCall?._audioSource ?? "silence";
547
+ this.#feeder = new audio_feeder_js_1.AudioFeeder(this.#captureSampleRate, this.#captureChannels, this.#captureFramesPerChunk, (chunk) => {
548
+ if (this.#engine && this.#capturePtr)
549
+ this.#engine.sendAudioData(chunk, this.#capturePtr);
550
+ }, audioSource);
551
+ this.#feeder.start();
552
+ };
553
+ #handleAudioCaptureStop = () => {
554
+ this.#feeder?.stop();
555
+ this.#feeder = null;
556
+ if (this.#engine && this.#capturePtr) {
557
+ try {
558
+ this.#engine.free(this.#capturePtr);
559
+ }
560
+ catch { }
561
+ this.#capturePtr = 0;
562
+ }
563
+ };
564
+ }
565
+ exports.VoipClient = VoipClient;
566
+
567
+ return module.exports;
568
+ })();
569
+ for (const key of Object.keys(__kageModule104)) {
570
+ if (key !== '__esModule' && !Object.prototype.hasOwnProperty.call(exports,key)) Object.defineProperty(exports,key,{enumerable:true,configurable:true,get:()=>__kageModule104[key]});
571
+ }