@ryuhan/baileys 1.0.1 → 1.0.4

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 (115) hide show
  1. package/LICENSE +1 -1
  2. package/{README.md → README.MD} +16 -30
  3. package/lib/Defaults/index.js +50 -35
  4. package/lib/Defaults/ryuhan-version.json +3 -0
  5. package/lib/Socket/chats.js +147 -87
  6. package/lib/Socket/messages-recv.js +127 -43
  7. package/lib/Socket/socket.js +17 -4
  8. package/lib/Store/make-in-memory-store.js +1 -1
  9. package/lib/Utils/browser-utils.js +35 -0
  10. package/lib/Utils/event-buffer.js +2 -2
  11. package/lib/Utils/generics.js +36 -10
  12. package/lib/Utils/identity-change-handler.js +52 -0
  13. package/lib/Utils/index.js +4 -1
  14. package/lib/Utils/message-retry-manager.js +135 -0
  15. package/lib/Utils/process-message.js +17 -7
  16. package/lib/Utils/{baileys-event-stream.js → ryuhan-event-stream.js} +1 -1
  17. package/lib/Utils/use-multi-file-auth-state.js +0 -2
  18. package/lib/Utils/validate-connection.js +77 -21
  19. package/lib/index.js +30 -2
  20. package/package.json +11 -10
  21. package/WAProto/index.d.ts +0 -55057
  22. package/WAProto/index.ts.ts +0 -53473
  23. package/WAProto/p.html +0 -1
  24. package/lib/Defaults/baileys-version.json +0 -3
  25. package/lib/Defaults/index.d.ts +0 -51
  26. package/lib/Signal/Group/ciphertext-message.d.ts +0 -9
  27. package/lib/Signal/Group/group-session-builder.d.ts +0 -14
  28. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  29. package/lib/Signal/Group/index.d.ts +0 -11
  30. package/lib/Signal/Group/keyhelper.d.ts +0 -10
  31. package/lib/Signal/Group/queue-job.d.ts +0 -1
  32. package/lib/Signal/Group/sender-chain-key.d.ts +0 -13
  33. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -16
  34. package/lib/Signal/Group/sender-key-message.d.ts +0 -18
  35. package/lib/Signal/Group/sender-key-name.d.ts +0 -17
  36. package/lib/Signal/Group/sender-key-record.d.ts +0 -30
  37. package/lib/Signal/Group/sender-key-state.d.ts +0 -38
  38. package/lib/Signal/Group/sender-message-key.d.ts +0 -11
  39. package/lib/Signal/libsignal.d.ts +0 -3
  40. package/lib/Socket/Client/index.d.ts +0 -2
  41. package/lib/Socket/Client/types.d.ts +0 -16
  42. package/lib/Socket/Client/websocket.d.ts +0 -13
  43. package/lib/Socket/business.d.ts +0 -172
  44. package/lib/Socket/chats.d.ts +0 -82
  45. package/lib/Socket/groups.d.ts +0 -124
  46. package/lib/Socket/index.d.ts +0 -172
  47. package/lib/Socket/messages-recv.d.ts +0 -161
  48. package/lib/Socket/messages-send.d.ts +0 -151
  49. package/lib/Socket/newsletter.d.ts +0 -136
  50. package/lib/Socket/socket.d.ts +0 -43
  51. package/lib/Socket/usync.d.ts +0 -36
  52. package/lib/Store/index.d.ts +0 -2
  53. package/lib/Store/make-in-memory-store.d.ts +0 -118
  54. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  55. package/lib/Store/object-repository.d.ts +0 -10
  56. package/lib/Types/Auth.d.ts +0 -103
  57. package/lib/Types/Call.d.ts +0 -13
  58. package/lib/Types/Chat.d.ts +0 -109
  59. package/lib/Types/Contact.d.ts +0 -23
  60. package/lib/Types/Events.d.ts +0 -199
  61. package/lib/Types/GroupMetadata.d.ts +0 -64
  62. package/lib/Types/Label.d.ts +0 -35
  63. package/lib/Types/LabelAssociation.d.ts +0 -29
  64. package/lib/Types/Message.d.ts +0 -400
  65. package/lib/Types/Newsletter.d.ts +0 -79
  66. package/lib/Types/Product.d.ts +0 -78
  67. package/lib/Types/Signal.d.ts +0 -57
  68. package/lib/Types/Socket.d.ts +0 -119
  69. package/lib/Types/State.d.ts +0 -27
  70. package/lib/Types/USync.d.ts +0 -25
  71. package/lib/Types/index.d.ts +0 -64
  72. package/lib/Utils/auth-utils.d.ts +0 -18
  73. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  74. package/lib/Utils/business.d.ts +0 -22
  75. package/lib/Utils/chat-utils.d.ts +0 -70
  76. package/lib/Utils/crypto.d.ts +0 -40
  77. package/lib/Utils/decode-wa-message.d.ts +0 -35
  78. package/lib/Utils/event-buffer.d.ts +0 -35
  79. package/lib/Utils/generics.d.ts +0 -89
  80. package/lib/Utils/history.d.ts +0 -19
  81. package/lib/Utils/index.d.ts +0 -17
  82. package/lib/Utils/link-preview.d.ts +0 -21
  83. package/lib/Utils/logger.d.ts +0 -11
  84. package/lib/Utils/lt-hash.d.ts +0 -12
  85. package/lib/Utils/make-mutex.d.ts +0 -7
  86. package/lib/Utils/messages-media.d.ts +0 -120
  87. package/lib/Utils/messages.d.ts +0 -80
  88. package/lib/Utils/noise-handler.d.ts +0 -19
  89. package/lib/Utils/process-message.d.ts +0 -42
  90. package/lib/Utils/signal.d.ts +0 -33
  91. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  92. package/lib/Utils/validate-connection.d.ts +0 -10
  93. package/lib/WABinary/constants.d.ts +0 -27
  94. package/lib/WABinary/decode.d.ts +0 -6
  95. package/lib/WABinary/encode.d.ts +0 -2
  96. package/lib/WABinary/generic-utils.d.ts +0 -14
  97. package/lib/WABinary/index.d.ts +0 -5
  98. package/lib/WABinary/jid-utils.d.ts +0 -37
  99. package/lib/WABinary/jid-utils.js.bak +0 -83
  100. package/lib/WABinary/types.d.ts +0 -18
  101. package/lib/WAM/BinaryInfo.d.ts +0 -8
  102. package/lib/WAM/constants.d.ts +0 -38
  103. package/lib/WAM/encode.d.ts +0 -2
  104. package/lib/WAM/index.d.ts +0 -3
  105. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -9
  106. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -22
  107. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -12
  108. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -12
  109. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -25
  110. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -8
  111. package/lib/WAUSync/Protocols/index.d.ts +0 -4
  112. package/lib/WAUSync/USyncQuery.d.ts +0 -28
  113. package/lib/WAUSync/USyncUser.d.ts +0 -12
  114. package/lib/WAUSync/index.d.ts +0 -3
  115. package/lib/index.d.ts +0 -16
