@awangxcode/qiro-baileys 7.0.0-rc25.6 → 7.0.0-rc26.2

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 (298) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +1445 -1041
  3. package/WAProto/WAProto.proto +4 -0
  4. package/WAProto/index.d.ts +4067 -243
  5. package/WAProto/index.js +74957 -43330
  6. package/assets/branding/qiro-logo.svg +24 -0
  7. package/assets/branding/qiro-mark.png +0 -0
  8. package/assets/branding/qiro-mark.svg +34 -0
  9. package/assets/branding/qiro-social-preview.png +0 -0
  10. package/lib/Defaults/index.d.ts +16 -1
  11. package/lib/Defaults/index.d.ts.map +1 -1
  12. package/lib/Defaults/index.js +43 -10
  13. package/lib/Defaults/index.js.map +1 -1
  14. package/lib/Extensions/advanced.d.ts +1 -1
  15. package/lib/Extensions/experimental.d.ts +1 -3
  16. package/lib/Extensions/experimental.d.ts.map +1 -1
  17. package/lib/Extensions/experimental.js +0 -2
  18. package/lib/Extensions/experimental.js.map +1 -1
  19. package/lib/MessageBuilder/index.d.ts +5 -5
  20. package/lib/MessageBuilder/index.d.ts.map +1 -1
  21. package/lib/MessageBuilder/index.js +12 -3
  22. package/lib/MessageBuilder/index.js.map +1 -1
  23. package/lib/Signal/Group/group-session-builder.d.ts +3 -3
  24. package/lib/Signal/Group/group-session-builder.js +4 -4
  25. package/lib/Signal/Group/group_cipher.d.ts +2 -2
  26. package/lib/Signal/Group/group_cipher.js +4 -4
  27. package/lib/Signal/Group/index.d.ts +11 -11
  28. package/lib/Signal/Group/index.js +11 -11
  29. package/lib/Signal/Group/sender-chain-key.d.ts +1 -1
  30. package/lib/Signal/Group/sender-chain-key.js +1 -1
  31. package/lib/Signal/Group/sender-key-distribution-message.d.ts +1 -1
  32. package/lib/Signal/Group/sender-key-distribution-message.js +1 -1
  33. package/lib/Signal/Group/sender-key-message.d.ts +1 -1
  34. package/lib/Signal/Group/sender-key-message.js +1 -1
  35. package/lib/Signal/Group/sender-key-record.d.ts +1 -1
  36. package/lib/Signal/Group/sender-key-record.js +2 -2
  37. package/lib/Signal/Group/sender-key-state.d.ts +2 -2
  38. package/lib/Signal/Group/sender-key-state.js +2 -2
  39. package/lib/Signal/libsignal.d.ts +3 -3
  40. package/lib/Signal/libsignal.js +6 -6
  41. package/lib/Signal/lid-mapping.d.ts +2 -2
  42. package/lib/Signal/lid-mapping.js +4 -4
  43. package/lib/Signal/lid-mapping.js.map +1 -1
  44. package/lib/Socket/Client/index.d.ts +2 -2
  45. package/lib/Socket/Client/index.js +2 -2
  46. package/lib/Socket/Client/types.d.ts +1 -1
  47. package/lib/Socket/Client/websocket.d.ts +1 -1
  48. package/lib/Socket/Client/websocket.js +2 -2
  49. package/lib/Socket/business.d.ts +347 -65
  50. package/lib/Socket/business.d.ts.map +1 -1
  51. package/lib/Socket/business.js +5 -5
  52. package/lib/Socket/chats.d.ts +129 -16
  53. package/lib/Socket/chats.d.ts.map +1 -1
  54. package/lib/Socket/chats.js +293 -18
  55. package/lib/Socket/chats.js.map +1 -1
  56. package/lib/Socket/communities.d.ts +332 -50
  57. package/lib/Socket/communities.d.ts.map +1 -1
  58. package/lib/Socket/communities.js +5 -5
  59. package/lib/Socket/groups.d.ts +133 -27
  60. package/lib/Socket/groups.d.ts.map +1 -1
  61. package/lib/Socket/groups.js +4 -4
  62. package/lib/Socket/index.d.ts +366 -84
  63. package/lib/Socket/index.d.ts.map +1 -1
  64. package/lib/Socket/index.js +8 -5
  65. package/lib/Socket/index.js.map +1 -1
  66. package/lib/Socket/messages-recv.d.ts +324 -41
  67. package/lib/Socket/messages-recv.d.ts.map +1 -1
  68. package/lib/Socket/messages-recv.js +81 -30
  69. package/lib/Socket/messages-recv.js.map +1 -1
  70. package/lib/Socket/messages-send.d.ts +340 -44
  71. package/lib/Socket/messages-send.d.ts.map +1 -1
  72. package/lib/Socket/messages-send.js +171 -35
  73. package/lib/Socket/messages-send.js.map +1 -1
  74. package/lib/Socket/mex.d.ts +1 -1
  75. package/lib/Socket/mex.js +1 -1
  76. package/lib/Socket/newsletter.d.ts +324 -39
  77. package/lib/Socket/newsletter.d.ts.map +1 -1
  78. package/lib/Socket/newsletter.js +345 -5
  79. package/lib/Socket/newsletter.js.map +1 -1
  80. package/lib/Socket/socket.d.ts +24 -11
  81. package/lib/Socket/socket.d.ts.map +1 -1
  82. package/lib/Socket/socket.js +89 -36
  83. package/lib/Socket/socket.js.map +1 -1
  84. package/lib/Store/index.d.ts +4 -0
  85. package/lib/Store/index.js +4 -0
  86. package/lib/Store/make-in-memory-store.d.ts +63 -0
  87. package/lib/Store/make-in-memory-store.js +397 -0
  88. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  89. package/lib/Store/make-ordered-dictionary.js +79 -0
  90. package/lib/Store/object-repository.d.ts +11 -0
  91. package/lib/Store/object-repository.js +24 -0
  92. package/lib/Types/Auth.d.ts +2 -2
  93. package/lib/Types/Chat.d.ts +19 -6
  94. package/lib/Types/Chat.d.ts.map +1 -1
  95. package/lib/Types/Chat.js +7 -0
  96. package/lib/Types/Chat.js.map +1 -1
  97. package/lib/Types/Events.d.ts +9 -9
  98. package/lib/Types/GroupMetadata.d.ts +2 -2
  99. package/lib/Types/Message.d.ts +70 -6
  100. package/lib/Types/Message.d.ts.map +1 -1
  101. package/lib/Types/Message.js +11 -0
  102. package/lib/Types/Message.js.map +1 -1
  103. package/lib/Types/Mex.d.ts +68 -39
  104. package/lib/Types/Mex.d.ts.map +1 -1
  105. package/lib/Types/Mex.js +66 -0
  106. package/lib/Types/Mex.js.map +1 -1
  107. package/lib/Types/Product.d.ts +1 -1
  108. package/lib/Types/Signal.d.ts +1 -1
  109. package/lib/Types/Socket.d.ts +50 -5
  110. package/lib/Types/Socket.d.ts.map +1 -1
  111. package/lib/Types/Socket.js +1 -1
  112. package/lib/Types/State.d.ts +1 -1
  113. package/lib/Types/USync.d.ts +2 -2
  114. package/lib/Types/USync.js +1 -1
  115. package/lib/Types/index.d.ts +14 -14
  116. package/lib/Types/index.js +12 -12
  117. package/lib/Utils/audio-sticker.d.ts +14 -0
  118. package/lib/Utils/audio-sticker.js +172 -0
  119. package/lib/Utils/auth-store.d.ts +30 -0
  120. package/lib/Utils/auth-store.js +77 -0
  121. package/lib/Utils/auth-utils.d.ts +2 -2
  122. package/lib/Utils/auth-utils.js +4 -4
  123. package/lib/Utils/browser-utils.d.ts +1 -1
  124. package/lib/Utils/business.d.ts +2 -2
  125. package/lib/Utils/business.js +3 -3
  126. package/lib/Utils/chat-theme.d.ts +34 -0
  127. package/lib/Utils/chat-theme.js +336 -0
  128. package/lib/Utils/chat-utils.d.ts +3 -3
  129. package/lib/Utils/chat-utils.js +9 -9
  130. package/lib/Utils/chat-utils.js.map +1 -1
  131. package/lib/Utils/companion-reg-client-utils.d.ts +3 -3
  132. package/lib/Utils/companion-reg-client-utils.js +1 -1
  133. package/lib/Utils/crypto.d.ts +1 -1
  134. package/lib/Utils/crypto.js +1 -1
  135. package/lib/Utils/decode-wa-message.d.ts +18 -4
  136. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  137. package/lib/Utils/decode-wa-message.js +57 -2
  138. package/lib/Utils/decode-wa-message.js.map +1 -1
  139. package/lib/Utils/event-buffer.d.ts +4 -3
  140. package/lib/Utils/event-buffer.d.ts.map +1 -1
  141. package/lib/Utils/event-buffer.js +7 -8
  142. package/lib/Utils/event-buffer.js.map +1 -1
  143. package/lib/Utils/generics.d.ts +5 -4
  144. package/lib/Utils/generics.d.ts.map +1 -1
  145. package/lib/Utils/generics.js +13 -22
  146. package/lib/Utils/generics.js.map +1 -1
  147. package/lib/Utils/group-metadata-cache.d.ts +4 -0
  148. package/lib/Utils/group-metadata-cache.js +25 -0
  149. package/lib/Utils/history.d.ts +1 -1
  150. package/lib/Utils/history.js +6 -6
  151. package/lib/Utils/history.js.map +1 -1
  152. package/lib/Utils/html-app.d.ts +19 -0
  153. package/lib/Utils/html-app.js +96 -0
  154. package/lib/Utils/html-multiplayer.d.ts +10 -0
  155. package/lib/Utils/html-multiplayer.js +94 -0
  156. package/lib/Utils/identity-change-handler.d.ts +2 -2
  157. package/lib/Utils/identity-change-handler.js +2 -2
  158. package/lib/Utils/index.d.ts +46 -21
  159. package/lib/Utils/index.d.ts.map +1 -1
  160. package/lib/Utils/index.js +48 -21
  161. package/lib/Utils/index.js.map +1 -1
  162. package/lib/Utils/link-preview-metadata.d.ts +47 -0
  163. package/lib/Utils/link-preview-metadata.js +88 -0
  164. package/lib/Utils/link-preview.d.ts +2 -2
  165. package/lib/Utils/link-preview.js +2 -2
  166. package/lib/Utils/message-retry-manager.d.ts +1 -1
  167. package/lib/Utils/messages-media.d.ts +35 -6
  168. package/lib/Utils/messages-media.d.ts.map +1 -1
  169. package/lib/Utils/messages-media.js +69 -22
  170. package/lib/Utils/messages-media.js.map +1 -1
  171. package/lib/Utils/messages.d.ts +45 -5
  172. package/lib/Utils/messages.d.ts.map +1 -1
  173. package/lib/Utils/messages.js +123 -32
  174. package/lib/Utils/messages.js.map +1 -1
  175. package/lib/Utils/modern-messages.d.ts +150 -0
  176. package/lib/Utils/modern-messages.js +496 -0
  177. package/lib/Utils/native-flow.d.ts +11 -0
  178. package/lib/Utils/native-flow.js +116 -0
  179. package/lib/Utils/newsletter-status.d.ts +158 -0
  180. package/lib/Utils/newsletter-status.js +651 -0
  181. package/lib/Utils/noise-handler.d.ts +3 -3
  182. package/lib/Utils/noise-handler.js +3 -3
  183. package/lib/Utils/offline-node-processor.d.ts +1 -1
  184. package/lib/Utils/optional-media.d.ts +3 -0
  185. package/lib/Utils/optional-media.js +46 -0
  186. package/lib/Utils/payment-messages.d.ts +38 -0
  187. package/lib/Utils/payment-messages.js +160 -0
  188. package/lib/Utils/pre-key-manager.d.ts +2 -2
  189. package/lib/Utils/process-message.d.ts +13 -2
  190. package/lib/Utils/process-message.d.ts.map +1 -1
  191. package/lib/Utils/process-message.js +87 -7
  192. package/lib/Utils/process-message.js.map +1 -1
  193. package/lib/Utils/reporting-utils.d.ts +2 -2
  194. package/lib/Utils/reporting-utils.js +1 -1
  195. package/lib/Utils/scheduled-message.d.ts +51 -0
  196. package/lib/Utils/scheduled-message.js +113 -0
  197. package/lib/Utils/sender-key-memory.d.ts +19 -0
  198. package/lib/Utils/sender-key-memory.js +51 -0
  199. package/lib/Utils/signal.d.ts +4 -4
  200. package/lib/Utils/signal.js +4 -4
  201. package/lib/Utils/stanza-ack.d.ts +1 -1
  202. package/lib/Utils/status-stickers.d.ts +127 -0
  203. package/lib/Utils/status-stickers.js +261 -0
  204. package/lib/Utils/sync-action-utils.d.ts +2 -2
  205. package/lib/Utils/sync-action-utils.js +1 -1
  206. package/lib/Utils/tc-token-utils.d.ts +2 -2
  207. package/lib/Utils/tc-token-utils.js +1 -1
  208. package/lib/Utils/ttl-cache.d.ts +29 -0
  209. package/lib/Utils/ttl-cache.js +121 -0
  210. package/lib/Utils/use-mongo-auth-state.d.ts +22 -0
  211. package/lib/Utils/use-mongo-auth-state.js +68 -0
  212. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -1
  213. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -1
  214. package/lib/Utils/use-multi-file-auth-state.js +28 -15
  215. package/lib/Utils/use-multi-file-auth-state.js.map +1 -1
  216. package/lib/Utils/use-mysql-auth-state.d.ts +20 -0
  217. package/lib/Utils/use-mysql-auth-state.js +80 -0
  218. package/lib/Utils/use-nekodb-auth.d.ts +19 -0
  219. package/lib/Utils/use-nekodb-auth.js +111 -0
  220. package/lib/Utils/use-postgres-auth-state.d.ts +20 -0
  221. package/lib/Utils/use-postgres-auth-state.js +80 -0
  222. package/lib/Utils/use-redis-auth-state.d.ts +20 -0
  223. package/lib/Utils/use-redis-auth-state.js +90 -0
  224. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  225. package/lib/Utils/use-single-file-auth-state.js +109 -0
  226. package/lib/Utils/use-sqlite-auth-state.d.ts +13 -0
  227. package/lib/Utils/use-sqlite-auth-state.js +121 -0
  228. package/lib/Utils/username.d.ts +12 -0
  229. package/lib/Utils/username.js +59 -0
  230. package/lib/Utils/validate-connection.d.ts +2 -2
  231. package/lib/Utils/validate-connection.js +5 -5
  232. package/lib/Utils/voice-recognition.d.ts +53 -0
  233. package/lib/Utils/voice-recognition.js +219 -0
  234. package/lib/VoIP/audio-feeder.d.ts +24 -0
  235. package/lib/VoIP/audio-feeder.js +276 -0
  236. package/lib/VoIP/index.d.ts +93 -0
  237. package/lib/VoIP/index.js +998 -0
  238. package/lib/VoIP/relay-transport.d.ts +5 -0
  239. package/lib/VoIP/relay-transport.js +824 -0
  240. package/lib/VoIP/signaling.d.ts +11 -0
  241. package/lib/VoIP/signaling.js +1099 -0
  242. package/lib/VoIP/types.d.ts +2 -0
  243. package/lib/VoIP/types.js +12 -0
  244. package/lib/VoIP/video-feeder.d.ts +24 -0
  245. package/lib/VoIP/video-feeder.js +276 -0
  246. package/lib/VoIP/wasm-engine.d.ts +26 -0
  247. package/lib/VoIP/wasm-engine.js +1318 -0
  248. package/lib/VoIP/worker-bootstrap.js +1022 -0
  249. package/lib/WABinary/decode.d.ts +1 -1
  250. package/lib/WABinary/decode.js +2 -2
  251. package/lib/WABinary/encode.d.ts +1 -1
  252. package/lib/WABinary/encode.js +2 -2
  253. package/lib/WABinary/generic-utils.d.ts +3 -1
  254. package/lib/WABinary/generic-utils.d.ts.map +1 -1
  255. package/lib/WABinary/generic-utils.js +3 -1
  256. package/lib/WABinary/generic-utils.js.map +1 -1
  257. package/lib/WABinary/index.d.ts +5 -5
  258. package/lib/WABinary/index.js +5 -5
  259. package/lib/WABinary/jid-utils.d.ts +2 -0
  260. package/lib/WABinary/jid-utils.d.ts.map +1 -1
  261. package/lib/WABinary/jid-utils.js +3 -1
  262. package/lib/WABinary/jid-utils.js.map +1 -1
  263. package/lib/WABinary/types.d.ts +1 -1
  264. package/lib/WABinary/types.js +1 -1
  265. package/lib/WAM/BinaryInfo.d.ts +1 -1
  266. package/lib/WAM/encode.d.ts +1 -1
  267. package/lib/WAM/encode.js +2 -2
  268. package/lib/WAM/index.d.ts +3 -3
  269. package/lib/WAM/index.js +3 -3
  270. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +3 -3
  271. package/lib/WAUSync/Protocols/USyncContactProtocol.js +2 -2
  272. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -2
  273. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +1 -1
  274. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -2
  275. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  276. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -2
  277. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +1 -1
  278. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +3 -3
  279. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +2 -2
  280. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +3 -3
  281. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +2 -2
  282. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +3 -3
  283. package/lib/WAUSync/Protocols/index.d.ts +5 -5
  284. package/lib/WAUSync/Protocols/index.js +5 -5
  285. package/lib/WAUSync/USyncQuery.d.ts +3 -3
  286. package/lib/WAUSync/USyncQuery.js +5 -5
  287. package/lib/WAUSync/index.d.ts +3 -3
  288. package/lib/WAUSync/index.js +3 -3
  289. package/lib/extensions/awang-MessageBuilder.js +1 -1
  290. package/lib/index.d.ts +14 -10
  291. package/lib/index.d.ts.map +1 -1
  292. package/lib/index.js +15 -11
  293. package/lib/index.js.map +1 -1
  294. package/package.json +78 -31
  295. package/MIGRASI-QIRO-BAILEYS-RC25.md +0 -102
  296. package/QIRO-BAILEYS-RC25.md +0 -168
  297. package/THIRD_PARTY_NOTICES.md +0 -49
  298. /package/{engine-requirements.js → config/engine-requirements.js} +0 -0
