@hbmodsofc/baileys 2.5.0 → 3.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 (162) hide show
  1. package/LICENSE +1 -1
  2. package/README.MD +220 -1198
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +5619 -0
  5. package/engine-requirements.js +1 -1
  6. package/lib/Defaults/baileys-version.json +1 -1
  7. package/lib/Defaults/index.js +97 -122
  8. package/lib/Defaults/phonenumber_mcc.json +223 -0
  9. package/lib/Socket/Client/index.js +2 -3
  10. package/lib/Socket/Client/{web-socket-client.js → websocket.js} +54 -5
  11. package/lib/Socket/business.js +8 -2
  12. package/lib/Socket/chats.js +455 -288
  13. package/lib/Socket/communities.js +441 -0
  14. package/lib/Socket/groups.js +38 -23
  15. package/lib/Socket/hbmods.js +374 -406
  16. package/lib/Socket/index.js +43 -11
  17. package/lib/Socket/messages-recv.js +24 -69
  18. package/lib/Socket/messages-send.js +391 -419
  19. package/lib/Socket/newsletter.js +104 -190
  20. package/lib/Socket/socket.js +40 -54
  21. package/lib/Store/index.js +1 -3
  22. package/lib/Store/make-in-memory-store.js +27 -15
  23. package/lib/Store/make-ordered-dictionary.js +2 -2
  24. package/lib/Types/Label.js +1 -1
  25. package/lib/Types/LabelAssociation.js +1 -1
  26. package/lib/Types/Message.js +0 -2
  27. package/lib/Types/Newsletter.js +18 -38
  28. package/lib/Types/index.js +2 -2
  29. package/lib/Utils/async-iterable.js +41 -0
  30. package/lib/Utils/audioToBuffer.js +29 -0
  31. package/lib/Utils/auth-utils.js +6 -13
  32. package/lib/Utils/baileys-event-stream.js +1 -1
  33. package/lib/Utils/browser-utils.js +35 -0
  34. package/lib/Utils/business.js +2 -2
  35. package/lib/Utils/chat-utils.js +36 -35
  36. package/lib/Utils/crypto.js +71 -29
  37. package/lib/Utils/decode-wa-message.js +65 -56
  38. package/lib/Utils/event-buffer.js +13 -9
  39. package/lib/Utils/generics.js +88 -84
  40. package/lib/Utils/history.js +4 -6
  41. package/lib/Utils/index.js +3 -0
  42. package/lib/Utils/link-preview.js +34 -1
  43. package/lib/Utils/lt-hash.js +6 -6
  44. package/lib/Utils/message-retry-manager.js +128 -0
  45. package/lib/Utils/messages-media.js +340 -246
  46. package/lib/Utils/messages.js +329 -192
  47. package/lib/Utils/noise-handler.js +18 -23
  48. package/lib/Utils/process-message.js +108 -25
  49. package/lib/Utils/resolveJid.js +52 -0
  50. package/lib/Utils/signal.js +26 -26
  51. package/lib/Utils/streamToBuffer.js +15 -0
  52. package/lib/Utils/use-multi-file-auth-state.js +3 -0
  53. package/lib/Utils/validate-connection.js +1 -3
  54. package/lib/WABinary/constants.js +1276 -13
  55. package/lib/WABinary/decode.js +26 -13
  56. package/lib/WABinary/encode.js +137 -152
  57. package/lib/WABinary/generic-utils.js +37 -125
  58. package/lib/WABinary/jid-utils.js +28 -5
  59. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -1
  60. package/lib/index.js +2 -1
  61. package/package.json +112 -104
  62. package/lib/Defaults/index.d.ts +0 -53
  63. package/lib/Defaults/phonenumber-mcc.json +0 -223
  64. package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
  65. package/lib/Signal/Group/group-session-builder.d.ts +0 -14
  66. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  67. package/lib/Signal/Group/index.d.ts +0 -11
  68. package/lib/Signal/Group/keyhelper.d.ts +0 -10
  69. package/lib/Signal/Group/queue-job.d.ts +0 -1
  70. package/lib/Signal/Group/sender-chain-key.d.ts +0 -13
  71. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -16
  72. package/lib/Signal/Group/sender-key-message.d.ts +0 -18
  73. package/lib/Signal/Group/sender-key-name.d.ts +0 -17
  74. package/lib/Signal/Group/sender-key-record.d.ts +0 -30
  75. package/lib/Signal/Group/sender-key-state.d.ts +0 -38
  76. package/lib/Signal/Group/sender-message-key.d.ts +0 -11
  77. package/lib/Signal/libsignal.d.ts +0 -3
  78. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  79. package/lib/Socket/Client/index.d.ts +0 -3
  80. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  81. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  82. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  83. package/lib/Socket/business.d.ts +0 -171
  84. package/lib/Socket/chats.d.ts +0 -267
  85. package/lib/Socket/groups.d.ts +0 -115
  86. package/lib/Socket/hbmods.d.ts +0 -254
  87. package/lib/Socket/index.d.ts +0 -173
  88. package/lib/Socket/messages-recv.d.ts +0 -161
  89. package/lib/Socket/messages-send.d.ts +0 -149
  90. package/lib/Socket/newsletter.d.ts +0 -134
  91. package/lib/Socket/registration.d.ts +0 -267
  92. package/lib/Socket/registration.js +0 -166
  93. package/lib/Socket/socket.d.ts +0 -43
  94. package/lib/Socket/usync.d.ts +0 -36
  95. package/lib/Store/index.d.ts +0 -3
  96. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  97. package/lib/Store/make-cache-manager-store.js +0 -83
  98. package/lib/Store/make-in-memory-store.d.ts +0 -118
  99. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  100. package/lib/Store/object-repository.d.ts +0 -10
  101. package/lib/Types/Auth.d.ts +0 -110
  102. package/lib/Types/Call.d.ts +0 -13
  103. package/lib/Types/Chat.d.ts +0 -102
  104. package/lib/Types/Contact.d.ts +0 -19
  105. package/lib/Types/Events.d.ts +0 -157
  106. package/lib/Types/GroupMetadata.d.ts +0 -55
  107. package/lib/Types/Label.d.ts +0 -35
  108. package/lib/Types/LabelAssociation.d.ts +0 -29
  109. package/lib/Types/Message.d.ts +0 -273
  110. package/lib/Types/Newsletter.d.ts +0 -103
  111. package/lib/Types/Product.d.ts +0 -78
  112. package/lib/Types/Signal.d.ts +0 -57
  113. package/lib/Types/Socket.d.ts +0 -111
  114. package/lib/Types/State.d.ts +0 -27
  115. package/lib/Types/USync.d.ts +0 -25
  116. package/lib/Types/index.d.ts +0 -57
  117. package/lib/Utils/auth-utils.d.ts +0 -18
  118. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  119. package/lib/Utils/business.d.ts +0 -22
  120. package/lib/Utils/chat-utils.d.ts +0 -71
  121. package/lib/Utils/crypto.d.ts +0 -41
  122. package/lib/Utils/decode-wa-message.d.ts +0 -19
  123. package/lib/Utils/event-buffer.d.ts +0 -35
  124. package/lib/Utils/generics.d.ts +0 -92
  125. package/lib/Utils/generics.js.bak +0 -433
  126. package/lib/Utils/history.d.ts +0 -15
  127. package/lib/Utils/index.d.ts +0 -17
  128. package/lib/Utils/link-preview.d.ts +0 -21
  129. package/lib/Utils/logger.d.ts +0 -4
  130. package/lib/Utils/lt-hash.d.ts +0 -12
  131. package/lib/Utils/make-mutex.d.ts +0 -7
  132. package/lib/Utils/messages-media.d.ts +0 -116
  133. package/lib/Utils/messages.d.ts +0 -77
  134. package/lib/Utils/noise-handler.d.ts +0 -21
  135. package/lib/Utils/process-message.d.ts +0 -41
  136. package/lib/Utils/signal.d.ts +0 -32
  137. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  138. package/lib/Utils/validate-connection.d.ts +0 -11
  139. package/lib/Utils/validate-connection.js.bak +0 -237
  140. package/lib/WABinary/constants.d.ts +0 -30
  141. package/lib/WABinary/decode.d.ts +0 -7
  142. package/lib/WABinary/encode.d.ts +0 -3
  143. package/lib/WABinary/generic-utils.d.ts +0 -17
  144. package/lib/WABinary/index.d.ts +0 -5
  145. package/lib/WABinary/jid-utils.d.ts +0 -31
  146. package/lib/WABinary/types.d.ts +0 -18
  147. package/lib/WAM/BinaryInfo.d.ts +0 -17
  148. package/lib/WAM/constants.d.ts +0 -38
  149. package/lib/WAM/encode.d.ts +0 -3
  150. package/lib/WAM/index.d.ts +0 -3
  151. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  152. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  153. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  154. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  155. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  156. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  157. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  158. package/lib/WAUSync/USyncQuery.d.ts +0 -28
  159. package/lib/WAUSync/USyncUser.d.ts +0 -12
  160. package/lib/WAUSync/index.d.ts +0 -3
  161. package/lib/index.d.ts +0 -12
  162. /package/lib/Socket/Client/{abstract-socket-client.js → types.js} +0 -0
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
4
+ };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.makeChatsSocket = void 0;
7
7
  const boom_1 = require("@hapi/boom");
