@realvare/baileys 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/LICENSE +41 -0
  2. package/README.MD +2227 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +5604 -0
  5. package/WAProto/index.d.ts +63156 -0
  6. package/WAProto/index.js +195638 -0
  7. package/WAProto/p.html +1 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/baileys-version.json +3 -0
  10. package/lib/Defaults/index.d.ts +53 -0
  11. package/lib/Defaults/index.js +108 -0
  12. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  13. package/lib/Signal/Group/ciphertext-message.js +15 -0
  14. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  15. package/lib/Signal/Group/group-session-builder.js +64 -0
  16. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  17. package/lib/Signal/Group/group_cipher.js +96 -0
  18. package/lib/Signal/Group/index.d.ts +11 -0
  19. package/lib/Signal/Group/index.js +57 -0
  20. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  21. package/lib/Signal/Group/keyhelper.js +55 -0
  22. package/lib/Signal/Group/queue-job.d.ts +1 -0
  23. package/lib/Signal/Group/queue-job.js +57 -0
  24. package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
  25. package/lib/Signal/Group/sender-chain-key.js +34 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  28. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  29. package/lib/Signal/Group/sender-key-message.js +69 -0
  30. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  31. package/lib/Signal/Group/sender-key-name.js +51 -0
  32. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  33. package/lib/Signal/Group/sender-key-record.js +53 -0
  34. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  35. package/lib/Signal/Group/sender-key-state.js +99 -0
  36. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  37. package/lib/Signal/Group/sender-message-key.js +29 -0
  38. package/lib/Signal/libsignal.d.ts +3 -0
  39. package/lib/Signal/libsignal.js +174 -0
  40. package/lib/Socket/Client/index.d.ts +2 -0
  41. package/lib/Socket/Client/index.js +18 -0
  42. package/lib/Socket/Client/types.d.ts +16 -0
  43. package/lib/Socket/Client/types.js +13 -0
  44. package/lib/Socket/Client/websocket.d.ts +13 -0
  45. package/lib/Socket/Client/websocket.js +111 -0
  46. package/lib/Socket/business.d.ts +172 -0
  47. package/lib/Socket/business.js +260 -0
  48. package/lib/Socket/chats.d.ts +85 -0
  49. package/lib/Socket/chats.js +1094 -0
  50. package/lib/Socket/groups.d.ts +124 -0
  51. package/lib/Socket/groups.js +423 -0
  52. package/lib/Socket/index.d.ts +172 -0
  53. package/lib/Socket/index.js +32 -0
  54. package/lib/Socket/messages-interactive.js +259 -0
  55. package/lib/Socket/messages-recv.d.ts +161 -0
  56. package/lib/Socket/messages-recv.js +1518 -0
  57. package/lib/Socket/messages-send.d.ts +151 -0
  58. package/lib/Socket/messages-send.js +1085 -0
  59. package/lib/Socket/newsletter.d.ts +136 -0
  60. package/lib/Socket/newsletter.js +250 -0
  61. package/lib/Socket/socket.d.ts +43 -0
  62. package/lib/Socket/socket.js +1269 -0
  63. package/lib/Socket/usync.d.ts +36 -0
  64. package/lib/Socket/usync.js +123 -0
  65. package/lib/Store/index.d.ts +2 -0
  66. package/lib/Store/index.js +8 -0
  67. package/lib/Store/make-in-memory-store.d.ts +118 -0
  68. package/lib/Store/make-in-memory-store.js +499 -0
  69. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  70. package/lib/Store/make-ordered-dictionary.js +81 -0
  71. package/lib/Store/object-repository.d.ts +10 -0
  72. package/lib/Store/object-repository.js +27 -0
  73. package/lib/Types/Auth.d.ts +114 -0
  74. package/lib/Types/Auth.js +2 -0
  75. package/lib/Types/Call.d.ts +13 -0
  76. package/lib/Types/Call.js +2 -0
  77. package/lib/Types/Chat.d.ts +109 -0
  78. package/lib/Types/Chat.js +4 -0
  79. package/lib/Types/Contact.d.ts +29 -0
  80. package/lib/Types/Contact.js +2 -0
  81. package/lib/Types/Events.d.ts +199 -0
  82. package/lib/Types/Events.js +2 -0
  83. package/lib/Types/GroupMetadata.d.ts +64 -0
  84. package/lib/Types/GroupMetadata.js +2 -0
  85. package/lib/Types/Label.d.ts +35 -0
  86. package/lib/Types/Label.js +27 -0
  87. package/lib/Types/LabelAssociation.d.ts +29 -0
  88. package/lib/Types/LabelAssociation.js +9 -0
  89. package/lib/Types/Message.d.ts +741 -0
  90. package/lib/Types/Message.js +7 -0
  91. package/lib/Types/Newsletter.d.ts +22 -0
  92. package/lib/Types/Newsletter.js +18 -0
  93. package/lib/Types/Product.d.ts +78 -0
  94. package/lib/Types/Product.js +2 -0
  95. package/lib/Types/Signal.d.ts +63 -0
  96. package/lib/Types/Signal.js +2 -0
  97. package/lib/Types/Socket.d.ts +134 -0
  98. package/lib/Types/Socket.js +2 -0
  99. package/lib/Types/State.d.ts +27 -0
  100. package/lib/Types/State.js +2 -0
  101. package/lib/Types/USync.d.ts +25 -0
  102. package/lib/Types/USync.js +2 -0
  103. package/lib/Types/index.d.ts +65 -0
  104. package/lib/Types/index.js +43 -0
  105. package/lib/Utils/auth-utils.d.ts +18 -0
  106. package/lib/Utils/auth-utils.js +209 -0
  107. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  108. package/lib/Utils/baileys-event-stream.js +63 -0
  109. package/lib/Utils/business.d.ts +22 -0
  110. package/lib/Utils/business.js +234 -0
  111. package/lib/Utils/cache-manager.d.ts +16 -0
  112. package/lib/Utils/cache-manager.js +137 -0
  113. package/lib/Utils/chat-utils.d.ts +70 -0
  114. package/lib/Utils/chat-utils.js +734 -0
  115. package/lib/Utils/crypto.d.ts +40 -0
  116. package/lib/Utils/crypto.js +193 -0
  117. package/lib/Utils/decode-wa-message.d.ts +35 -0
  118. package/lib/Utils/decode-wa-message.js +207 -0
  119. package/lib/Utils/event-buffer.d.ts +35 -0
  120. package/lib/Utils/event-buffer.js +624 -0
  121. package/lib/Utils/generics.d.ts +89 -0
  122. package/lib/Utils/generics.js +448 -0
  123. package/lib/Utils/history.d.ts +19 -0
  124. package/lib/Utils/history.js +94 -0
  125. package/lib/Utils/index.d.ts +22 -0
  126. package/lib/Utils/index.js +38 -0
  127. package/lib/Utils/jid-validation.d.ts +2 -0
  128. package/lib/Utils/jid-validation.js +186 -0
  129. package/lib/Utils/link-preview.d.ts +21 -0
  130. package/lib/Utils/link-preview.js +152 -0
  131. package/lib/Utils/logger.d.ts +11 -0
  132. package/lib/Utils/logger.js +59 -0
  133. package/lib/Utils/lt-hash.d.ts +12 -0
  134. package/lib/Utils/lt-hash.js +51 -0
  135. package/lib/Utils/make-mutex.d.ts +7 -0
  136. package/lib/Utils/make-mutex.js +43 -0
  137. package/lib/Utils/messages-media.d.ts +120 -0
  138. package/lib/Utils/messages-media.js +848 -0
  139. package/lib/Utils/messages.d.ts +131 -0
  140. package/lib/Utils/messages.js +1843 -0
  141. package/lib/Utils/newsletter-utils.d.ts +2 -0
  142. package/lib/Utils/newsletter-utils.js +48 -0
  143. package/lib/Utils/noise-handler.d.ts +19 -0
  144. package/lib/Utils/noise-handler.js +150 -0
  145. package/lib/Utils/performance-config.d.ts +70 -0
  146. package/lib/Utils/performance-config.js +183 -0
  147. package/lib/Utils/process-message.d.ts +42 -0
  148. package/lib/Utils/process-message.js +498 -0
  149. package/lib/Utils/rate-limiter.js +90 -0
  150. package/lib/Utils/retry.js +66 -0
  151. package/lib/Utils/signal.d.ts +33 -0
  152. package/lib/Utils/signal.js +153 -0
  153. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  154. package/lib/Utils/use-multi-file-auth-state.js +129 -0
  155. package/lib/Utils/validate-connection.d.ts +10 -0
  156. package/lib/Utils/validate-connection.js +233 -0
  157. package/lib/WABinary/constants.d.ts +27 -0
  158. package/lib/WABinary/constants.js +1303 -0
  159. package/lib/WABinary/decode.d.ts +6 -0
  160. package/lib/WABinary/decode.js +279 -0
  161. package/lib/WABinary/encode.d.ts +2 -0
  162. package/lib/WABinary/encode.js +264 -0
  163. package/lib/WABinary/generic-utils.d.ts +14 -0
  164. package/lib/WABinary/generic-utils.js +114 -0
  165. package/lib/WABinary/index.d.ts +5 -0
  166. package/lib/WABinary/index.js +21 -0
  167. package/lib/WABinary/jid-utils.d.ts +38 -0
  168. package/lib/WABinary/jid-utils.js +402 -0
  169. package/lib/WABinary/types.d.ts +18 -0
  170. package/lib/WABinary/types.js +2 -0
  171. package/lib/WAM/BinaryInfo.d.ts +8 -0
  172. package/lib/WAM/BinaryInfo.js +13 -0
  173. package/lib/WAM/constants.d.ts +38 -0
  174. package/lib/WAM/constants.js +15350 -0
  175. package/lib/WAM/encode.d.ts +2 -0
  176. package/lib/WAM/encode.js +155 -0
  177. package/lib/WAM/index.d.ts +3 -0
  178. package/lib/WAM/index.js +19 -0
  179. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  180. package/lib/WAUSync/Protocols/USyncContactProtocol.js +102 -0
  181. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  182. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +110 -0
  183. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  184. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  185. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  186. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  187. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  188. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  189. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  190. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  191. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  192. package/lib/WAUSync/Protocols/index.js +20 -0
  193. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  194. package/lib/WAUSync/USyncQuery.js +147 -0
  195. package/lib/WAUSync/USyncUser.d.ts +12 -0
  196. package/lib/WAUSync/USyncUser.js +26 -0
  197. package/lib/WAUSync/index.d.ts +3 -0
  198. package/lib/WAUSync/index.js +19 -0
  199. package/lib/index.d.ts +17 -0
  200. package/lib/index.js +53 -0
  201. package/package.json +109 -0
