nrx-bails 0.0.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 (199) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1541 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +4775 -0
  5. package/WAProto/index.d.ts +2 -0
  6. package/WAProto/index.js +169661 -0
  7. package/lib/Defaults/index.d.ts +113 -0
  8. package/lib/Defaults/index.js +156 -0
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Defaults/ye-bail-version.json +3 -0
  11. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  12. package/lib/Signal/Group/ciphertext-message.js +41 -0
  13. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  14. package/lib/Signal/Group/group-session-builder.js +90 -0
  15. package/lib/Signal/Group/group_cipher.d.ts +12 -0
  16. package/lib/Signal/Group/group_cipher.js +122 -0
  17. package/lib/Signal/Group/index.d.ts +22 -0
  18. package/lib/Signal/Group/index.js +83 -0
  19. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  20. package/lib/Signal/Group/keyhelper.js +81 -0
  21. package/lib/Signal/Group/queue-job.d.ts +3 -0
  22. package/lib/Signal/Group/queue-job.js +83 -0
  23. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  24. package/lib/Signal/Group/sender-chain-key.js +60 -0
  25. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.js +92 -0
  27. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  28. package/lib/Signal/Group/sender-key-message.js +95 -0
  29. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  30. package/lib/Signal/Group/sender-key-name.js +77 -0
  31. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  32. package/lib/Signal/Group/sender-key-record.js +79 -0
  33. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  34. package/lib/Signal/Group/sender-key-state.js +125 -0
  35. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  36. package/lib/Signal/Group/sender-message-key.js +55 -0
  37. package/lib/Signal/libsignal.d.ts +37 -0
  38. package/lib/Signal/libsignal.js +200 -0
  39. package/lib/Socket/Client/index.d.ts +1 -0
  40. package/lib/Socket/Client/index.js +44 -0
  41. package/lib/Socket/Client/types.d.ts +7 -0
  42. package/lib/Socket/Client/types.js +39 -0
  43. package/lib/Socket/Client/websocket.d.ts +19 -0
  44. package/lib/Socket/Client/websocket.js +137 -0
  45. package/lib/Socket/business.d.ts +329 -0
  46. package/lib/Socket/business.js +286 -0
  47. package/lib/Socket/chats.d.ts +84 -0
  48. package/lib/Socket/chats.js +1022 -0
  49. package/lib/Socket/groups.d.ts +216 -0
  50. package/lib/Socket/groups.js +358 -0
  51. package/lib/Socket/index.d.ts +330 -0
  52. package/lib/Socket/index.js +36 -0
  53. package/lib/Socket/messages-recv.d.ts +271 -0
  54. package/lib/Socket/messages-recv.js +1079 -0
  55. package/lib/Socket/messages-send.d.ts +258 -0
  56. package/lib/Socket/messages-send.js +1190 -0
  57. package/lib/Socket/newsletter.d.ts +253 -0
  58. package/lib/Socket/newsletter.js +362 -0
  59. package/lib/Socket/registration.d.ts +361 -0
  60. package/lib/Socket/registration.js +179 -0
  61. package/lib/Socket/socket.d.ts +33 -0
  62. package/lib/Socket/socket.js +699 -0
  63. package/lib/Socket/usync.d.ts +27 -0
  64. package/lib/Socket/usync.js +96 -0
  65. package/lib/Store/index.d.ts +3 -0
  66. package/lib/Store/index.js +36 -0
  67. package/lib/Store/make-cache-manager-auth-state.d.ts +16 -0
  68. package/lib/Store/make-cache-manager-auth-state.js +118 -0
  69. package/lib/Store/make-in-memory-store.d.ts +64 -0
  70. package/lib/Store/make-in-memory-store.js +465 -0
  71. package/lib/Store/make-ordered-dictionary.d.ts +14 -0
  72. package/lib/Store/make-ordered-dictionary.js +107 -0
  73. package/lib/Store/object-repository.d.ts +11 -0
  74. package/lib/Store/object-repository.js +53 -0
  75. package/lib/Types/Auth.d.ts +1 -0
  76. package/lib/Types/Auth.js +28 -0
  77. package/lib/Types/Call.d.ts +1 -0
  78. package/lib/Types/Call.js +28 -0
  79. package/lib/Types/Chat.d.ts +2 -0
  80. package/lib/Types/Chat.js +30 -0
  81. package/lib/Types/Contact.d.ts +1 -0
  82. package/lib/Types/Contact.js +28 -0
  83. package/lib/Types/Events.d.ts +1 -0
  84. package/lib/Types/Events.js +28 -0
  85. package/lib/Types/GroupMetadata.d.ts +1 -0
  86. package/lib/Types/GroupMetadata.js +28 -0
  87. package/lib/Types/Label.d.ts +2 -0
  88. package/lib/Types/Label.js +53 -0
  89. package/lib/Types/LabelAssociation.d.ts +2 -0
  90. package/lib/Types/LabelAssociation.js +35 -0
  91. package/lib/Types/Message.d.ts +2 -0
  92. package/lib/Types/Message.js +33 -0
  93. package/lib/Types/Newsletter.d.ts +4 -0
  94. package/lib/Types/Newsletter.js +62 -0
  95. package/lib/Types/Product.d.ts +1 -0
  96. package/lib/Types/Product.js +28 -0
  97. package/lib/Types/Signal.d.ts +1 -0
  98. package/lib/Types/Signal.js +28 -0
  99. package/lib/Types/Socket.d.ts +1 -0
  100. package/lib/Types/Socket.js +28 -0
  101. package/lib/Types/State.d.ts +1 -0
  102. package/lib/Types/State.js +28 -0
  103. package/lib/Types/USync.d.ts +1 -0
  104. package/lib/Types/USync.js +28 -0
  105. package/lib/Types/index.d.ts +2 -0
  106. package/lib/Types/index.js +68 -0
  107. package/lib/Utils/auth-utils.d.ts +63 -0
  108. package/lib/Utils/auth-utils.js +248 -0
  109. package/lib/Utils/browser-utils.d.ts +3 -0
  110. package/lib/Utils/browser-utils.js +61 -0
  111. package/lib/Utils/business.d.ts +53 -0
  112. package/lib/Utils/business.js +260 -0
  113. package/lib/Utils/chat-utils.d.ts +253 -0
  114. package/lib/Utils/chat-utils.js +756 -0
  115. package/lib/Utils/crypto.d.ts +43 -0
  116. package/lib/Utils/crypto.js +219 -0
  117. package/lib/Utils/decode-wa-message.d.ts +61 -0
  118. package/lib/Utils/decode-wa-message.js +233 -0
  119. package/lib/Utils/event-buffer.d.ts +17 -0
  120. package/lib/Utils/event-buffer.js +544 -0
  121. package/lib/Utils/generics.d.ts +89 -0
  122. package/lib/Utils/generics.js +471 -0
  123. package/lib/Utils/history.d.ts +59 -0
  124. package/lib/Utils/history.js +120 -0
  125. package/lib/Utils/index.d.ts +1 -0
  126. package/lib/Utils/index.js +61 -0
  127. package/lib/Utils/link-preview.d.ts +19 -0
  128. package/lib/Utils/link-preview.js +152 -0
  129. package/lib/Utils/logger.d.ts +3 -0
  130. package/lib/Utils/logger.js +33 -0
  131. package/lib/Utils/lt-hash.d.ts +13 -0
  132. package/lib/Utils/lt-hash.js +77 -0
  133. package/lib/Utils/make-mutex.d.ts +7 -0
  134. package/lib/Utils/make-mutex.js +69 -0
  135. package/lib/Utils/message-retry-manager.d.ts +34 -0
  136. package/lib/Utils/message-retry-manager.js +154 -0
  137. package/lib/Utils/messages-media.d.ts +137 -0
  138. package/lib/Utils/messages-media.js +1024 -0
  139. package/lib/Utils/messages.d.ts +66 -0
  140. package/lib/Utils/messages.js +1407 -0
  141. package/lib/Utils/noise-handler.d.ts +21 -0
  142. package/lib/Utils/noise-handler.js +176 -0
  143. package/lib/Utils/pre-key-manager.d.ts +13 -0
  144. package/lib/Utils/pre-key-manager.js +93 -0
  145. package/lib/Utils/process-message.d.ts +40 -0
  146. package/lib/Utils/process-message.js +430 -0
  147. package/lib/Utils/signal.d.ts +72 -0
  148. package/lib/Utils/signal.js +179 -0
  149. package/lib/Utils/use-multi-file-auth-state.d.ts +18 -0
  150. package/lib/Utils/use-multi-file-auth-state.js +151 -0
  151. package/lib/Utils/validate-connection.d.ts +43 -0
  152. package/lib/Utils/validate-connection.js +255 -0
  153. package/lib/Utils/ye-bail-event-stream.d.ts +16 -0
  154. package/lib/Utils/ye-bail-event-stream.js +89 -0
  155. package/lib/WABinary/constants.d.ts +23 -0
  156. package/lib/WABinary/constants.js +1328 -0
  157. package/lib/WABinary/decode.d.ts +10 -0
  158. package/lib/WABinary/decode.js +291 -0
  159. package/lib/WABinary/encode.d.ts +2 -0
  160. package/lib/WABinary/encode.js +276 -0
  161. package/lib/WABinary/generic-utils.d.ts +16 -0
  162. package/lib/WABinary/generic-utils.js +155 -0
  163. package/lib/WABinary/index.d.ts +1 -0
  164. package/lib/WABinary/index.js +47 -0
  165. package/lib/WABinary/jid-utils.d.ts +34 -0
  166. package/lib/WABinary/jid-utils.js +111 -0
  167. package/lib/WABinary/types.d.ts +1 -0
  168. package/lib/WABinary/types.js +28 -0
  169. package/lib/WAM/BinaryInfo.d.ts +8 -0
  170. package/lib/WAM/BinaryInfo.js +39 -0
  171. package/lib/WAM/constants.d.ts +35374 -0
  172. package/lib/WAM/constants.js +15376 -0
  173. package/lib/WAM/encode.d.ts +2 -0
  174. package/lib/WAM/encode.js +181 -0
  175. package/lib/WAM/index.d.ts +1 -0
  176. package/lib/WAM/index.js +45 -0
  177. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +14 -0
  178. package/lib/WAUSync/Protocols/USyncContactProtocol.js +58 -0
  179. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  180. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +83 -0
  181. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  182. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +56 -0
  183. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  184. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +68 -0
  185. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  186. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +79 -0
  187. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  188. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +50 -0
  189. package/lib/WAUSync/Protocols/index.d.ts +1 -0
  190. package/lib/WAUSync/Protocols/index.js +46 -0
  191. package/lib/WAUSync/USyncQuery.d.ts +20 -0
  192. package/lib/WAUSync/USyncQuery.js +115 -0
  193. package/lib/WAUSync/USyncUser.d.ts +13 -0
  194. package/lib/WAUSync/USyncUser.js +52 -0
  195. package/lib/WAUSync/index.d.ts +1 -0
  196. package/lib/WAUSync/index.js +45 -0
  197. package/lib/index.js +81 -0
  198. package/package.json +113 -0
  199. package/requirements.js +32 -0