8
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
8
9
  const WAProto_1 = require("../../WAProto");
9
10
  const Defaults_1 = require("../Defaults");
10
11
  const Types_1 = require("../Types");
@@ -12,20 +13,40 @@ const Utils_1 = require("../Utils");
12
13
  const make_mutex_1 = require("../Utils/make-mutex");
13
14
  const process_message_1 = __importDefault(require("../Utils/process-message"));
14
15
  const WABinary_1 = require("../WABinary");
15
- const socket_1 = require("./socket");
16
16
  const WAUSync_1 = require("../WAUSync");
17
17
  const usync_1 = require("./usync");
18
+ const chalk = require('chalk');
18
19
  const MAX_SYNC_ATTEMPTS = 2;
20
+ const SyncState = {
21
+ Connecting: 'connecting',
22
+ AwaitingInitialSync: 'awaiting_initial_sync',
23
+ Syncing: 'syncing',
24
+ Online: 'online'
25
+ };
19
26
  const makeChatsSocket = (config) => {
20
- const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
27
+ const {
28
+ logger,
29
+ markOnlineOnConnect,
30
+ fireInitQueries,
31
+ appStateMacVerification,
32
+ shouldIgnoreJid,
33
+ shouldSyncHistoryMessage,
34
+ relayMessage, } = config;
21
35
  const sock = (0, usync_1.makeUSyncSocket)(config);
22
- const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, } = sock;
36
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, } = sock;
23
37
  let privacySettings;
38
+ let syncState = SyncState.Connecting;
24
39
  let needToFlushWithAppStateSync = false;
25
40
  let pendingAppStateSync = false;
26
- /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
41
+ let awaitingSyncTimeout;
27
42
  const processingMutex = (0, make_mutex_1.makeMutex)();
28
- /** helper function to fetch the given app state sync key */
43
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
44
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
45
+ useClones: false
46
+ });
47
+ if (!config.placeholderResendCache) {
48
+ config.placeholderResendCache = placeholderResendCache;
49
+ }
29
50
  const getAppStateSyncKey = async (keyId) => {
30
51
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
31
52
  return key;
@@ -47,7 +68,6 @@ const makeChatsSocket = (config) => {
47
68
  }
48
69
  return privacySettings;
49
70
  };