@@ -15,24 +15,43 @@ const process_message_1 = __importDefault(require("../Utils/process-message"));
15
15
  const WABinary_1 = require("../WABinary");
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
27
  const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
21
28
  const sock = (0, usync_1.makeUSyncSocket)(config);
22
- const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, } = sock;
29
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, } = sock;
23
30
  let privacySettings;
31
+ let syncState = SyncState.Connecting;
24
32
  let needToFlushWithAppStateSync = false;
25
33
  let pendingAppStateSync = false;
26
- /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
34
+ let awaitingSyncTimeout;
27
35
  const processingMutex = (0, make_mutex_1.makeMutex)();
36
+ const messageMutex = (0, make_mutex_1.makeMutex)();
37
+ const notificationMutex = (0, make_mutex_1.makeMutex)();
38
+ const receiptMutex = (0, make_mutex_1.makeMutex)();
28
39
  const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
29
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
40
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
30
41
  useClones: false
31
42
  });
32
43
  if (!config.placeholderResendCache) {
33
44
  config.placeholderResendCache = placeholderResendCache;
34
45
  }
35
- /** helper function to fetch the given app state sync key */
46
+ // Initialize message retry manager
47
+ const messageRetryManager = config.messageRetryManager || (0, Utils_1.createMessageRetryManager)({
48
+ maxRetries: config.maxMsgRetryCount || Defaults_1.DEFAULT_MAX_MSG_RETRY_COUNT,
49
+ phoneRequestDelayMs: config.phoneRequestDelayMs || Defaults_1.DEFAULT_PHONE_REQUEST_DELAY_MS,
50
+ logger
51
+ });
52
+ if (!config.messageRetryManager) {
53
+ config.messageRetryManager = messageRetryManager;
54
+ }
36
55
  const getAppStateSyncKey = async (keyId) => {
37
56
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
38
57
  return key;
@@ -54,7 +73,6 @@ const makeChatsSocket = (config) => {
54
73
  }
55
74
  return privacySettings;
56
75
  };