@@ -0,0 +1,998 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { createHmac, randomBytes } from 'node:crypto';
3
+ import { WasmEngine } from './wasm-engine.js';
4
+ import { RelayRtcTransport } from './relay-transport.js';
5
+ import { SignalingBridge } from './signaling.js';
6
+ import { AudioFeeder } from './audio-feeder.js';
7
+ import { VideoFeeder, VIDEO_FORMAT_I420 } from './video-feeder.js';
8
+ import { CallState } from './types.js';
9
+ export { CallState };
10
+
11
+ const SHA256_LEN = 32;
12
+
13
+
14
+ const toBareJid = jid => {
15
+ if (!jid) return jid;
16
+ const value = String(jid);
17
+ const at = value.indexOf("@");
18
+ if (at < 0) return value;
19
+ const user = value.slice(0, at).split(":")[0];
20
+ return `${user}@${value.slice(at + 1)}`;
21
+ };
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
+
31
+ for (let i = 1; i <= blocks; i += 1) {
32
+ prev = createHmac("sha256", prk)
33
+ .update(prev)
34
+ .update(info)
35
+ .update(Buffer.from([i]))
36
+ .digest();
37
+ prev.copy(okm, (i - 1) * SHA256_LEN);
38
+ }
39
+
40
+ return new Uint8Array(okm.buffer, okm.byteOffset, length);
41
+ };
42
+
43
+ const computeHmacSha256 = (data, key) => {
44
+ const result = createHmac("sha256", Buffer.from(key)).update(data).digest();
45
+ return new Uint8Array(result.buffer, result.byteOffset, result.byteLength);
46
+ };
47
+
48
+ const isCallReceiptNode = node => {
49
+ if (node?.tag !== "receipt") return false;
50
+ const child = Array.isArray(node.content) ? node.content[0] : null;
51
+ return !!(child?.attrs?.["call-id"] || child?.attrs?.call_id);
52
+ };
53
+
54
+ export class ActiveCall extends EventEmitter {
55
+ constructor(callId, engine, durationMs) {
56
+ super();
57
+ this.callId = callId;
58
+ this.engine = engine;
59
+ this._state = CallState.Idle;
60
+ this._endResolver = undefined;
61
+ this._endPromise = undefined;
62
+ this._endTimer = null;
63
+ this._ended = false;
64
+ this._audioSource = "silence";
65
+
66
+ this.end = () => {
67
+ if (this._ended) return;
68
+ try { this.engine.endCall(0, true); } catch {}
69
+ this._forceEnd("local_end");
70
+ };
71
+
72
+ this.mute = muted => {
73
+ try { this.engine.setMute(muted); } catch {}
74
+ };
75
+
76
+ this.waitForEnd = () => this._endPromise;
77
+
78
+ this._playlist = [];
79
+ this._feeder = null;
80
+ this._idleTimer = null;
81
+ this._endWhenQueueEmpty = true;
82
+ this._idleGraceMs = 0;
83
+
84
+ this._attachFeeder = feeder => {
85
+ this._feeder = feeder;
86
+ };
87
+
88
+ this.play = source => {
89
+ this._clearIdleTimer();
90
+ this._playlist = [];
91
+ if (this._feeder) {
92
+ const hadCurrent = !!this._feeder.currentTrack;
93
+ this._feeder.clearPlaylist();
94
+ this._feeder.enqueue(source);
95
+ if (hadCurrent) {
96
+ this._feeder.skip();
97
+ }
98
+ return true;
99
+ }
100
+ this._playlist.push(source);
101
+ return false;
102
+ };
103
+
104
+ this.enqueue = source => {
105
+ this._clearIdleTimer();
106
+ if (this._feeder) {
107
+ return this._feeder.enqueue(source);
108
+ }
109
+ const tracks = Array.isArray(source) ? source : [source];
110
+ for (const track of tracks) {
111
+ if (track) {
112
+ this._playlist.push(track);
113
+ }
114
+ }
115
+ return this._playlist.length;
116
+ };
117
+
118
+ this.skip = () => this._feeder?.skip() ?? false;
119
+
120
+ this.queued = () => this._feeder?.playlistLength ?? this._playlist.length;
121
+
122
+ this.nowPlaying = () => this._feeder?.currentTrack ?? null;
123
+
124
+ this._video = false;
125
+ this._videoSource = "black";
126
+ this._videoPlaylist = [];
127
+ this._videoFeeder = null;
128
+
129
+ this._attachVideoFeeder = feeder => {
130
+ this._videoFeeder = feeder;
131
+ };
132
+
133
+ this.playVideo = source => {
134
+ this._videoPlaylist = [];
135
+ if (this._videoFeeder) {
136
+ const hadCurrent = !!this._videoFeeder.currentTrack;
137
+ this._videoFeeder.clearPlaylist();
138
+ this._videoFeeder.enqueue(source);
139
+ if (hadCurrent) {
140
+ this._videoFeeder.skip();
141
+ }
142
+ return true;
143
+ }
144
+ this._videoPlaylist.push(source);
145
+ return false;
146
+ };
147
+
148
+ this.enqueueVideo = source => {
149
+ if (this._videoFeeder) {
150
+ return this._videoFeeder.enqueue(source);
151
+ }
152
+ const tracks = Array.isArray(source) ? source : [source];
153
+ for (const track of tracks) {
154
+ if (track) {
155
+ this._videoPlaylist.push(track);
156
+ }
157
+ }
158
+ return this._videoPlaylist.length;
159
+ };
160
+
161
+ this.skipVideo = () => this._videoFeeder?.skip() ?? false;
162
+
163
+ this.queuedVideo = () => this._videoFeeder?.playlistLength ?? this._videoPlaylist.length;
164
+
165
+ this.nowPlayingVideo = () => this._videoFeeder?.currentTrack ?? null;
166
+
167
+ this.isVideo = () => this._video;
168
+
169
+ this._screenShare = false;
170
+
171
+ this.startScreenShare = () => {
172
+ if (!this._video) {
173
+ throw new Error("screen share needs a video call: pass video: true, or screenShare: true which implies it");
174
+ }
175
+ this._screenShare = true;
176
+ try {
177
+ return this.engine.startScreenShare();
178
+ }
179
+ catch {
180
+ return undefined;
181
+ }
182
+ };
183
+
184
+ this.stopScreenShare = () => {
185
+ this._screenShare = false;
186
+ try {
187
+ return this.engine.stopScreenShare();
188
+ }
189
+ catch {
190
+ return undefined;
191
+ }
192
+ };
193
+
194
+ this.isScreenShare = () => this._screenShare;
195
+
196
+ this._onVideoTrackStart = track => {
197
+ this.emit("videotrack", track);
198
+ };
199
+
200
+ this._onVideoTrackEnd = track => {
201
+ this.emit("videotrackend", track);
202
+ };
203
+
204
+ this._clearIdleTimer = () => {
205
+ if (this._idleTimer) {
206
+ clearTimeout(this._idleTimer);
207
+ this._idleTimer = null;
208
+ }
209
+ };
210
+
211
+ this._onTrackStart = track => {
212
+ this._clearIdleTimer();
213
+ this.emit("track", track);
214
+ };
215
+
216
+ this._onTrackEnd = track => {
217
+ this.emit("trackend", track);
218
+ };
219
+
220
+ this._onPlaylistIdle = () => {
221
+ this.emit("idle");
222
+ if (!this._endWhenQueueEmpty) {
223
+ return;
224
+ }
225
+ this._clearIdleTimer();
226
+ this._idleTimer = setTimeout(() => {
227
+ this._idleTimer = null;
228
+ if (this._feeder?.playlistLength || this._feeder?.currentTrack) {
229
+ return;
230
+ }
231
+ this.end();
232
+ }, this._idleGraceMs);
233
+ };
234
+
235
+ this._updateState = state => {
236
+ this._state = state;
237
+ if (state === CallState.PreacceptReceived) {
238
+ this.emit("ringing");
239
+ } else if (state === CallState.Active) {
240
+ this.emit("connected");
241
+ if (this._screenShare) {
242
+ try { this.engine.startScreenShare(); } catch {}
243
+ }
244
+ } else if (state === CallState.Idle || state === CallState.ActiveElsewhere || state === CallState.Ending) {
245
+ this._forceEnd("ended");
246
+ }
247
+ };
248
+
249
+ this._emitAudio = pcm => {
250
+ this.emit("audio", pcm);
251
+ };
252
+
253
+ this._forceEnd = reason => {
254
+ if (this._ended) return;
255
+ this._ended = true;
256
+ this._clearIdleTimer();
257
+ if (this._endTimer) {
258
+ clearTimeout(this._endTimer);
259
+ this._endTimer = null;
260
+ }
261
+ this.emit("ended", reason);
262
+ this._endResolver(reason);
263
+ };
264
+
265
+ this._endPromise = new Promise(resolve => {
266
+ this._endResolver = resolve;
267
+ });
268
+
269
+ if (durationMs > 0) {
270
+ this._endTimer = setTimeout(() => this.end(), durationMs);
271
+ }
272
+ }
273
+
274
+ get state() {
275
+ return this._state;
276
+ }
277
+ }
278
+
279
+
280
+ export class VoipClient {
281
+ constructor(config = {}) {
282
+ this._config = config;
283
+ this._log = typeof config.logger === 'function'
284
+ ? config.logger
285
+ : config.debug ? (...args) => console.log(...args) : () => {};
286
+ this._engine = null;
287
+ this._relay = null;
288
+ this._signaling = null;
289
+ this._sock = config.socket || config.sock || config.conn || null;
290
+ this._activeCall = null;
291
+ this._externalSocket = !!this._sock;
292
+ this._capturePtr = 0;
293
+ this._captureChunkBytes = 0;
294
+ this._captureSampleRate = 16000;
295
+ this._captureChannels = 1;
296
+ this._captureFramesPerChunk = 320;
297
+ this._feeder = null;
298
+ this._videoFeeder = null;
299
+ this._wsCallHandler = null;
300
+ this._wsReceiptHandler = null;
301
+ this._captureStartRequested = false;
302
+ this._audioStartTimer = null;
303
+ this._videoFeederMode = null;
304
+
305
+ this._cleanupActiveCall = reason => {
306
+ const hadActiveCall = !!this._activeCall;
307
+ try { this._activeCall?._forceEnd(reason); } catch {}
308
+ if (hadActiveCall) {
309
+ try { this._engine?.endCall?.(0, true); } catch {}
310
+ }
311
+ try { this._feeder?.stop(); } catch {}
312
+ this._feeder = null;
313
+ try { this._videoFeeder?.stop(); } catch {}
314
+ this._videoFeeder = null;
315
+ this._videoFeederMode = null;
316
+ try { this._engine?.releaseVideoFrameBuffer?.(); } catch {}
317
+ if (this._audioStartTimer) {
318
+ clearTimeout(this._audioStartTimer);
319
+ this._audioStartTimer = null;
320
+ }
321
+ this._captureStartRequested = false;
322
+ this._activeCall = null;
323
+ };
324
+
325
+ this.connect = async () => {
326
+ if (!this._sock) {
327
+ throw new Error('VoipClient needs the socket you are already logged in with: new VoipClient({ socket: sock }). It never opens a session of its own, so there is no second pairing or QR scan.');
328
+ }
329
+ if (!this._sock.ws) {
330
+ throw new Error('the socket has no websocket yet; call connect() once connection.update reports "open"');
331
+ }
332
+ await this._initVoipStack();
333
+ };
334
+
335
+ this.attach = async socket => {
336
+ if (!socket) {
337
+ throw new Error('attach needs the reconnected socket');
338
+ }
339
+ this._detachSocketHandlers();
340
+ this._sock = socket;
341
+ this._externalSocket = true;
342
+ this._signaling?.setSocket?.(socket);
343
+ this._bindSocketHandlers();
344
+ };
345
+
346
+ this.call = async (phoneNumber, opts = {}) => {
347
+ if (!this._engine || !this._signaling) {
348
+ throw new Error("Not connected. Call connect() first.");
349
+ }
350
+
351
+ this._cleanupActiveCall("replaced");
352
+
353
+ const targetNumber = phoneNumber.replace(/\D/g, "");
354
+ if (!targetNumber) {
355
+ throw new Error("Nomor target tidak valid.");
356
+ }
357
+
358
+ const targetPnJid = `${targetNumber}@s.whatsapp.net`;
359
+ const durationMs = opts.durationMs ?? 120000;
360
+ const audioSource = opts.audioSource ?? "silence";
361
+
362
+ const peerLid = await this._signaling.resolveLid(targetPnJid);
363
+ if (!peerLid) {
364
+ throw new Error(`Tidak bisa resolve LID untuk ${targetPnJid}. Pastikan target valid dan sudah tersimpan mapping LID/PN atau USync LID bisa diakses.`);
365
+ }
366
+
367
+ const peerJid = peerLid;
368
+ const peerPn = targetPnJid;
369
+ const isLidCall = true;
370
+
371
+ for (const jid of [targetPnJid, peerLid]) {
372
+ try { await this._sock.presenceSubscribe(jid); } catch {}
373
+ }
374
+ await new Promise(resolve => setTimeout(resolve, 150));
375
+
376
+ let peerDeviceJids = [];
377
+ try {
378
+ peerDeviceJids = await this._signaling.discoverPeerDevices(peerLid);
379
+ } catch (err) {
380
+ this._log("[RTC DISCOVER DEVICES ERROR]", err?.message || err);
381
+ }
382
+
383
+ const deviceList = peerDeviceJids.length ? peerDeviceJids : [toBareJid(peerLid)];
384
+
385
+ try {
386
+ await this._signaling.ensureSessionsForPeers(deviceList);
387
+ } catch (err) {
388
+ this._log("[RTC ENSURE SESSIONS WARNING]", err?.message || err);
389
+ }
390
+
391
+ await new Promise(resolve => setTimeout(resolve, 100));
392
+
393
+ let tcToken = null;
394
+ try {
395
+ this._signaling.issueTcToken(peerLid).catch(err => {
396
+ this._log("[RTC ISSUE TC TOKEN ASYNC ERROR]", err?.message || err);
397
+ });
398
+
399
+ tcToken = await Promise.race([
400
+ this._signaling.ensureTcToken(peerLid, targetPnJid).catch(err => {
401
+ this._log("[RTC ENSURE TC TOKEN ERROR]", err?.message || err);
402
+ return null;
403
+ }),
404
+ new Promise(resolve => setTimeout(() => resolve(null), 1500))
405
+ ]);
406
+ } catch (err) {
407
+ this._log("[RTC TC TOKEN FAST PATH ERROR]", err?.message || err);
408
+ }
409
+
410
+ if (!tcToken || !tcToken.length) {
411
+ this._log("[RTC TC TOKEN WARNING] TC token kosong, lanjut startCall dengan token kosong.");
412
+ tcToken = undefined;
413
+ }
414
+
415
+ const callId = ("00" + randomBytes(16).toString("hex").slice(2)).toUpperCase();
416
+ const call = new ActiveCall(callId, this._engine, durationMs);
417
+
418
+ call._audioSource = audioSource;
419
+ call._audioStartDelayMs = Number(opts.audioStartDelayMs ?? opts.audioDelayMs ?? 1800) || 0;
420
+ call._playlist = Array.isArray(opts.playlist) ? opts.playlist.filter(Boolean) : [];
421
+ call._endWhenQueueEmpty = opts.endWhenQueueEmpty ?? true;
422
+ call._idleGraceMs = Number(opts.idleGraceMs ?? 0) || 0;
423
+ call._screenShare = !!opts.screenShare;
424
+ call._video = !!(opts.video ?? opts.isVideo) || call._screenShare;
425
+ call._videoSource = opts.videoSource ?? "black";
426
+ call._videoPlaylist = Array.isArray(opts.videoPlaylist) ? opts.videoPlaylist.filter(Boolean) : [];
427
+ this._activeCall = call;
428
+
429
+ call.once("ended", () => {
430
+ if (this._activeCall === call) this._activeCall = null;
431
+ });
432
+
433
+ call.once("error", () => {
434
+ if (this._activeCall === call) this._activeCall = null;
435
+ });
436
+
437
+ this._log("[RTC START CALL PARAMS]", {
438
+ peerJid,
439
+ peerPn,
440
+ peerList: deviceList,
441
+ callId,
442
+ isLidCall,
443
+ targetPnJid,
444
+ peerLid,
445
+ hasTcToken: !!tcToken,
446
+ tcTokenLength: tcToken?.length || 0
447
+ });
448
+
449
+ try {
450
+ const startResult = this._engine.startCall({
451
+ peerJid,
452
+ peerPn,
453
+ peerList: deviceList,
454
+ callId,
455
+ isVideo: call._video,
456
+ isLidCall,
457
+ isFromDialer: false,
458
+ extraData: tcToken
459
+ });
460
+ this._log("[RTC START CALL RESULT]", startResult);
461
+ } catch (err) {
462
+ if (this._activeCall === call) this._activeCall = null;
463
+ try { call._forceEnd("start_call_failed"); } catch {}
464
+ throw err;
465
+ }
466
+
467
+ return call;
468
+ };
469
+
470
+ this.callGroup = async (groupJid, opts = {}) => {
471
+ if (!this._engine || !this._signaling) {
472
+ throw new Error("Not connected. Call connect() first.");
473
+ }
474
+ if (typeof groupJid !== "string" || !groupJid.endsWith("@g.us")) {
475
+ throw new Error(`${JSON.stringify(groupJid)} is not a group jid`);
476
+ }
477
+
478
+ this._cleanupActiveCall("replaced");
479
+ const metadata = opts.metadata ?? await this._sock.groupMetadata(groupJid);
480
+ const selfPn = toBareJid(this._sock.authState?.creds?.me?.id ?? this._sock.user?.id ?? "");
481
+ const selfLid = toBareJid(this._sock.authState?.creds?.me?.lid ?? "");
482
+ const isSelf = member => [member.id, member.pn, member.lid].some(jid => jid && (jid === selfPn || jid === selfLid));
483
+ const members = (metadata?.participants ?? [])
484
+ .map(participant => {
485
+ const id = toBareJid(participant.id ?? participant.jid ?? "");
486
+ const pn = toBareJid(participant.phoneNumber ?? (id && !id.endsWith("@lid") ? id : ""));
487
+ const lid = toBareJid(participant.lid ?? (id.endsWith("@lid") ? id : ""));
488
+ return { id, pn, lid };
489
+ })
490
+ .filter(member => (member.pn || member.lid) && !isSelf(member));
491
+ const wanted = Array.isArray(opts.participants) && opts.participants.length
492
+ ? opts.participants.map(toBareJid).filter(Boolean).map(jid => {
493
+ const known = members.find(member => member.id === jid || member.pn === jid || member.lid === jid);
494
+ return known ?? {
495
+ id: jid,
496
+ pn: jid.endsWith("@lid") ? "" : jid,
497
+ lid: jid.endsWith("@lid") ? jid : ""
498
+ };
499
+ }).filter(member => !isSelf(member))
500
+ : members;
501
+
502
+ if (!wanted.length) {
503
+ throw new Error(`no one to call in ${groupJid}`);
504
+ }
505
+
506
+ const pnUserJids = [];
507
+ const lidUserJids = [];
508
+ const deviceJidsCsv = [];
509
+ const seenMembers = new Set();
510
+
511
+ for (const member of wanted) {
512
+ let lid = member.lid;
513
+ let pn = member.pn;
514
+ if (!lid && pn) {
515
+ lid = await this._signaling.resolveLid(pn).catch(() => null);
516
+ }
517
+ if (!pn && lid) {
518
+ try {
519
+ pn = toBareJid(await this._sock.signalRepository?.lidMapping?.getPNForLID?.(lid) ?? "");
520
+ } catch {}
521
+ }
522
+ const memberKey = lid || pn;
523
+ if (!memberKey || seenMembers.has(memberKey)) continue;
524
+ seenMembers.add(memberKey);
525
+ if (pn) {
526
+ pnUserJids.push(pn);
527
+ }
528
+ if (lid) {
529
+ lidUserJids.push(lid);
530
+ let devices = [];
531
+ try {
532
+ devices = await this._signaling.discoverPeerDevices(lid);
533
+ } catch (err) {
534
+ this._log("[RTC GROUP DISCOVER DEVICES ERROR]", member.id, err?.message || err);
535
+ }
536
+ deviceJidsCsv.push((devices.length ? devices : [lid]).join(","));
537
+ }
538
+ }
539
+
540
+ if (!lidUserJids.length) {
541
+ throw new Error(`could not resolve a LID for anyone in ${groupJid}`);
542
+ }
543
+
544
+ const flatDevices = deviceJidsCsv.join(",").split(",").filter(Boolean);
545
+ try {
546
+ await this._signaling.ensureSessionsForPeers(flatDevices);
547
+ } catch (err) {
548
+ this._log("[RTC GROUP ENSURE SESSIONS WARNING]", err?.message || err);
549
+ }
550
+
551
+ const callId = ("00" + randomBytes(16).toString("hex").slice(2)).toUpperCase();
552
+ const call = new ActiveCall(callId, this._engine, opts.durationMs ?? 120000);
553
+
554
+ call._audioSource = opts.audioSource ?? "silence";
555
+ call._audioStartDelayMs = Number(opts.audioStartDelayMs ?? opts.audioDelayMs ?? 1800) || 0;
556
+ call._playlist = Array.isArray(opts.playlist) ? opts.playlist.filter(Boolean) : [];
557
+ call._endWhenQueueEmpty = opts.endWhenQueueEmpty ?? true;
558
+ call._idleGraceMs = Number(opts.idleGraceMs ?? 0) || 0;
559
+ call._screenShare = !!opts.screenShare;
560
+ call._video = !!(opts.video ?? opts.isVideo) || call._screenShare;
561
+ call._videoSource = opts.videoSource ?? "black";
562
+ call._videoPlaylist = Array.isArray(opts.videoPlaylist) ? opts.videoPlaylist.filter(Boolean) : [];
563
+ call.groupJid = groupJid;
564
+ this._activeCall = call;
565
+
566
+ call.once("ended", () => {
567
+ if (this._activeCall === call) this._activeCall = null;
568
+ });
569
+
570
+ this._log("[RTC START GROUP CALL PARAMS]", { groupJid, callId, pnUserJids, lidUserJids, deviceJidsCsv });
571
+
572
+ try {
573
+ const startResult = this._engine.startGroupCall({
574
+ pnUserJids,
575
+ lidUserJids,
576
+ deviceJidsCsv,
577
+ callId,
578
+ isVideo: call._video,
579
+ groupJid,
580
+ chatName: metadata?.subject ?? ""
581
+ });
582
+ this._log("[RTC START GROUP CALL RESULT]", startResult);
583
+ if (startResult !== 0) {
584
+ throw new Error(`startGroupCall failed with status ${startResult}`);
585
+ }
586
+ } catch (err) {
587
+ if (this._activeCall === call) this._activeCall = null;
588
+ try { call._forceEnd("start_group_call_failed"); } catch {}
589
+ throw err;
590
+ }
591
+
592
+ return call;
593
+ };
594
+
595
+ this.joinGroupCall = async (invite, opts = {}) => {
596
+ if (!this._engine || !this._signaling) {
597
+ throw new Error("Not connected. Call connect() first.");
598
+ }
599
+ const callId = invite?.callId ?? invite?.id;
600
+ const groupJid = invite?.groupJid ?? invite?.from;
601
+ const callCreatorJid = invite?.callCreatorJid ?? invite?.creator ?? invite?.from;
602
+ if (!callId || !callCreatorJid) {
603
+ throw new Error("joinGroupCall needs at least { callId, callCreatorJid } from the incoming offer");
604
+ }
605
+
606
+ this._cleanupActiveCall("replaced");
607
+ const call = new ActiveCall(callId, this._engine, opts.durationMs ?? 0);
608
+ call._audioSource = opts.audioSource ?? "silence";
609
+ call._audioStartDelayMs = Number(opts.audioStartDelayMs ?? opts.audioDelayMs ?? 1800) || 0;
610
+ call._playlist = Array.isArray(opts.playlist) ? opts.playlist.filter(Boolean) : [];
611
+ call._endWhenQueueEmpty = opts.endWhenQueueEmpty ?? true;
612
+ call._idleGraceMs = Number(opts.idleGraceMs ?? 0) || 0;
613
+ call._screenShare = !!opts.screenShare;
614
+ call._video = !!(opts.video ?? opts.isVideo) || call._screenShare;
615
+ call._videoSource = opts.videoSource ?? "black";
616
+ call._videoPlaylist = Array.isArray(opts.videoPlaylist) ? opts.videoPlaylist.filter(Boolean) : [];
617
+ call.groupJid = groupJid;
618
+ this._activeCall = call;
619
+
620
+ call.once("ended", () => {
621
+ if (this._activeCall === call) this._activeCall = null;
622
+ });
623
+
624
+ try {
625
+ const result = this._engine.joinOngoingCall({
626
+ callId,
627
+ callCreatorJid,
628
+ initialPeerJid: invite?.initialPeerJid ?? callCreatorJid,
629
+ pnUserJids: invite?.pnUserJids ?? [],
630
+ lidUserJids: invite?.lidUserJids ?? [],
631
+ deviceJidsCsv: invite?.deviceJidsCsv ?? [],
632
+ groupJid: groupJid ?? "",
633
+ isVideo: call._video,
634
+ joinAndAccept: opts.joinAndAccept ?? true,
635
+ chatName: invite?.chatName ?? ""
636
+ });
637
+ this._log("[RTC JOIN CALL RESULT]", result);
638
+ if (result !== 0) {
639
+ throw new Error(`joinOngoingCall failed with status ${result}`);
640
+ }
641
+ } catch (err) {
642
+ if (this._activeCall === call) this._activeCall = null;
643
+ try { call._forceEnd("join_call_failed"); } catch {}
644
+ throw err;
645
+ }
646
+
647
+ return call;
648
+ };
649
+
650
+ this.acceptCall = (isMicEnabled = true) => this._engine?.acceptCall(isMicEnabled, false);
651
+
652
+ this.disconnect = () => {
653
+ this._activeCall?._forceEnd("disconnect");
654
+ this._activeCall = null;
655
+ this._captureStartRequested = false;
656
+ try { this._feeder?.stop(); } catch {}
657
+ this._feeder = null;
658
+ try { this._videoFeeder?.stop(); } catch {}
659
+ this._videoFeeder = null;
660
+ this._videoFeederMode = null;
661
+ if (this._audioStartTimer) {
662
+ clearTimeout(this._audioStartTimer);
663
+ this._audioStartTimer = null;
664
+ }
665
+ try { this._signaling?.attachEngine?.(null); } catch {}
666
+ this._detachSocketHandlers();
667
+ this._relay?.closeAll();
668
+ this._engine?.destroy();
669
+ if (!this._externalSocket) {
670
+ this._sock?.end?.();
671
+ }
672
+ this._engine = null;
673
+ this._relay = null;
674
+ this._signaling = null;
675
+ if (!this._externalSocket) {
676
+ this._sock = null;
677
+ }
678
+ };
679
+
680
+ this.resetCallState = () => {
681
+ const hadActiveCall = !!this._activeCall;
682
+ this._cleanupActiveCall("reset");
683
+ if (!hadActiveCall) {
684
+ try { this._engine?.endCall?.(0, true); } catch {}
685
+ }
686
+ };
687
+
688
+ this._initVoipStack = async () => {
689
+ if (!this._sock) {
690
+ throw new Error("Socket Baileys belum tersedia.");
691
+ }
692
+
693
+ this._signaling = new SignalingBridge({
694
+ sock: this._sock,
695
+ logger: this._config.logger,
696
+ debug: this._config.debug
697
+ });
698
+ await this._signaling.init();
699
+
700
+ this._relay = new RelayRtcTransport({
701
+ onTransportMessage: (data, ip, port) => this._engine?.handleOnTransportMessage(data, ip, port),
702
+ onIceRtt: (rttMs, ip, port) => this._engine?.updateIceRtt(rttMs, ip, port)
703
+ });
704
+
705
+ this._engine = new WasmEngine({
706
+ callbacks: {
707
+ onSignalingXmpp: (peerJid, callId, xmlPayload) => {
708
+ this._log("[RTC WASM SIGNALING XMPP]", {
709
+ peerJid,
710
+ callId,
711
+ payloadLength: xmlPayload?.length || 0
712
+ });
713
+ return this._signaling.sendSignaling(peerJid, callId, xmlPayload);
714
+ },
715
+ onCallEvent: (eventType, eventData) => this._handleCallEvent(eventType, eventData),
716
+ sendDataToRelay: (data, ip, port) => this._relay.send(data, ip, port),
717
+ onAudioCaptureInit: config => this._handleAudioCaptureInit(config),
718
+ onAudioCaptureStart: () => this._handleAudioCaptureStart(),
719
+ onAudioCaptureStop: () => this._handleAudioCaptureStop(),
720
+ onAudioPlaybackData: audioData => this._activeCall?._emitAudio(audioData),
721
+ onVideoCaptureStart: config => this._handleVideoCaptureStart(config),
722
+ onVideoCaptureStop: () => this._handleVideoCaptureStop(),
723
+ onDesktopCaptureStart: config => this._handleDesktopCaptureStart(config),
724
+ onDesktopCaptureStop: () => this._handleDesktopCaptureStop(),
725
+ cryptoHkdf: computeHkdf,
726
+ hmacSha256: computeHmacSha256
727
+ }
728
+ });
729
+
730
+ await this._engine.initialize();
731
+ this._signaling.attachEngine(this._engine);
732
+
733
+ const selfPnJidRaw =
734
+ this._sock.authState?.creds?.me?.id ||
735
+ this._sock.authState?.creds?.me?.jid ||
736
+ this._sock.user?.id ||
737
+ this._sock.user?.jid;
738
+
739
+ const selfPnJid = toBareJid(selfPnJidRaw);
740
+ const selfLidJid =
741
+ this._sock.authState?.creds?.me?.lid ||
742
+ this._sock.authState?.creds?.me?.lidJid ||
743
+ "";
744
+
745
+ if (!selfPnJid) {
746
+ throw new Error("Tidak bisa membaca JID bot dari socket utama.");
747
+ }
748
+
749
+ this._log("[RTC SELF JID]", { selfPnJid, selfLidJid });
750
+
751
+ this._engine.initVoipStack(selfPnJid, selfPnJid, selfLidJid);
752
+ await this._engine.waitForVoipStackReady();
753
+
754
+ try { this._engine.updateNetworkMedium(2, 0); } catch {}
755
+
756
+ this._bindSocketHandlers();
757
+ };
758
+
759
+ this._detachSocketHandlers = () => {
760
+ const ws = this._sock?.ws;
761
+ if (ws?.off) {
762
+ try { if (this._wsCallHandler) ws.off("CB:call", this._wsCallHandler); } catch {}
763
+ try { if (this._wsReceiptHandler) ws.off("CB:receipt", this._wsReceiptHandler); } catch {}
764
+ }
765
+ this._wsCallHandler = null;
766
+ this._wsReceiptHandler = null;
767
+ };
768
+
769
+ this._bindSocketHandlers = () => {
770
+ if (!this._sock?.ws?.on) {
771
+ return;
772
+ }
773
+ this._detachSocketHandlers();
774
+
775
+ this._wsCallHandler = node => {
776
+ const signaling = this._signaling;
777
+ const engine = this._engine;
778
+ if (!signaling || !engine) return;
779
+ if (typeof engine.isInitialized === "function" && !engine.isInitialized()) return;
780
+ signaling.processIncomingCall(node, engine, this._activeCall?.callId ?? "");
781
+ };
782
+
783
+ this._wsReceiptHandler = node => {
784
+ if (!isCallReceiptNode(node)) return;
785
+ const signaling = this._signaling;
786
+ const engine = this._engine;
787
+ if (!signaling || !engine) return;
788
+ if (typeof engine.isInitialized === "function" && !engine.isInitialized()) return;
789
+ signaling.processIncomingReceipt(node, engine, this._activeCall?.callId ?? "");
790
+ };
791
+
792
+ this._sock.ws.on("CB:call", this._wsCallHandler);
793
+ this._sock.ws.on("CB:receipt", this._wsReceiptHandler);
794
+ };
795
+
796
+ this._handleCallEvent = (eventType, eventData) => {
797
+ this._log("[RTC CALL EVENT]", { eventType, hasData: !!eventData, data: eventData });
798
+
799
+ const call = this._activeCall;
800
+ let parsed;
801
+ if (eventData) {
802
+ try { parsed = JSON.parse(eventData); } catch {}
803
+ }
804
+ const info = parsed?.call_info ?? parsed?.callInfo ?? {};
805
+ const eventCallId = parsed?.call_id ?? parsed?.callId ?? info.call_id ?? info.callId;
806
+ if (call?.callId && eventCallId && String(eventCallId) !== call.callId) {
807
+ return;
808
+ }
809
+
810
+ if (eventType === 16 && parsed) {
811
+ const callState = Number(info.call_state ?? info.callState ?? 0);
812
+ this._log("[RTC CALL STATE]", callState);
813
+ call?._updateState(callState);
814
+ if (callState === CallState.Active && call) {
815
+ this._captureStartRequested = true;
816
+ setTimeout(() => {
817
+ if (this._activeCall !== call || call.state !== CallState.Active) return;
818
+ try { this._startAudioFeeder?.(); } catch (err) {
819
+ this._log("[RTC AUDIO START ON ACTIVE ERROR]", err?.message || err);
820
+ }
821
+ }, 300);
822
+ }
823
+ } else if (eventType === 156 && parsed) {
824
+ this._relay?.updateRelayList(parsed);
825
+ } else if (eventType === 10 || eventType === 11 || eventType === 38) {
826
+ call?._forceEnd("remote_end");
827
+ }
828
+ };
829
+
830
+ this._handleAudioCaptureInit = config => {
831
+ if (!this._engine) return;
832
+ this._captureSampleRate = config.sampleRate || 16000;
833
+ this._captureChannels = config.channels || 1;
834
+ this._captureFramesPerChunk = config.framesPerChunk || 320;
835
+ const chunkSamples = this._captureFramesPerChunk * this._captureChannels;
836
+ this._captureChunkBytes = chunkSamples * Float32Array.BYTES_PER_ELEMENT;
837
+ this._capturePtr = this._engine.malloc(this._captureChunkBytes);
838
+ if (this._captureStartRequested && this._activeCall?.state === CallState.Active) {
839
+ setTimeout(() => {
840
+ try { this._startAudioFeeder?.(); } catch {}
841
+ }, 100);
842
+ }
843
+ };
844
+
845
+ this._startAudioFeeder = () => {
846
+ this._captureStartRequested = true;
847
+
848
+ if (this._activeCall?.state !== CallState.Active) {
849
+ this._log("[RTC AUDIO] capture siap, tunggu call active sebelum audio start");
850
+ return;
851
+ }
852
+
853
+ if (!this._engine || !this._capturePtr) {
854
+ this._log("[RTC AUDIO] capturePtr belum siap, audio feeder batal start");
855
+ return;
856
+ }
857
+
858
+ if (this._feeder) return;
859
+
860
+ const audioDelayMs = Number(this._activeCall?._audioStartDelayMs ?? 0) || 0;
861
+ if (audioDelayMs > 0 && !this._audioStartTimer) {
862
+ const delayedCall = this._activeCall;
863
+ this._log("[RTC AUDIO] call active, audio ditunda:", audioDelayMs);
864
+ this._audioStartTimer = setTimeout(() => {
865
+ this._audioStartTimer = null;
866
+ if (this._activeCall === delayedCall && delayedCall?.state === CallState.Active) {
867
+ delayedCall._audioStartDelayMs = 0;
868
+ this._startAudioFeeder();
869
+ }
870
+ }, audioDelayMs);
871
+ return;
872
+ }
873
+
874
+ if (this._audioStartTimer) return;
875
+
876
+ const call = this._activeCall;
877
+ const playlist = call?._playlist?.length ? [...call._playlist] : [call?._audioSource ?? "silence"];
878
+
879
+ this._log("[RTC AUDIO] start feeder:", {
880
+ playlist,
881
+ sampleRate: this._captureSampleRate,
882
+ channels: this._captureChannels,
883
+ framesPerChunk: this._captureFramesPerChunk
884
+ });
885
+
886
+ this._feeder = new AudioFeeder(
887
+ this._captureSampleRate,
888
+ this._captureChannels,
889
+ this._captureFramesPerChunk,
890
+ chunk => {
891
+ if (this._engine && this._capturePtr && (!this._engine.isInitialized || this._engine.isInitialized())) {
892
+ this._engine.sendAudioData(chunk, this._capturePtr);
893
+ }
894
+ },
895
+ undefined,
896
+ {
897
+ onTrackStart: track => call?._onTrackStart(track),
898
+ onTrackEnd: track => call?._onTrackEnd(track),
899
+ onIdle: () => call?._onPlaylistIdle(),
900
+ ffmpegPath: this._config.ffmpegPath
901
+ }
902
+ );
903
+
904
+ call?._attachFeeder(this._feeder);
905
+ this._feeder.start(playlist);
906
+ };
907
+
908
+ this._startVideoFeeder = (config, useDesktopCapture) => {
909
+ const call = this._activeCall;
910
+ const label = useDesktopCapture ? "SCREEN" : "VIDEO";
911
+ const mode = useDesktopCapture ? "desktop" : "camera";
912
+ if (!call?._video) {
913
+ this._log(`[RTC ${label}] capture diminta tapi call ini bukan video, diabaikan`);
914
+ return;
915
+ }
916
+ if (this._videoFeeder) {
917
+ if (this._videoFeederMode === mode) {
918
+ return;
919
+ }
920
+ this._stopVideoFeeder(label);
921
+ }
922
+ this._videoFeederMode = mode;
923
+ const width = config?.width ?? 640;
924
+ const height = config?.height ?? 480;
925
+ const fps = config?.fps ?? 24;
926
+ const playlist = call._videoPlaylist?.length ? [...call._videoPlaylist] : [call._videoSource ?? "black"];
927
+
928
+ this._log(`[RTC ${label}] start feeder:`, { width, height, fps, playlist });
929
+
930
+ this._videoFeeder = new VideoFeeder(
931
+ width,
932
+ height,
933
+ fps,
934
+ (frame, w, h, rate) => {
935
+ if (this._engine && (!this._engine.isInitialized || this._engine.isInitialized())) {
936
+ this._engine.sendVideoFrame(frame, w, h, rate, VIDEO_FORMAT_I420, 1, useDesktopCapture);
937
+ }
938
+ },
939
+ undefined,
940
+ {
941
+ onTrackStart: track => call._onVideoTrackStart(track),
942
+ onTrackEnd: track => call._onVideoTrackEnd(track),
943
+ ffmpegPath: this._config.ffmpegPath
944
+ }
945
+ );
946
+
947
+ call._attachVideoFeeder(this._videoFeeder);
948
+ this._videoFeeder.start(playlist);
949
+ };
950
+
951
+ this._stopVideoFeeder = (label, expectedMode = null) => {
952
+ if (expectedMode && this._videoFeederMode !== expectedMode) {
953
+ this._log(`[RTC ${label}] stop capture lama diabaikan`);
954
+ return;
955
+ }
956
+ this._log(`[RTC ${label}] stop feeder`);
957
+ try { this._videoFeeder?.stop(); } catch {}
958
+ this._videoFeeder = null;
959
+ this._videoFeederMode = null;
960
+ try { this._engine?.releaseVideoFrameBuffer?.(); } catch {}
961
+ };
962
+
963
+ this._handleVideoCaptureStart = config => this._startVideoFeeder(config, false);
964
+ this._handleVideoCaptureStop = () => this._stopVideoFeeder("VIDEO", "camera");
965
+ this._handleDesktopCaptureStart = config => this._startVideoFeeder(config, true);
966
+ this._handleDesktopCaptureStop = () => this._stopVideoFeeder("SCREEN", "desktop");
967
+
968
+ this._handleAudioCaptureStart = () => {
969
+ this._captureStartRequested = true;
970
+ if (this._activeCall?.state === CallState.Active) {
971
+ this._startAudioFeeder();
972
+ } else {
973
+ this._log("[RTC AUDIO] startCaptureJS diterima sebelum active, audio ditahan dulu");
974
+ }
975
+ };
976
+
977
+ this._handleAudioCaptureStop = () => {
978
+ this._captureStartRequested = false;
979
+ this._feeder?.stop();
980
+ this._feeder = null;
981
+ try { this._videoFeeder?.stop(); } catch {}
982
+ this._videoFeeder = null;
983
+ if (this._engine && this._capturePtr) {
984
+ try { this._engine.free(this._capturePtr); } catch {}
985
+ this._capturePtr = 0;
986
+ }
987
+ };
988
+ }
989
+ }
990
+
991
+ export { VideoFeeder, VIDEO_FORMAT_I420 } from './video-feeder.js';
992
+ export { AudioFeeder } from './audio-feeder.js';
993
+ export const makeVoipClient = async (socket, config = {}) => {
994
+ const client = new VoipClient({ ...config, socket });
995
+ await client.connect();
996
+ return client;
997
+ };
998
+ export default VoipClient;