50
- /** helper function to run a privacy IQ query */
51
71
  const privacyQuery = async (name, value) => {
52
72
  await query({
53
73
  tag: 'iq',
@@ -68,6 +88,12 @@ const makeChatsSocket = (config) => {
68
88
  }]
69
89
  });
70
90
  };
91
+ const updateMessagesPrivacy = async (value) => {
92
+ await privacyQuery('messages', value);
93
+ };
94
+ const updateCallPrivacy = async (value) => {
95
+ await privacyQuery('calladd', value);
96
+ };
71
97
  const updateLastSeenPrivacy = async (value) => {
72
98
  await privacyQuery('last', value);
73
99
  };
@@ -86,73 +112,8 @@ const makeChatsSocket = (config) => {
86
112
  const updateGroupsAddPrivacy = async (value) => {
87
113
  await privacyQuery('groupadd', value);
88
114
  };
89
- /** check whether your WhatsApp account is blocked or not */
90
- const checkStatusWA = async (phoneNumber) => {
91
- if (!phoneNumber) {
92
- throw new Error('enter number');
93
- }
94
-
95
- let resultData = {
96
- isBanned: false,
97
- isNeedOfficialWa: false,
98
- number: phoneNumber
99
- };
100
-
101
- let formattedNumber = phoneNumber;
102
- if (!formattedNumber.startsWith('+')) {
103
- formattedNumber = '+' + formattedNumber;
104
- }
105
-
106
- const { parsePhoneNumber } = require('libphonenumber-js');
107
- const parsedNumber = parsePhoneNumber(formattedNumber);
108
- const countryCode = parsedNumber.countryCallingCode;
109
- const nationalNumber = parsedNumber.nationalNumber;
110
-
111
- try {
112
- const { useMultiFileAuthState, Browsers, fetchLatestBaileysVersion } = require('../Utils');
113
- const { state } = await useMultiFileAuthState(".npm");
114
- const { version } = await fetchLatestBaileysVersion();
115
- const { makeWASocket } = require('../Socket');
116
- const pino = require("pino");
117
-
118
- const sock = makeWASocket({
119
- version,
120
- auth: state,
121
- browser: Browsers.ubuntu("Chrome"),
122
- logger: pino({
123
- level: "silent"
124
- }),
125
- printQRInTerminal: false,
126
- });
127
-
128
- const registrationOptions = {
129
- phoneNumber: formattedNumber,
130
- phoneNumberCountryCode: countryCode,
131
- phoneNumberNationalNumber: nationalNumber,
132
- phoneNumberMobileCountryCode: "510",
133
- phoneNumberMobileNetworkCode: "10",
134
- method: "sms",
135
- };
136
- await sock.requestRegistrationCode(registrationOptions);
137
- if (sock.ws) {
138
- sock.ws.close();
139
- }
140
-
141
- return JSON.stringify(resultData, null, 2);
142
- } catch (err) {
143
- if (err?.appeal_token) {
144
- resultData.isBanned = true;
145
- resultData.data = {
146
- violation_type: err.violation_type || null,
147
- in_app_ban_appeal: err.in_app_ban_appeal || null,
148
- appeal_token: err.appeal_token || null,
149
- };
150
- }
151
- else if (err?.custom_block_screen || err?.reason === 'blocked') {
152
- resultData.isNeedOfficialWa = true;
153
- }
154
- return JSON.stringify(resultData, null, 2);
155
- }
115
+ const updateDisableLinkPreviewsPrivacy = async (isPreviewsDisabled) => {
116
+ return chatModify({ disableLinkPreviews: { isPreviewsDisabled } }, '');
156
117
  };
157
118
  const updateDefaultDisappearingMode = async (duration) => {
158
119
  await query({
@@ -170,46 +131,228 @@ const makeChatsSocket = (config) => {
170
131
  }]
171
132
  });
172
133
  };
173
- /** helper function to run a generic IQ query */
174
- const interactiveQuery = async (userNodes, queryNode) => {
175
- const result = await query({
134
+ const getBotListV2 = async () => {
135
+ const resp = await query({
176
136
  tag: 'iq',
177
137
  attrs: {
138
+ xmlns: 'bot',
178
139
  to: WABinary_1.S_WHATSAPP_NET,
179
- type: 'get',
180
- xmlns: 'usync',
140
+ type: 'get'
181
141
  },
182
- content: [
183
- {
184
- tag: 'usync',
142
+ content: [{
143
+ tag: 'bot',
185
144
  attrs: {
186
- sid: generateMessageTag(),
187
- mode: 'query',
188
- last: 'true',
189
- index: '0',
190
- context: 'interactive',
191
- },
192
- content: [
193
- {
194
- tag: 'query',
195
- attrs: {},
196
- content: [queryNode]
197
- },
198
- {
199
- tag: 'list',
200
- attrs: {},
201
- content: userNodes
202
- }
203
- ]
204
- }
205
- ],
145
+ v: '2'
146
+ }
147
+ }]
206
148
  });
207
- const usyncNode = (0, WABinary_1.getBinaryNodeChild)(result, 'usync');
208
- const listNode = (0, WABinary_1.getBinaryNodeChild)(usyncNode, 'list');
209
- const users = (0, WABinary_1.getBinaryNodeChildren)(listNode, 'user');
210
- return users;
149
+ const botNode = (0, WABinary_1.getBinaryNodeChild)(resp, 'bot');
150
+ const botList = [];
151
+ for (const section of (0, WABinary_1.getBinaryNodeChildren)(botNode, 'section')) {
152
+ if (section.attrs.type === 'all') {
153
+ for (const bot of (0, WABinary_1.getBinaryNodeChildren)(section, 'bot')) {
154
+ botList.push({
155
+ jid: bot.attrs.jid,
156
+ personaId: bot.attrs['persona_id']
157
+ });
158
+ }
159
+ }
160
+ }
161
+ return botList;
162
+ };
163
+ const onWhatsApp = async (...jids) => {
164
+ const usyncQuery = new WAUSync_1.USyncQuery()
165
+ .withContactProtocol()
166
+ .withLIDProtocol();
167
+ for (const jid of jids) {
168
+ const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`;
169
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
170
+ }
171
+ const results = await sock.executeUSyncQuery(usyncQuery);
172
+ if (results) {
173
+ return results.list.filter((a) => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }));
174
+ }
175
+ };
176
+ const fetchStatus = async (...jids) => {
177
+ const usyncQuery = new WAUSync_1.USyncQuery()
178
+ .withStatusProtocol();
179
+ for (const jid of jids) {
180
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
181
+ }
182
+ const result = await sock.executeUSyncQuery(usyncQuery);
183
+ if (result) {
184
+ return result.list;
185
+ }
211
186
  };
212
- const getBusinessProfile = async (jid) => {
187
+ const cekid = async (link) => {
188
+ try {
189
+ let url;
190
+ try {
191
+ url = new URL(link);
192
+ } catch {
193
+ return {
194
+ link,
195
+ jid: "-",
196
+ exists: false,
197
+ IsBanned: true,
198
+ metadata: "-",
199
+ error: "Invalid link format"
200
+ };
201
+ }
202
+
203
+ const isChannel =
204
+ url.hostname === "whatsapp.com" &&
205
+ url.pathname.startsWith("/channel/");
206
+
207
+ if (!isChannel) {
208
+ return {
209
+ link,
210
+ jid: "-",
211
+ exists: false,
212
+ IsBanned: true,
213
+ metadata: "-",
214
+ error: "The link is not a WhatsApp channel link"
215
+ };
216
+ }
217
+
218
+ const code = url.pathname.split("/channel/")[1]?.split("/")[0];
219
+
220
+ if (!code) {
221
+ return {
222
+ link,
223
+ jid: "-",
224
+ exists: false,
225
+ IsBanned: true,
226
+ metadata: "-",
227
+ error: "Invalid channel code"
228
+ };
229
+ }
230
+
231
+ let data = null;
232
+
233
+ try {
234
+ data = await conn.newsletterMetadata("invite", code);
235
+ } catch {
236
+ data = await conn.newsletterMetadata(code).catch(() => null);
237
+ }
238
+
239
+ if (!data?.id) {
240
+ return {
241
+ link,
242
+ jid: "-",
243
+ exists: false,
244
+ IsBanned: true,
245
+ metadata: "-",
246
+ error: "Failed to fetch channel metadata"
247
+ };
248
+ }
249
+
250
+ return {
251
+ link,
252
+ jid: data.id,
253
+ exists: true,
254
+ IsBanned: false,
255
+ metadata: {
256
+ id: data.id || "-",
257
+ name: data.name || "-",
258
+ description: data.description || "-",
259
+ subscribers: data.subscribers || "-",
260
+ ownerJid: data.ownerJid || "-",
261
+ invite: data.invite || "-",
262
+ verification: data.verification || "-",
263
+ state: data.state || "-",
264
+ creation: data.creation || "-"
265
+ },
266
+ error: null
267
+ };
268
+
269
+ } catch (e) {
270
+ return {
271
+ link,
272
+ jid: "-",
273
+ exists: false,
274
+ IsBanned: true,
275
+ metadata: "-",
276
+ error: e.message
277
+ };
278
+ }
279
+ };
280
+ const checkStatusWA = async (numberOrJid) => {
281
+ try {
282
+ const jid = numberOrJid.includes('@s.whatsapp.net')
283
+ ? numberOrJid
284
+ : numberOrJid.replace(/[^0-9]/g, '') + '@s.whatsapp.net'
285
+
286
+ const exists = await onWhatsApp(jid)
287
+ if (!exists || !exists[0]?.exists) {
288
+ return {
289
+ jid,
290
+ IsBanned: true,
291
+ Statusbio: "-",
292
+ setAt: "-",
293
+ businessProfile: {
294
+ wid: "-",
295
+ address: "-",
296
+ description: "-",
297
+ website: "-",
298
+ email: "-",
299
+ category: "-",
300
+ business_hours: "-"
301
+ }
302
+ }
303
+ }
304
+
305
+ const fetched = await fetchStatus(jid).catch(() => [])
306
+ const status = fetched?.[0]?.status?.status || "-"
307
+ const setAt = fetched?.[0]?.status?.setAt || "-"
308
+
309
+ const business = await getBusinessProfile(jid).catch(() => null)
310
+
311
+ const businessProfile = business ? {
312
+ wid: business.wid || "-",
313
+ address: business.address || "-",
314
+ description: business.description || "-",
315
+ website: business.website?.[0] || "-",
316
+ email: business.email || "-",
317
+ category: business.category || "-",
318
+ business_hours: business.business_hours || "-"
319
+ } : {
320
+ wid: "-",
321
+ address: "-",
322
+ description: "-",
323
+ website: "-",
324
+ email: "-",
325
+ category: "-",
326
+ business_hours: "-"
327
+ }
328
+
329
+ return {
330
+ jid,
331
+ IsBanned: false,
332
+ Statusbio: status,
333
+ setAt,
334
+ businessProfile
335
+ }
336
+ } catch (e) {
337
+ return {
338
+ jid: numberOrJid,
339
+ IsBanned: true,
340
+ Statusbio: "-",
341
+ setAt: "-",
342
+ businessProfile: {
343
+ wid: "-",
344
+ address: "-",
345
+ description: "-",
346
+ website: "-",
347
+ email: "-",
348
+ category: "-",
349
+ business_hours: "-"
350
+ },
351
+ error: e.message
352
+ }
353
+ }
354
+ };
355
+ const getBusinessProfile = async (jid) => {
213
356
  var _a, _b, _c, _d, _e, _f, _g;
214
357
  const results = await query({
215
358
  tag: 'iq',
@@ -254,76 +397,28 @@ const makeChatsSocket = (config) => {
254
397
  };
255
398
  }
256
399
  };
257
- const onWhatsApp = async (...jids) => {
400
+
401
+
402
+ const fetchDisappearingDuration = async (...jids) => {
258
403
  const usyncQuery = new WAUSync_1.USyncQuery()
259
- .withContactProtocol()
260
- .withLIDProtocol();
261
-
404
+ .withDisappearingModeProtocol();
262
405
  for (const jid of jids) {
263
- const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`;
264
- usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone));
265
- }
266
-
267
- const results = await sock.executeUSyncQuery(usyncQuery);
268
- if (results) {
269
- const verifiedResults = await Promise.all(
270
- results.list
271
- .filter((a) => !!a.contact)
272
- .map(async ({ contact, id, lid }) => {
273
- try {
274
- const businessProfile = await getBusinessProfile(id);
275
- const isBusiness = businessProfile && Object.keys(businessProfile).length > 0;
276
- if (isBusiness) {
277
- const { wid, ...businessInfo } = businessProfile;
278
-
279
- return {
280
- jid: id,
281
- exists: true,
282
- lid: lid,
283
- status: 'business',
284
- businessInfo: businessInfo
285
- };
286
- } else {
287
- return {
288
- jid: id,
289
- exists: true,
290
- lid: lid,
291
- status: 'regular'
292
- };
293
- }
294
- } catch (error) {
295
- return {
296
- jid: id,
297
- exists: true,
298
- lid: lid,
299
- status: error
300
- };
301
- }
302
- })
303
- );
304
- return verifiedResults;
406
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid));
305
407
  }
