@nerxa/socketon 0.0.0-stage → 1.21.1

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 (289) hide show
  1. package/EXPERIMENTAL.md +350 -0
  2. package/LICENSE +24 -0
  3. package/README.md +6317 -2
  4. package/WAProto/index.d.ts +17301 -0
  5. package/WAProto/index.js +125088 -0
  6. package/engine-requirements.js +14 -0
  7. package/package.json +125 -4
  8. package/src/Defaults/index.d.ts +152 -0
  9. package/src/Defaults/index.js +164 -0
  10. package/src/MessageBuilder/bot-signature.d.ts +22 -0
  11. package/src/MessageBuilder/bot-signature.js +122 -0
  12. package/src/MessageBuilder/extras.d.ts +449 -0
  13. package/src/MessageBuilder/extras.js +1356 -0
  14. package/src/MessageBuilder/index.d.ts +210 -0
  15. package/src/MessageBuilder/index.js +3594 -0
  16. package/src/MessageBuilder/metaai.d.ts +438 -0
  17. package/src/MessageBuilder/metaai.js +890 -0
  18. package/src/Signal/Group/ciphertext-message.d.ts +9 -0
  19. package/src/Signal/Group/ciphertext-message.js +11 -0
  20. package/src/Signal/Group/group-session-builder.d.ts +7 -0
  21. package/src/Signal/Group/group-session-builder.js +27 -0
  22. package/src/Signal/Group/group_cipher.d.ts +11 -0
  23. package/src/Signal/Group/group_cipher.js +78 -0
  24. package/src/Signal/Group/index.d.ts +11 -0
  25. package/src/Signal/Group/index.js +11 -0
  26. package/src/Signal/Group/keyhelper.d.ts +6 -0
  27. package/src/Signal/Group/keyhelper.js +17 -0
  28. package/src/Signal/Group/sender-chain-key.d.ts +13 -0
  29. package/src/Signal/Group/sender-chain-key.js +25 -0
  30. package/src/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  31. package/src/Signal/Group/sender-key-distribution-message.js +62 -0
  32. package/src/Signal/Group/sender-key-message.d.ts +18 -0
  33. package/src/Signal/Group/sender-key-message.js +65 -0
  34. package/src/Signal/Group/sender-key-name.d.ts +11 -0
  35. package/src/Signal/Group/sender-key-name.js +47 -0
  36. package/src/Signal/Group/sender-key-record.d.ts +12 -0
  37. package/src/Signal/Group/sender-key-record.js +40 -0
  38. package/src/Signal/Group/sender-key-state.d.ts +16 -0
  39. package/src/Signal/Group/sender-key-state.js +83 -0
  40. package/src/Signal/Group/sender-message-key.d.ts +11 -0
  41. package/src/Signal/Group/sender-message-key.js +25 -0
  42. package/src/Signal/libsignal.d.ts +54 -0
  43. package/src/Signal/libsignal.js +427 -0
  44. package/src/Signal/lid-mapping.d.ts +20 -0
  45. package/src/Signal/lid-mapping.js +274 -0
  46. package/src/Socket/Client/index.d.ts +2 -0
  47. package/src/Socket/Client/index.js +3 -0
  48. package/src/Socket/Client/tcp.js +177 -0
  49. package/src/Socket/Client/types.d.ts +5 -0
  50. package/src/Socket/Client/types.js +9 -0
  51. package/src/Socket/Client/websocket.d.ts +12 -0
  52. package/src/Socket/Client/websocket.js +53 -0
  53. package/src/Socket/business.d.ts +431 -0
  54. package/src/Socket/business.js +379 -0
  55. package/src/Socket/chats.d.ts +247 -0
  56. package/src/Socket/chats.js +1484 -0
  57. package/src/Socket/communities.d.ts +598 -0
  58. package/src/Socket/communities.js +421 -0
  59. package/src/Socket/email.js +145 -0
  60. package/src/Socket/groups.d.ts +298 -0
  61. package/src/Socket/groups.js +339 -0
  62. package/src/Socket/index.d.ts +581 -0
  63. package/src/Socket/index.js +77 -0
  64. package/src/Socket/messages-recv.d.ts +370 -0
  65. package/src/Socket/messages-recv.js +1864 -0
  66. package/src/Socket/messages-send.d.ts +390 -0
  67. package/src/Socket/messages-send.js +1574 -0
  68. package/src/Socket/mex.d.ts +1 -0
  69. package/src/Socket/mex.js +44 -0
  70. package/src/Socket/mobile-builders.js +72 -0
  71. package/src/Socket/mobile.js +424 -0
  72. package/src/Socket/newsletter.d.ts +468 -0
  73. package/src/Socket/newsletter.js +671 -0
  74. package/src/Socket/socket.d.ts +77 -0
  75. package/src/Socket/socket.js +1106 -0
  76. package/src/Store/index.d.ts +3 -0
  77. package/src/Store/index.js +3 -0
  78. package/src/Store/make-in-memory-store.d.ts +62 -0
  79. package/src/Store/make-in-memory-store.js +396 -0
  80. package/src/Store/make-ordered-dictionary.d.ts +12 -0
  81. package/src/Store/make-ordered-dictionary.js +78 -0
  82. package/src/Store/object-repository.d.ts +10 -0
  83. package/src/Store/object-repository.js +23 -0
  84. package/src/Types/Auth.d.ts +1 -0
  85. package/src/Types/Auth.js +1 -0
  86. package/src/Types/Bussines.d.ts +1 -0
  87. package/src/Types/Bussines.js +1 -0
  88. package/src/Types/Call.d.ts +1 -0
  89. package/src/Types/Call.js +1 -0
  90. package/src/Types/Chat.d.ts +2 -0
  91. package/src/Types/Chat.js +24 -0
  92. package/src/Types/Contact.d.ts +1 -0
  93. package/src/Types/Contact.js +1 -0
  94. package/src/Types/Events.d.ts +1 -0
  95. package/src/Types/Events.js +0 -0
  96. package/src/Types/GroupMetadata.d.ts +5 -0
  97. package/src/Types/GroupMetadata.js +6 -0
  98. package/src/Types/Label.d.ts +2 -0
  99. package/src/Types/Label.js +24 -0
  100. package/src/Types/LabelAssociation.d.ts +2 -0
  101. package/src/Types/LabelAssociation.js +6 -0
  102. package/src/Types/Message.d.ts +13 -0
  103. package/src/Types/Message.js +23 -0
  104. package/src/Types/Mex.d.ts +2 -0
  105. package/src/Types/Mex.js +95 -0
  106. package/src/Types/Product.d.ts +1 -0
  107. package/src/Types/Product.js +1 -0
  108. package/src/Types/Signal.d.ts +1 -0
  109. package/src/Types/Signal.js +0 -0
  110. package/src/Types/Socket.d.ts +1 -0
  111. package/src/Types/Socket.js +0 -0
  112. package/src/Types/State.d.ts +5 -0
  113. package/src/Types/State.js +54 -0
  114. package/src/Types/USync.d.ts +1 -0
  115. package/src/Types/USync.js +0 -0
  116. package/src/Types/index.d.ts +13 -0
  117. package/src/Types/index.js +25 -0
  118. package/src/Utils/auth-store.d.ts +29 -0
  119. package/src/Utils/auth-store.js +76 -0
  120. package/src/Utils/auth-utils.d.ts +58 -0
  121. package/src/Utils/auth-utils.js +273 -0
  122. package/src/Utils/browser-utils.d.ts +9 -0
  123. package/src/Utils/browser-utils.js +28 -0
  124. package/src/Utils/business.d.ts +49 -0
  125. package/src/Utils/business.js +226 -0
  126. package/src/Utils/chat-utils.d.ts +408 -0
  127. package/src/Utils/chat-utils.js +846 -0
  128. package/src/Utils/companion-reg-client-utils.d.ts +4 -0
  129. package/src/Utils/companion-reg-client-utils.js +39 -0
  130. package/src/Utils/crypto.d.ts +39 -0
  131. package/src/Utils/crypto.js +110 -0
  132. package/src/Utils/decode-wa-message.d.ts +99 -0
  133. package/src/Utils/decode-wa-message.js +373 -0
  134. package/src/Utils/event-buffer.d.ts +22 -0
  135. package/src/Utils/event-buffer.js +624 -0
  136. package/src/Utils/generics.d.ts +63 -0
  137. package/src/Utils/generics.js +375 -0
  138. package/src/Utils/group-metadata-cache.d.ts +4 -0
  139. package/src/Utils/group-metadata-cache.js +25 -0
  140. package/src/Utils/history.d.ts +75 -0
  141. package/src/Utils/history.js +131 -0
  142. package/src/Utils/html-app.d.ts +19 -0
  143. package/src/Utils/html-app.js +96 -0
  144. package/src/Utils/html-multiplayer.d.ts +10 -0
  145. package/src/Utils/html-multiplayer.js +94 -0
  146. package/src/Utils/identity-change-handler.d.ts +13 -0
  147. package/src/Utils/identity-change-handler.js +48 -0
  148. package/src/Utils/index.d.ts +44 -0
  149. package/src/Utils/index.js +44 -0
  150. package/src/Utils/link-preview-metadata.d.ts +47 -0
  151. package/src/Utils/link-preview-metadata.js +88 -0
  152. package/src/Utils/link-preview.d.ts +12 -0
  153. package/src/Utils/link-preview.js +79 -0
  154. package/src/Utils/logger.d.ts +2 -0
  155. package/src/Utils/logger.js +2 -0
  156. package/src/Utils/lt-hash.d.ts +6 -0
  157. package/src/Utils/lt-hash.js +3 -0
  158. package/src/Utils/make-mutex.d.ts +6 -0
  159. package/src/Utils/make-mutex.js +32 -0
  160. package/src/Utils/message-retry-manager.d.ts +79 -0
  161. package/src/Utils/message-retry-manager.js +255 -0
  162. package/src/Utils/messages-media.d.ts +136 -0
  163. package/src/Utils/messages-media.js +814 -0
  164. package/src/Utils/messages.d.ts +62 -0
  165. package/src/Utils/messages.js +2223 -0
  166. package/src/Utils/mobile-companion-crypto.js +191 -0
  167. package/src/Utils/modern-messages.d.ts +150 -0
  168. package/src/Utils/modern-messages.js +496 -0
  169. package/src/Utils/native-flow.d.ts +11 -0
  170. package/src/Utils/native-flow.js +115 -0
  171. package/src/Utils/newsletter-status.d.ts +158 -0
  172. package/src/Utils/newsletter-status.js +651 -0
  173. package/src/Utils/noise-handler.d.ts +20 -0
  174. package/src/Utils/noise-handler.js +200 -0
  175. package/src/Utils/offline-node-processor.d.ts +9 -0
  176. package/src/Utils/offline-node-processor.js +33 -0
  177. package/src/Utils/optional-media.d.ts +3 -0
  178. package/src/Utils/optional-media.js +45 -0
  179. package/src/Utils/payment-messages.d.ts +66 -0
  180. package/src/Utils/payment-messages.js +160 -0
  181. package/src/Utils/pre-key-manager.d.ts +25 -0
  182. package/src/Utils/pre-key-manager.js +95 -0
  183. package/src/Utils/process-message.d.ts +60 -0
  184. package/src/Utils/process-message.js +688 -0
  185. package/src/Utils/reporting-utils.d.ts +12 -0
  186. package/src/Utils/reporting-utils.js +256 -0
  187. package/src/Utils/scheduled-message.d.ts +51 -0
  188. package/src/Utils/scheduled-message.js +112 -0
  189. package/src/Utils/sender-key-memory.d.ts +19 -0
  190. package/src/Utils/sender-key-memory.js +51 -0
  191. package/src/Utils/signal.d.ts +82 -0
  192. package/src/Utils/signal.js +193 -0
  193. package/src/Utils/stanza-ack.d.ts +16 -0
  194. package/src/Utils/stanza-ack.js +30 -0
  195. package/src/Utils/status-stickers.d.ts +127 -0
  196. package/src/Utils/status-stickers.js +260 -0
  197. package/src/Utils/sync-action-utils.d.ts +2 -0
  198. package/src/Utils/sync-action-utils.js +44 -0
  199. package/src/Utils/tc-token-utils.d.ts +29 -0
  200. package/src/Utils/tc-token-utils.js +155 -0
  201. package/src/Utils/ttl-cache.d.ts +28 -0
  202. package/src/Utils/ttl-cache.js +120 -0
  203. package/src/Utils/use-mongo-auth-state.d.ts +21 -0
  204. package/src/Utils/use-mongo-auth-state.js +67 -0
  205. package/src/Utils/use-multi-file-auth-state.d.ts +11 -0
  206. package/src/Utils/use-multi-file-auth-state.js +106 -0
  207. package/src/Utils/use-mysql-auth-state.d.ts +19 -0
  208. package/src/Utils/use-mysql-auth-state.js +79 -0
  209. package/src/Utils/use-postgres-auth-state.d.ts +19 -0
  210. package/src/Utils/use-postgres-auth-state.js +79 -0
  211. package/src/Utils/use-redis-auth-state.d.ts +19 -0
  212. package/src/Utils/use-redis-auth-state.js +89 -0
  213. package/src/Utils/use-single-file-auth-state.d.ts +10 -0
  214. package/src/Utils/use-single-file-auth-state.js +108 -0
  215. package/src/Utils/use-sqlite-auth-state.d.ts +12 -0
  216. package/src/Utils/use-sqlite-auth-state.js +120 -0
  217. package/src/Utils/useNekoDBAuth.d.ts +19 -0
  218. package/src/Utils/useNekoDBAuth.js +111 -0
  219. package/src/Utils/username.d.ts +12 -0
  220. package/src/Utils/username.js +58 -0
  221. package/src/Utils/validate-connection.d.ts +43 -0
  222. package/src/Utils/validate-connection.js +277 -0
  223. package/src/Utils/voice-recognition.d.ts +53 -0
  224. package/src/Utils/voice-recognition.js +219 -0
  225. package/src/Voip/audio-feeder.d.ts +24 -0
  226. package/src/Voip/audio-feeder.js +268 -0
  227. package/src/Voip/index.d.ts +88 -0
  228. package/src/Voip/index.js +936 -0
  229. package/src/Voip/relay-transport.d.ts +5 -0
  230. package/src/Voip/relay-transport.js +824 -0
  231. package/src/Voip/signaling.d.ts +11 -0
  232. package/src/Voip/signaling.js +1099 -0
  233. package/src/Voip/types.d.ts +2 -0
  234. package/src/Voip/types.js +12 -0
  235. package/src/Voip/video-feeder.d.ts +24 -0
  236. package/src/Voip/video-feeder.js +268 -0
  237. package/src/Voip/wasm-engine.d.ts +26 -0
  238. package/src/Voip/wasm-engine.js +1307 -0
  239. package/src/Voip/worker-bootstrap.js +1023 -0
  240. package/src/WABinary/constants.d.ts +22 -0
  241. package/src/WABinary/constants.js +1300 -0
  242. package/src/WABinary/decode.d.ts +9 -0
  243. package/src/WABinary/decode.js +261 -0
  244. package/src/WABinary/encode.d.ts +2 -0
  245. package/src/WABinary/encode.js +219 -0
  246. package/src/WABinary/generic-utils.d.ts +76 -0
  247. package/src/WABinary/generic-utils.js +214 -0
  248. package/src/WABinary/index.d.ts +5 -0
  249. package/src/WABinary/index.js +5 -0
  250. package/src/WABinary/jid-utils.d.ts +30 -0
  251. package/src/WABinary/jid-utils.js +97 -0
  252. package/src/WABinary/types.d.ts +1 -0
  253. package/src/WABinary/types.js +0 -0
  254. package/src/WAM/BinaryInfo.d.ts +7 -0
  255. package/src/WAM/BinaryInfo.js +9 -0
  256. package/src/WAM/constants.d.ts +34926 -0
  257. package/src/WAM/constants.js +22852 -0
  258. package/src/WAM/encode.d.ts +1 -0
  259. package/src/WAM/encode.js +148 -0
  260. package/src/WAM/index.d.ts +3 -0
  261. package/src/WAM/index.js +3 -0
  262. package/src/WAUSync/Protocols/USyncContactProtocol.d.ts +36 -0
  263. package/src/WAUSync/Protocols/USyncContactProtocol.js +50 -0
  264. package/src/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  265. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +51 -0
  266. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  267. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +26 -0
  268. package/src/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  269. package/src/WAUSync/Protocols/USyncStatusProtocol.js +37 -0
  270. package/src/WAUSync/Protocols/USyncUsernameProtocol.d.ts +9 -0
  271. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +23 -0
  272. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +38 -0
  273. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.js +49 -0
  274. package/src/WAUSync/Protocols/UsyncLIDProtocol.d.ts +14 -0
  275. package/src/WAUSync/Protocols/UsyncLIDProtocol.js +28 -0
  276. package/src/WAUSync/Protocols/index.d.ts +5 -0
  277. package/src/WAUSync/Protocols/index.js +5 -0
  278. package/src/WAUSync/USyncQuery.d.ts +20 -0
  279. package/src/WAUSync/USyncQuery.js +93 -0
  280. package/src/WAUSync/USyncUser.d.ts +16 -0
  281. package/src/WAUSync/USyncUser.js +30 -0
  282. package/src/WAUSync/index.d.ts +3 -0
  283. package/src/WAUSync/index.js +3 -0
  284. package/src/assets/wasm/README.md +76 -0
  285. package/src/assets/wasm/loader.js +5 -0
  286. package/src/assets/wasm/whatsapp.wasm +0 -0
  287. package/src/assets/wasm/worker-modules.js +273 -0
  288. package/src/index.d.ts +43 -0
  289. package/src/index.js +48 -0