@@ -0,0 +1,1022 @@
1
+ /**
2
+ * ╔═══════════════════════════════════════════════════════════╗
3
+ * ║ NEROX - WhatsApp API Library ║
4
+ * ║ Premium Edition ║
5
+ * ╚═══════════════════════════════════════════════════════════╝
6
+ *
7
+ * @package nerox-bails
8
+ * @version 0.1.0
9
+ * @author NEROX Development Team
10
+ * @copyright Copyright (c) 2025 NEROX. All rights reserved.
11
+ * @license MIT License
12
+ *
13
+ * Permission is hereby granted, free of charge, to any person obtaining
14
+ * a copy of this software and associated documentation files (the "Software"),
15
+ * to deal in the Software without restriction, including without limitation
16
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
17
+ * and/or sell copies of the Software, and to permit persons to whom the
18
+ * Software is furnished to do so, subject to the following conditions:
19
+ *
20
+ * The above copyright notice and this permission notice shall be included
21
+ * in all copies or substantial portions of the Software.
22
+ *
23
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
26
+ */
27
+ "use strict";
28
+ var __importDefault = (this && this.__importDefault) || function (mod) {
29
+ return (mod && mod.__esModule) ? mod : { "default": mod };
30
+ };
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.makeChatsSocket = void 0;
33
+ const boom_1 = require("@hapi/boom");
34
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
35
+ const WAProto_1 = require("../../WAProto");
36
+ const Defaults_1 = require("../Defaults");
37
+ const Types_1 = require("../Types");
38
+ const Utils_1 = require("../Utils");
39
+ const make_mutex_1 = require("../Utils/make-mutex");
40
+ const process_message_1 = __importDefault(require("../Utils/process-message"));
41
+ const WABinary_1 = require("../WABinary");
42
+ const WAUSync_1 = require("../WAUSync");
43
+ const usync_1 = require("./usync");
44
+ const chalk = require('chalk');
45
+ const MAX_SYNC_ATTEMPTS = 2;
46
+ const SyncState = {
47
+ Connecting: 'connecting',
48
+ AwaitingInitialSync: 'awaiting_initial_sync',
49
+ Syncing: 'syncing',
50
+ Online: 'online'
51
+ };
52
+ const makeChatsSocket = (config) => {
53
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
54
+ const sock = (0, usync_1.makeUSyncSocket)(config);
55
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, } = sock;
56
+ let privacySettings;
57
+ let syncState = SyncState.Connecting;
58
+ let needToFlushWithAppStateSync = false;
59
+ let pendingAppStateSync = false;
60
+ let awaitingSyncTimeout;
61
+ const processingMutex = (0, make_mutex_1.makeMutex)();
62
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
63
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
64
+ useClones: false
65
+ });
66
+ if (!config.placeholderResendCache) {
67
+ config.placeholderResendCache = placeholderResendCache;
68
+ }
69
+ const getAppStateSyncKey = async (keyId) => {
70
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
71
+ return key;
72
+ };
73
+ const fetchPrivacySettings = async (force = false) => {
74
+ if (!privacySettings || force) {
75
+ const { content } = await query({
76
+ tag: 'iq',
77
+ attrs: {
78
+ xmlns: 'privacy',
79
+ to: WABinary_1.S_WHATSAPP_NET,
80
+ type: 'get'
81
+ },
82
+ content: [
83
+ { tag: 'privacy', attrs: {} }
84
+ ]
85
+ });
86
+ privacySettings = (0, WABinary_1.reduceBinaryNodeToDictionary)(content === null || content === void 0 ? void 0 : content[0], 'category');
87
+ }
88
+ return privacySettings;
89
+ };
90
+ const privacyQuery = async (name, value) => {
91
+ await query({
92
+ tag: 'iq',
93
+ attrs: {
94
+ xmlns: 'privacy',
95
+ to: WABinary_1.S_WHATSAPP_NET,
96
+ type: 'set'
97
+ },
98
+ content: [{
99
+ tag: 'privacy',
100
+ attrs: {},
101
+ content: [
102
+ {
103
+ tag: 'category',
104
+ attrs: { name, value }
105
+ }
106
+ ]
107
+ }]
108
+ });
109
+ };
110
+ const updateMessagesPrivacy = async (value) => {
111
+ await privacyQuery('messages', value);
112
+ };
113
+ const updateCallPrivacy = async (value) => {
114
+ await privacyQuery('calladd', value);
115
+ };
116
+ const updateLastSeenPrivacy = async (value) => {
117
+ await privacyQuery('last', value);
118
+ };
119
+ const updateOnlinePrivacy = async (value) => {
120
+ await privacyQuery('online', value);
121
+ };
122
+ const updateProfilePicturePrivacy = async (value) => {
123
+ await privacyQuery('profile', value);
124
+ };
125
+ const updateStatusPrivacy = async (value) => {
126
+ await privacyQuery('status', value);
127
+ };
128
+ const updateReadReceiptsPrivacy = async (value) => {
129
+ await privacyQuery('readreceipts', value);
130
+ };
131
+ const updateGroupsAddPrivacy = async (value) => {
132
+ await privacyQuery('groupadd', value);
133
+ };
134
+ const checkWhatsApp = async (jid) => {
135
+ if (!jid) {
136
+ throw new Error('enter jid');
137
+ }
138
+ let resultData = {
139
+ isBanned: false,
140
+ isNeedOfficialWa: false,
141
+ number: jid
142
+ };
143
+
144
+ let phoneNumber = jid;
145
+ if (phoneNumber.includes('@')) {
146
+ phoneNumber = phoneNumber.split('@')[0];
147
+ }
148
+
149
+ phoneNumber = phoneNumber.replace(/[^\d+]/g, '');
150
+ if (!phoneNumber.startsWith('+')) {
151
+ if (phoneNumber.startsWith('0')) {
152
+ phoneNumber = phoneNumber.substring(1);
153
+ }
154
+
155
+ if (!phoneNumber.startsWith('62') && phoneNumber.length > 0) {
156
+ phoneNumber = '62' + phoneNumber;
157
+ }
158
+
159
+ if (!phoneNumber.startsWith('+') && phoneNumber.length > 0) {
160
+ phoneNumber = '+' + phoneNumber;
161
+ }
162
+ }
163
+
164
+ let formattedNumber = phoneNumber;
165
+ const { parsePhoneNumber } = require('libphonenumber-js');
166
+ const parsedNumber = parsePhoneNumber(formattedNumber);
167
+ const countryCode = parsedNumber.countryCallingCode;
168
+ const nationalNumber = parsedNumber.nationalNumber;
169
+
170
+ try {
171
+ const { useMultiFileAuthState, Browsers, fetchLatestYeBailVersion } = require('../Utils');
172
+ const { makeRegistrationSocket } = require('./registration');
173
+ const { state } = await useMultiFileAuthState(".npm");
174
+ const { version } = await fetchLatestYeBailVersion();
175
+ const pino = require("pino");
176
+ const sock = makeRegistrationSocket({
177
+ version,
178
+ auth: state,
179
+ browser: Utils_1.Browsers("Chrome"),
180
+ logger: pino({
181
+ level: "silent"
182
+ }),
183
+ printQRInTerminal: false,
184
+ });
185
+ const registrationOptions = {
186
+ phoneNumber: formattedNumber,
187
+ phoneNumberCountryCode: countryCode,
188
+ phoneNumberNationalNumber: nationalNumber,
189
+ phoneNumberMobileCountryCode: "510",
190
+ phoneNumberMobileNetworkCode: "10",
191
+ method: "sms",
192
+ };
193
+
194
+ await sock.requestRegistrationCode(registrationOptions);
195
+ if (sock.ws) {
196
+ sock.ws.close();
197
+ }
198
+ return JSON.stringify(resultData, null, 2);
199
+ } catch (err) {
200
+ if (err === null || err === void 0 ? void 0 : err.appeal_token) {
201
+ resultData.isBanned = true;
202
+ resultData.data = {
203
+ violation_type: err.violation_type || null,
204
+ in_app_ban_appeal: err.in_app_ban_appeal || null,
205
+ appeal_token: err.appeal_token || null,
206
+ };
207
+ }
208
+ else if (err === null || err === void 0 ? void 0 : err.custom_block_screen || err === null || err === void 0 ? void 0 : err.reason === 'blocked') {
209
+ resultData.isNeedOfficialWa = true;
210
+ }
211
+ return JSON.stringify(resultData, null, 2);
212
+ }
213
+ };
214
+ const updateDisableLinkPreviewsPrivacy = async (isPreviewsDisabled) => {
215
+ return chatModify({ disableLinkPreviews: { isPreviewsDisabled } }, '');
216
+ };
217
+ const updateDefaultDisappearingMode = async (duration) => {
218
+ await query({
219
+ tag: 'iq',
220
+ attrs: {
221
+ xmlns: 'disappearing_mode',
222
+ to: WABinary_1.S_WHATSAPP_NET,
223
+ type: 'set'
224
+ },
225
+ content: [{
226
+ tag: 'disappearing_mode',
227
+ attrs: {
228
+ duration: duration.toString()
229
+ }
230
+ }]
231
+ });
232
+ };
233
+ const getBotListV2 = async () => {
234
+ const resp = await query({
235
+ tag: 'iq',
236
+ attrs: {
237
+ xmlns: 'bot',
238
+ to: WABinary_1.S_WHATSAPP_NET,
239
+ type: 'get'
240
+ },
241
+ content: [{
242
+ tag: 'bot',
243
+ attrs: {
244
+ v: '2'
245
+ }
246
+ }]
247
+ });
248
+ const botNode = (0, WABinary_1.getBinaryNodeChild)(resp, 'bot');
249
+ const botList = [];
250
+ for (const section of (0, WABinary_1.getBinaryNodeChildren)(botNode, 'section')) {
251
+ if (section.attrs.type === 'all') {
252
+ for (const bot of (0, WABinary_1.getBinaryNodeChildren)(section, 'bot')) {
253
+ botList.push({
254
+ jid: bot.attrs.jid,
255
+ personaId: bot.attrs['persona_id']
256
+ });
257
+ }
258
+ }
259
+ }
260
+ return botList;
261
+ };
262
+ const onWhatsApp = async (...jids) => {
263
+ const usyncQuery = new WAUSync_1.USyncQuery()
264
+ .withContactProtocol()
265
+ .withLIDProtocol();
266
+ for (const jid of jids) {
267
+ const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`;
268
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
269
+ }
270
+ const results = await sock.executeUSyncQuery(usyncQuery);
271
+ if (results) {
272
+ return results.list.filter((a) => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }));
273
+ }
274
+ };
275
+ const fetchStatus = async (...jids) => {
276
+ const usyncQuery = new WAUSync_1.USyncQuery()
277
+ .withStatusProtocol();
278
+ for (const jid of jids) {
279
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
280
+ }
281
+ const result = await sock.executeUSyncQuery(usyncQuery);
282
+ if (result) {
283
+ return result.list;
284
+ }
285
+ };
286
+ const fetchDisappearingDuration = async (...jids) => {
287
+ const usyncQuery = new WAUSync_1.USyncQuery()
288
+ .withDisappearingModeProtocol();
289
+ for (const jid of jids) {
290
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
291
+ }
292
+ const result = await sock.executeUSyncQuery(usyncQuery);
293
+ if (result) {
294
+ return result.list;
295
+ }
296
+ };
297
+ const updateProfilePicture = async (jid, content, dimensions) => {
298
+ let targetJid;
299
+ if (!jid) {
300
+ throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
301
+ }
302
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
303
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
304
+ }
305
+ const { img } = await (0, Utils_1.generateProfilePicture)(content, dimensions);
306
+ await query({
307
+ tag: 'iq',
308
+ attrs: {
309
+ target: targetJid,
310
+ to: WABinary_1.S_WHATSAPP_NET,
311
+ type: 'set',
312
+ xmlns: 'w:profile:picture'
313
+ },
314
+ content: [
315
+ {
316
+ tag: 'picture',
317
+ attrs: { type: 'image' },
318
+ content: img
319
+ }
320
+ ]
321
+ });
322
+ };
323
+ const removeProfilePicture = async (jid) => {
324
+ let targetJid;
325
+ if (!jid) {
326
+ throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
327
+ }
328
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
329
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
330
+ }
331
+ await query({
332
+ tag: 'iq',
333
+ attrs: {
334
+ target: targetJid,
335
+ to: WABinary_1.S_WHATSAPP_NET,
336
+ type: 'set',
337
+ xmlns: 'w:profile:picture'
338
+ }
339
+ });
340
+ };
341
+ const updateProfileStatus = async (status) => {
342
+ await query({
343
+ tag: 'iq',
344
+ attrs: {
345
+ to: WABinary_1.S_WHATSAPP_NET,
346
+ type: 'set',
347
+ xmlns: 'status'
348
+ },
349
+ content: [
350
+ {
351
+ tag: 'status',
352
+ attrs: {},
353
+ content: Buffer.from(status, 'utf-8')
354
+ }
355
+ ]
356
+ });
357
+ };
358
+ const updateProfileName = async (name) => {
359
+ await chatModify({ pushNameSetting: name }, '');
360
+ };
361
+ const fetchBlocklist = async () => {
362
+ const result = await query({
363
+ tag: 'iq',
364
+ attrs: {
365
+ xmlns: 'blocklist',
366
+ to: WABinary_1.S_WHATSAPP_NET,
367
+ type: 'get'
368
+ }
369
+ });
370
+ const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
371
+ return (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item')
372
+ .map(n => n.attrs.jid);
373
+ };
374
+ const updateBlockStatus = async (jid, action) => {
375
+ await query({
376
+ tag: 'iq',
377
+ attrs: {
378
+ xmlns: 'blocklist',
379
+ to: WABinary_1.S_WHATSAPP_NET,
380
+ type: 'set'
381
+ },
382
+ content: [
383
+ {
384
+ tag: 'item',
385
+ attrs: {
386
+ action,
387
+ jid
388
+ }
389
+ }
390
+ ]
391
+ });
392
+ };
393
+ const getBusinessProfile = async (jid) => {
394
+ var _a, _b, _c, _d, _e, _f, _g;
395
+ const results = await query({
396
+ tag: 'iq',
397
+ attrs: {
398
+ to: 's.whatsapp.net',
399
+ xmlns: 'w:biz',
400
+ type: 'get'
401
+ },
402
+ content: [{
403
+ tag: 'business_profile',
404
+ attrs: { v: '244' },
405
+ content: [{
406
+ tag: 'profile',
407
+ attrs: { jid }
408
+ }]
409
+ }]
410
+ });
411
+ const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile');
412
+ const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile');
413
+ if (profiles) {
414
+ const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address');
415
+ const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description');
416
+ const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website');
417
+ const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
418
+ const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
419
+ const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
420
+ const businessHoursConfig = businessHours
421
+ ? (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config')
422
+ : undefined;
423
+ const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
424
+ return {
425
+ wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
426
+ address: (_c = address === null || address === void 0 ? void 0 : address.content) === null || _c === void 0 ? void 0 : _c.toString(),
427
+ description: ((_d = description === null || description === void 0 ? void 0 : description.content) === null || _d === void 0 ? void 0 : _d.toString()) || '',
428
+ website: websiteStr ? [websiteStr] : [],
429
+ email: (_e = email === null || email === void 0 ? void 0 : email.content) === null || _e === void 0 ? void 0 : _e.toString(),
430
+ category: (_f = category === null || category === void 0 ? void 0 : category.content) === null || _f === void 0 ? void 0 : _f.toString(),
431
+ 'business_hours': {
432
+ timezone: (_g = businessHours === null || businessHours === void 0 ? void 0 : businessHours.attrs) === null || _g === void 0 ? void 0 : _g.timezone,
433
+ 'business_config': businessHoursConfig === null || businessHoursConfig === void 0 ? void 0 : businessHoursConfig.map(({ attrs }) => attrs)
434
+ }
435
+ };
436
+ }
437
+ };
438
+ const cleanDirtyBits = async (type, fromTimestamp) => {
439
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
440
+ await sendNode({
441
+ tag: 'iq',
442
+ attrs: {
443
+ to: WABinary_1.S_WHATSAPP_NET,
444
+ type: 'set',
445
+ xmlns: 'urn:xmpp:whatsapp:dirty',
446
+ id: generateMessageTag(),
447
+ },
448
+ content: [
449
+ {
450
+ tag: 'clean',
451
+ attrs: {
452
+ type,
453
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
454
+ }
455
+ }
456
+ ]
457
+ });
458
+ };
459
+ const newAppStateChunkHandler = (isInitialSync) => {
460
+ return {
461
+ onMutation(mutation) {
462
+ (0, Utils_1.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
463
+ }
464
+ };
465
+ };
466
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
467
+ const initialVersionMap = {};
468
+ const globalMutationMap = {};
469
+ await authState.keys.transaction(async () => {
470
+ var _a;
471
+ const collectionsToHandle = new Set(collections);
472
+ const attemptsMap = {};
473
+ while (collectionsToHandle.size) {
474
+ const states = {};
475
+ const nodes = [];
476
+ for (const name of collectionsToHandle) {
477
+ const result = await authState.keys.get('app-state-sync-version', [name]);
478
+ let state = result[name];
479
+ if (state) {
480
+ if (typeof initialVersionMap[name] === 'undefined') {
481
+ initialVersionMap[name] = state.version;
482
+ }
483
+ }
484
+ else {
485
+ state = (0, Utils_1.newLTHashState)();
486
+ }
487
+ states[name] = state;
488
+ logger.info(`resyncing ${name} from v${state.version}`);
489
+ nodes.push({
490
+ tag: 'collection',
491
+ attrs: {
492
+ name,
493
+ version: state.version.toString(),
494
+ 'return_snapshot': (!state.version).toString()
495
+ }
496
+ });
497
+ }
498
+ const result = await query({
499
+ tag: 'iq',
500
+ attrs: {
501
+ to: WABinary_1.S_WHATSAPP_NET,
502
+ xmlns: 'w:sync:app:state',
503
+ type: 'set'
504
+ },
505
+ content: [
506
+ {
507
+ tag: 'sync',
508
+ attrs: {},
509
+ content: nodes
510
+ }
511
+ ]
512
+ });
513
+ const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
514
+ for (const key in decoded) {
515
+ const name = key;
516
+ const { patches, hasMorePatches, snapshot } = decoded[name];
517
+ try {
518
+ if (snapshot) {
519
+ const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
520
+ states[name] = newState;
521
+ Object.assign(globalMutationMap, mutationMap);
522
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
523
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
524
+ }
525
+ if (patches.length) {
526
+ const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
527
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
528
+ logger.info(`synced ${name} to v${newState.version}`);
529
+ initialVersionMap[name] = newState.version;
530
+ Object.assign(globalMutationMap, mutationMap);
531
+ }
532
+ if (hasMorePatches) {
533
+ logger.info(`${name} has more patches...`);
534
+ }
535
+ else {
536
+ collectionsToHandle.delete(name);
537
+ }
538
+ }
539
+ catch (error) {
540
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
541
+ || ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404
542
+ || error.name === 'TypeError';
543
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
544
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
545
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
546
+ if (isIrrecoverableError) {
547
+ collectionsToHandle.delete(name);
548
+ }
549
+ }
550
+ }
551
+ }
552
+ });
553
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
554
+ for (const key in globalMutationMap) {
555
+ onMutation(globalMutationMap[key]);
556
+ }
557
+ });
558
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
559
+ var _a;
560
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
561
+ try {
562
+ const result = await query({
563
+ tag: 'iq',
564
+ attrs: {
565
+ target: jid,
566
+ to: WABinary_1.S_WHATSAPP_NET,
567
+ type: 'get',
568
+ xmlns: 'w:profile:picture'
569
+ },
570
+ content: [
571
+ { tag: 'picture', attrs: { type, query: 'url' } }
572
+ ]
573
+ }, timeoutMs);
574
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
575
+ return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
576
+ } catch (error) {
577
+ if (error.message?.includes('item-not-found') ||
578
+ error.output?.payload?.statusCode === 404 ||
579
+ error.statusCode === 404) {
580
+ logger.info(chalk.gray(`[INFO] Profile pic not found for ${jid}, using fallback`));
581
+ return {
582
+ eurl: undefined,
583
+ id: jid.split('@')[0],
584
+ status: null,
585
+ img: null
586
+ };
587
+ }
588
+ throw error;
589
+ }
590
+ };
591
+ const createCallLink = async (type, event, timeoutMs) => {
592
+ const result = await query({
593
+ tag: 'call',
594
+ attrs: {
595
+ id: generateMessageTag(),
596
+ to: '@call'
597
+ },
598
+ content: [
599
+ {
600
+ tag: 'link_create',
601
+ attrs: { media: type },
602
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
603
+ }
604
+ ]
605
+ }, timeoutMs);
606
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'link_create');
607
+ return child?.attrs?.token;
608
+ };
609
+ const sendPresenceUpdate = async (type, toJid) => {
610
+ const me = authState.creds.me;
611
+ if (type === 'available' || type === 'unavailable') {
612
+ if (!me.name) {
613
+ logger.warn('no name present, ignoring presence update request...');
614
+ return;
615
+ }
616
+ ev.emit('connection.update', { isOnline: type === 'available' });
617
+ await sendNode({
618
+ tag: 'presence',
619
+ attrs: {
620
+ name: me.name.replace(/@/g, ''),
621
+ type
622
+ }
623
+ });
624
+ }
625
+ else {
626
+ const { server } = (0, WABinary_1.jidDecode)(toJid);
627
+ const isLid = server === 'lid';
628
+ await sendNode({
629
+ tag: 'chatstate',
630
+ attrs: {
631
+ from: isLid ? me.lid : me.id,
632
+ to: toJid,
633
+ },
634
+ content: [
635
+ {
636
+ tag: type === 'recording' ? 'composing' : type,
637
+ attrs: type === 'recording' ? { media: 'audio' } : {}
638
+ }
639
+ ]
640
+ });
641
+ }
642
+ };
643
+ const presenceSubscribe = (toJid, tcToken) => (sendNode({
644
+ tag: 'presence',
645
+ attrs: {
646
+ to: toJid,
647
+ id: generateMessageTag(),
648
+ type: 'subscribe'
649
+ },
650
+ content: tcToken
651
+ ? [
652
+ {
653
+ tag: 'tctoken',
654
+ attrs: {},
655
+ content: tcToken
656
+ }
657
+ ]
658
+ : undefined
659
+ }));
660
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
661
+ var _a;
662
+ let presence;
663
+ const jid = attrs.from;
664
+ const participant = attrs.participant || attrs.from;
665
+ if (shouldIgnoreJid(jid) && jid != '@s.whatsapp.net') {
666
+ return;
667
+ }
668
+ if (tag === 'presence') {
669
+ presence = {
670
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
671
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
672
+ };
673
+ }
674
+ else if (Array.isArray(content)) {
675
+ const [firstChild] = content;
676
+ let type = firstChild.tag;
677
+ if (type === 'paused') {
678
+ type = 'available';
679
+ }
680
+ if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
681
+ type = 'recording';
682
+ }
683
+ presence = { lastKnownPresence: type };
684
+ }
685
+ else {
686
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
687
+ }
688
+ if (presence) {
689
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
690
+ }
691
+ };
692
+ const appPatch = async (patchCreate) => {
693
+ const name = patchCreate.type;
694
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
695
+ if (!myAppStateKeyId) {
696
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
697
+ }
698
+ let initial;
699
+ let encodeResult;
700
+ await processingMutex.mutex(async () => {
701
+ await authState.keys.transaction(async () => {
702
+ logger.debug({ patch: patchCreate }, 'applying app patch');
703
+ await resyncAppState([name], false);
704
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
705
+ initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
706
+ encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
707
+ const { patch, state } = encodeResult;
708
+ const node = {
709
+ tag: 'iq',
710
+ attrs: {
711
+ to: WABinary_1.S_WHATSAPP_NET,
712
+ type: 'set',
713
+ xmlns: 'w:sync:app:state'
714
+ },
715
+ content: [
716
+ {
717
+ tag: 'sync',
718
+ attrs: {},
719
+ content: [
720
+ {
721
+ tag: 'collection',
722
+ attrs: {
723
+ name,
724
+ version: (state.version - 1).toString(),
725
+ 'return_snapshot': 'false'
726
+ },
727
+ content: [
728
+ {
729
+ tag: 'patch',
730
+ attrs: {},
731
+ content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
732
+ }
733
+ ]
734
+ }
735
+ ]
736
+ }
737
+ ]
738
+ };
739
+ await query(node);
740
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
741
+ });
742
+ });
743
+ if (config.emitOwnEvents) {
744
+ const { onMutation } = newAppStateChunkHandler(false);
745
+ const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
746
+ for (const key in mutationMap) {
747
+ onMutation(mutationMap[key]);
748
+ }
749
+ }
750
+ };
751
+ const fetchProps = async () => {
752
+ var _a, _b, _c;
753
+ const resultNode = await query({
754
+ tag: 'iq',
755
+ attrs: {
756
+ to: WABinary_1.S_WHATSAPP_NET,
757
+ xmlns: 'w',
758
+ type: 'get',
759
+ },
760
+ content: [
761
+ { tag: 'props', attrs: {
762
+ protocol: '2',
763
+ hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
764
+ } }
765
+ ]
766
+ });
767
+ const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
768
+ let props = {};
769
+ if (propsNode) {
770
+ if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) {
771
+ authState.creds.lastPropHash = (_c = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _c === void 0 ? void 0 : _c.hash;
772
+ ev.emit('creds.update', authState.creds);
773
+ }
774
+ props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
775
+ }
776
+ logger.debug('fetched props');
777
+ return props;
778
+ };
779
+ const chatModify = (mod, jid) => {
780
+ const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
781
+ return appPatch(patch);
782
+ };
783
+ const star = (jid, messages, star) => {
784
+ return chatModify({
785
+ star: {
786
+ messages,
787
+ star
788
+ }
789
+ }, jid);
790
+ };
791
+ const addOrEditContact = (jid, contact) => {
792
+ return chatModify({ contact }, jid);
793
+ };
794
+ const removeContact = (jid) => {
795
+ return chatModify({ contact: null }, jid);
796
+ };
797
+ const addLabel = (jid, labels) => {
798
+ return chatModify({ addLabel: { ...labels } }, jid);
799
+ };
800
+ const addChatLabel = (jid, labelId) => {
801
+ return chatModify({
802
+ addChatLabel: {
803
+ labelId
804
+ }
805
+ }, jid);
806
+ };
807
+ const removeChatLabel = (jid, labelId) => {
808
+ return chatModify({
809
+ removeChatLabel: {
810
+ labelId
811
+ }
812
+ }, jid);
813
+ };
814
+ const addMessageLabel = (jid, messageId, labelId) => {
815
+ return chatModify({
816
+ addMessageLabel: {
817
+ messageId,
818
+ labelId
819
+ }
820
+ }, jid);
821
+ };
822
+ const removeMessageLabel = (jid, messageId, labelId) => {
823
+ return chatModify({
824
+ removeMessageLabel: {
825
+ messageId,
826
+ labelId
827
+ }
828
+ }, jid);
829
+ };
830
+ const executeInitQueries = async () => {
831
+ await Promise.all([
832
+ fetchProps(),
833
+ fetchBlocklist(),
834
+ fetchPrivacySettings(),
835
+ ]);
836
+ };
837
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
838
+ var _a, _b, _c;
839
+ ev.emit('messages.upsert', { messages: [msg], type });
840
+ if (!!msg.pushName) {
841
+ let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
842
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
843
+ if (!msg.key.fromMe) {
844
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
845
+ }
846
+ if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
847
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
848
+ }
849
+ }
850
+ const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
851
+ const shouldProcessHistoryMsg = historyMsg
852
+ ? (shouldSyncHistoryMessage(historyMsg)
853
+ && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
854
+ : false;
855
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
856
+ if (awaitingSyncTimeout) {
857
+ clearTimeout(awaitingSyncTimeout);
858
+ awaitingSyncTimeout = undefined;
859
+ }
860
+ if (shouldProcessHistoryMsg) {
861
+ syncState = SyncState.Syncing;
862
+ logger.info('Transitioned to Syncing state');
863
+ } else {
864
+ syncState = SyncState.Online;
865
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
866
+ ev.flush();
867
+ }
868
+ }
869
+ const doAppStateSync = async () => {
870
+ if (syncState === SyncState.Syncing) {
871
+ logger.info('Doing app state sync');
872
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
873
+ syncState = SyncState.Online;
874
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
875
+ ev.flush();
876
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
877
+ ev.emit('creds.update', { accountSyncCounter });
878
+ }
879
+ };
880
+ if (historyMsg && !authState.creds.myAppStateKeyId) {
881
+ logger.warn('skipping app state sync, as myAppStateKeyId is not set');
882
+ pendingAppStateSync = true;
883
+ }
884
+ await Promise.all([
885
+ (async () => {
886
+ if (historyMsg
887
+ && authState.creds.myAppStateKeyId) {
888
+ pendingAppStateSync = false;
889
+ await doAppStateSync();
890
+ }
891
+ })(),
892
+ (0, process_message_1.default)(msg, {
893
+ signalRepository,
894
+ shouldProcessHistoryMsg,
895
+ placeholderResendCache,
896
+ ev,
897
+ creds: authState.creds,
898
+ keyStore: authState.keys,
899
+ logger,
900
+ options: config.options,
901
+ getMessage: config.getMessage,
902
+ })
903
+ ]);
904
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare)
905
+ && pendingAppStateSync) {
906
+ await doAppStateSync();
907
+ pendingAppStateSync = false;
908
+ }
909
+ });
910
+ ws.on('CB:presence', handlePresenceUpdate);
911
+ ws.on('CB:chatstate', handlePresenceUpdate);
912
+ ws.on('CB:ib,,dirty', async (node) => {
913
+ const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
914
+ const type = attrs.type;
915
+ switch (type) {
916
+ case 'account_sync':
917
+ if (attrs.timestamp) {
918
+ let { lastAccountSyncTimestamp } = authState.creds;
919
+ if (lastAccountSyncTimestamp) {
920
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
921
+ }
922
+ lastAccountSyncTimestamp = +attrs.timestamp;
923
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
924
+ }
925
+ break;
926
+ case 'groups':
927
+ break;
928
+ default:
929
+ logger.info({ node }, 'received unknown sync');
930
+ break;
931
+ }
932
+ });
933
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
934
+ var _a;
935
+ if (connection === 'open') {
936
+ if (fireInitQueries) {
937
+ executeInitQueries()
938
+ .catch(error => onUnexpectedError(error, 'init queries'));
939
+ }
940
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
941
+ .catch(error => onUnexpectedError(error, 'presence update requests'));
942
+ }
943
+ if (receivedPendingNotifications &&
944
+ !((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId)) {
945
+ ev.buffer();
946
+ needToFlushWithAppStateSync = true;
947
+ }
948
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
949
+ return;
950
+ }
951
+ syncState = SyncState.AwaitingInitialSync;
952
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
953
+ ev.buffer();
954
+ const willSyncHistory = shouldSyncHistoryMessage(
955
+ WAProto_1.proto.Message.HistorySyncNotification.create({
956
+ syncType: WAProto_1.proto.HistorySync.HistorySyncType.RECENT
957
+ })
958
+ );
959
+ if (!willSyncHistory) {
960
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
961
+ syncState = SyncState.Online;
962
+ setTimeout(() => ev.flush(), 0);
963
+ return;
964
+ }
965
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
966
+ if (awaitingSyncTimeout) {
967
+ clearTimeout(awaitingSyncTimeout);
968
+ }
969
+ awaitingSyncTimeout = setTimeout(() => {
970
+ if (syncState === SyncState.AwaitingInitialSync) {
971
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
972
+ syncState = SyncState.Online;
973
+ ev.flush();
974
+ }
975
+ }, 20000);
976
+ });
977
+ return {
978
+ ...sock,
979
+ createCallLink,
980
+ getBotListV2,
981
+ processingMutex,
982
+ fetchPrivacySettings,
983
+ upsertMessage,
984
+ appPatch,
985
+ sendPresenceUpdate,
986
+ presenceSubscribe,
987
+ profilePictureUrl,
988
+ onWhatsApp,
989
+ fetchBlocklist,
990
+ fetchDisappearingDuration,
991
+ fetchStatus,
992
+ updateProfilePicture,
993
+ removeProfilePicture,
994
+ updateProfileStatus,
995
+ updateProfileName,
996
+ updateBlockStatus,
997
+ updateDisableLinkPreviewsPrivacy,
998
+ updateCallPrivacy,
999
+ updateMessagesPrivacy,
1000
+ updateLastSeenPrivacy,
1001
+ updateOnlinePrivacy,
1002
+ updateProfilePicturePrivacy,
1003
+ updateStatusPrivacy,
1004
+ updateReadReceiptsPrivacy,
1005
+ updateGroupsAddPrivacy,
1006
+ updateDefaultDisappearingMode,
1007
+ getBusinessProfile,
1008
+ resyncAppState,
1009
+ chatModify,
1010
+ cleanDirtyBits,
1011
+ addOrEditContact,
1012
+ removeContact,
1013
+ addLabel,
1014
+ addChatLabel,
1015
+ removeChatLabel,
1016
+ addMessageLabel,
1017
+ removeMessageLabel,
1018
+ star,
1019
+ checkWhatsApp
1020
+ };
1021
+ };
1022
+ exports.makeChatsSocket = makeChatsSocket;