306
- };
307
- const fetchStatus = async (jid) => {
308
- const [result] = await interactiveQuery([{ tag: 'user', attrs: { jid } }], { tag: 'status', attrs: {} });
408
+ const result = await sock.executeUSyncQuery(usyncQuery);
309
409
  if (result) {
310
- const status = (0, WABinary_1.getBinaryNodeChild)(result, 'status');
311
- return {
312
- status: status === null || status === void 0 ? void 0 : status.content.toString(),
313
- setAt: new Date(+((status === null || status === void 0 ? void 0 : status.attrs.t) || 0) * 1000)
314
- };
410
+ return result.list;
315
411
  }
316
412
  };
317
- /** update the profile picture for yourself or a group */
318
- const updateProfilePicture = async (jid, content) => {
413
+ const updateProfilePicture = async (jid, content, dimensions) => {
319
414
  let targetJid;
320
415
  if (!jid) {
321
416
  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');
322
417
  }
323
418
  if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
324
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
419
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
325
420
  }
326
- const { img } = await (0, Utils_1.generateProfilePicture)(content);
421
+ const { img } = await (0, Utils_1.generateProfilePicture)(content, dimensions);
327
422
  await query({
328
423
  tag: 'iq',
329
424
  attrs: {
@@ -341,14 +436,13 @@ const makeChatsSocket = (config) => {
341
436
  ]
342
437
  });
343
438
  };
344
- /** remove the profile picture for yourself or a group */
345
439
  const removeProfilePicture = async (jid) => {
346
440
  let targetJid;
347
441
  if (!jid) {
348
442
  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');
349
443
  }
350
444
  if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
351
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
445
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
352
446
  }
353
447
  await query({
354
448
  tag: 'iq',
@@ -360,7 +454,6 @@ const makeChatsSocket = (config) => {
360
454
  }
361
455
  });
362
456
  };