@@ -0,0 +1,375 @@
1
+ import { Boom } from '@hapi/boom';
2
+ import { createHash, randomBytes, randomFillSync } from 'crypto';
3
+ import { proto } from '../../WAProto/index.js';
4
+ const baileysVersion = [2, 3000, 1051456098];
5
+ import { DisconnectReason } from '../Types/index.js';
6
+ import { getAllBinaryNodeChildren } from '../WABinary/index.js';
7
+ import { sha256 } from './crypto.js';
8
+ export const BufferJSON = {
9
+
10
+ replacer: (k, value) => {
11
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
12
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
13
+ }
14
+ return value;
15
+ },
16
+
17
+ reviver: (_, value) => {
18
+ if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
19
+ return Buffer.from(value.data, 'base64');
20
+ }
21
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
22
+ const keys = Object.keys(value);
23
+ if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
24
+ const values = Object.values(value);
25
+ if (values.every(v => typeof v === 'number')) {
26
+ return Buffer.from(values);
27
+ }
28
+ }
29
+ }
30
+ return value;
31
+ }
32
+ };
33
+ export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || '';
34
+ export const isStringNullOrEmpty = (value) =>
35
+
36
+ value == null || value === '';
37
+ export const writeRandomPadMax16 = (msg) => {
38
+ const pad = randomBytes(1);
39
+ const padLength = (pad[0] & 0x0f) + 1;
40
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
41
+ };
42
+ export const unpadRandomMax16 = (e) => {
43
+ const t = new Uint8Array(e);
44
+ if (0 === t.length) {
45
+ throw new Error('unpadPkcs7 given empty bytes');
46
+ }
47
+ var r = t[t.length - 1];
48
+ if (r > t.length) {
49
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
50
+ }
51
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
52
+ };
53
+
54
+ export const generateParticipantHashV2 = (participants) => {
55
+ participants.sort();
56
+ const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64');
57
+ return '2:' + sha256Hash.slice(0, 6);
58
+ };
59
+ export const encodeWAMessage = (message) => writeRandomPadMax16(proto.Message.encode(message).finish());
60
+ export const generateRegistrationId = () => {
61
+ return Uint16Array.from(randomBytes(2))[0] & 16383;
62
+ };
63
+ export const encodeBigEndian = (e, t = 4) => {
64
+ let r = e;
65
+ const a = new Uint8Array(t);
66
+ for (let i = t - 1; i >= 0; i--) {
67
+ a[i] = 255 & r;
68
+ r >>>= 8;
69
+ }
70
+ return a;
71
+ };
72
+ export const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
73
+
74
+ export const unixTimestampSeconds = (date = new Date()) => date.getTime() / 1000 | 0;
75
+ export const debouncedTimeout = (intervalMs = 1000, task) => {
76
+ let timeout;
77
+ return {
78
+ start: (newIntervalMs, newTask) => {
79
+ task = newTask || task;
80
+ intervalMs = newIntervalMs || intervalMs;
81
+ timeout && clearTimeout(timeout);
82
+ timeout = setTimeout(() => task?.(), intervalMs);
83
+ },
84
+ cancel: () => {
85
+ timeout && clearTimeout(timeout);
86
+ timeout = undefined;
87
+ },
88
+ setTask: (newTask) => (task = newTask),
89
+ setInterval: (newInterval) => (intervalMs = newInterval)
90
+ };
91
+ };
92
+ export const delay = (ms) => delayCancellable(ms).delay;
93
+ export const delayCancellable = (ms) => {
94
+ const stack = new Error().stack;
95
+ let timeout;
96
+ let reject;
97
+ const delay = new Promise((resolve, _reject) => {
98
+ timeout = setTimeout(resolve, ms);
99
+ reject = _reject;
100
+ });
101
+ const cancel = () => {
102
+ clearTimeout(timeout);
103
+ reject(new Boom('Cancelled', {
104
+ statusCode: 500,
105
+ data: {
106
+ stack
107
+ }
108
+ }));
109
+ };
110
+ return { delay, cancel };
111
+ };
112
+ export async function promiseTimeout(ms, promise) {
113
+ if (!ms) {
114
+ return new Promise(promise);
115
+ }
116
+ const stack = new Error().stack;
117
+
118
+ const { delay, cancel } = delayCancellable(ms);
119
+ const p = new Promise((resolve, reject) => {
120
+ delay
121
+ .then(() => reject(new Boom('Timed Out', {
122
+ statusCode: DisconnectReason.timedOut,
123
+ data: {
124
+ stack
125
+ }
126
+ })))
127
+ .catch(err => reject(err));
128
+ promise(resolve, reject);
129
+ }).finally(cancel);
130
+ return p;
131
+ }
132
+
133
+ export const generateMessageIDV2 = (userId) => {
134
+ const data = Buffer.allocUnsafe(44);
135
+ data.writeBigUInt64BE(BigInt(Date.now() / 1000 | 0), 0);
136
+ if (userId) {
137
+ const userStr = userId.split('@')[0].split(':')[0];
138
+ if (userStr) {
139
+ const len = data.write(userStr, 8);
140
+ data.write('@c.us', 8 + len);
141
+ }
142
+ }
143
+ randomFillSync(data, 28, 16);
144
+ const hash = createHash('sha256').update(data).digest();
145
+ return '3EB0' + hash.toString('hex', 0, 9).toUpperCase();
146
+ };
147
+
148
+ export const generateMessageID = () => '3EB0' + randomBytes(8).toString('hex').toUpperCase();
149
+ export function bindWaitForEvent(ev, event) {
150
+ return async (check, timeoutMs) => {
151
+ let listener;
152
+ let closeListener;
153
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
154
+ closeListener = ({ connection, lastDisconnect }) => {
155
+ if (connection === 'close') {
156
+ reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
157
+ }
158
+ };
159
+ ev.on('connection.update', closeListener);
160
+ listener = async (update) => {
161
+ if (await check(update)) {
162
+ resolve();
163
+ }
164
+ };
165
+ ev.on(event, listener);
166
+ }).finally(() => {
167
+ ev.off(event, listener);
168
+ ev.off('connection.update', closeListener);
169
+ });
170
+ };
171
+ }
172
+ export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
173
+
174
+ export const fetchLatestBaileysVersion = async (options = {}) => {
175
+ const URL = 'https://raw.githubusercontent.com/noxXza/luna-baileys/main/src/Defaults/index.js';
176
+ try {
177
+ const response = await fetch(URL, {
178
+ dispatcher: options.dispatcher,
179
+ method: 'GET',
180
+ headers: options.headers
181
+ });
182
+ if (!response.ok) {
183
+ throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
184
+ }
185
+ const text = await response.text();
186
+
187
+ const lines = text.split('\n');
188
+ const versionLine = lines[4];
189
+ const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
190
+ if (versionMatch) {
191
+ const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
192
+ return {
193
+ version,
194
+ isLatest: true
195
+ };
196
+ }
197
+ else {
198
+ throw new Error('Could not parse version from Defaults/index.ts');
199
+ }
200
+ }
201
+ catch (error) {
202
+ return {
203
+ version: baileysVersion,
204
+ isLatest: false,
205
+ error
206
+ };
207
+ }
208
+ };
209
+
210
+ export const fetchLatestWaWebVersion = async (options = {}) => {
211
+ try {
212
+
213
+ const defaultHeaders = {
214
+ 'sec-fetch-site': 'none',
215
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
216
+ };
217
+ const headers = { ...defaultHeaders, ...options.headers };
218
+ const response = await fetch('https://web.whatsapp.com/sw.js', {
219
+ ...options,
220
+ method: 'GET',
221
+ headers
222
+ });
223
+ if (!response.ok) {
224
+ throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
225
+ }
226
+ const data = await response.text();
227
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
228
+ const match = data.match(regex);
229
+ if (!match?.[1]) {
230
+ return {
231
+ version: baileysVersion,
232
+ isLatest: false,
233
+ error: {
234
+ message: 'Could not find client revision in the fetched content'
235
+ }
236
+ };
237
+ }
238
+ const clientRevision = match[1];
239
+ return {
240
+ version: [2, 3000, +clientRevision],
241
+ isLatest: true
242
+ };
243
+ }
244
+ catch (error) {
245
+ return {
246
+ version: baileysVersion,
247
+ isLatest: false,
248
+ error
249
+ };
250
+ }
251
+ };
252
+
253
+ export const generateMdTagPrefix = () => {
254
+ const bytes = randomBytes(4);
255
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
256
+ };
257
+ const STATUS_MAP = {
258
+ sender: proto.WebMessageInfo.Status.SERVER_ACK,
259
+ played: proto.WebMessageInfo.Status.PLAYED,
260
+ read: proto.WebMessageInfo.Status.READ,
261
+ 'read-self': proto.WebMessageInfo.Status.READ
262
+ };
263
+
264
+ export const getStatusFromReceiptType = (type) => {
265
+ const status = STATUS_MAP[type];
266
+ if (typeof type === 'undefined') {
267
+ return proto.WebMessageInfo.Status.DELIVERY_ACK;
268
+ }
269
+ return status;
270
+ };
271
+ const CODE_MAP = {
272
+ conflict: DisconnectReason.connectionReplaced
273
+ };
274
+
275
+ export const getErrorCodeFromStreamError = (node) => {
276
+ const [reasonNode] = getAllBinaryNodeChildren(node);
277
+ let reason = reasonNode?.tag || 'unknown';
278
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
279
+ if (statusCode === DisconnectReason.restartRequired) {
280
+ reason = 'restart required';
281
+ }
282
+ return {
283
+ reason,
284
+ statusCode
285
+ };
286
+ };
287
+ export const getCallStatusFromNode = ({ tag, attrs }) => {
288
+ let status;
289
+ switch (tag) {
290
+ case 'offer':
291
+ case 'offer_notice':
292
+ status = 'offer';
293
+ break;
294
+ case 'terminate':
295
+ if (attrs.reason === 'timeout') {
296
+ status = 'timeout';
297
+ }
298
+ else {
299
+
300
+ status = 'terminate';
301
+ }
302
+ break;
303
+ case 'preaccept':
304
+ status = 'preaccept';
305
+ break;
306
+ case 'transport':
307
+ status = 'transport';
308
+ break;
309
+ case 'relaylatency':
310
+ status = 'relaylatency';
311
+ break;
312
+ case 'reject':
313
+ status = 'reject';
314
+ break;
315
+ case 'accept':
316
+ status = 'accept';
317
+ break;
318
+ default:
319
+ status = 'ringing';
320
+ break;
321
+ }
322
+ return status;
323
+ };
324
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
325
+ export const getCodeFromWSError = (error) => {
326
+ let statusCode = 500;
327
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
328
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
329
+ if (!Number.isNaN(code) && code >= 400) {
330
+ statusCode = code;
331
+ }
332
+ }
333
+ else if (
334
+
335
+ error?.code?.startsWith('E') ||
336
+ error?.message?.includes('timed out')) {
337
+
338
+ statusCode = 408;
339
+ }
340
+ return statusCode;
341
+ };
342
+
343
+ export const isWABusinessPlatform = (platform) => {
344
+ return platform === 'smbi' || platform === 'smba';
345
+ };
346
+
347
+ export function trimUndefined(obj) {
348
+ for (const key in obj) {
349
+ if (typeof obj[key] === 'undefined') {
350
+ delete obj[key];
351
+ }
352
+ }
353
+ return obj;
354
+ }
355
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
356
+ export function bytesToCrockford(buffer) {
357
+ let value = 0;
358
+ let bitCount = 0;
359
+ const crockford = [];
360
+ for (const element of buffer) {
361
+ value = (value << 8) | (element & 0xff);
362
+ bitCount += 8;
363
+ while (bitCount >= 5) {
364
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
365
+ bitCount -= 5;
366
+ }
367
+ }
368
+ if (bitCount > 0) {
369
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
370
+ }
371
+ return crockford.join('');
372
+ }
373
+ export function encodeNewsletterMessage(message) {
374
+ return proto.Message.encode(message).finish();
375
+ }
@@ -0,0 +1,4 @@
1
+
2
+ export declare const GROUP_ADDRESSING_MODES: readonly string[]
3
+ export declare function isUsableGroupMetadata(metadata: any): boolean
4
+ export declare function describeUnusableGroupMetadata(metadata: any): string
@@ -0,0 +1,25 @@
1
+
2
+ export const GROUP_ADDRESSING_MODES = Object.freeze(['pn', 'lid'])
3
+
4
+ export const isUsableGroupMetadata = metadata => {
5
+ if (!metadata || typeof metadata !== 'object') {
6
+ return false
7
+ }
8
+ if (!Array.isArray(metadata.participants)) {
9
+ return false
10
+ }
11
+ return GROUP_ADDRESSING_MODES.includes(metadata.addressingMode)
12
+ }
13
+
14
+ export const describeUnusableGroupMetadata = metadata => {
15
+ if (!metadata || typeof metadata !== 'object') {
16
+ return 'nothing cached'
17
+ }
18
+ if (!Array.isArray(metadata.participants)) {
19
+ return 'no participants'
20
+ }
21
+ if (metadata.addressingMode === undefined || metadata.addressingMode === null) {
22
+ return 'no addressingMode'
23
+ }
24
+ return `addressingMode ${JSON.stringify(metadata.addressingMode)} is not pn or lid`
25
+ }
@@ -0,0 +1,75 @@
1
+ export function downloadHistory(msg: any, options: any): Promise<proto.HistorySync>;
2
+ export function processHistoryMessage(item: any, logger: any): {
3
+ chats: any[];
4
+ contacts: ({
5
+ id: any;
6
+ name: any;
7
+ username: any;
8
+ lid: any;
9
+ phoneNumber: any;
10
+ verifiedName?: undefined;
11
+ notify?: undefined;
12
+ } | {
13
+ id: any;
14
+ verifiedName: any;
15
+ name?: undefined;
16
+ username?: undefined;
17
+ lid?: undefined;
18
+ phoneNumber?: undefined;
19
+ notify?: undefined;
20
+ } | {
21
+ id: any;
22
+ notify: any;
23
+ name?: undefined;
24
+ username?: undefined;
25
+ lid?: undefined;
26
+ phoneNumber?: undefined;
27
+ verifiedName?: undefined;
28
+ })[];
29
+ messages: any[];
30
+ lidPnMappings: {
31
+ lid: any;
32
+ pn: any;
33
+ }[];
34
+ pastParticipants: any;
35
+ syncType: any;
36
+ progress: any;
37
+ };
38
+ export function downloadAndProcessHistorySyncNotification(msg: any, options: any, logger: any): Promise<{
39
+ chats: any[];
40
+ contacts: ({
41
+ id: any;
42
+ name: any;
43
+ username: any;
44
+ lid: any;
45
+ phoneNumber: any;
46
+ verifiedName?: undefined;
47
+ notify?: undefined;
48
+ } | {
49
+ id: any;
50
+ verifiedName: any;
51
+ name?: undefined;
52
+ username?: undefined;
53
+ lid?: undefined;
54
+ phoneNumber?: undefined;
55
+ notify?: undefined;
56
+ } | {
57
+ id: any;
58
+ notify: any;
59
+ name?: undefined;
60
+ username?: undefined;
61
+ lid?: undefined;
62
+ phoneNumber?: undefined;
63
+ verifiedName?: undefined;
64
+ })[];
65
+ messages: any[];
66
+ lidPnMappings: {
67
+ lid: any;
68
+ pn: any;
69
+ }[];
70
+ pastParticipants: any;
71
+ syncType: any;
72
+ progress: any;
73
+ }>;
74
+ export function getHistoryMsg(message: any): any;
75
+ import { proto } from '../../WAProto/index.js';
@@ -0,0 +1,131 @@
1
+ import { pipeline } from 'stream/promises';
2
+ import { promisify } from 'util';
3
+ import { createInflate, inflate } from 'zlib';
4
+ import { proto } from '../../WAProto/index.js';
5
+ import { WAMessageStubType } from '../Types/index.js';
6
+ import { isHostedLidUser, isHostedPnUser, isLidUser, isPnUser } from '../WABinary/index.js';
7
+ import { toNumber } from './generics.js';
8
+ import { normalizeMessageContent } from './messages.js';
9
+ import { downloadContentFromMessage } from './messages-media.js';
10
+ const inflatePromise = promisify(inflate);
11
+ const extractPnFromMessages = (messages) => {
12
+ for (const msgItem of messages) {
13
+ const message = msgItem.message;
14
+
15
+ if (!message?.key?.fromMe || !message.userReceipt?.length) {
16
+ continue;
17
+ }
18
+ const userJid = message.userReceipt[0]?.userJid;
19
+ if (userJid && (isPnUser(userJid) || isHostedPnUser(userJid))) {
20
+ return userJid;
21
+ }
22
+ }
23
+ return undefined;
24
+ };
25
+ export const downloadHistory = async (msg, options) => {
26
+ const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options });
27
+
28
+ const inflater = createInflate();
29
+ const chunks = [];
30
+ inflater.on('data', (chunk) => chunks.push(chunk));
31
+ await pipeline(stream, inflater);
32
+ const buffer = Buffer.concat(chunks);
33
+ const syncData = proto.HistorySync.decode(buffer);
34
+ return syncData;
35
+ };
36
+ export const processHistoryMessage = (item, logger) => {
37
+ const messages = [];
38
+ const contacts = [];
39
+ const chats = [];
40
+ const lidPnMappings = [];
41
+ logger?.trace({ progress: item.progress }, 'processing history of type ' + item.syncType?.toString());
42
+
43
+ for (const m of item.phoneNumberToLidMappings || []) {
44
+ if (m.lidJid && m.pnJid) {
45
+ lidPnMappings.push({ lid: m.lidJid, pn: m.pnJid });
46
+ }
47
+ }
48
+ switch (item.syncType) {
49
+ case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
50
+ case proto.HistorySync.HistorySyncType.RECENT:
51
+ case proto.HistorySync.HistorySyncType.FULL:
52
+ case proto.HistorySync.HistorySyncType.ON_DEMAND:
53
+ for (const chat of item.conversations) {
54
+ contacts.push({
55
+ id: chat.id,
56
+ name: chat.displayName || chat.name || chat.username || undefined,
57
+ username: chat.username || undefined,
58
+ lid: chat.lidJid || chat.accountLid || undefined,
59
+ phoneNumber: chat.pnJid || undefined
60
+ });
61
+ const chatId = chat.id;
62
+ const isLid = isLidUser(chatId) || isHostedLidUser(chatId);
63
+ const isPn = isPnUser(chatId) || isHostedPnUser(chatId);
64
+ if (isLid && chat.pnJid) {
65
+ lidPnMappings.push({ lid: chatId, pn: chat.pnJid });
66
+ }
67
+ else if (isPn && chat.lidJid) {
68
+ lidPnMappings.push({ lid: chat.lidJid, pn: chatId });
69
+ }
70
+ else if (isLid && !chat.pnJid) {
71
+
72
+ const pnFromReceipt = extractPnFromMessages(chat.messages || []);
73
+ if (pnFromReceipt) {
74
+ lidPnMappings.push({ lid: chatId, pn: pnFromReceipt });
75
+ }
76
+ }
77
+ const msgs = chat.messages || [];
78
+ delete chat.messages;
79
+ for (const item of msgs) {
80
+ const message = item.message;
81
+ messages.push(message);
82
+ if (!chat.messages?.length) {
83
+
84
+ chat.messages = [{ message }];
85
+ }
86
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
87
+ chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp);
88
+ }
89
+ if ((message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
90
+ message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
91
+ message.messageStubParameters?.[0]) {
92
+ contacts.push({
93
+ id: message.key.participant || message.key.remoteJid,
94
+ verifiedName: message.messageStubParameters?.[0]
95
+ });
96
+ }
97
+ }
98
+ chats.push(chat);
99
+ }
100
+ break;
101
+ case proto.HistorySync.HistorySyncType.PUSH_NAME:
102
+ for (const c of item.pushnames) {
103
+ contacts.push({ id: c.id, notify: c.pushname });
104
+ }
105
+ break;
106
+ }
107
+ return {
108
+ chats,
109
+ contacts,
110
+ messages,
111
+ lidPnMappings,
112
+ pastParticipants: item.pastParticipants,
113
+ syncType: item.syncType,
114
+ progress: item.progress
115
+ };
116
+ };
117
+ export const downloadAndProcessHistorySyncNotification = async (msg, options, logger) => {
118
+ let historyMsg;
119
+ if (msg.initialHistBootstrapInlinePayload) {
120
+ historyMsg = proto.HistorySync.decode(await inflatePromise(msg.initialHistBootstrapInlinePayload));
121
+ }
122
+ else {
123
+ historyMsg = await downloadHistory(msg, options);
124
+ }
125
+ return processHistoryMessage(historyMsg, logger);
126
+ };
127
+ export const getHistoryMsg = (message) => {
128
+ const normalizedContent = !!message ? normalizeMessageContent(message) : undefined;
129
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
130
+ return anyHistoryMsg;
131
+ };
@@ -0,0 +1,19 @@
1
+ export declare const HTML_APP_MESSAGE_CEILING: number
2
+ export declare const HTML_APP_BYTE_BUDGET: number
3
+ export declare const HTML_APP_BYTE_LIMIT: number
4
+
5
+ export declare function wireBytes(html: string): number
6
+
7
+ export interface HtmlAppReport {
8
+ ok: boolean
9
+ bytes: number
10
+ wireBytes: number
11
+ embeddedBytes: number
12
+ problems: string[]
13
+ warnings: string[]
14
+ }
15
+
16
+ export declare function checkHtmlApp(html: string, options?: {
17
+ height?: number
18
+ maxBytes?: number
19
+ }): HtmlAppReport