57
- /** helper function to run a privacy IQ query */
58
76
  const privacyQuery = async (name, value) => {
59
77
  await query({
60
78
  tag: 'iq',
@@ -99,6 +117,9 @@ const makeChatsSocket = (config) => {
99
117
  const updateGroupsAddPrivacy = async (value) => {
100
118
  await privacyQuery('groupadd', value);
101
119
  };
120
+ const updateDisableLinkPreviewsPrivacy = async (isPreviewsDisabled) => {
121
+ return chatModify({ disableLinkPreviews: { isPreviewsDisabled } }, '');
122
+ };
102
123
  const updateDefaultDisappearingMode = async (duration) => {
103
124
  await query({
104
125
  tag: 'iq',
@@ -179,16 +200,15 @@ const makeChatsSocket = (config) => {
179
200
  return result.list;
180
201
  }
181
202
  };
182
- /** update the profile picture for yourself or a group */
183
- const updateProfilePicture = async (jid, content) => {
203
+ const updateProfilePicture = async (jid, content, dimensions) => {
184
204
  let targetJid;
185
205
  if (!jid) {
186
206
  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');
187
207
  }
188
208
  if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
189
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
209
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
190
210
  }
191
- const { img } = await (0, Utils_1.generateProfilePicture)(content);
211
+ const { img } = await (0, Utils_1.generateProfilePicture)(content, dimensions);
192
212
  await query({
193
213
  tag: 'iq',
194
214
  attrs: {
@@ -206,14 +226,13 @@ const makeChatsSocket = (config) => {
206
226
  ]
207
227
  });
208
228
  };
209
- /** remove the profile picture for yourself or a group */
210
229
  const removeProfilePicture = async (jid) => {
211
230
  let targetJid;
212
231
  if (!jid) {
213
232
  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');
214
233
  }
215
234
  if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
216
- targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
235
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid);
217
236
  }
218
237
  await query({
219
238
  tag: 'iq',
@@ -225,7 +244,6 @@ const makeChatsSocket = (config) => {
225
244
  }
226
245
  });
227
246
  };
228
- /** update the profile status for yourself */
229
247
  const updateProfileStatus = async (status) => {
230
248
  await query({
231
249
  tag: 'iq',
@@ -352,18 +370,12 @@ const makeChatsSocket = (config) => {
352
370
  };
353
371
  };
354
372
  const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
355
- // we use this to determine which events to fire
356
- // otherwise when we resync from scratch -- all notifications will fire
357
373
  const initialVersionMap = {};
358
374
  const globalMutationMap = {};
359
375
  await authState.keys.transaction(async () => {
360
376
  var _a;
361
377
  const collectionsToHandle = new Set(collections);
362
- // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
363
378
  const attemptsMap = {};
364
- // keep executing till all collections are done
365
- // sometimes a single patch request will not return all the patches (God knows why)
366
- // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
367
379
  while (collectionsToHandle.size) {
368
380
  const states = {};
369
381
  const nodes = [];
@@ -385,7 +397,6 @@ const makeChatsSocket = (config) => {
385
397
  attrs: {
386
398
  name,
387
399
  version: state.version.toString(),
388
- // return snapshot if being synced from scratch
389
400
  'return_snapshot': (!state.version).toString()
390
401
  }
391
402
  });
@@ -405,7 +416,6 @@ const makeChatsSocket = (config) => {
405
416
  }
406
417
  ]
407
418
  });
408
- // extract from binary node
409
419
  const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
410
420
  for (const key in decoded) {
411
421
  const name = key;
@@ -418,7 +428,6 @@ const makeChatsSocket = (config) => {
418
428
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
419
429
  await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
420
430
  }
421
- // only process if there are syncd patches
422
431
  if (patches.length) {
423
432
  const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
424
433
  await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
@@ -429,22 +438,18 @@ const makeChatsSocket = (config) => {
429
438
  if (hasMorePatches) {
430
439
  logger.info(`${name} has more patches...`);
431
440
  }
432
- else { // collection is done with sync
441
+ else {
433
442
  collectionsToHandle.delete(name);
434
443
  }
435
444
  }
436
445
  catch (error) {
437
- // if retry attempts overshoot
438
- // or key not found
439
446
  const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
440
447
  || ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404
441
448
  || error.name === 'TypeError';
442
449
  logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
443
450
  await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
444
- // increment number of retries
445
451
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
446
452
  if (isIrrecoverableError) {
447
- // stop retrying
448
453
  collectionsToHandle.delete(name);
449
454
  }
450
455
  }
@@ -456,28 +461,56 @@ const makeChatsSocket = (config) => {
456
461
  onMutation(globalMutationMap[key]);
457
462
  }
458
463
  });
459
- /**
460
- * fetch the profile picture of a user/group
461
- * type = "preview" for a low res picture
462
- * type = "image for the high res picture"
463
- */
464
464
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
465
465
  var _a;
466
466
  jid = (0, WABinary_1.jidNormalizedUser)(jid);
467
+ try {
468
+ const result = await query({
469
+ tag: 'iq',
470
+ attrs: {
471
+ target: jid,
472
+ to: WABinary_1.S_WHATSAPP_NET,
473
+ type: 'get',
474
+ xmlns: 'w:profile:picture'
475
+ },
476
+ content: [
477
+ { tag: 'picture', attrs: { type, query: 'url' } }
478
+ ]
479
+ }, timeoutMs);
480
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
481
+ return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
482
+ } catch (error) {
483
+ if (error.message?.includes('item-not-found') ||
484
+ error.output?.payload?.statusCode === 404 ||
485
+ error.statusCode === 404) {
486
+ logger.info(chalk.gray(`[INFO] Profile pic not found for ${jid}, using fallback`));
487
+ return {
488
+ eurl: undefined,
489
+ id: jid.split('@')[0],
490
+ status: null,
491
+ img: null
492
+ };
493
+ }
494
+ throw error;
495
+ }
496
+ };
497
+ const createCallLink = async (type, event, timeoutMs) => {
467
498
  const result = await query({
468
- tag: 'iq',
499
+ tag: 'call',
469
500
  attrs: {
470
- target: jid,
471
- to: WABinary_1.S_WHATSAPP_NET,
472
- type: 'get',
473
- xmlns: 'w:profile:picture'
501
+ id: generateMessageTag(),
502
+ to: '@call'
474
503
  },
475
504
  content: [
476
- { tag: 'picture', attrs: { type, query: 'url' } }
505
+ {
506
+ tag: 'link_create',
507
+ attrs: { media: type },
508
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
509
+ }
477
510
  ]
478
511
  }, timeoutMs);
479
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
480
- return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
512
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'link_create');
513
+ return child?.attrs?.token;
481
514
  };
482
515
  const sendPresenceUpdate = async (type, toJid) => {
483
516
  const me = authState.creds.me;
@@ -513,10 +546,6 @@ const makeChatsSocket = (config) => {
513
546
  });
514
547
  }
515
548
  };
516
- /**
517
- * @param toJid the jid to subscribe to
518
- * @param tcToken token for subscription, use if present
519
- */
520
549
  const presenceSubscribe = (toJid, tcToken) => (sendNode({
521
550
  tag: 'presence',
522
551
  attrs: {
@@ -625,7 +654,6 @@ const makeChatsSocket = (config) => {
625
654
  }
626
655
  }
627
656
  };
628
- /** sending non-abt props may fix QR scan fail if server expects */
629
657
  const fetchProps = async () => {
630
658
  var _a, _b, _c;
631
659
  const resultNode = await query({
@@ -645,7 +673,7 @@ const makeChatsSocket = (config) => {
645
673
  const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
646
674
  let props = {};
647
675
  if (propsNode) {
648
- if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) { // on some clients, the hash is returning as undefined
676
+ if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) {
649
677
  authState.creds.lastPropHash = (_c = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _c === void 0 ? void 0 : _c.hash;
650
678
  ev.emit('creds.update', authState.creds);
651
679
  }
@@ -654,18 +682,10 @@ const makeChatsSocket = (config) => {
654
682
  logger.debug('fetched props');
655
683
  return props;
656
684
  };
657
- /**
658
- * modify a chat -- mark unread, read etc.
659
- * lastMessages must be sorted in reverse chronologically
660
- * requires the last messages till the last message received; required for archive & unread
661
- */
662
685
  const chatModify = (mod, jid) => {
663
686
  const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
664
687
  return appPatch(patch);
665
688
  };
666
- /**
667
- * Star or Unstar a message
668
- */
669
689
  const star = (jid, messages, star) => {
670
690
  return chatModify({
671
691
  star: {
@@ -674,9 +694,15 @@ const makeChatsSocket = (config) => {
674
694
  }
675
695
  }, jid);
676
696
  };
677
- /**
678
- * Adds label for the chats
679
- */
697
+ const addOrEditContact = (jid, contact) => {
698
+ return chatModify({ contact }, jid);
699
+ };
700
+ const removeContact = (jid) => {
701
+ return chatModify({ contact: null }, jid);
702
+ };
703
+ const addLabel = (jid, labels) => {
704
+ return chatModify({ addLabel: { ...labels } }, jid);
705
+ };
680
706
  const addChatLabel = (jid, labelId) => {
681
707
  return chatModify({
682
708
  addChatLabel: {
@@ -684,9 +710,6 @@ const makeChatsSocket = (config) => {
684
710
  }
685
711
  }, jid);
686
712
  };
687
- /**
688
- * Removes label for the chat
689
- */
690
713
  const removeChatLabel = (jid, labelId) => {
691
714
  return chatModify({
692
715
  removeChatLabel: {
@@ -694,9 +717,6 @@ const makeChatsSocket = (config) => {
694
717
  }
695
718
  }, jid);
696
719
  };
697
- /**
698
- * Adds label for the message
699
- */
700
720
  const addMessageLabel = (jid, messageId, labelId) => {
701
721
  return chatModify({
702
722
  addMessageLabel: {
@@ -705,9 +725,6 @@ const makeChatsSocket = (config) => {
705
725
  }
706
726
  }, jid);
707
727
  };
708
- /**
709
- * Removes label for the message
710
- */
711
728
  const removeMessageLabel = (jid, messageId, labelId) => {
712
729
  return chatModify({
713
730
  removeMessageLabel: {
@@ -716,10 +733,6 @@ const makeChatsSocket = (config) => {
716
733
  }
717
734
  }, jid);
718
735
  };
719
- /**
720
- * queries need to be fired on connection open
721
- * help ensure parity with WA Web
722
- * */
723
736
  const executeInitQueries = async () => {
724
737
  await Promise.all([
725
738
  fetchProps(),
@@ -736,7 +749,6 @@ const makeChatsSocket = (config) => {
736
749
  if (!msg.key.fromMe) {
737
750
  ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
738
751
  }
739
- // update our pushname too
740
752
  if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
741
753
  ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
742
754
  }
@@ -746,6 +758,31 @@ const makeChatsSocket = (config) => {
746
758
  ? (shouldSyncHistoryMessage(historyMsg)
747
759
  && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
748
760
  : false;
761
+ if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
762
+ if (awaitingSyncTimeout) {
763
+ clearTimeout(awaitingSyncTimeout);
764
+ awaitingSyncTimeout = undefined;
765
+ }
766
+ if (shouldProcessHistoryMsg) {
767
+ syncState = SyncState.Syncing;
768
+ logger.info('Transitioned to Syncing state');
769
+ } else {
770
+ syncState = SyncState.Online;
771
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
772
+ ev.flush();
773
+ }
774
+ }
775
+ const doAppStateSync = async () => {
776
+ if (syncState === SyncState.Syncing) {
777
+ logger.info('Doing app state sync');
778
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
779
+ syncState = SyncState.Online;
780
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
781
+ ev.flush();
782
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
783
+ ev.emit('creds.update', { accountSyncCounter });
784
+ }
785
+ };
749
786
  if (historyMsg && !authState.creds.myAppStateKeyId) {
750
787
  logger.warn('skipping app state sync, as myAppStateKeyId is not set');
751
788
  pendingAppStateSync = true;
@@ -759,6 +796,7 @@ const makeChatsSocket = (config) => {
759
796
  }
760
797
  })(),
761
798
  (0, process_message_1.default)(msg, {
799
+ signalRepository,
762
800
  shouldProcessHistoryMsg,
763
801
  placeholderResendCache,
764
802
  ev,
@@ -774,18 +812,6 @@ const makeChatsSocket = (config) => {
774
812
  await doAppStateSync();
775
813
  pendingAppStateSync = false;
776
814
  }
777
- async function doAppStateSync() {
778
- if (!authState.creds.accountSyncCounter) {
779
- logger.info('doing initial app state sync');
780
- await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
781
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
782
- ev.emit('creds.update', { accountSyncCounter });
783
- if (needToFlushWithAppStateSync) {
784
- logger.debug('flushing with app state sync');
785
- ev.flush();
786
- }
787
- }
788
- }
789
815
  });
790
816
  ws.on('CB:presence', handlePresenceUpdate);
791
817
  ws.on('CB:chatstate', handlePresenceUpdate);
@@ -804,7 +830,6 @@ const makeChatsSocket = (config) => {
804
830
  }
805
831
  break;
806
832
  case 'groups':
807
- // handled in groups.ts
808
833
  break;
809
834
  default:
810
835
  logger.info({ node }, 'received unknown sync');
@@ -821,18 +846,49 @@ const makeChatsSocket = (config) => {
821
846
  sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
822
847
  .catch(error => onUnexpectedError(error, 'presence update requests'));
823
848
  }
824
- if (receivedPendingNotifications && // if we don't have the app state key
825
- // we keep buffering events until we finally have
826
- // the key and can sync the messages
849
+ if (receivedPendingNotifications &&
827
850
  !((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId)) {
828
851
  ev.buffer();
829
852
  needToFlushWithAppStateSync = true;
830
853
  }
854
+ if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
855
+ return;
856
+ }
857
+ syncState = SyncState.AwaitingInitialSync;
858
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
859
+ ev.buffer();
860
+ const willSyncHistory = shouldSyncHistoryMessage(
861
+ WAProto_1.proto.Message.HistorySyncNotification.create({
862
+ syncType: WAProto_1.proto.HistorySync.HistorySyncType.RECENT
863
+ })
864
+ );
865
+ if (!willSyncHistory) {
866
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
867
+ syncState = SyncState.Online;
868
+ setTimeout(() => ev.flush(), 0);
869
+ return;
870
+ }
871
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
872
+ if (awaitingSyncTimeout) {
873
+ clearTimeout(awaitingSyncTimeout);
874
+ }
875
+ awaitingSyncTimeout = setTimeout(() => {
876
+ if (syncState === SyncState.AwaitingInitialSync) {
877
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
878
+ syncState = SyncState.Online;
879
+ ev.flush();
880
+ }
881
+ }, 20000);
831
882
  });
832
883
  return {
833
884
  ...sock,
885
+ createCallLink,
834
886
  getBotListV2,
835
887
  processingMutex,
888
+ messageMutex,
889
+ notificationMutex,
890
+ receiptMutex,
891
+ messageRetryManager,
836
892
  fetchPrivacySettings,
837
893
  upsertMessage,
838
894
  appPatch,
@@ -848,6 +904,7 @@ const makeChatsSocket = (config) => {
848
904
  updateProfileStatus,
849
905
  updateProfileName,
850
906
  updateBlockStatus,
907
+ updateDisableLinkPreviewsPrivacy,
851
908
  updateCallPrivacy,
852
909
  updateMessagesPrivacy,
853
910
  updateLastSeenPrivacy,
@@ -861,6 +918,9 @@ const makeChatsSocket = (config) => {
861
918
  resyncAppState,
862
919
  chatModify,
863
920
  cleanDirtyBits,
921
+ addOrEditContact,
922
+ removeContact,
923
+ addLabel,
864
924
  addChatLabel,
865
925
  removeChatLabel,
866
926
  addMessageLabel,
@@ -868,4 +928,4 @@ const makeChatsSocket = (config) => {
868
928
  star
869
929
  };
870
930
  };
871
- exports.makeChatsSocket = makeChatsSocket;
931
+ exports.makeChatsSocket = makeChatsSocket;