@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,1318 @@
1
+ import * as vm from 'node:vm';
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { tmpdir } from 'node:os';
5
+ import { Worker } from 'node:worker_threads';
6
+ import { randomFillSync } from 'node:crypto';
7
+ import { fileURLToPath } from 'node:url';
8
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
9
+ const CALL_WASM_AB_PROPS_JSON = process.env.CALL_WASM_AB_PROPS_JSON ?? "";
10
+ const PTHREAD_POOL_SIZE = 20;
11
+ const VOIP_READY_TIMEOUT_MS = 15_000;
12
+ const parseJsonObjectEnv = (raw) => {
13
+ if (!raw)
14
+ return {};
15
+ try {
16
+ const parsed = JSON.parse(raw);
17
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
18
+ return parsed;
19
+ }
20
+ catch { }
21
+ return {};
22
+ };
23
+ const toByteArray = (input) => {
24
+ if (!input)
25
+ return new Uint8Array(0);
26
+ if (input instanceof Uint8Array)
27
+ return input;
28
+ if (typeof input === "string")
29
+ return new TextEncoder().encode(input);
30
+ if (ArrayBuffer.isView(input))
31
+ return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
32
+ if (input instanceof ArrayBuffer)
33
+ return new Uint8Array(input);
34
+ if (typeof input === "object" && typeof input.length === "number") {
35
+ const arr = new Uint8Array(input.length);
36
+ for (let i = 0; i < input.length; i += 1)
37
+ arr[i] = input[i] ?? 0;
38
+ return arr;
39
+ }
40
+ return new Uint8Array(0);
41
+ };
42
+ const filterWorkerStderr = (chunk) => {
43
+ const line = chunk.toString().trim();
44
+ if (line && !line.startsWith("voip:") && !line.startsWith("still waiting")) {
45
+ process.stderr.write(chunk);
46
+ }
47
+ };
48
+ const normalizeVideoCaptureConfig = (data) => ({
49
+ width: Math.trunc(Number(data?.width ?? data?.frame_width ?? data?.frameWidth ?? 0)) || 640,
50
+ height: Math.trunc(Number(data?.height ?? data?.frame_height ?? data?.frameHeight ?? 0)) || 480,
51
+ fps: Math.trunc(Number(data?.fps ?? data?.frame_rate ?? data?.frameRate ?? data?.max_framerate ?? 0)) || 24,
52
+ raw: data
53
+ });
54
+ const resolveWorkerScriptPath = () => {
55
+ const compiled = path.join(__dirname, "worker-bootstrap.js");
56
+ return fs.existsSync(compiled) ? compiled : path.join(__dirname, "worker-bootstrap.mts");
57
+ };
58
+ class NodeWorkerMessagePort {
59
+ #listeners = new Map();
60
+ #worker;
61
+ #notifyCallbacks;
62
+ fullyConnected;
63
+ name;
64
+ workerID = 0;
65
+ pthread_ptr = 0;
66
+ constructor(worker, name = "WAWebVoipWebWasmWorker", notifyCallbacks) {
67
+ this.#worker = worker;
68
+ this.#notifyCallbacks = notifyCallbacks;
69
+ this.name = name;
70
+ this.fullyConnected = new Promise((resolve) => {
71
+ const loadedHandler = (msg) => {
72
+ if (msg && msg.cmd === "loaded") {
73
+ this.workerID = msg.workerID ?? 0;
74
+ resolve(this);
75
+ }
76
+ };
77
+ this.addMessageListener("cmd", loadedHandler);
78
+ });
79
+ if (typeof worker.on === "function") {
80
+ worker.on("message", (data) => this.#handleMessage(data));
81
+ worker.on("error", () => { });
82
+ }
83
+ else if (typeof worker.addEventListener === "function") {
84
+ worker.addEventListener("message", (ev) => this.#handleMessage(ev?.data ?? ev));
85
+ }
86
+ }
87
+ postMessage = (msg, transferList) => {
88
+ const out = msg && typeof msg === "object" && msg.cmd && !msg.type ? { ...msg, type: "cmd" } : msg;
89
+ this.#worker.postMessage(out, transferList);
90
+ };
91
+ addMessageListener = (type, handler) => {
92
+ let set = this.#listeners.get(type);
93
+ if (!set) {
94
+ set = new Set();
95
+ this.#listeners.set(type, set);
96
+ }
97
+ set.add(handler);
98
+ return handler;
99
+ };
100
+ removeMessageListener = (type, handler) => this.#listeners.get(type)?.delete(handler) ?? false;
101
+ removeAllMessageListeners = (type) => {
102
+ if (type)
103
+ this.#listeners.get(type)?.clear();
104
+ else
105
+ this.#listeners.clear();
106
+ };
107
+ terminate = () => { this.#worker.terminate(); };
108
+ close = () => { };
109
+ isWrappingVirtualMessagePort = () => false;
110
+ getWorker = () => this.#worker;
111
+ #handleMessage = (data) => {
112
+ if (!data || typeof data !== "object")
113
+ return;
114
+ if (data.type === "callback" || data.type === "waWasmWorkerCompatibleCallback") {
115
+ let callbackName;
116
+ let callbackArgs;
117
+ if (data.__name) {
118
+ callbackName = data.__name;
119
+ callbackArgs = {};
120
+ for (const key in data) {
121
+ if (key !== "type" && key !== "__name" && key !== "prototype" && key !== "args" && !key.startsWith("__")) {
122
+ callbackArgs[key] = data[key];
123
+ }
124
+ }
125
+ }
126
+ else if (data.name) {
127
+ callbackName = data.name;
128
+ callbackArgs = data.args ?? {};
129
+ }
130
+ else if (data.payload?.name) {
131
+ callbackName = data.payload.name;
132
+ callbackArgs = data.payload.args ?? {};
133
+ }
134
+ else {
135
+ return;
136
+ }
137
+ if (callbackName === "onSignalingXmpp" &&
138
+ (!callbackArgs || Object.keys(callbackArgs).length === 0)) {
139
+ callbackArgs = {
140
+ peerJid: data.peerJid, callId: data.callId, xmlPayload: data.xmlPayload,
141
+ };
142
+ }
143
+ let listenerData = callbackArgs;
144
+ if (!callbackArgs || Object.keys(callbackArgs).length === 0 ||
145
+ (Object.keys(callbackArgs).length === 1 && callbackArgs.prototype)) {
146
+ listenerData = {};
147
+ for (const key in data) {
148
+ if (key !== "type" && key !== "__name" && key !== "prototype" && key !== "args" && !key.startsWith("__")) {
149
+ listenerData[key] = data[key];
150
+ }
151
+ }
152
+ }
153
+ else if (callbackName === "sendDataToRelay") {
154
+ listenerData = { ...callbackArgs };
155
+ if (data.data !== undefined)
156
+ listenerData.data = data.data;
157
+ if (data.len !== undefined)
158
+ listenerData.len = data.len;
159
+ if (data.ip !== undefined)
160
+ listenerData.ip = data.ip;
161
+ if (data.port !== undefined)
162
+ listenerData.port = data.port;
163
+ }
164
+ else if (callbackName === "onCallEvent") {
165
+ listenerData = { ...callbackArgs };
166
+ if (data.eventType !== undefined)
167
+ listenerData.eventType = data.eventType;
168
+ if (data.userData !== undefined)
169
+ listenerData.userData = data.userData;
170
+ if (data.eventDataJson !== undefined)
171
+ listenerData.eventDataJson = data.eventDataJson;
172
+ }
173
+ this.#notifyCallbacks?.(callbackName, listenerData);
174
+ return;
175
+ }
176
+ const dispatch = (key) => {
177
+ if (!key)
178
+ return;
179
+ for (const handler of this.#listeners.get(key) ?? []) {
180
+ try {
181
+ handler(data);
182
+ }
183
+ catch { }
184
+ }
185
+ };
186
+ dispatch(data.type);
187
+ if (data.cmd !== data.type)
188
+ dispatch(data.cmd);
189
+ };
190
+ }
191
+ export class WasmEngine {
192
+ #jsWorkers = new Set();
193
+ #globalCallbackListeners = new Map();
194
+ #registerGlobalCallbackListener = (callbackName, handler) => {
195
+ const key = `callback:${callbackName}`;
196
+ let set = this.#globalCallbackListeners.get(key);
197
+ if (!set) {
198
+ set = new Set();
199
+ this.#globalCallbackListeners.set(key, set);
200
+ }
201
+ set.add(handler);
202
+ };
203
+ #notifyGlobalCallbackListeners = (callbackName, data) => {
204
+ const set = this.#globalCallbackListeners.get(`callback:${callbackName}`);
205
+ if (!set)
206
+ return;
207
+ for (const handler of set) {
208
+ try {
209
+ handler(data);
210
+ }
211
+ catch { }
212
+ }
213
+ };
214
+ #config;
215
+ #instance = null;
216
+ #initialized = false;
217
+ #moduleRegistry = new Map();
218
+ #vmContext = null;
219
+ #unusedWorkers = [];
220
+ #runningWorkers = [];
221
+ #pthreads = {};
222
+ #nextWorkerID = 1;
223
+ #wasmModule = null;
224
+ #wasmMemory = null;
225
+ #removeRunDependencyCallback = null;
226
+ #workersLoadedCount = 0;
227
+ #audioPlaybackLoopInterval = null;
228
+ #audioPlaybackBuffer = null;
229
+ #isPlaybackActive = false;
230
+ #voipStackInitialized = false;
231
+ #voipStackInitPromise = null;
232
+ #voipReadyResolver = null;
233
+ #voipReadyPromise = null;
234
+ #workerModulesCode = "";
235
+ #loaderCode = "";
236
+ constructor(config = {}) {
237
+ const basePath = config.resourcesPath
238
+ ? (path.isAbsolute(config.resourcesPath) ? config.resourcesPath : path.resolve(process.cwd(), config.resourcesPath))
239
+ : path.resolve(__dirname, "..");
240
+ const wasmPath = config.wasmPath
241
+ ? (path.isAbsolute(config.wasmPath) ? config.wasmPath : path.resolve(process.cwd(), config.wasmPath))
242
+ : path.join(basePath, "assets", "wasm", "whatsapp.wasm");
243
+ this.#config = {
244
+ ...config,
245
+ storageDir: config.storageDir
246
+ ? (path.isAbsolute(config.storageDir) ? config.storageDir : path.resolve(process.cwd(), config.storageDir))
247
+ : path.join(tmpdir(), "qiro-voip"),
248
+ wasmPath,
249
+ resourcesPath: basePath,
250
+ enableLogs: config.enableLogs ?? true,
251
+ options: {
252
+ heartbeatInterval: 30,
253
+ lobbyTimeout: 1,
254
+ maxParticipantsScreenShare: 32,
255
+ maxGroupSizeLongRingtone: 32,
256
+ ...config.options,
257
+ },
258
+ };
259
+ }
260
+ initialize = async () => {
261
+ if (this.#initialized)
262
+ throw new Error("WasmEngine already initialized");
263
+ const voipStorageDir = this.#config.storageDir;
264
+ try {
265
+ if (!fs.existsSync(voipStorageDir))
266
+ fs.mkdirSync(voipStorageDir, { recursive: true });
267
+ }
268
+ catch { }
269
+ const loaderFile = path.join(this.#config.resourcesPath, "assets", "wasm", "loader.js");
270
+ const workerFile = path.join(this.#config.resourcesPath, "assets", "wasm", "worker-modules.js");
271
+ if (!this.#config.wasmBinary && !fs.existsSync(this.#config.wasmPath)) {
272
+ throw new Error(`WhatsApp VoIP WASM not found at ${this.#config.wasmPath}. Point wasmPath at it, hand the bytes over as wasmBinary, or put whatsapp.wasm, loader.js and worker-modules.js under <resourcesPath>/assets/wasm/.`);
273
+ }
274
+ const wasmBuffer = this.#config.wasmBinary
275
+ ? Buffer.from(this.#config.wasmBinary)
276
+ : fs.readFileSync(this.#config.wasmPath);
277
+ const diskWorkerCode = fs.existsSync(workerFile) ? fs.readFileSync(workerFile, "utf8") : "";
278
+ this.#workerModulesCode = this.#config.workerModulesCode ?? diskWorkerCode;
279
+ const workerBundleHasLoader = typeof this.#workerModulesCode === "string" && /WAWebVoipWebWasmLoader/.test(this.#workerModulesCode);
280
+ this.#loaderCode = this.#config.loaderCode ??
281
+ (workerBundleHasLoader ? "" : fs.existsSync(loaderFile) ? fs.readFileSync(loaderFile, "utf8") : "");
282
+ if (!this.#loaderCode && !this.#workerModulesCode) {
283
+ throw new Error("No loader/worker code available to initialize VoIP");
284
+ }
285
+ const memory = new WebAssembly.Memory({ initial: 256, maximum: 32768, shared: true });
286
+ this.#wasmMemory = memory;
287
+ this.#wasmModule = await WebAssembly.compile(wasmBuffer);
288
+ this.#vmContext = this.#createVMContext(memory);
289
+ const runModuleCode = (code) => {
290
+ if (code)
291
+ vm.runInContext(code, this.#vmContext);
292
+ };
293
+ runModuleCode(this.#workerModulesCode);
294
+ runModuleCode(this.#loaderCode);
295
+ this.#vmContext.WAWebVoipWebWasmWorkerResource = this.#requireModule("WAWebVoipWebWasmWorkerResource");
296
+ const loaderModuleNames = [
297
+ this.#config.loaderModuleName,
298
+ "WAWebVoipWebWasmLoader",
299
+ "WAWebVoipWebWasmLoader.worker",
300
+ "WAWebVoipWebWasmLoader_ProdLab_internal.worker",
301
+ "WAWebVoipWebWasmLoader_ProdLabvideo_internal.worker",
302
+ ].filter((v, i, a) => !!v && a.indexOf(v) === i);
303
+ let wasmLoader = null;
304
+ for (const moduleName of loaderModuleNames) {
305
+ const candidate = this.#requireModule(moduleName);
306
+ if (typeof candidate === "function") {
307
+ wasmLoader = candidate;
308
+ break;
309
+ }
310
+ if (typeof candidate?.default === "function") {
311
+ wasmLoader = candidate.default;
312
+ break;
313
+ }
314
+ }
315
+ if (typeof wasmLoader !== "function") {
316
+ throw new Error(`No compatible WASM loader found. Tried: ${loaderModuleNames.join(", ")}`);
317
+ }
318
+ this.#registerGlobalCallbacks();
319
+ await this.#initPThreadPool();
320
+ const workersLoadingPromise = this.#loadWasmModuleToAllWorkers();
321
+ const readyPromise = wasmLoader({
322
+ wasmBinary: wasmBuffer,
323
+ wasmMemory: memory,
324
+ locateFile: () => this.#config.wasmPath,
325
+ onRuntimeInitialized: () => { },
326
+ });
327
+ const [instance] = await Promise.all([readyPromise, workersLoadingPromise]);
328
+ this.#instance = instance;
329
+ this.#initialized = true;
330
+ };
331
+ isInitialized = () => this.#initialized;
332
+ destroy = () => {
333
+ this.#stopAudioPlaybackLoop();
334
+ if (this.#instance && typeof this.#instance.endCall === "function") {
335
+ try {
336
+ this.#instance.endCall(0, false);
337
+ }
338
+ catch { }
339
+ }
340
+ for (const worker of [...this.#runningWorkers, ...this.#unusedWorkers, ...this.#jsWorkers]) {
341
+ try {
342
+ worker.terminate();
343
+ }
344
+ catch { }
345
+ }
346
+ this.#runningWorkers = [];
347
+ this.#unusedWorkers = [];
348
+ this.#jsWorkers.clear();
349
+ this.#instance = null;
350
+ this.#vmContext = null;
351
+ this.#moduleRegistry.clear();
352
+ this.#globalCallbackListeners.clear();
353
+ this.#wasmModule = null;
354
+ this.#wasmMemory = null;
355
+ this.#initialized = false;
356
+ };
357
+ initVoipStack = (selfJid, meUserJid, selfLid) => {
358
+ this.#ensureInitialized();
359
+ if (this.#voipStackInitialized || this.#voipStackInitPromise)
360
+ return;
361
+ this.#voipStackInitPromise = new Promise((resolveInit) => {
362
+ this.#voipReadyPromise = new Promise((readyResolve) => {
363
+ this.#voipReadyResolver = () => {
364
+ this.#voipStackInitialized = true;
365
+ this.#voipReadyResolver = null;
366
+ this.#voipReadyPromise = null;
367
+ readyResolve();
368
+ };
369
+ });
370
+ try {
371
+ this.#applyDefaultAbProps();
372
+ try {
373
+ this.#instance.initVoipStack(selfJid, meUserJid, selfLid);
374
+ }
375
+ catch (modernErr) {
376
+ if (modernErr?.name === "BindingError" &&
377
+ (String(modernErr?.message ?? "").includes("expected 8 args") ||
378
+ String(modernErr?.message ?? "").includes("takes 8"))) {
379
+ this.#instance.initVoipStack(selfJid, meUserJid, selfLid, true, 5, 0, 8, 16);
380
+ }
381
+ else {
382
+ throw modernErr;
383
+ }
384
+ }
385
+ Promise.race([
386
+ this.#voipReadyPromise,
387
+ new Promise((r) => setTimeout(() => {
388
+ this.#voipStackInitialized = true;
389
+ r();
390
+ }, VOIP_READY_TIMEOUT_MS)),
391
+ ]).finally(() => {
392
+ this.#voipStackInitPromise = null;
393
+ resolveInit();
394
+ });
395
+ }
396
+ catch {
397
+ this.#voipReadyResolver = null;
398
+ this.#voipReadyPromise = null;
399
+ this.#voipStackInitPromise = null;
400
+ resolveInit();
401
+ }
402
+ });
403
+ };
404
+ waitForVoipStackReady = async () => {
405
+ if (this.#voipStackInitialized)
406
+ return;
407
+ if (this.#voipStackInitPromise) {
408
+ await this.#voipStackInitPromise;
409
+ }
410
+ else {
411
+ await new Promise((r) => setTimeout(r, 100));
412
+ }
413
+ };
414
+ isVoipStackReady = () => this.#voipStackInitialized;
415
+ startCall = (options) => {
416
+ this.#ensureInitialized();
417
+ const peers = this.#makeStringList(options.peerList ?? [options.peerJid]);
418
+ const tcToken = this.#createUint8List(options.extraData);
419
+ const isLidCall = options.isLidCall ?? options.peerJid.includes("@lid");
420
+ const isFromDialer = options.isFromDialer ?? false;
421
+ const peerJid = String(options.peerJid);
422
+ try {
423
+ try {
424
+ return this.#instance.startVoipCall(peerJid, peers, options.callId, options.isVideo, options.peerPn, isLidCall, isFromDialer, tcToken);
425
+ }
426
+ catch (error) {
427
+ if (error?.name !== "BindingError")
428
+ throw error;
429
+ return this.#instance.startVoipCall(peerJid, peers, options.callId, options.isVideo, options.peerPn, isFromDialer, tcToken);
430
+ }
431
+ }
432
+ finally {
433
+ peers?.delete?.();
434
+ tcToken?.delete?.();
435
+ }
436
+ };
437
+ startGroupCall = (options) => {
438
+ this.#ensureInitialized();
439
+ const pnUserJids = this.#makeStringList(options.pnUserJids ?? []);
440
+ const lidUserJids = this.#makeStringList(options.lidUserJids ?? []);
441
+ const deviceJidsCsv = this.#makeStringList(options.deviceJidsCsv ?? []);
442
+ try {
443
+ return this.#instance.startVoipGroupCall(pnUserJids, lidUserJids, deviceJidsCsv, options.callId, options.isVideo ?? false, options.groupJid, options.isLightWeight ?? false, options.scheduleId ?? "", options.chatName ?? "", options.chatIcon ?? "", options.callFromUI ?? 0, options.lobbyEntryType ?? 0, options.username ?? "");
444
+ }
445
+ finally {
446
+ pnUserJids?.delete?.();
447
+ lidUserJids?.delete?.();
448
+ deviceJidsCsv?.delete?.();
449
+ }
450
+ };
451
+ joinOngoingCall = (options) => {
452
+ this.#ensureInitialized();
453
+ const pnUserJids = this.#makeStringList(options.pnUserJids ?? []);
454
+ const lidUserJids = this.#makeStringList(options.lidUserJids ?? []);
455
+ const deviceJidsCsv = this.#makeStringList(options.deviceJidsCsv ?? []);
456
+ try {
457
+ return this.#instance.joinVoipOngoingCall(options.callId, options.callCreatorJid, options.initialPeerJid ?? options.callCreatorJid, pnUserJids, lidUserJids, deviceJidsCsv, options.isVideo ?? false, options.groupJid ?? "", options.initialGroupTransactionId ?? 0, options.callCreatorIsNotContact ?? false, options.callLinkCode ?? "", options.isLightweight ?? false, options.scheduledId ?? "", options.joinAndAccept ?? true, options.chatName ?? "", options.lobbyEntryType ?? 0, options.isDeviceSwitch ?? false);
458
+ }
459
+ finally {
460
+ pnUserJids?.delete?.();
461
+ lidUserJids?.delete?.();
462
+ deviceJidsCsv?.delete?.();
463
+ }
464
+ };
465
+ acceptCall = (isMicEnabled = true, isCameraEnabled = false) => {
466
+ this.#ensureInitialized();
467
+ return this.#instance.acceptCall(isMicEnabled, isCameraEnabled);
468
+ };
469
+ endCall = (reason = 0, sendTerminate = true) => {
470
+ this.#ensureInitialized();
471
+ this.#instance.endCall(reason, sendTerminate);
472
+ };
473
+ setMute = (muted) => {
474
+ this.#ensureInitialized();
475
+ return this.#instance.setCallMute(muted);
476
+ };
477
+ updateNetworkMedium = (networkMedium, networkMtu = 0) => {
478
+ this.#ensureInitialized();
479
+ this.#instance.updateNetworkMedium?.(networkMedium, networkMtu);
480
+ };
481
+ handleSignalingOffer = (msg) => {
482
+ this.#ensureInitialized();
483
+ const tcTokenList = this.#createUint8List(msg.tcToken);
484
+ try {
485
+ this.#instance.handleIncomingSignalingOffer(msg.payload, String(msg.peerPlatform ?? 0), String(msg.peerAppVersion ?? "0"), String(msg.epochId ?? "0"), String(msg.timestamp ?? "0"), msg.isOffline ?? false, msg.isOfferNotContact ?? false, String(msg.peerJid), tcTokenList);
486
+ }
487
+ finally {
488
+ tcTokenList?.delete?.();
489
+ }
490
+ };
491
+ handleSignalingMessage = (msg) => {
492
+ this.#ensureInitialized();
493
+ const tcTokenList = this.#createUint8List(msg.tcToken);
494
+ try {
495
+ this.#instance.handleIncomingSignalingMessage(msg.payload, String(msg.peerPlatform ?? "0"), String(msg.peerAppVersion ?? "0"), String(msg.epochId ?? "0"), String(msg.timestamp ?? "0"), msg.isOffline ?? false, String(msg.peerJid), tcTokenList);
496
+ }
497
+ finally {
498
+ tcTokenList?.delete?.();
499
+ }
500
+ };
501
+ handleSignalingAck = (msg) => {
502
+ this.#ensureInitialized();
503
+ const options = this.#createUint8List(msg.extraData);
504
+ try {
505
+ this.#instance.handleIncomingSignalingAck(msg.payload, String(msg.ackError ?? "0"), String(msg.msgType ?? ""), msg.peerJid ?? "", options);
506
+ }
507
+ finally {
508
+ options?.delete?.();
509
+ }
510
+ };
511
+ handleSignalingReceipt = (msg) => {
512
+ this.#ensureInitialized();
513
+ const tcTokenList = this.#createUint8List(msg.tcToken);
514
+ try {
515
+ this.#instance.handleIncomingSignalingReceipt?.(msg.payload, msg.peerJid, tcTokenList);
516
+ }
517
+ finally {
518
+ tcTokenList?.delete?.();
519
+ }
520
+ };
521
+ handleOnTransportMessage = (data, ip, port) => {
522
+ this.#ensureInitialized();
523
+ if (typeof this.#instance.handleOnMessageFromHeap === "function") {
524
+ const ptr = this.malloc(data.byteLength);
525
+ if (!ptr)
526
+ return;
527
+ try {
528
+ const heapU8 = this.#instance.GROWABLE_HEAP_U8?.() ?? this.#instance.HEAPU8;
529
+ if (!heapU8)
530
+ return;
531
+ heapU8.set(data, ptr);
532
+ this.#instance.handleOnMessageFromHeap(ptr, data.byteLength, ip, port);
533
+ }
534
+ finally {
535
+ this.free(ptr);
536
+ }
537
+ return;
538
+ }
539
+ if (typeof this.#instance.handleOnMessage !== "function")
540
+ return;
541
+ const dataList = this.#createUint8List(data);
542
+ try {
543
+ this.#instance.handleOnMessage(dataList, ip, port);
544
+ }
545
+ finally {
546
+ dataList?.delete?.();
547
+ }
548
+ };
549
+ updateIceRtt = (rttMs, relayIp, relayPort) => {
550
+ this.#ensureInitialized();
551
+ this.#instance.updateIceRtt?.(rttMs, relayIp, relayPort);
552
+ };
553
+ startScreenShare = () => {
554
+ this.#ensureInitialized();
555
+ return this.#instance.startScreenShare?.();
556
+ };
557
+ stopScreenShare = () => {
558
+ this.#ensureInitialized();
559
+ return this.#instance.stopScreenShare?.();
560
+ };
561
+ sendVideoFrame = (frame, width, height, fps, format = 1, orientation = 1, useDesktopCapture = false) => {
562
+ if (!this.#jsWorkers.size || !frame?.byteLength || !width || !height) {
563
+ return false;
564
+ }
565
+ const timestamp = Date.now();
566
+ for (const worker of this.#jsWorkers) {
567
+ const copy = frame.buffer.slice(frame.byteOffset, frame.byteOffset + frame.byteLength);
568
+ try {
569
+ worker.postMessage({
570
+ type: "jsWorkerCmd",
571
+ jsWorkerCmd: "pushRawVideoFrame",
572
+ useDesktopCapture,
573
+ frameBuffer: copy,
574
+ width,
575
+ height,
576
+ fps,
577
+ format,
578
+ orientation,
579
+ timestamp
580
+ }, [copy]);
581
+ }
582
+ catch { }
583
+ }
584
+ return true;
585
+ };
586
+ releaseVideoFrameBuffer = () => {
587
+ for (const worker of this.#jsWorkers) {
588
+ try {
589
+ worker.postMessage({ type: "jsWorkerCmd", jsWorkerCmd: "releaseRawVideoFrameBuffer" });
590
+ }
591
+ catch { }
592
+ }
593
+ };
594
+ sendAudioData = (data, ptr) => {
595
+ this.#ensureInitialized();
596
+ if (!data || data.length === 0 || !ptr)
597
+ return;
598
+ if (typeof this.#instance.onAudioDataFromJs !== "function")
599
+ return;
600
+ try {
601
+ const heapF32 = this.#instance.GROWABLE_HEAP_F32?.();
602
+ if (!heapF32)
603
+ return;
604
+ const index = Math.floor(ptr / 4);
605
+ if (index < 0 || index + data.length > heapF32.length)
606
+ return;
607
+ heapF32.set(data, index);
608
+ this.#instance.onAudioDataFromJs(ptr, data.length);
609
+ }
610
+ catch { }
611
+ };
612
+ malloc = (size) => {
613
+ this.#ensureInitialized();
614
+ return this.#instance._malloc(size);
615
+ };
616
+ free = (ptr) => {
617
+ this.#ensureInitialized();
618
+ this.#instance._free(ptr);
619
+ };
620
+ #ensureInitialized = () => {
621
+ if (!this.#initialized || !this.#instance) {
622
+ throw new Error("WasmEngine not initialized. Call initialize() first.");
623
+ }
624
+ };
625
+ #makeStringList = (arr) => {
626
+ const list = new this.#instance.StringList();
627
+ for (const v of arr)
628
+ list.push_back(v);
629
+ return list;
630
+ };
631
+ #createUint8List = (data) => {
632
+ if (!this.#instance?.Uint8List)
633
+ return null;
634
+ const list = new this.#instance.Uint8List();
635
+ if (data)
636
+ data.forEach((byte) => list.push_back(byte));
637
+ return list;
638
+ };
639
+ #startAudioPlaybackLoop = () => {
640
+ if (this.#audioPlaybackLoopInterval)
641
+ return;
642
+ this.#ensureInitialized();
643
+ this.#isPlaybackActive = true;
644
+ if (typeof this.#instance.requestAudioDataFromWasmVoip !== "function")
645
+ return;
646
+ const framesPerChunk = 320;
647
+ const bufferSize = framesPerChunk * 4;
648
+ try {
649
+ const _malloc = this.#instance._malloc ?? this.#instance.malloc;
650
+ if (!_malloc)
651
+ return;
652
+ this.#audioPlaybackBuffer = _malloc(bufferSize);
653
+ }
654
+ catch {
655
+ return;
656
+ }
657
+ if (!this.#audioPlaybackBuffer || this.#audioPlaybackBuffer <= 0)
658
+ return;
659
+ this.#audioPlaybackLoopInterval = setInterval(() => {
660
+ if (!this.#isPlaybackActive || !this.#instance || !this.#initialized) {
661
+ this.#stopAudioPlaybackLoop();
662
+ return;
663
+ }
664
+ try {
665
+ this.#instance.requestAudioDataFromWasmVoip(this.#audioPlaybackBuffer, bufferSize);
666
+ const heapF32 = this.#instance.GROWABLE_HEAP_F32?.();
667
+ if (!heapF32)
668
+ return;
669
+ const index = Math.floor(this.#audioPlaybackBuffer / 4);
670
+ const numFloats = Math.floor(bufferSize / 4);
671
+ if (index < 0 || index + numFloats > heapF32.length)
672
+ return;
673
+ const audioData = new Float32Array(heapF32.buffer, heapF32.byteOffset + index * 4, numFloats);
674
+ const hasNonZero = audioData.some((s) => Math.abs(s) > 0.0001);
675
+ if (hasNonZero)
676
+ this.#config.callbacks?.onAudioPlaybackData?.(audioData);
677
+ }
678
+ catch { }
679
+ }, 16);
680
+ };
681
+ #stopAudioPlaybackLoop = () => {
682
+ this.#isPlaybackActive = false;
683
+ if (this.#audioPlaybackLoopInterval) {
684
+ clearInterval(this.#audioPlaybackLoopInterval);
685
+ this.#audioPlaybackLoopInterval = null;
686
+ }
687
+ if (this.#audioPlaybackBuffer && this.#audioPlaybackBuffer > 0) {
688
+ try {
689
+ this.#instance?._free?.(this.#audioPlaybackBuffer);
690
+ }
691
+ catch { }
692
+ this.#audioPlaybackBuffer = null;
693
+ }
694
+ };
695
+ #applyDefaultAbProps = () => {
696
+ if (!this.#instance)
697
+ return;
698
+ const setInt = typeof this.#instance.setABPropInt === "function"
699
+ ? (k, v) => { this.#instance.setABPropInt(k, v); }
700
+ : null;
701
+ const setBool = typeof this.#instance.setABPropBool === "function"
702
+ ? (k, v) => { this.#instance.setABPropBool(k, v); }
703
+ : null;
704
+ const setString = typeof this.#instance.setABPropString === "function"
705
+ ? (k, v) => { this.#instance.setABPropString(k, v); }
706
+ : null;
707
+ if (!setInt && !setBool && !setString)
708
+ return;
709
+ const opts = this.#config.options ?? {};
710
+ const intProps = {
711
+ heartbeat_interval_s: opts.heartbeatInterval ?? 30,
712
+ lobby_timeout_min: opts.lobbyTimeout ?? 1,
713
+ max_num_participants_for_ss: opts.maxParticipantsScreenShare ?? 32,
714
+ max_group_size_for_long_ringtone: opts.maxGroupSizeLongRingtone ?? 32,
715
+ app_exit_reason_version: 1,
716
+ log_level: opts.logLevel ?? 3,
717
+ calling_rust_migration_bitmap: 0,
718
+ calling_rust_migration_incoming_stanza_bitmap: 0,
719
+ default_endpoint_thread_poll_timeout: 0,
720
+ aigc_version: 0,
721
+ call_admin_version: 0,
722
+ vid_stream_pause_resume_jb_reset_threshold_ms: 0,
723
+ opus_max_bandwidth: 1103, // OPUS_BANDWIDTH_WIDEBAND
724
+ };
725
+ const boolProps = {
726
+ enable_av_downgrade: false,
727
+ enable_new_user_action_stanza_for_raise_hand_sender: false,
728
+ enable_webcodec_video_encode: false,
729
+ enable_init_bwe_for_group_call: false,
730
+ enable_ring_for_gc_on_offer_expire: false,
731
+ allow_reporting_call_replayer_id: false,
732
+ enable_offer_v2_upgrade: false,
733
+ enable_silent_offer: false,
734
+ voice_ai_conversation_starter_latency_tracking: false,
735
+ enable_waiting_room_logging: false,
736
+ attach_transport_rtx: false,
737
+ ignore_joinable_terminate_on_expired_offer: false,
738
+ enable_passthrough_video_decoder: false,
739
+ };
740
+ for (const [key, value] of Object.entries(intProps)) {
741
+ if (setInt && Number.isFinite(value))
742
+ try {
743
+ setInt(key, value);
744
+ }
745
+ catch { }
746
+ }
747
+ for (const [key, value] of Object.entries(boolProps)) {
748
+ if (setBool)
749
+ try {
750
+ setBool(key, value);
751
+ }
752
+ catch { }
753
+ }
754
+ const overrideProps = parseJsonObjectEnv(CALL_WASM_AB_PROPS_JSON);
755
+ for (const [key, value] of Object.entries(overrideProps)) {
756
+ try {
757
+ if (typeof value === "boolean" && setBool)
758
+ setBool(key, value);
759
+ else if (typeof value === "number" && setInt)
760
+ setInt(key, value);
761
+ else if (typeof value === "string" && setString)
762
+ setString(key, value);
763
+ }
764
+ catch { }
765
+ }
766
+ };
767
+ #allocateUnusedWorker = () => {
768
+ const workerScriptPath = resolveWorkerScriptPath();
769
+ if (!fs.existsSync(workerScriptPath))
770
+ return;
771
+ try {
772
+ const worker = new Worker(workerScriptPath, {
773
+ stdout: true, stderr: true,
774
+ workerData: {
775
+ wasmPath: this.#config.wasmPath,
776
+ wasmBinary: this.#config.wasmBinary,
777
+ workerModulesCode: this.#workerModulesCode,
778
+ loaderCode: this.#loaderCode,
779
+ loaderModuleName: this.#config.loaderModuleName,
780
+ resourcesPath: this.#config.resourcesPath,
781
+ storageDir: this.#config.storageDir,
782
+ enableLogs: this.#config.enableLogs,
783
+ },
784
+ });
785
+ const port = new NodeWorkerMessagePort(
786
+ worker,
787
+ "WAWebVoipWebWasmWorker",
788
+ (callbackName, data) => this.#notifyGlobalCallbackListeners(callbackName, data)
789
+ );
790
+ worker.stdout?.on("data", () => { }); // suppress noisy worker stdout
791
+ worker.stderr?.on("data", filterWorkerStderr);
792
+ this.#unusedWorkers.push(port);
793
+ }
794
+ catch { }
795
+ };
796
+ #initPThreadPool = async () => {
797
+ for (let i = 0; i < PTHREAD_POOL_SIZE; i += 1)
798
+ this.#allocateUnusedWorker();
799
+ };
800
+ #loadWasmModuleToWorker = (worker) => new Promise((resolve) => {
801
+ const loadedHandler = (msg) => {
802
+ if (msg && msg.cmd === "loaded") {
803
+ worker.removeMessageListener("cmd", loadedHandler);
804
+ this.#workersLoadedCount += 1;
805
+ if (this.#workersLoadedCount >= PTHREAD_POOL_SIZE && this.#removeRunDependencyCallback) {
806
+ this.#removeRunDependencyCallback("loading-workers");
807
+ }
808
+ resolve();
809
+ }
810
+ };
811
+ worker.addMessageListener("cmd", loadedHandler);
812
+ worker.workerID = this.#nextWorkerID++;
813
+ worker.postMessage({
814
+ cmd: "load", type: "cmd",
815
+ wasmMemory: this.#wasmMemory,
816
+ wasmModule: this.#wasmModule,
817
+ workerID: worker.workerID,
818
+ handlers: [],
819
+ });
820
+ });
821
+ #loadWasmModuleToAllWorkers = async () => {
822
+ this.#workersLoadedCount = 0;
823
+ await Promise.all(this.#unusedWorkers.map((w) => this.#loadWasmModuleToWorker(w)));
824
+ };
825
+ #registerGlobalCallbacks = () => {
826
+ const callbacks = this.#config.callbacks ?? {};
827
+ this.#registerGlobalCallbackListener("loggingCallback", (data) => {
828
+ if (!this.#config.enableLogs)
829
+ return;
830
+ const level = data?.level;
831
+ const msg = data?.message ?? "";
832
+ const mapped = level === 1 ? "error" : level === 2 ? "warn" : level === 3 ? "log" : "debug";
833
+ callbacks.onLog?.(mapped, msg);
834
+ });
835
+ if (callbacks.onAudioCaptureInit) {
836
+ this.#registerGlobalCallbackListener("initCaptureDriverJS", (data) => {
837
+ callbacks.onAudioCaptureInit({
838
+ sampleRate: data?.sample_rate ?? data?.sampleRate,
839
+ channels: data?.channels,
840
+ bitsPerSample: data?.bits_per_sample ?? data?.bitsPerSample,
841
+ framesPerChunk: data?.frames_per_chunk ?? data?.framesPerChunk,
842
+ });
843
+ });
844
+ }
845
+ this.#registerGlobalCallbackListener("startVideoCaptureJS", (data) => callbacks.onVideoCaptureStart?.(normalizeVideoCaptureConfig(data)));
846
+ this.#registerGlobalCallbackListener("stopVideoCaptureJS", () => callbacks.onVideoCaptureStop?.());
847
+ this.#registerGlobalCallbackListener("videoFrameConsumed", () => callbacks.onVideoFrameConsumed?.());
848
+ this.#registerGlobalCallbackListener("startDesktopCaptureJS", (data) => callbacks.onDesktopCaptureStart?.(normalizeVideoCaptureConfig(data)));
849
+ this.#registerGlobalCallbackListener("stopDesktopCaptureJS", () => callbacks.onDesktopCaptureStop?.());
850
+ this.#registerGlobalCallbackListener("startCaptureJS", () => callbacks.onAudioCaptureStart?.());
851
+ this.#registerGlobalCallbackListener("stopCaptureJS", () => callbacks.onAudioCaptureStop?.());
852
+ if (callbacks.onAudioPlaybackInit) {
853
+ this.#registerGlobalCallbackListener("initPlaybackDriverJS", (data) => {
854
+ callbacks.onAudioPlaybackInit({
855
+ sampleRate: data?.sample_rate ?? data?.sampleRate,
856
+ channels: data?.channels,
857
+ bitsPerSample: data?.bits_per_sample ?? data?.bitsPerSample,
858
+ framesPerChunk: data?.frames_per_chunk ?? data?.framesPerChunk,
859
+ });
860
+ });
861
+ }
862
+ this.#registerGlobalCallbackListener("startPlaybackJS", () => {
863
+ callbacks.onAudioPlaybackStart?.();
864
+ this.#startAudioPlaybackLoop();
865
+ });
866
+ this.#registerGlobalCallbackListener("stopPlaybackJS", () => {
867
+ this.#stopAudioPlaybackLoop();
868
+ callbacks.onAudioPlaybackStop?.();
869
+ });
870
+ if (callbacks.onSignalingXmpp) {
871
+ this.#registerGlobalCallbackListener("onSignalingXmpp", (data) => {
872
+ const peerJid = data.peerJid ?? data.args?.peerJid;
873
+ const callId = data.callId ?? data.args?.callId;
874
+ let xmlPayload = data.xmlPayload ?? data.args?.xmlPayload;
875
+ if (Array.isArray(xmlPayload))
876
+ xmlPayload = new Uint8Array(xmlPayload);
877
+ else if (xmlPayload && typeof xmlPayload === "object" &&
878
+ !(xmlPayload instanceof Uint8Array) && !Buffer.isBuffer(xmlPayload)) {
879
+ xmlPayload = new Uint8Array(xmlPayload);
880
+ }
881
+ callbacks.onSignalingXmpp(peerJid, callId, xmlPayload);
882
+ });
883
+ }
884
+ if (callbacks.onCallEvent) {
885
+ this.#registerGlobalCallbackListener("onCallEvent", (data) => {
886
+ callbacks.onCallEvent(data.eventType, data.eventDataJson);
887
+ });
888
+ }
889
+ if (callbacks.sendDataToRelay) {
890
+ this.#registerGlobalCallbackListener("sendDataToRelay", (data) => {
891
+ let relayData = data.data ?? data.args?.data;
892
+ const ip = data.ip ?? data.args?.ip;
893
+ const portNum = data.port ?? data.args?.port;
894
+ if (relayData instanceof Uint8Array) { /* ok */ }
895
+ else if (Array.isArray(relayData))
896
+ relayData = new Uint8Array(relayData);
897
+ else if (Buffer.isBuffer(relayData))
898
+ relayData = new Uint8Array(relayData);
899
+ else if (relayData && typeof relayData === "object" && relayData.buffer) {
900
+ relayData = new Uint8Array(relayData.buffer, relayData.byteOffset ?? 0, relayData.byteLength ?? relayData.length);
901
+ }
902
+ else if (relayData instanceof ArrayBuffer)
903
+ relayData = new Uint8Array(relayData);
904
+ else
905
+ return 0;
906
+ if (!ip || !portNum)
907
+ return 0;
908
+ callbacks.sendDataToRelay(relayData, ip, portNum);
909
+ return relayData.byteLength;
910
+ });
911
+ }
912
+ };
913
+ #requireModule = (name) => {
914
+ const notifyCallbacks = (callbackName, data) => this.#notifyGlobalCallbackListeners(callbackName, data);
915
+ const EngineWorkerMessagePort = class extends NodeWorkerMessagePort {
916
+ constructor(worker, portName) {
917
+ super(worker, portName, notifyCallbacks);
918
+ }
919
+ };
920
+ const preDefinedModules = {
921
+ Promise,
922
+ WAWebVoipWebWasmWorkerResource: {
923
+ resourcePath: resolveWorkerScriptPath(),
924
+ name: "WAWebVoipWebWasmWorker",
925
+ },
926
+ WorkerBundleResource: {
927
+ createDedicatedWebWorker: (resource) => {
928
+ const scriptPath = resource?.resourcePath && fs.existsSync(resource.resourcePath)
929
+ ? resource.resourcePath
930
+ : resolveWorkerScriptPath();
931
+ const worker = new Worker(scriptPath, {
932
+ stdout: true, stderr: true,
933
+ workerData: {
934
+ wasmPath: this.#config.wasmPath,
935
+ wasmBinary: this.#config.wasmBinary,
936
+ workerModulesCode: this.#workerModulesCode,
937
+ loaderCode: this.#loaderCode,
938
+ loaderModuleName: this.#config.loaderModuleName,
939
+ resourcesPath: this.#config.resourcesPath,
940
+ storageDir: this.#config.storageDir,
941
+ enableLogs: this.#config.enableLogs,
942
+ },
943
+ });
944
+ worker.stdout?.on("data", () => { });
945
+ worker.stderr?.on("data", filterWorkerStderr);
946
+ this.#jsWorkers.add(worker);
947
+ worker.on("exit", () => this.#jsWorkers.delete(worker));
948
+ return worker;
949
+ },
950
+ },
951
+ WorkerClient: { init: () => { } },
952
+ WorkerMessagePort: {
953
+ WorkerMessagePort: EngineWorkerMessagePort,
954
+ CastWorkerMessagePort: (w) => w,
955
+ WorkerSyncedMessagePort: EngineWorkerMessagePort,
956
+ },
957
+ bx: Object.assign((id) => String(id), { getURL: () => "" }),
958
+ HasteSupportData: { handle: () => { } },
959
+ ServiceWorkerDynamicModules: { handle: () => { } },
960
+ WhatsAppWebServiceWorker: { default: true },
961
+ WAWebLogger: { initializeWAWebLogger: () => { } },
962
+ WAWebSw: { initHandlers: () => { } },
963
+ WAWebWamRuntimeProvider: { setWamRuntime: () => { } },
964
+ WAWebWamWorkerInterface: { commit: () => { }, set: () => { } },
965
+ ServerJSDefine: { handleDefine: () => { } },
966
+ ix: { add: () => { } },
967
+ MetaConfigMap: { add: () => { } },
968
+ QPLHasteSupportDataStorage: { default: { add: () => { }, get: () => null } },
969
+ getFalcoLogPolicy_DO_NOT_USE: { add: () => { } },
970
+ gkx: { add: () => { } },
971
+ justknobx: { add: () => { } },
972
+ qex: { add: () => { } },
973
+ };
974
+ if (preDefinedModules[name])
975
+ return preDefinedModules[name];
976
+ const mod = this.#moduleRegistry.get(name);
977
+ if (!mod)
978
+ return {};
979
+ if (mod.exports !== undefined)
980
+ return mod.exports;
981
+ const requireFn = this.#requireModule;
982
+ const normalizeModuleResult = (value) => {
983
+ if (value && typeof value === "object" && "exports" in value && Object.keys(value).length === 1) {
984
+ return value.exports;
985
+ }
986
+ return value;
987
+ };
988
+ const importDefaultFn = (dep) => {
989
+ const v = requireFn(dep);
990
+ return v && v.__esModule ? v.default : v;
991
+ };
992
+ const importAllFn = (dep) => {
993
+ const v = requireFn(dep);
994
+ if (v == null)
995
+ return { default: v };
996
+ if (v.__esModule)
997
+ return v;
998
+ if (typeof v !== "object" && typeof v !== "function")
999
+ return { default: v };
1000
+ const ns = {};
1001
+ for (const key of Object.keys(v))
1002
+ ns[key] = v[key];
1003
+ ns.default = v;
1004
+ return ns;
1005
+ };
1006
+ const tryMetro = () => {
1007
+ const module = { exports: {} };
1008
+ mod.factory(this.#vmContext ?? globalThis, requireFn, importDefaultFn, importAllFn, null, module, module.exports);
1009
+ return normalizeModuleResult(module.exports);
1010
+ };
1011
+ const tryLegacy = () => {
1012
+ const exports = {};
1013
+ const module = { exports };
1014
+ const resolvedDeps = mod.deps.map((dep) => requireFn(dep));
1015
+ mod.factory(this.#vmContext ?? globalThis, requireFn, requireFn, requireFn, module, exports, ...resolvedDeps);
1016
+ return normalizeModuleResult(module.exports);
1017
+ };
1018
+ let result = {};
1019
+ let metroError = null;
1020
+ try {
1021
+ result = tryMetro();
1022
+ }
1023
+ catch (e) {
1024
+ metroError = e;
1025
+ }
1026
+ if (metroError != null || (result && typeof result === "object" && Object.keys(result).length === 0)) {
1027
+ try {
1028
+ const legacyResult = tryLegacy();
1029
+ if (typeof legacyResult === "function" || (legacyResult && Object.keys(legacyResult).length > 0)) {
1030
+ result = legacyResult;
1031
+ }
1032
+ }
1033
+ catch { }
1034
+ }
1035
+ mod.exports = result;
1036
+ return result;
1037
+ };
1038
+ #createVMContext = (memory) => {
1039
+ const callbacks = this.#config.callbacks ?? {};
1040
+ const wasmCallbacks = {
1041
+ onVoipReady: () => {
1042
+ this.#voipReadyResolver?.();
1043
+ callbacks.onVoipReady?.();
1044
+ },
1045
+ onSignalingXmpp: (data) => callbacks.onSignalingXmpp?.(data?.peerJid, data?.callId, data?.xmlPayload),
1046
+ onCallEvent: (data) => callbacks.onCallEvent?.(data?.eventType, data?.eventDataJson),
1047
+ sendDataToRelay: (data) => callbacks.sendDataToRelay?.(data?.data, data?.ip, data?.port),
1048
+ loggingCallback: (data) => {
1049
+ if (!this.#config.enableLogs)
1050
+ return;
1051
+ const level = data?.level;
1052
+ const msg = data?.message ?? "";
1053
+ const mapped = level === 1 ? "error" : level === 2 ? "warn" : level === 3 ? "log" : "debug";
1054
+ callbacks.onLog?.(mapped, msg);
1055
+ },
1056
+ initCaptureDriverJS: (data) => {
1057
+ callbacks.onAudioCaptureInit?.({
1058
+ sampleRate: data?.sample_rate, channels: data?.channels,
1059
+ bitsPerSample: data?.bits_per_sample, framesPerChunk: data?.frames_per_chunk,
1060
+ });
1061
+ return 0;
1062
+ },
1063
+ startCaptureJS: () => { callbacks.onAudioCaptureStart?.(); return 0; },
1064
+ stopCaptureJS: () => { callbacks.onAudioCaptureStop?.(); return 0; },
1065
+ initPlaybackDriverJS: (data) => {
1066
+ callbacks.onAudioPlaybackInit?.({
1067
+ sampleRate: data?.sample_rate, channels: data?.channels,
1068
+ bitsPerSample: data?.bits_per_sample, framesPerChunk: data?.frames_per_chunk,
1069
+ });
1070
+ return 0;
1071
+ },
1072
+ startPlaybackJS: () => {
1073
+ callbacks.onAudioPlaybackStart?.();
1074
+ this.#startAudioPlaybackLoop();
1075
+ return 0;
1076
+ },
1077
+ stopPlaybackJS: () => {
1078
+ this.#stopAudioPlaybackLoop();
1079
+ callbacks.onAudioPlaybackStop?.();
1080
+ return 0;
1081
+ },
1082
+ startVideoCaptureJS: (data) => {
1083
+ callbacks.onVideoCaptureStart?.(normalizeVideoCaptureConfig(data));
1084
+ return 0;
1085
+ },
1086
+ stopVideoCaptureJS: () => {
1087
+ callbacks.onVideoCaptureStop?.();
1088
+ return 0;
1089
+ },
1090
+ startDesktopCaptureJS: (data) => {
1091
+ callbacks.onDesktopCaptureStart?.(normalizeVideoCaptureConfig(data));
1092
+ return 0;
1093
+ },
1094
+ stopDesktopCaptureJS: () => {
1095
+ callbacks.onDesktopCaptureStop?.();
1096
+ return 0;
1097
+ },
1098
+ dataChannelStateCallback: () => 0,
1099
+ getBrowserAudioProcessingStatus: () => 7,
1100
+ getBweModelPath: () => null,
1101
+ videoFrameConsumed: () => {
1102
+ callbacks.onVideoFrameConsumed?.();
1103
+ return 0;
1104
+ },
1105
+ cryptoHkdfExtractWithSaltAndExpand: (data) => {
1106
+ const key = toByteArray(data?.key_);
1107
+ const salt = data?.salt_ ? toByteArray(data.salt_) : new Uint8Array(0);
1108
+ const info = toByteArray(data?.info_);
1109
+ const length = data?.length ?? 32;
1110
+ return callbacks.cryptoHkdf?.(key, salt, info, length) ?? new Uint8Array(length);
1111
+ },
1112
+ hmacSha256KeyGenerator: (data) => {
1113
+ const hmacData = new Uint8Array(data?.data_ ?? []);
1114
+ const hmacKey = new Uint8Array(data?.key_ ?? []);
1115
+ return callbacks.hmacSha256?.(hmacData, hmacKey) ?? new Uint8Array(32);
1116
+ },
1117
+ isParticipantKnownContact: () => true,
1118
+ getPersistentDirectoryPath: () => {
1119
+ const dir = this.#config.storageDir;
1120
+ try {
1121
+ if (!fs.existsSync(dir))
1122
+ fs.mkdirSync(dir, { recursive: true });
1123
+ }
1124
+ catch { }
1125
+ return dir;
1126
+ },
1127
+ };
1128
+ const __d = (name, deps, factory) => {
1129
+ this.#moduleRegistry.set(name, { deps, factory, exports: undefined });
1130
+ };
1131
+ const babelHelpers = {
1132
+ extends: Object.assign,
1133
+ inheritsLoose: (sub, sup) => {
1134
+ sub.prototype = Object.create(sup.prototype);
1135
+ sub.prototype.constructor = sub;
1136
+ sub.__proto__ = sup;
1137
+ },
1138
+ objectWithoutPropertiesLoose: (source, excluded) => {
1139
+ if (source == null)
1140
+ return {};
1141
+ const target = {};
1142
+ for (const key of Object.keys(source)) {
1143
+ if (excluded.indexOf(key) >= 0)
1144
+ continue;
1145
+ target[key] = source[key];
1146
+ }
1147
+ return target;
1148
+ },
1149
+ taggedTemplateLiteralLoose: (strings, raw) => {
1150
+ if (!raw)
1151
+ raw = strings.slice(0);
1152
+ strings.raw = raw;
1153
+ return strings;
1154
+ },
1155
+ wrapNativeSuper: (Class) => Class,
1156
+ };
1157
+ const addRunDependency = (dep) => {
1158
+ if (dep === "loading-workers" && this.#workersLoadedCount >= PTHREAD_POOL_SIZE) {
1159
+ setImmediate(() => this.#removeRunDependencyCallback?.(dep));
1160
+ }
1161
+ };
1162
+ const removeRunDependency = (_dep) => { };
1163
+ this.#removeRunDependencyCallback = removeRunDependency;
1164
+ const webCrypto = {
1165
+ getRandomValues: (arr) => {
1166
+ if (!arr || !ArrayBuffer.isView(arr)) {
1167
+ throw new TypeError("crypto.getRandomValues expects a TypedArray");
1168
+ }
1169
+ const bytes = Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength);
1170
+ randomFillSync(bytes);
1171
+ return arr;
1172
+ },
1173
+ };
1174
+ const selfObj = {
1175
+ __swData: { dynamic_data: { hsdp: {}, dynamic_modules: [] } },
1176
+ WhatsAppVoipWasmCallbacks: wasmCallbacks,
1177
+ WhatsAppVoipWasmWorkerCompatibleCallbacks: wasmCallbacks,
1178
+ crypto: webCrypto,
1179
+ };
1180
+ selfObj.self = selfObj;
1181
+ selfObj.window = selfObj;
1182
+ selfObj.globalThis = selfObj;
1183
+ if (typeof global !== "undefined") {
1184
+ global.WhatsAppVoipWasmCallbacks = wasmCallbacks;
1185
+ global.WhatsAppVoipWasmWorkerCompatibleCallbacks = wasmCallbacks;
1186
+ }
1187
+ const context = vm.createContext({
1188
+ self: selfObj, globalThis: selfObj, global: selfObj, window: selfObj,
1189
+ console, setTimeout, setInterval, clearTimeout, clearInterval,
1190
+ queueMicrotask, performance, babelHelpers, __d,
1191
+ require: this.#requireModule,
1192
+ addRunDependency, removeRunDependency,
1193
+ WebAssembly, SharedArrayBuffer,
1194
+ Atomics: this.#createAtomicsWrapper(memory),
1195
+ Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array,
1196
+ Float32Array, Float64Array, BigInt64Array, BigUint64Array,
1197
+ ArrayBuffer, DataView, Error, TypeError, RangeError, Promise,
1198
+ Map, Set, WeakMap, WeakSet, Symbol, Object, Array, String, Number,
1199
+ Boolean, Math, Date, JSON, RegExp, Function, Proxy, Reflect,
1200
+ crypto: webCrypto,
1201
+ WhatsAppVoipWasmCallbacks: wasmCallbacks,
1202
+ WhatsAppVoipWasmWorkerCompatibleCallbacks: wasmCallbacks,
1203
+ navigator: {
1204
+ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
1205
+ hardwareConcurrency: 4,
1206
+ },
1207
+ process: undefined,
1208
+ document: { currentScript: null },
1209
+ location: { href: "file:///wasm" },
1210
+ Worker: class {
1211
+ constructor() { }
1212
+ postMessage() { }
1213
+ terminate() { }
1214
+ addEventListener() { }
1215
+ },
1216
+ fetch: async () => { throw new Error("fetch not supported"); },
1217
+ XMLHttpRequest: class {
1218
+ open() { }
1219
+ send() { }
1220
+ setRequestHeader() { }
1221
+ },
1222
+ Blob: class {
1223
+ constructor() { }
1224
+ },
1225
+ URL: { createObjectURL: () => "blob:fake", revokeObjectURL: () => { } },
1226
+ Image: class {
1227
+ src = "";
1228
+ onload = null;
1229
+ onerror = null;
1230
+ },
1231
+ Audio: class {
1232
+ src = "";
1233
+ addEventListener() { }
1234
+ },
1235
+ __NODE_PTHREAD: {
1236
+ getUnusedWorker: () => {
1237
+ if (this.#unusedWorkers.length === 0)
1238
+ return null;
1239
+ const worker = this.#unusedWorkers.pop();
1240
+ this.#runningWorkers.push(worker);
1241
+ return worker;
1242
+ },
1243
+ returnWorkerToPool: (worker) => {
1244
+ const idx = this.#runningWorkers.indexOf(worker);
1245
+ if (idx >= 0) {
1246
+ this.#runningWorkers.splice(idx, 1);
1247
+ this.#unusedWorkers.push(worker);
1248
+ }
1249
+ },
1250
+ spawnThread: (params) => {
1251
+ const worker = this.#unusedWorkers.pop();
1252
+ if (!worker)
1253
+ return 6;
1254
+ this.#runningWorkers.push(worker);
1255
+ this.#pthreads[params.pthread_ptr] = worker;
1256
+ worker.pthread_ptr = params.pthread_ptr;
1257
+ const pthreadTable = this.#instance?.PThread?.pthreads;
1258
+ if (pthreadTable)
1259
+ pthreadTable[params.pthread_ptr] = worker;
1260
+ worker.postMessage({
1261
+ cmd: "run",
1262
+ start_routine: params.startRoutine,
1263
+ arg: params.arg,
1264
+ pthread_ptr: params.pthread_ptr,
1265
+ });
1266
+ return 0;
1267
+ },
1268
+ unusedWorkersCount: () => this.#unusedWorkers.length,
1269
+ runningWorkersCount: () => this.#runningWorkers.length,
1270
+ },
1271
+ __IS_NODE_PTHREAD_ENV: true,
1272
+ });
1273
+ context.self = context;
1274
+ context.globalThis = context;
1275
+ context.global = context;
1276
+ context.window = context;
1277
+ return context;
1278
+ };
1279
+ #createAtomicsWrapper = (_memory) => {
1280
+ const atomicsWrapper = {
1281
+ add: Atomics.add.bind(Atomics),
1282
+ and: Atomics.and.bind(Atomics),
1283
+ compareExchange: Atomics.compareExchange.bind(Atomics),
1284
+ exchange: Atomics.exchange.bind(Atomics),
1285
+ isLockFree: Atomics.isLockFree.bind(Atomics),
1286
+ load: Atomics.load.bind(Atomics),
1287
+ or: Atomics.or.bind(Atomics),
1288
+ store: Atomics.store.bind(Atomics),
1289
+ sub: Atomics.sub.bind(Atomics),
1290
+ xor: Atomics.xor.bind(Atomics),
1291
+ notify: (typedArray, index, count) => {
1292
+ try {
1293
+ return Atomics.notify(typedArray, index, count);
1294
+ }
1295
+ catch (e) {
1296
+ if (e?.message?.includes("futex_wake") || e?.message?.includes("main_browser_thread"))
1297
+ return 0;
1298
+ throw e;
1299
+ }
1300
+ },
1301
+ waitAsync: Atomics.waitAsync
1302
+ ? Atomics.waitAsync.bind(Atomics)
1303
+ : () => ({ async: true, value: Promise.resolve("ok") }),
1304
+ wait: (typedArray, index, value, timeout) => {
1305
+ const currentValue = Atomics.load(typedArray, index);
1306
+ if (currentValue !== value)
1307
+ return "not-equal";
1308
+ if (timeout !== undefined && timeout <= 0)
1309
+ return "timed-out";
1310
+ return "timed-out";
1311
+ },
1312
+ [Symbol.toStringTag]: "Atomics",
1313
+ };
1314
+ return atomicsWrapper;
1315
+ };
1316
+ }
1317
+
1318
+ export default WasmEngine;