363
- /** update the profile status for yourself */
364
457
  const updateProfileStatus = async (status) => {
365
458
  await query({
366
459
  tag: 'iq',
@@ -413,6 +506,7 @@ const makeChatsSocket = (config) => {
413
506
  ]
414
507
  });
415
508
  };
509
+
416
510
  const cleanDirtyBits = async (type, fromTimestamp) => {
417
511
  logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
418
512
  await sendNode({
@@ -442,18 +536,12 @@ const makeChatsSocket = (config) => {
442
536
  };
443
537
  };
444
538
  const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
445
- // we use this to determine which events to fire
446
- // otherwise when we resync from scratch -- all notifications will fire
447
539
  const initialVersionMap = {};
448
540
  const globalMutationMap = {};
449
541
  await authState.keys.transaction(async () => {
450
542
  var _a;
451
543
  const collectionsToHandle = new Set(collections);
452
- // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
453
544
  const attemptsMap = {};
454
- // keep executing till all collections are done
455
- // sometimes a single patch request will not return all the patches (God knows why)
456
- // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
457
545
  while (collectionsToHandle.size) {
458
546
  const states = {};
459
547
  const nodes = [];
@@ -475,7 +563,6 @@ const makeChatsSocket = (config) => {
475
563
  attrs: {
476
564
  name,
477
565
  version: state.version.toString(),
478
- // return snapshot if being synced from scratch
479
566
  'return_snapshot': (!state.version).toString()
480
567
  }
481
568
  });
@@ -495,7 +582,6 @@ const makeChatsSocket = (config) => {
495
582
  }
496
583
  ]
497
584
  });
498
- // extract from binary node
499
585
  const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
500
586
  for (const key in decoded) {
501
587
  const name = key;
@@ -506,16 +592,11 @@ const makeChatsSocket = (config) => {
506
592
  states[name] = newState;
507
593
  Object.assign(globalMutationMap, mutationMap);
508
594
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
509
- await authState.keys.set({ 'app-state-sync-version': {
510
- [name]: newState
511
- } });
595
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
512
596
  }
513
- // only process if there are syncd patches
514
597
  if (patches.length) {
515
598
  const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
516
- await authState.keys.set({ 'app-state-sync-version': {
517
- [name]: newState
518
- } });
599
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
519
600
  logger.info(`synced ${name} to v${newState.version}`);
520
601
  initialVersionMap[name] = newState.version;
521
602
  Object.assign(globalMutationMap, mutationMap);
@@ -523,24 +604,18 @@ const makeChatsSocket = (config) => {
523
604
  if (hasMorePatches) {
524
605
  logger.info(`${name} has more patches...`);
525
606
  }
526
- else { // collection is done with sync
607
+ else {
527
608
  collectionsToHandle.delete(name);
528
609
  }
529
610
  }
530
611
  catch (error) {
531
- // if retry attempts overshoot
532
- // or key not found
533
- const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
534
- ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404 ||
535
- error.name === 'TypeError';
612
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
613
+ || ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404
614
+ || error.name === 'TypeError';
536
615
  logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
537
- await authState.keys.set({ 'app-state-sync-version': {
538
- [name]: null
539
- } });
540
- // increment number of retries
616
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
541
617
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
542
618
  if (isIrrecoverableError) {
543
- // stop retrying
544
619
  collectionsToHandle.delete(name);
545
620
  }
546
621
  }
@@ -552,28 +627,56 @@ const makeChatsSocket = (config) => {
552
627
  onMutation(globalMutationMap[key]);
553
628
  }
554
629
  });
555
- /**
556
- * fetch the profile picture of a user/group
557
- * type = "preview" for a low res picture
558
- * type = "image for the high res picture"
559
- */
560
630
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
561
631
  var _a;
562
632
  jid = (0, WABinary_1.jidNormalizedUser)(jid);
633
+ try {
634
+ const result = await query({
635
+ tag: 'iq',
636
+ attrs: {
637
+ target: jid,
638
+ to: WABinary_1.S_WHATSAPP_NET,
639
+ type: 'get',
640
+ xmlns: 'w:profile:picture'
641
+ },
642
+ content: [
643
+ { tag: 'picture', attrs: { type, query: 'url' } }
644
+ ]
645
+ }, timeoutMs);
646
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
647
+ return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
648
+ } catch (error) {
649
+ if (error.message?.includes('item-not-found') ||
650
+ error.output?.payload?.statusCode === 404 ||
651
+ error.statusCode === 404) {
652
+ logger.info(chalk.gray(`[INFO] Profile pic not found for ${jid}, using fallback`));
653
+ return {
654
+ eurl: undefined,
655
+ id: jid.split('@')[0],
656
+ status: null,
657
+ img: null
658
+ };
659
+ }
660
+ throw error;
661
+ }
662
+ };
663
+ const createCallLink = async (type, event, timeoutMs) => {
563
664
  const result = await query({
564
- tag: 'iq',
665
+ tag: 'call',
565
666
  attrs: {
566
- target: jid,
567
- to: WABinary_1.S_WHATSAPP_NET,
568
- type: 'get',
569
- xmlns: 'w:profile:picture'
667
+ id: generateMessageTag(),
668
+ to: '@call'
570
669
  },
571
670
  content: [
572
- { tag: 'picture', attrs: { type, query: 'url' } }
671
+ {
672
+ tag: 'link_create',
673
+ attrs: { media: type },
674
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
675
+ }
573
676
  ]
574
677
  }, timeoutMs);
575
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
576
- return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
678
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'link_create');
679
+ return child?.attrs?.token;
577
680
  };