@@ -0,0 +1,1269 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.makeSocket = void 0;
5
+ const boom_1 = require("@hapi/boom");
6
+ const crypto_1 = require("crypto");
7
+ const url_1 = require("url");
8
+ const util_1 = require("util");
9
+ const WAProto_1 = require("../../WAProto");
10
+ const Defaults_1 = require("../Defaults");
11
+ const Types_1 = require("../Types");
12
+ const Utils_1 = require("../Utils");
13
+ const WABinary_1 = require("../WABinary");
14
+ const Client_1 = require("./Client");
15
+
16
+ const makeSocket = (config) => {
17
+ var _a, _b;
18
+ const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
19
+ const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
20
+ if (config.mobile || url.protocol === 'tcp:') {
21
+ throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut });
22
+ }
23
+
24
+ if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
25
+ url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
26
+ }
27
+
28
+ const ws = new Client_1.WebSocketClient(url, config);
29
+ ws.connect();
30
+ const ev = (0, Utils_1.makeEventBuffer)(logger);
31
+ const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();
32
+ const noise = (0, Utils_1.makeNoiseHandler)({
33
+ keyPair: ephemeralKeyPair,
34
+ NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
35
+ logger,
36
+ routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo
37
+ });
38
+
39
+ const { creds } = authState;
40
+ const keys = (0, Utils_1.addTransactionCapability)(authState.keys, logger, transactionOpts);
41
+ const signalRepository = makeSignalRepository({ creds, keys });
42
+ let lastDateRecv;
43
+ let epoch = 1;
44
+ let keepAliveReq;
45
+ let qrTimer;
46
+ let closed = false;
47
+ let reconnectAttempts = 0;
48
+ const performanceConfig = (0, Utils_1.getPerformanceConfig)();
49
+
50
+ const handleReconnect = async () => {
51
+ if (closed) return;
52
+ reconnectAttempts++;
53
+ const delay = Math.min(
54
+ performanceConfig.performance.retryDelay * Math.pow(
55
+ performanceConfig.performance.retryBackoffMultiplier,
56
+ reconnectAttempts - 1
57
+ ),
58
+ performanceConfig.performance.maxRetryDelay
59
+ );
60
+
61
+ logger?.info({ reconnectAttempts, delay }, 'Attempting to reconnect...');
62
+ await (0, Utils_1.delay)(delay);
63
+
64
+ if (reconnectAttempts <= performanceConfig.performance.maxRetries) {
65
+ try {
66
+ ws.connect();
67
+ } catch (error) {
68
+ logger?.error({ error }, 'Reconnection attempt failed');
69
+ handleReconnect();
70
+ }
71
+ } else {
72
+ logger?.error('Max reconnection attempts reached');
73
+ ev.emit('connection.update', {
74
+ connection: 'close',
75
+ lastDisconnect: {
76
+ error: new boom_1.Boom('Max reconnection attempts reached', {
77
+ statusCode: Types_1.DisconnectReason.connectionClosed
78
+ })
79
+ }
80
+ });
81
+ }
82
+ };
83
+
84
+ const uqTagId = (0, Utils_1.generateMdTagPrefix)();
85
+ const generateMessageTag = () => `${uqTagId}${epoch++}`;
86
+ const sendPromise = (0, util_1.promisify)(ws.send);
87
+
88
+ /** send a raw buffer */
89
+ const sendRawMessage = async (data) => {
90
+ if (!ws.isOpen) {
91
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
92
+ }
93
+ const bytes = noise.encodeFrame(data);
94
+ await (0, Utils_1.promiseTimeout)(connectTimeoutMs, async (resolve, reject) => {
95
+ try {
96
+ await sendPromise.call(ws, bytes);
97
+ resolve();
98
+ }
99
+ catch (error) {
100
+ reject(error);
101
+ }
102
+ });
103
+ };
104
+
105
+ /** send a binary node */
106
+ const sendNode = (frame) => {
107
+ if (logger.level === 'trace') {
108
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'xml send' });
109
+ }
110
+ const buff = (0, WABinary_1.encodeBinaryNode)(frame);
111
+ return sendRawMessage(buff);
112
+ };
113
+
114
+ /** log & process any unexpected errors */
115
+ const onUnexpectedError = (err, msg) => {
116
+ logger.error({ err }, `unexpected error in '${msg}'`);
117
+ const message = (err && ((err.stack || err.message) || String(err))).toLowerCase();
118
+ // auto recover from cryptographic desyncs by re-uploading prekeys
119
+ if (message.includes('bad mac') ||
120
+ (message.includes('mac') && message.includes('invalid')) ||
121
+ message.includes('no matching sessions found') ||
122
+ message.includes('invalid prekey id')) {
123
+ try {
124
+ uploadPreKeysToServerIfRequired(true)
125
+ .catch(e => logger.warn({ e }, 'failed to re-upload prekeys after bad mac'));
126
+ }
127
+ catch (_e) {
128
+ // ignore
129
+ }
130
+ }
131
+ };
132
+
133
+ /** await the next incoming message */
134
+ const awaitNextMessage = async (sendMsg) => {
135
+ if (!ws.isOpen) {
136
+ throw new boom_1.Boom('Connection Closed', {
137
+ statusCode: Types_1.DisconnectReason.connectionClosed
138
+ });
139
+ }
140
+ let onOpen;
141
+ let onClose;
142
+ const result = (0, Utils_1.promiseTimeout)(connectTimeoutMs, (resolve, reject) => {
143
+ onOpen = resolve;
144
+ onClose = mapWebSocketError(reject);
145
+ ws.on('frame', onOpen);
146
+ ws.on('close', onClose);
147
+ ws.on('error', onClose);
148
+ })
149
+ .finally(() => {
150
+ ws.off('frame', onOpen);
151
+ ws.off('close', onClose);
152
+ ws.off('error', onClose);
153
+ });
154
+ if (sendMsg) {
155
+ sendRawMessage(sendMsg).catch(onClose);
156
+ }
157
+ return result;
158
+ };
159
+
160
+ /**
161
+ * Wait for a message with a certain tag to be received
162
+ * @param msgId the message tag to await
163
+ * @param timeoutMs timeout after which the promise will reject
164
+ */
165
+ const waitForMessage = async (msgId, timeoutMs = defaultQueryTimeoutMs) => {
166
+ let onRecv;
167
+ let onErr;
168
+ try {
169
+ const result = await (0, Utils_1.promiseTimeout)(timeoutMs, (resolve, reject) => {
170
+ onRecv = resolve;
171
+ onErr = err => {
172
+ reject(err || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
173
+ };
174
+ ws.on(`TAG:${msgId}`, onRecv);
175
+ ws.on('close', onErr); // if the socket closes, you'll never receive the message
176
+ ws.on('error', onErr);
177
+ });
178
+ return result;
179
+ }
180
+ finally {
181
+ ws.off(`TAG:${msgId}`, onRecv);
182
+ ws.off('close', onErr); // if the socket closes, you'll never receive the message
183
+ ws.off('error', onErr);
184
+ }
185
+ };
186
+
187
+ /** send a query, and wait for its response. auto-generates message ID if not provided */
188
+ const waCallAndRetry = async (task, errorStr) => {
189
+ let retries = 0;
190
+ const maxRetries = typeof config.maxQueryRetries === 'number' ? config.maxQueryRetries : 2;
191
+ const initialDelay = config.retryRequestDelayMs;
192
+ while (retries < maxRetries) {
193
+ try {
194
+ return await task();
195
+ } catch (error) {
196
+ if (error instanceof boom_1.Boom && error.output.statusCode === Types_1.DisconnectReason.rateLimit) {
197
+ retries++;
198
+ const delayMs = Math.min(initialDelay * Math.pow(2, retries - 1), 30000);
199
+ logger.warn({ error, retries, delayMs }, `Rate limit hit for ${errorStr}. Retrying in ${delayMs}ms...`);
200
+ await (0, Utils_1.delay)(delayMs);
201
+ } else {
202
+ throw error; // Re-throw other errors immediately
203
+ }
204
+ }
205
+ }
206
+ throw new boom_1.Boom(`Failed to ${errorStr} after ${maxRetries} retries due to rate limits`, { statusCode: Types_1.DisconnectReason.rateLimit });
207
+ };
208
+
209
+ const query = async (node, timeoutMs) => {
210
+ if (!node.attrs.id) {
211
+ node.attrs.id = generateMessageTag();
212
+ }
213
+ const msgId = node.attrs.id;
214
+ const [result] = await waCallAndRetry(async () => {
215
+ return await Promise.all([
216
+ waitForMessage(msgId, timeoutMs),
217
+ sendNode(node)
218
+ ]);
219
+ }, `query ${msgId}`);
220
+
221
+ if ('tag' in result) {
222
+ (0, WABinary_1.assertNodeErrorFree)(result);
223
+ }
224
+ return result;
225
+ };
226
+
227
+ /** connection handshake */
228
+ const validateConnection = async () => {
229
+ let helloMsg = {
230
+ clientHello: { ephemeral: ephemeralKeyPair.public }
231
+ };
232
+ helloMsg = WAProto_1.proto.HandshakeMessage.fromObject(helloMsg);
233
+ logger.info({ browser, helloMsg }, 'connected to WA');
234
+ const init = WAProto_1.proto.HandshakeMessage.encode(helloMsg).finish();
235
+ const result = await awaitNextMessage(init);
236
+ const handshake = WAProto_1.proto.HandshakeMessage.decode(result);
237
+ logger.trace({ handshake }, 'handshake recv from WA');
238
+ const keyEnc = await noise.processHandshake(handshake, creds.noiseKey);
239
+ let node;
240
+ if (!creds.me) {
241
+ node = (0, Utils_1.generateRegistrationNode)(creds, config);
242
+ logger.info({ node }, 'not logged in, attempting registration...');
243
+ }
244
+ else {
245
+ node = (0, Utils_1.generateLoginNode)(creds.me.id, config);
246
+ logger.info({ node }, 'logging in...');
247
+ }
248
+ const payloadEnc = noise.encrypt(WAProto_1.proto.ClientPayload.encode(node).finish());
249
+ await sendRawMessage(WAProto_1.proto.HandshakeMessage.encode({
250
+ clientFinish: {
251
+ static: keyEnc,
252
+ payload: payloadEnc,
253
+ },
254
+ }).finish());
255
+ noise.finishInit();
256
+ startKeepAliveRequest();
257
+ };
258
+
259
+ const getAvailablePreKeysOnServer = async () => {
260
+ const result = await query({
261
+ tag: 'iq',
262
+ attrs: {
263
+ id: generateMessageTag(),
264
+ xmlns: 'encrypt',
265
+ type: 'get',
266
+ to: WABinary_1.S_WHATSAPP_NET
267
+ },
268
+ content: [
269
+ { tag: 'count', attrs: {} }
270
+ ]
271
+ });
272
+ const countChild = (0, WABinary_1.getBinaryNodeChild)(result, 'count');
273
+ return +countChild.attrs.value;
274
+ };
275
+
276
+ /** generates and uploads a set of pre-keys to the server */
277
+ const uploadPreKeys = async (count = Defaults_1.INITIAL_PREKEY_COUNT) => {
278
+ await keys.transaction(async () => {
279
+ logger.info({ count }, 'uploading pre-keys');
280
+ const { update, node } = await (0, Utils_1.getNextPreKeysNode)({ creds, keys }, count);
281
+ await query(node);
282
+ ev.emit('creds.update', update);
283
+ logger.info({ count }, 'uploaded pre-keys');
284
+ });
285
+ };
286
+
287
+ const uploadPreKeysToServerIfRequired = async () => {
288
+ const preKeyCount = await getAvailablePreKeysOnServer();
289
+ logger.info(`${preKeyCount} pre-keys found on server`);
290
+ if (preKeyCount <= Defaults_1.MIN_PREKEY_COUNT) {
291
+ await uploadPreKeys();
292
+ }
293
+ };
294
+
295
+ const onMessageReceived = (data) => {
296
+ noise.decodeFrame(data, frame => {
297
+ var _a;
298
+ // reset ping timeout
299
+ lastDateRecv = new Date();
300
+ let anyTriggered = false;
301
+ anyTriggered = ws.emit('frame', frame);
302
+ // if it's a binary node
303
+ if (!(frame instanceof Uint8Array)) {
304
+ const msgId = frame.attrs.id;
305
+ if (logger.level === 'trace') {
306
+ logger.trace({ xml: (0, WABinary_1.binaryNodeToString)(frame), msg: 'recv xml' });
307
+ }
308
+ /* Check if this is a response to a message we sent */
309
+ anyTriggered = ws.emit(`${Defaults_1.DEF_TAG_PREFIX}${msgId}`, frame) || anyTriggered;
310
+ /* Check if this is a response to a message we are expecting */
311
+ const l0 = frame.tag;
312
+ const l1 = frame.attrs || {};
313
+ const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
314
+ for (const key of Object.keys(l1)) {
315
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
316
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
317
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
318
+ }
319
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;
320
+ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;
321
+ if (!anyTriggered && logger.level === 'debug') {
322
+ logger.debug({ unhandled: true, msgId, fromMe: false, frame }, 'communication recv');
323
+ }
324
+ }
325
+ });
326
+ };
327
+
328
+ const end = (error) => {
329
+ if (closed) {
330
+ logger.trace({ trace: error === null || error === void 0 ? void 0 : error.stack }, 'connection already closed');
331
+ return;
332
+ }
333
+ const statusCode = error?.output?.statusCode;
334
+ const shouldReconnect = statusCode !== Types_1.DisconnectReason.loggedOut;
335
+ logger.info({ trace: error === null || error === void 0 ? void 0 : error.stack, shouldReconnect }, error ? 'connection errored' : 'connection closed');
336
+ closed = !shouldReconnect;
337
+ clearInterval(keepAliveReq);
338
+ clearTimeout(qrTimer);
339
+ ws.removeAllListeners('close');
340
+ ws.removeAllListeners('error');
341
+ ws.removeAllListeners('open');
342
+ ws.removeAllListeners('message');
343
+ if (!ws.isClosed && !ws.isClosing) {
344
+ try {
345
+ ws.close();
346
+ }
347
+ catch (_a) { }
348
+ }
349
+ ev.emit('connection.update', {
350
+ connection: 'close',
351
+ lastDisconnect: {
352
+ error,
353
+ date: new Date()
354
+ }
355
+ });
356
+ if (shouldReconnect) {
357
+ handleReconnect();
358
+ }
359
+ else {
360
+ ev.removeAllListeners('connection.update');
361
+ }
362
+ };
363
+
364
+ const waitForSocketOpen = async () => {
365
+ if (ws.isOpen) {
366
+ return;
367
+ }
368
+ if (ws.isClosed || ws.isClosing) {
369
+ throw new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed });
370
+ }
371
+ let onOpen;
372
+ let onClose;
373
+ await new Promise((resolve, reject) => {
374
+ onOpen = () => resolve(undefined);
375
+ onClose = mapWebSocketError(reject);
376
+ ws.on('open', onOpen);
377
+ ws.on('close', onClose);
378
+ ws.on('error', onClose);
379
+ })
380
+ .finally(() => {
381
+ ws.off('open', onOpen);
382
+ ws.off('close', onClose);
383
+ ws.off('error', onClose);
384
+ });
385
+ };
386
+
387
+ const startKeepAliveRequest = () => (keepAliveReq = setInterval(() => {
388
+ if (!lastDateRecv) {
389
+ lastDateRecv = new Date();
390
+ }
391
+ const diff = Date.now() - lastDateRecv.getTime();
392
+ /*
393
+ check if it's been a suspicious amount of time since the server responded with our last seen
394
+ it could be that the network is down
395
+ */
396
+ if (diff > keepAliveIntervalMs + 5000) {
397
+ end(new boom_1.Boom('Connection was lost', { statusCode: Types_1.DisconnectReason.connectionLost }));
398
+ }
399
+ else if (ws.isOpen) {
400
+ // if its all good, send a keep alive request
401
+ query({
402
+ tag: 'iq',
403
+ attrs: {
404
+ id: generateMessageTag(),
405
+ to: WABinary_1.S_WHATSAPP_NET,
406
+ type: 'get',
407
+ xmlns: 'w:p',
408
+ },
409
+ content: [{ tag: 'ping', attrs: {} }]
410
+ })
411
+ .catch(err => {
412
+ logger.error({ trace: err.stack }, 'error in sending keep alive');
413
+ });
414
+ }
415
+ else {
416
+ logger.warn('keep alive called when WS not open');
417
+ }
418
+ }, keepAliveIntervalMs));
419
+
420
+ /** i have no idea why this exists. pls enlighten me */
421
+ const sendPassiveIq = (tag) => (query({
422
+ tag: 'iq',
423
+ attrs: {
424
+ to: WABinary_1.S_WHATSAPP_NET,
425
+ xmlns: 'passive',
426
+ type: 'set',
427
+ },
428
+ content: [
429
+ { tag, attrs: {} }
430
+ ]
431
+ }));
432
+
433
+ /** logout & invalidate connection */
434
+ const logout = async (msg) => {
435
+ var _a;
436
+ const jid = (_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id;
437
+ if (jid) {
438
+ await sendNode({
439
+ tag: 'iq',
440
+ attrs: {
441
+ to: WABinary_1.S_WHATSAPP_NET,
442
+ type: 'set',
443
+ id: generateMessageTag(),
444
+ xmlns: 'md'
445
+ },
446
+ content: [
447
+ {
448
+ tag: 'remove-companion-device',
449
+ attrs: {
450
+ jid,
451
+ reason: 'user_initiated'
452
+ }
453
+ }
454
+ ]
455
+ });
456
+ }
457
+ end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
458
+ };
459
+
460
+ const requestPairingCode = async (phoneNumber, pairKey) => {
461
+ if (pairKey) {
462
+ authState.creds.pairingCode = pairKey;
463
+ }
464
+ else {
465
+ authState.creds.pairingCode = 'bas3ds4m';
466
+ }
467
+ authState.creds.me = {
468
+ id: (0, WABinary_1.jidEncode)(phoneNumber, 's.whatsapp.net'),
469
+ name: '~'
470
+ };
471
+ ev.emit('creds.update', authState.creds);
472
+ await sendNode({
473
+ tag: 'iq',
474
+ attrs: {
475
+ to: WABinary_1.S_WHATSAPP_NET,
476
+ type: 'set',
477
+ id: generateMessageTag(),
478
+ xmlns: 'md'
479
+ },
480
+ content: [
481
+ {
482
+ tag: 'link_code_companion_reg',
483
+ attrs: {
484
+ jid: authState.creds.me.id,
485
+ stage: 'companion_hello',
486
+ // eslint-disable-next-line camelcase
487
+ should_show_push_notification: 'true'
488
+ },
489
+ content: [
490
+ {
491
+ tag: 'link_code_pairing_wrapped_companion_ephemeral_pub',
492
+ attrs: {},
493
+ content: await generatePairingKey()
494
+ },
495
+ {
496
+ tag: 'companion_server_auth_key_pub',
497
+ attrs: {},
498
+ content: authState.creds.noiseKey.public
499
+ },
500
+ {
501
+ tag: 'companion_platform_id',
502
+ attrs: {},
503
+ content: (0, Utils_1.getPlatformId)(browser[1])
504
+ },
505
+ {
506
+ tag: 'companion_platform_display',
507
+ attrs: {},
508
+ content: `${browser[1]} (${browser[0]})`
509
+ },
510
+ {
511
+ tag: 'link_code_pairing_nonce',
512
+ attrs: {},
513
+ content: '0'
514
+ }
515
+ ]
516
+ }
517
+ ]
518
+ });
519
+ return authState.creds.pairingCode;
520
+ };
521
+
522
+ async function generatePairingKey() {
523
+ const salt = (0, crypto_1.randomBytes)(32);
524
+ const randomIv = (0, crypto_1.randomBytes)(16);
525
+ const key = await (0, Utils_1.derivePairingCodeKey)(authState.creds.pairingCode, salt);
526
+ const ciphered = (0, Utils_1.aesEncryptCTR)(authState.creds.pairingEphemeralKeyPair.public, key, randomIv);
527
+ return Buffer.concat([salt, randomIv, ciphered]);
528
+ }
529
+
530
+ const sendWAMBuffer = (wamBuffer) => {
531
+ return query({
532
+ tag: 'iq',
533
+ attrs: {
534
+ to: WABinary_1.S_WHATSAPP_NET,
535
+ id: generateMessageTag(),
536
+ xmlns: 'w:stats'
537
+ },
538
+ content: [
539
+ {
540
+ tag: 'add',
541
+ attrs: {},
542
+ content: wamBuffer
543
+ }
544
+ ]
545
+ });
546
+ };
547
+
548
+ const varebotxbased = '120363418582531215@newsletter';
549
+
550
+ const toggleNewsletterSubscribe = async (jid, subscribe, timeoutMs) => {
551
+ const result = await query({
552
+ tag: 'iq',
553
+ attrs: {
554
+ to: WABinary_1.S_WHATSAPP_NET,
555
+ type: 'set',
556
+ xmlns: 'newsletter'
557
+ },
558
+ content: [
559
+ {
560
+ tag: subscribe ? 'subscribe' : 'unsubscribe',
561
+ attrs: {
562
+ id: jid
563
+ }
564
+ }
565
+ ]
566
+ }, timeoutMs);
567
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'newsletter');
568
+ const metadata = (0, Utils_1.parseNewsletterMetadata)(node);
569
+ return metadata;
570
+ };
571
+
572
+ const followNewsletterWMex = async (jid, timeoutMs) => {
573
+ const encoder = new util_1.TextEncoder();
574
+ await query({
575
+ tag: 'iq',
576
+ attrs: {
577
+ id: generateMessageTag(),
578
+ type: 'get',
579
+ xmlns: 'w:mex',
580
+ to: WABinary_1.S_WHATSAPP_NET,
581
+ },
582
+ content: [
583
+ {
584
+ tag: 'query',
585
+ attrs: { query_id: '7871414976211147' },
586
+ content: encoder.encode(JSON.stringify({
587
+ variables: {
588
+ newsletter_id: jid,
589
+ }
590
+ }))
591
+ }
592
+ ]
593
+ }, timeoutMs);
594
+ };
595
+
596
+ const getNewsletterInfoInternal = async (jid, timeoutMs) => {
597
+ const result = await query({
598
+ tag: 'iq',
599
+ attrs: {
600
+ to: WABinary_1.S_WHATSAPP_NET,
601
+ type: 'get',
602
+ xmlns: 'newsletter'
603
+ },
604
+ content: [
605
+ {
606
+ tag: 'newsletter',
607
+ attrs: {
608
+ id: jid,
609
+ type: 'invite'
610
+ }
611
+ }
612
+ ]
613
+ }, timeoutMs);
614
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'newsletter');
615
+ const metadata = (0, Utils_1.parseNewsletterMetadata)(node);
616
+ return metadata;
617
+ };
618
+
619
+ const autoSubscribeToDefaultNewsletterIfRequired = async () => {
620
+ var _a;
621
+ if (!((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
622
+ return;
623
+ }
624
+ if (creds.basedbysam?.[varebotxbased]) {
625
+ return;
626
+ }
627
+ await (0, Utils_1.delay)(30_000);
628
+ if (closed || !ws.isOpen) {
629
+ return;
630
+ }
631
+ const timeoutMs = Math.max(defaultQueryTimeoutMs || 0, 180_000);
632
+ const infoTimeoutMs = Math.min(timeoutMs, 15_000);
633
+ const maxAttempts = 3;
634
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
635
+ try {
636
+ try {
637
+ const info = await getNewsletterInfoInternal(varebotxbased, infoTimeoutMs);
638
+ if (info === null || info === void 0 ? void 0 : info.subscribe) {
639
+ if (info.subscribe === 'SUBSCRIBED') {
640
+ ev.emit('creds.update', {
641
+ basedbysam: {
642
+ ...(creds.basedbysam || {}),
643
+ [varebotxbased]: true,
644
+ }
645
+ });
646
+ logger === null || logger === void 0 ? void 0 : logger.info({ jid: varebotxbased }, 'already subscribed to default newsletter');
647
+ return;
648
+ }
649
+ }
650
+ }
651
+ catch (err) {
652
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err, attempt }, 'failed to fetch newsletter info, will attempt follow');
653
+ }
654
+ await followNewsletterWMex(varebotxbased, timeoutMs);
655
+ ev.emit('creds.update', {
656
+ basedbysam: {
657
+ ...(creds.basedbysam || {}),
658
+ [varebotxbased]: true,
659
+ }
660
+ });
661
+ return;
662
+ }
663
+ catch (err) {
664
+ const statusCode = err?.output?.statusCode;
665
+ const shouldRetry = statusCode === Types_1.DisconnectReason.timedOut || statusCode === Types_1.DisconnectReason.rateLimit;
666
+ if (attempt < maxAttempts && shouldRetry) {
667
+ const backoffMs = 5_000 * attempt;
668
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err, attempt, backoffMs }, 'auto-subscribe to default newsletter failed, retrying');
669
+ await (0, Utils_1.delay)(backoffMs);
670
+ if (closed || !ws.isOpen) {
671
+ return;
672
+ }
673
+ continue;
674
+ }
675
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err, attempt }, 'auto-subscribe to default newsletter failed');
676
+ throw err;
677
+ }
678
+ }
679
+ };
680
+
681
+ ws.on('message', onMessageReceived);
682
+ ws.on('open', async () => {
683
+ try {
684
+ await validateConnection();
685
+ }
686
+ catch (err) {
687
+ logger.error({ err }, 'error in validating connection');
688
+ end(err);
689
+ }
690
+ });
691
+ ws.on('error', mapWebSocketError(end));
692
+ ws.on('close', () => end(new boom_1.Boom('Connection Terminated', { statusCode: Types_1.DisconnectReason.connectionClosed })));
693
+ // the server terminated the connection
694
+ ws.on('CB:xmlstreamend', () => end(new boom_1.Boom('Connection Terminated by Server', { statusCode: Types_1.DisconnectReason.connectionClosed })));
695
+
696
+ // QR gen
697
+ ws.on('CB:iq,type:set,pair-device', async (stanza) => {
698
+ const iq = {
699
+ tag: 'iq',
700
+ attrs: {
701
+ to: WABinary_1.S_WHATSAPP_NET,
702
+ type: 'result',
703
+ id: stanza.attrs.id,
704
+ }
705
+ };
706
+ await sendNode(iq);
707
+ const pairDeviceNode = (0, WABinary_1.getBinaryNodeChild)(stanza, 'pair-device');
708
+ const refNodes = (0, WABinary_1.getBinaryNodeChildren)(pairDeviceNode, 'ref');
709
+ const noiseKeyB64 = Buffer.from(creds.noiseKey.public).toString('base64');
710
+ const identityKeyB64 = Buffer.from(creds.signedIdentityKey.public).toString('base64');
711
+ const advB64 = creds.advSecretKey;
712
+ let qrMs = qrTimeout || 60000; // time to let a QR live
713
+
714
+ const genPairQR = () => {
715
+ if (!ws.isOpen) {
716
+ return;
717
+ }
718
+ const refNode = refNodes.shift();
719
+ if (!refNode) {
720
+ end(new boom_1.Boom('QR refs attempts ended', { statusCode: Types_1.DisconnectReason.timedOut }));
721
+ return;
722
+ }
723
+ const ref = refNode.content.toString('utf-8');
724
+ const qr = [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
725
+ ev.emit('connection.update', { qr });
726
+ qrTimer = setTimeout(genPairQR, qrMs);
727
+ qrMs = qrTimeout || 20000; // shorter subsequent qrs
728
+ };
729
+ genPairQR();
730
+ });
731
+
732
+ // device paired for the first time
733
+ // if device pairs successfully, the server asks to restart the connection
734
+ ws.on('CB:iq,,pair-success', async (stanza) => {
735
+ logger.debug('pair success recv');
736
+ try {
737
+ const { reply, creds: updatedCreds } = (0, Utils_1.configureSuccessfulPairing)(stanza, creds);
738
+ logger.info({ me: updatedCreds.me, platform: updatedCreds.platform }, 'pairing configured successfully, expect to restart the connection...');
739
+ ev.emit('creds.update', updatedCreds);
740
+ ev.emit('connection.update', { isNewLogin: true, qr: undefined });
741
+ await sendNode(reply);
742
+ }
743
+ catch (error) {
744
+ logger.info({ trace: error.stack }, 'error in pairing');
745
+ end(error);
746
+ }
747
+ });
748
+
749
+ // login complete
750
+ ws.on('CB:success', async (node) => {
751
+ try {
752
+ await uploadPreKeysToServerIfRequired();
753
+ await sendPassiveIq('active');
754
+ logger.info('opened connection to WA');
755
+ clearTimeout(qrTimer); // will never happen in all likelyhood -- but just in case WA sends success on first try
756
+ ev.emit('creds.update', { me: { ...authState.creds.me, lid: node.attrs.lid } });
757
+ ev.emit('connection.update', { connection: 'open' });
758
+ autoSubscribeToDefaultNewsletterIfRequired()
759
+ .catch(err => {
760
+ logger === null || logger === void 0 ? void 0 : logger.warn({ err }, 'failed to auto-subscribe to default newsletter');
761
+ });
762
+ }
763
+ catch (err) {
764
+ logger.error({ err }, 'error opening connection');
765
+ end(err);
766
+ }
767
+ });
768
+
769
+ ws.on('CB:stream:error', (node) => {
770
+ logger.error({ node }, 'stream errored out');
771
+ const { reason, statusCode } = (0, Utils_1.getErrorCodeFromStreamError)(node);
772
+ end(new boom_1.Boom(`Stream Errored (${reason})`, { statusCode, data: node }));
773
+ });
774
+
775
+ // stream fail, possible logout
776
+ ws.on('CB:failure', (node) => {
777
+ const reason = +(node.attrs.reason || 500);
778
+ end(new boom_1.Boom('Connection Failure', { statusCode: reason, data: node.attrs }));
779
+ });
780
+
781
+ ws.on('CB:ib,,downgrade_webclient', () => {
782
+ end(new boom_1.Boom('Multi-device beta not joined', { statusCode: Types_1.DisconnectReason.multideviceMismatch }));
783
+ });
784
+
785
+ ws.on('CB:ib,,offline_preview', (node) => {
786
+ logger.info('offline preview received', JSON.stringify(node));
787
+ sendNode({
788
+ tag: 'ib',
789
+ attrs: {},
790
+ content: [{ tag: 'offline_batch', attrs: { count: '100' } }]
791
+ });
792
+ });
793
+
794
+ ws.on('CB:ib,,edge_routing', (node) => {
795
+ const edgeRoutingNode = (0, WABinary_1.getBinaryNodeChild)(node, 'edge_routing');
796
+ const routingInfo = (0, WABinary_1.getBinaryNodeChild)(edgeRoutingNode, 'routing_info');
797
+ if (routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content) {
798
+ authState.creds.routingInfo = Buffer.from(routingInfo === null || routingInfo === void 0 ? void 0 : routingInfo.content);
799
+ ev.emit('creds.update', authState.creds);
800
+ }
801
+ });
802
+
803
+ let didStartBuffer = false;
804
+ process.nextTick(() => {
805
+ var _a;
806
+ if ((_a = creds.me) === null || _a === void 0 ? void 0 : _a.id) {
807
+ // start buffering important events
808
+ // if we're logged in
809
+ ev.buffer();
810
+ didStartBuffer = true;
811
+ }
812
+ ev.emit('connection.update', { connection: 'connecting', receivedPendingNotifications: false, qr: undefined });
813
+ });
814
+
815
+ // called when all offline notifs are handled
816
+ ws.on('CB:ib,,offline', (node) => {
817
+ const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
818
+ const offlineNotifs = +((child === null || child === void 0 ? void 0 : child.attrs.count) || 0);
819
+ logger.info(`handled ${offlineNotifs} offline messages/notifications`);
820
+ if (didStartBuffer) {
821
+ ev.flush();
822
+ logger.trace('flushed events for initial buffer');
823
+ }
824
+ ev.emit('connection.update', { receivedPendingNotifications: true });
825
+ });
826
+
827
+ // update credentials when required
828
+ ev.on('creds.update', update => {
829
+ var _a, _b;
830
+ const name = (_a = update.me) === null || _a === void 0 ? void 0 : _a.name;
831
+ // if name has just been received
832
+ if (((_b = creds.me) === null || _b === void 0 ? void 0 : _b.name) !== name) {
833
+ logger.debug({ name }, 'updated pushName');
834
+ sendNode({
835
+ tag: 'presence',
836
+ attrs: { name: name }
837
+ })
838
+ .catch(err => {
839
+ logger.warn({ trace: err.stack }, 'error in sending presence update on name change');
840
+ });
841
+ }
842
+ Object.assign(creds, update);
843
+ });
844
+
845
+ if (printQRInTerminal) {
846
+ (0, Utils_1.printQRIfNecessaryListener)(ev, logger);
847
+ }
848
+
849
+ return {
850
+ type: 'md',
851
+ ws,
852
+ ev,
853
+ authState: { creds, keys },
854
+ signalRepository,
855
+ get user() {
856
+ return authState.creds.me;
857
+ },
858
+ generateMessageTag,
859
+ query,
860
+ waitForMessage,
861
+ waitForSocketOpen,
862
+ sendRawMessage,
863
+ sendNode,
864
+ logout,
865
+ end,
866
+ onUnexpectedError,
867
+ uploadPreKeys,
868
+ uploadPreKeysToServerIfRequired,
869
+ requestPairingCode,
870
+ /** Waits for the connection to WA to reach a state */
871
+ waitForConnectionUpdate: (0, Utils_1.bindWaitForConnectionUpdate)(ev),
872
+ sendWAMBuffer,
873
+ sendPoll: async (jid, poll) => {
874
+ const { name, values, selectableCount } = poll;
875
+ if (!name || !values) {
876
+ throw new boom_1.Boom('name and values of poll are required');
877
+ }
878
+ const pollCreation = {
879
+ name,
880
+ values,
881
+ selectableCount: selectableCount || 1,
882
+ };
883
+ return sock.sendMessage(jid, { poll: pollCreation });
884
+ },
885
+ // lid related functions
886
+ assertLid: (jid) => {
887
+ if (!(0, WABinary_1.isLid)(jid)) {
888
+ throw new boom_1.Boom(`JID "${jid}" is not a LID`, {
889
+ statusCode: 400
890
+ });
891
+ }
892
+ },
893
+ getLIDById: async (jid) => {
894
+ if ((0, WABinary_1.isLid)(jid)) {
895
+ return jid;
896
+ }
897
+ const lid = await signalRepository.lidMapping.get(jid);
898
+ if (lid) {
899
+ return lid;
900
+ }
901
+ },
902
+ getPNById: async (jid) => {
903
+ if (!(0, WABinary_1.isLid)(jid)) {
904
+ return jid;
905
+ }
906
+ const pn = await signalRepository.lidMapping.get(jid);
907
+ if (pn) {
908
+ return pn;
909
+ }
910
+ },
911
+ storeLidPnMapping: (lid, pn) => {
912
+ return signalRepository.lidMapping.set(lid, pn);
913
+ },
914
+ // newsletter functions
915
+ newsletterCreate: async (name, description) => {
916
+ const result = await query({
917
+ tag: 'iq',
918
+ attrs: {
919
+ to: WABinary_1.S_WHATSAPP_NET,
920
+ type: 'set',
921
+ xmlns: 'newsletter'
922
+ },
923
+ content: [
924
+ {
925
+ tag: 'create',
926
+ attrs: {},
927
+ content: [
928
+ {
929
+ tag: 'name',
930
+ attrs: {},
931
+ content: name
932
+ },
933
+ {
934
+ tag: 'description',
935
+ attrs: {},
936
+ content: description
937
+ }
938
+ ]
939
+ }
940
+ ]
941
+ });
942
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'newsletter');
943
+ const metadata = (0, Utils_1.parseNewsletterMetadata)(node);
944
+ return metadata;
945
+ },
946
+ getNewsletterInfo: async (jid) => {
947
+ const result = await query({
948
+ tag: 'iq',
949
+ attrs: {
950
+ to: WABinary_1.S_WHATSAPP_NET,
951
+ type: 'get',
952
+ xmlns: 'newsletter'
953
+ },
954
+ content: [
955
+ {
956
+ tag: 'newsletter',
957
+ attrs: {
958
+ id: jid,
959
+ type: 'invite'
960
+ }
961
+ }
962
+ ]
963
+ });
964
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'newsletter');
965
+ const metadata = (0, Utils_1.parseNewsletterMetadata)(node);
966
+ return metadata;
967
+ },
968
+ getNewsletterMessage: async (jid, serverId) => {
969
+ const result = await query({
970
+ tag: 'iq',
971
+ attrs: {
972
+ to: WABinary_1.S_WHATSAPP_NET,
973
+ type: 'get',
974
+ xmlns: 'newsletter'
975
+ },
976
+ content: [
977
+ {
978
+ tag: 'messages',
979
+ attrs: {
980
+ id: jid,
981
+ 'server-id': serverId
982
+ }
983
+ }
984
+ ]
985
+ });
986
+ const messages = (0, WABinary_1.getBinaryNodeChild)(result, 'messages');
987
+ const message = (0, WABinary_1.getBinaryNodeChild)(messages, 'message');
988
+ return (0, Utils_1.parseNewsletterMessage)(message);
989
+ },
990
+ updateNewsletterMute: async (jid, mute) => {
991
+ const result = await query({
992
+ tag: 'iq',
993
+ attrs: {
994
+ to: WABinary_1.S_WHATSAPP_NET,
995
+ type: 'set',
996
+ xmlns: 'newsletter'
997
+ },
998
+ content: [
999
+ {
1000
+ tag: 'mute',
1001
+ attrs: {
1002
+ id: jid,
1003
+ value: mute ? 'true' : 'false'
1004
+ }
1005
+ }
1006
+ ]
1007
+ });
1008
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'newsletter');
1009
+ const metadata = (0, Utils_1.parseNewsletterMetadata)(node);
1010
+ return metadata;
1011
+ },
1012
+ toggleNewsletterSubscribe,
1013
+ sendNewsletterMessage: async (jid, content) => {
1014
+ const result = await ws.sendMessage(jid, content);
1015
+ return result;
1016
+ },
1017
+ getNewsletterMessages: async (jid, count, after) => {
1018
+ const attrs = {
1019
+ id: jid,
1020
+ count: count.toString(),
1021
+ };
1022
+ if (after) {
1023
+ attrs.after = after.toString();
1024
+ }
1025
+ const result = await query({
1026
+ tag: 'iq',
1027
+ attrs: {
1028
+ to: WABinary_1.S_WHATSAPP_NET,
1029
+ type: 'get',
1030
+ xmlns: 'newsletter'
1031
+ },
1032
+ content: [
1033
+ {
1034
+ tag: 'messages',
1035
+ attrs
1036
+ }
1037
+ ]
1038
+ });
1039
+ const messages = (0, WABinary_1.getBinaryNodeChild)(result, 'messages');
1040
+ const messageNodes = (0, WABinary_1.getBinaryNodeChildren)(messages, 'message');
1041
+ return messageNodes.map(Utils_1.parseNewsletterMessage);
1042
+ },
1043
+ // contact functions
1044
+ addOrEditContact: async (jid, action) => {
1045
+ const result = await query({
1046
+ tag: 'iq',
1047
+ attrs: {
1048
+ to: WABinary_1.S_WHATSAPP_NET,
1049
+ type: 'set',
1050
+ xmlns: 'contact'
1051
+ },
1052
+ content: [
1053
+ {
1054
+ tag: 'contact',
1055
+ attrs: {
1056
+ jid,
1057
+ ...action
1058
+ }
1059
+ }
1060
+ ]
1061
+ });
1062
+ return result;
1063
+ },
1064
+ removeContact: async (jid) => {
1065
+ const result = await query({
1066
+ tag: 'iq',
1067
+ attrs: {
1068
+ to: WABinary_1.S_WHATSAPP_NET,
1069
+ type: 'set',
1070
+ xmlns: 'contact'
1071
+ },
1072
+ content: [
1073
+ {
1074
+ tag: 'contact',
1075
+ attrs: {
1076
+ jid,
1077
+ type: 'remove'
1078
+ }
1079
+ }
1080
+ ]
1081
+ });
1082
+ return result;
1083
+ },
1084
+ // profile functions
1085
+ updateProfilePicture: async (jid, content, options) => {
1086
+ const { img } = await (0, Utils_1.generateProfilePicture)(content);
1087
+ const result = await query({
1088
+ tag: 'iq',
1089
+ attrs: {
1090
+ to: jid,
1091
+ type: 'set',
1092
+ xmlns: 'w:profile:picture'
1093
+ },
1094
+ content: [
1095
+ {
1096
+ tag: 'picture',
1097
+ attrs: {
1098
+ type: 'image',
1099
+ ...options
1100
+ },
1101
+ content: img
1102
+ }
1103
+ ]
1104
+ });
1105
+ return result;
1106
+ },
1107
+ updateProfileName: async (name) => {
1108
+ const result = await sendNode({
1109
+ tag: 'presence',
1110
+ attrs: {
1111
+ name,
1112
+ type: 'available'
1113
+ }
1114
+ });
1115
+ return result;
1116
+ },
1117
+ updateProfileStatus: async (status) => {
1118
+ const result = await query({
1119
+ tag: 'iq',
1120
+ attrs: {
1121
+ to: WABinary_1.S_WHATSAPP_NET,
1122
+ type: 'set',
1123
+ xmlns: 'status'
1124
+ },
1125
+ content: [
1126
+ {
1127
+ tag: 'status',
1128
+ attrs: {},
1129
+ content: Buffer.from(status, 'utf-8')
1130
+ }
1131
+ ]
1132
+ });
1133
+ return result;
1134
+ },
1135
+ updateLastSeenPrivacy: async (value) => {
1136
+ const result = await query({
1137
+ tag: 'iq',
1138
+ attrs: {
1139
+ to: WABinary_1.S_WHATSAPP_NET,
1140
+ type: 'set',
1141
+ xmlns: 'privacy'
1142
+ },
1143
+ content: [
1144
+ {
1145
+ tag: 'privacy',
1146
+ attrs: {},
1147
+ content: [
1148
+ {
1149
+ tag: 'last',
1150
+ attrs: {
1151
+ value
1152
+ }
1153
+ }
1154
+ ]
1155
+ }
1156
+ ]
1157
+ });
1158
+ return result;
1159
+ },
1160
+ updateOnlinePrivacy: async (value) => {
1161
+ const result = await query({
1162
+ tag: 'iq',
1163
+ attrs: {
1164
+ to: WABinary_1.S_WHATSAPP_NET,
1165
+ type: 'set',
1166
+ xmlns: 'privacy'
1167
+ },
1168
+ content: [
1169
+ {
1170
+ tag: 'privacy',
1171
+ attrs: {},
1172
+ content: [
1173
+ {
1174
+ tag: 'online',
1175
+ attrs: {
1176
+ value
1177
+ }
1178
+ }
1179
+ ]
1180
+ }
1181
+ ]
1182
+ });
1183
+ return result;
1184
+ },
1185
+ updateProfilePicturePrivacy: async (value) => {
1186
+ const result = await query({
1187
+ tag: 'iq',
1188
+ attrs: {
1189
+ to: WABinary_1.S_WHATSAPP_NET,
1190
+ type: 'set',
1191
+ xmlns: 'privacy'
1192
+ },
1193
+ content: [
1194
+ {
1195
+ tag: 'privacy',
1196
+ attrs: {},
1197
+ content: [
1198
+ {
1199
+ tag: 'profile',
1200
+ attrs: {
1201
+ value
1202
+ }
1203
+ }
1204
+ ]
1205
+ }
1206
+ ]
1207
+ });
1208
+ return result;
1209
+ },
1210
+ fetchStatus: async (jid) => {
1211
+ const result = await query({
1212
+ tag: 'iq',
1213
+ attrs: {
1214
+ to: jid,
1215
+ type: 'get',
1216
+ xmlns: 'status'
1217
+ }
1218
+ });
1219
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'status');
1220
+ return {
1221
+ status: node === null || node === void 0 ? void 0 : node.content.toString(),
1222
+ setAt: new Date(+(node === null || node === void 0 ? void 0 : node.attrs.t) * 1000)
1223
+ };
1224
+ },
1225
+ fetchBlocklist: async () => {
1226
+ const result = await query({
1227
+ tag: 'iq',
1228
+ attrs: {
1229
+ to: WABinary_1.S_WHATSAPP_NET,
1230
+ type: 'get',
1231
+ xmlns: 'blocklist'
1232
+ }
1233
+ });
1234
+ const node = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
1235
+ return (0, WABinary_1.getBinaryNodeChildren)(node, 'item').map(i => i.attrs.jid);
1236
+ },
1237
+ blocklistUpdate: async (jid, action) => {
1238
+ const result = await query({
1239
+ tag: 'iq',
1240
+ attrs: {
1241
+ to: WABinary_1.S_WHATSAPP_NET,
1242
+ type: 'set',
1243
+ xmlns: 'blocklist'
1244
+ },
1245
+ content: [
1246
+ {
1247
+ tag: 'item',
1248
+ attrs: {
1249
+ jid,
1250
+ action
1251
+ }
1252
+ }
1253
+ ]
1254
+ });
1255
+ return result;
1256
+ }
1257
+ };
1258
+ };
1259
+ exports.makeSocket = makeSocket;
1260
+
1261
+ /**
1262
+ * map the websocket error to the right type
1263
+ * so it can be retried by the caller
1264
+ * */
1265
+ function mapWebSocketError(handler) {
1266
+ return (error) => {
1267
+ handler(new boom_1.Boom(`WebSocket Error (${error === null || error === void 0 ? void 0 : error.message})`, { statusCode: (0, Utils_1.getCodeFromWSError)(error), data: error }));
1268
+ };
1269
+ }