578
681
  const sendPresenceUpdate = async (type, toJid) => {
579
682
  const me = authState.creds.me;
@@ -586,7 +689,7 @@ const makeChatsSocket = (config) => {
586
689
  await sendNode({
587
690
  tag: 'presence',
588
691
  attrs: {
589
- name: me.name,
692
+ name: me.name.replace(/@/g, ''),
590
693
  type
591
694
  }
592
695
  });
@@ -609,10 +712,6 @@ const makeChatsSocket = (config) => {
609
712
  });
610
713
  }
611
714
  };
612
- /**
613
- * @param toJid the jid to subscribe to
614
- * @param tcToken token for subscription, use if present
615
- */
616
715
  const presenceSubscribe = (toJid, tcToken) => (sendNode({
617
716
  tag: 'presence',
618
717
  attrs: {
@@ -620,22 +719,22 @@ const makeChatsSocket = (config) => {
620
719
  id: generateMessageTag(),
621
720
  type: 'subscribe'
622
721
  },
623
- content: tcToken ?
624
- [
722
+ content: tcToken
723
+ ? [
625
724
  {
626
725
  tag: 'tctoken',
627
726
  attrs: {},
628
727
  content: tcToken
629
728
  }
630
- ] :
631
- undefined
729
+ ]
730
+ : undefined
632
731
  }));
633
732
  const handlePresenceUpdate = ({ tag, attrs, content }) => {
634
733
  var _a;
635
734
  let presence;
636
735
  const jid = attrs.from;
637
736
  const participant = attrs.participant || attrs.from;
638
- if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
737
+ if (shouldIgnoreJid(jid) && jid != '@s.whatsapp.net') {
639
738
  return;
640
739
  }
641
740
  if (tag === 'presence') {
@@ -659,9 +758,7 @@ const makeChatsSocket = (config) => {
659
758
  logger.error({ tag, attrs, content }, 'recv invalid presence node');
660
759
  }
661
760
  if (presence) {
662
- ev.emit('presence.update', { id: jid, presences: {
663
- [participant]: presence
664
- } });
761
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
665
762
  }
666
763
  };
667
764
  const appPatch = async (patchCreate) => {
@@ -712,9 +809,7 @@ const makeChatsSocket = (config) => {
712
809
  ]
713
810
  };
714
811
  await query(node);
715
- await authState.keys.set({ 'app-state-sync-version': {
716
- [name]: state
717
- } });
812
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
718
813
  });
719
814
  });
720
815
  if (config.emitOwnEvents) {
@@ -725,9 +820,8 @@ const makeChatsSocket = (config) => {
725
820
  }
726
821
  }
727
822
  };
728
- /** sending non-abt props may fix QR scan fail if server expects */
729
823
  const fetchProps = async () => {
730
- var _a, _b;
824
+ var _a, _b, _c;
731
825
  const resultNode = await query({
732
826
  tag: 'iq',
733
827
  attrs: {
@@ -736,37 +830,28 @@ const makeChatsSocket = (config) => {
736
830
  type: 'get',
737
831
  },
738
832
  content: [
739
- {
740
- tag: 'props',
741
- attrs: {
833
+ { tag: 'props', attrs: {
742
834
  protocol: '2',
743
835
  hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
744
- }
745
- }
836
+ } }
746
837
  ]
747
838
  });
748
839
  const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
749
840
  let props = {};
750
841
  if (propsNode) {
751
- authState.creds.lastPropHash = (_b = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash;
752
- ev.emit('creds.update', authState.creds);
842
+ if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) {
843
+ authState.creds.lastPropHash = (_c = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _c === void 0 ? void 0 : _c.hash;
844
+ ev.emit('creds.update', authState.creds);
845
+ }
753
846
  props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
754
847
  }
755
848
  logger.debug('fetched props');
756
849
  return props;
757
850
  };
758
- /**
759
- * modify a chat -- mark unread, read etc.
760
- * lastMessages must be sorted in reverse chronologically
761
- * requires the last messages till the last message received; required for archive & unread
762
- */
763
851
  const chatModify = (mod, jid) => {
764
852
  const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
765
853
  return appPatch(patch);
766
854
  };
767
- /**
768
- * Star or Unstar a message
769
- */
770
855
  const star = (jid, messages, star) => {
771
856
  return chatModify({
772
857
  star: {
@@ -775,9 +860,56 @@ const makeChatsSocket = (config) => {
775
860
  }
776
861
  }, jid);
777
862
  };
778
- /**
779
- * Adds label for the chats
780
- */
863
+ const addOrEditContact = (jid, contact) => {
864
+ return chatModify({ contact }, jid);
865
+ };
866
+ const removeContact = (jid) => {
867
+ return chatModify({ contact: null }, jid);
868
+ };
869
+
870
+ const addLabelMember = async (jid, label, timestamp = Date.now()) => {
871
+ try {
872
+ return await relayMessage(
873
+ jid,
874
+ {
875
+ protocolMessage: {
876
+ type: 30,
877
+ memberLabel: {
878
+ label,
879
+ labelTimestamp: timestamp
880
+ }
881
+ }
882
+ },
883
+ {}
884
+ )
885
+ } catch (e) {
886
+ logger.error('Failed addLabelMember: ' + e)
887
+ throw e
888
+ }
889
+ }
890
+
891
+ const removeLabelMember = async (jid) => {
892
+ try {
893
+ return await relayMessage(
894
+ jid,
895
+ {
896
+ protocolMessage: {
897
+ type: 30,
898
+ memberLabel: {
899
+ label: ''
900
+ }
901
+ }
902
+ },
903
+ {}
904
+ )
905
+ } catch (e) {
906
+ logger.error('Failed removeLabelMember: ' + e)
907
+ throw e
908
+ }
909
+ }
910
+ const addLabel = (jid, labels) => {
911
+ return chatModify({ addLabel: { ...labels } }, jid);
912
+ };
781
913
  const addChatLabel = (jid, labelId) => {
782
914
  return chatModify({
783
915
  addChatLabel: {
@@ -785,9 +917,6 @@ const makeChatsSocket = (config) => {
785
917
  }
786
918
  }, jid);
787
919
  };
788
- /**
789
- * Removes label for the chat
790
- */
791
920
  const removeChatLabel = (jid, labelId) => {
792
921
  return chatModify({
793
922
  removeChatLabel: {
@@ -795,9 +924,6 @@ const makeChatsSocket = (config) => {
795
924
  }
796
925
  }, jid);
797
926
  };
798
- /**
799
- * Adds label for the message
800
- */
801
927
  const addMessageLabel = (jid, messageId, labelId) => {
802
928
  return chatModify({
803
929
  addMessageLabel: {
@@ -806,9 +932,6 @@ const makeChatsSocket = (config) => {
806
932
  }
807
933
  }, jid);
808
934
  };
809
- /**
810
- * Removes label for the message
811
- */
812
935
  const removeMessageLabel = (jid, messageId, labelId) => {
813
936
  return chatModify({
814
937
  removeMessageLabel: {
@@ -817,10 +940,6 @@ const makeChatsSocket = (config) => {
817
940
  }
818
941
  }, jid);
819
942
  };
820
- /**
821
- * queries need to be fired on connection open
822
- * help ensure parity with WA Web
823
- * */
824
943
  const executeInitQueries = async () => {
825
944
  await Promise.all([
826
945
  fetchProps(),
@@ -837,30 +956,56 @@ const makeChatsSocket = (config) => {
837
956
  if (!msg.key.fromMe) {
838
957
  ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
839
958
  }
840
- // update our pushname too
841
959
  if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
842
960
  ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
843
961
  }
844
962
  }
845
963
  const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
846
- const shouldProcessHistoryMsg = historyMsg ?
847
- (shouldSyncHistoryMessage(historyMsg) &&
848
- Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)) :
849
- false;
964
+ const shouldProcessHistoryMsg = historyMsg
965
+ ? (shouldSyncHistoryMessage(historyMsg)
966
+ && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
967
+ : false;
968
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
969
+ if (awaitingSyncTimeout) {
970
+ clearTimeout(awaitingSyncTimeout);
971
+ awaitingSyncTimeout = undefined;
972
+ }
973
+ if (shouldProcessHistoryMsg) {
974
+ syncState = SyncState.Syncing;
975
+ logger.info('Transitioned to Syncing state');
976
+ } else {
977
+ syncState = SyncState.Online;
978
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
979
+ ev.flush();
980
+ }
981
+ }
982
+ const doAppStateSync = async () => {
983
+ if (syncState === SyncState.Syncing) {
984
+ logger.info('Doing app state sync');
985
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
986
+ syncState = SyncState.Online;
987
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
988
+ ev.flush();
989
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
990
+ ev.emit('creds.update', { accountSyncCounter });
991
+ }
992
+ };
850
993
  if (historyMsg && !authState.creds.myAppStateKeyId) {
851
994
  logger.warn('skipping app state sync, as myAppStateKeyId is not set');
852
995
  pendingAppStateSync = true;
853
996
  }
854
997
  await Promise.all([
855
998
  (async () => {
856
- if (historyMsg &&
857
- authState.creds.myAppStateKeyId) {
999
+ if (historyMsg
1000
+ && authState.creds.myAppStateKeyId) {
858
1001
  pendingAppStateSync = false;
859
1002
  await doAppStateSync();
860
1003
  }
861
1004
  })(),
862
1005
  (0, process_message_1.default)(msg, {
1006
+ signalRepository,
863
1007
  shouldProcessHistoryMsg,
1008
+ placeholderResendCache,
864
1009
  ev,
865
1010
  creds: authState.creds,
866
1011
  keyStore: authState.keys,
@@ -869,23 +1014,11 @@ const makeChatsSocket = (config) => {
869
1014
  getMessage: config.getMessage,
870
1015
  })
871
1016
  ]);
872
- if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare) &&
873
- pendingAppStateSync) {
1017
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare)
1018
+ && pendingAppStateSync) {
874
1019
  await doAppStateSync();
875
1020
  pendingAppStateSync = false;
876
1021
  }
877
- async function doAppStateSync() {
878
- if (!authState.creds.accountSyncCounter) {
879
- logger.info('doing initial app state sync');
880
- await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
881
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
882
- ev.emit('creds.update', { accountSyncCounter });
883
- if (needToFlushWithAppStateSync) {
884
- logger.debug('flushing with app state sync');
885
- ev.flush();
886
- }
887
- }
888
- }
889
1022
  });
890
1023
  ws.on('CB:presence', handlePresenceUpdate);
891
1024
  ws.on('CB:chatstate', handlePresenceUpdate);
@@ -904,7 +1037,6 @@ const makeChatsSocket = (config) => {
904
1037
  }
905
1038
  break;
906
1039
  case 'groups':
907
- // handled in groups.ts
908
1040
  break;
909
1041
  default:
910
1042
  logger.info({ node }, 'received unknown sync');
@@ -921,18 +1053,44 @@ const makeChatsSocket = (config) => {
921
1053
  sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
922
1054
  .catch(error => onUnexpectedError(error, 'presence update requests'));
923
1055
  }
924
- if (receivedPendingNotifications) {
925
- // if we don't have the app state key
926
- // we keep buffering events until we finally have
927
- // the key and can sync the messages
928
- if (!((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId) && !config.mobile) {
929
- ev.buffer();
930
- needToFlushWithAppStateSync = true;
931
- }
1056
+ if (receivedPendingNotifications &&
1057
+ !((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId)) {
1058
+ ev.buffer();
1059
+ needToFlushWithAppStateSync = true;
1060
+ }
1061
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
1062
+ return;
932
1063
  }
1064
+ syncState = SyncState.AwaitingInitialSync;
1065
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
1066
+ ev.buffer();
1067
+ const willSyncHistory = shouldSyncHistoryMessage(
1068
+ WAProto_1.proto.Message.HistorySyncNotification.create({
1069
+ syncType: WAProto_1.proto.HistorySync.HistorySyncType.RECENT
1070
+ })
1071
+ );
1072
+ if (!willSyncHistory) {
1073
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
1074
+ syncState = SyncState.Online;
1075
+ setTimeout(() => ev.flush(), 0);
1076
+ return;
1077
+ }
1078
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
1079
+ if (awaitingSyncTimeout) {
1080
+ clearTimeout(awaitingSyncTimeout);
1081
+ }
1082
+ awaitingSyncTimeout = setTimeout(() => {
1083
+ if (syncState === SyncState.AwaitingInitialSync) {
1084
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1085
+ syncState = SyncState.Online;
1086
+ ev.flush();
1087
+ }
1088
+ }, 20000);
933
1089
  });
934
1090
  return {
935
1091
  ...sock,
1092
+ createCallLink,
1093
+ getBotListV2,
936
1094
  processingMutex,
937
1095
  fetchPrivacySettings,
938
1096
  upsertMessage,
@@ -941,13 +1099,18 @@ const makeChatsSocket = (config) => {
941
1099
  presenceSubscribe,
942
1100
  profilePictureUrl,
943
1101
  onWhatsApp,
1102
+ checkStatusWA,
944
1103
  fetchBlocklist,
1104
+ fetchDisappearingDuration,
945
1105
  fetchStatus,
946
1106
  updateProfilePicture,
947
1107
  removeProfilePicture,
948
1108
  updateProfileStatus,
949
1109
  updateProfileName,
950
1110
  updateBlockStatus,
1111
+ updateDisableLinkPreviewsPrivacy,
1112
+ updateCallPrivacy,
1113
+ updateMessagesPrivacy,
951
1114
  updateLastSeenPrivacy,
952
1115
  updateOnlinePrivacy,
953
1116
  updateProfilePicturePrivacy,
@@ -959,12 +1122,16 @@ const makeChatsSocket = (config) => {
959
1122
  resyncAppState,
960
1123
  chatModify,
961
1124
  cleanDirtyBits,
1125
+ addOrEditContact,
1126
+ removeContact,
1127
+ addLabel,
962
1128
  addChatLabel,
963
1129
  removeChatLabel,
964
1130
  addMessageLabel,
965
- checkStatusWA,
966
1131
  removeMessageLabel,
967
- star
1132
+ star,
1133
+ addLabelMember,
1134
+ removeLabelMember
968
1135
  };
969
1136
  };
970
1137
  exports.makeChatsSocket = makeChatsSocket;