@alannxd/baileys 6.0.5 → 6.0.6

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 (234) hide show
  1. package/WAProto/fix-import.js +29 -0
  2. package/WAProto/index.js +160 -201
  3. package/engine-requirements.js +1 -1
  4. package/lib/Defaults/baileys-version.json +3 -0
  5. package/lib/Defaults/index.d.ts +15 -37
  6. package/lib/Defaults/index.js +136 -119
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/Signal/Group/ciphertext-message.d.ts +0 -1
  9. package/lib/Signal/Group/ciphertext-message.js +5 -2
  10. package/lib/Signal/Group/group-session-builder.d.ts +3 -4
  11. package/lib/Signal/Group/group-session-builder.js +41 -7
  12. package/lib/Signal/Group/group_cipher.d.ts +4 -4
  13. package/lib/Signal/Group/group_cipher.js +51 -37
  14. package/lib/Signal/Group/index.d.ts +11 -12
  15. package/lib/Signal/Group/index.js +57 -12
  16. package/lib/Signal/Group/keyhelper.d.ts +1 -2
  17. package/lib/Signal/Group/keyhelper.js +44 -7
  18. package/lib/Signal/Group/queue-job.d.ts +1 -0
  19. package/lib/Signal/Group/queue-job.js +57 -0
  20. package/lib/Signal/Group/sender-chain-key.d.ts +2 -3
  21. package/lib/Signal/Group/sender-chain-key.js +15 -7
  22. package/lib/Signal/Group/sender-key-distribution-message.d.ts +1 -2
  23. package/lib/Signal/Group/sender-key-distribution-message.js +11 -8
  24. package/lib/Signal/Group/sender-key-message.d.ts +1 -2
  25. package/lib/Signal/Group/sender-key-message.js +12 -9
  26. package/lib/Signal/Group/sender-key-name.d.ts +0 -1
  27. package/lib/Signal/Group/sender-key-name.js +5 -2
  28. package/lib/Signal/Group/sender-key-record.d.ts +2 -3
  29. package/lib/Signal/Group/sender-key-record.js +21 -9
  30. package/lib/Signal/Group/sender-key-state.d.ts +6 -7
  31. package/lib/Signal/Group/sender-key-state.js +42 -27
  32. package/lib/Signal/Group/sender-message-key.d.ts +0 -1
  33. package/lib/Signal/Group/sender-message-key.js +7 -4
  34. package/lib/Signal/libsignal.d.ts +3 -5
  35. package/lib/Signal/libsignal.js +90 -347
  36. package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +5 -4
  37. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  38. package/lib/Socket/Client/index.d.ts +3 -3
  39. package/lib/Socket/Client/index.js +19 -3
  40. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  41. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  42. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +2 -3
  43. package/lib/Socket/Client/web-socket-client.js +62 -0
  44. package/lib/Socket/business.d.ts +108 -154
  45. package/lib/Socket/business.js +43 -162
  46. package/lib/Socket/chats.d.ts +239 -96
  47. package/lib/Socket/chats.js +427 -627
  48. package/lib/Socket/communities.d.ts +146 -239
  49. package/lib/Socket/communities.js +80 -90
  50. package/lib/Socket/groups.d.ts +57 -104
  51. package/lib/Socket/groups.js +161 -154
  52. package/lib/Socket/index.d.ts +115 -202
  53. package/lib/Socket/index.js +10 -11
  54. package/lib/Socket/luxu.d.ts +266 -22
  55. package/lib/Socket/luxu.js +465 -422
  56. package/lib/Socket/messages-recv.d.ts +84 -136
  57. package/lib/Socket/messages-recv.js +615 -1421
  58. package/lib/Socket/messages-send.d.ts +126 -142
  59. package/lib/Socket/messages-send.js +671 -878
  60. package/lib/Socket/newsletter.d.ts +85 -121
  61. package/lib/Socket/newsletter.js +272 -147
  62. package/lib/Socket/registration.d.ts +267 -0
  63. package/lib/Socket/registration.js +166 -0
  64. package/lib/Socket/socket.d.ts +19 -34
  65. package/lib/Socket/socket.js +313 -544
  66. package/lib/Socket/usync.d.ts +36 -0
  67. package/lib/Socket/usync.js +70 -0
  68. package/lib/Store/index.d.ts +3 -10
  69. package/lib/Store/index.js +10 -10
  70. package/lib/Store/make-cache-manager-store.d.ts +11 -17
  71. package/lib/Store/make-cache-manager-store.js +41 -43
  72. package/lib/Store/make-in-memory-store.d.ts +118 -39
  73. package/lib/Store/make-in-memory-store.js +341 -112
  74. package/lib/Store/make-ordered-dictionary.d.ts +10 -11
  75. package/lib/Store/make-ordered-dictionary.js +20 -14
  76. package/lib/Store/object-repository.d.ts +9 -10
  77. package/lib/Store/object-repository.js +6 -11
  78. package/lib/Types/Auth.d.ts +12 -19
  79. package/lib/Types/Auth.js +2 -2
  80. package/lib/Types/Call.d.ts +1 -3
  81. package/lib/Types/Call.js +2 -2
  82. package/lib/Types/Chat.d.ts +13 -35
  83. package/lib/Types/Chat.js +4 -8
  84. package/lib/Types/Contact.d.ts +1 -8
  85. package/lib/Types/Contact.js +2 -2
  86. package/lib/Types/Events.d.ts +17 -116
  87. package/lib/Types/Events.js +2 -2
  88. package/lib/Types/GroupMetadata.d.ts +5 -21
  89. package/lib/Types/GroupMetadata.js +2 -2
  90. package/lib/Types/Label.d.ts +0 -12
  91. package/lib/Types/Label.js +5 -3
  92. package/lib/Types/LabelAssociation.d.ts +0 -1
  93. package/lib/Types/LabelAssociation.js +5 -3
  94. package/lib/Types/Message.d.ts +58 -105
  95. package/lib/Types/Message.js +9 -11
  96. package/lib/Types/Newsletter.d.ts +103 -0
  97. package/lib/Types/Newsletter.js +38 -0
  98. package/lib/Types/Product.d.ts +1 -2
  99. package/lib/Types/Product.js +2 -2
  100. package/lib/Types/Signal.d.ts +2 -32
  101. package/lib/Types/Signal.js +2 -2
  102. package/lib/Types/Socket.d.ts +25 -50
  103. package/lib/Types/Socket.js +2 -3
  104. package/lib/Types/State.d.ts +2 -72
  105. package/lib/Types/State.js +2 -56
  106. package/lib/Types/USync.d.ts +2 -3
  107. package/lib/Types/USync.js +2 -2
  108. package/lib/Types/index.d.ts +14 -22
  109. package/lib/Types/index.js +31 -15
  110. package/lib/Utils/auth-utils.d.ts +6 -12
  111. package/lib/Utils/auth-utils.js +143 -239
  112. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  113. package/lib/Utils/baileys-event-stream.js +63 -0
  114. package/lib/Utils/business.d.ts +2 -3
  115. package/lib/Utils/business.js +69 -66
  116. package/lib/Utils/chat-utils.d.ts +23 -52
  117. package/lib/Utils/chat-utils.js +253 -396
  118. package/lib/Utils/crypto.d.ts +22 -18
  119. package/lib/Utils/crypto.js +90 -57
  120. package/lib/Utils/decode-wa-message.d.ts +8 -55
  121. package/lib/Utils/decode-wa-message.js +84 -203
  122. package/lib/Utils/event-buffer.d.ts +8 -9
  123. package/lib/Utils/event-buffer.js +77 -185
  124. package/lib/Utils/generics.d.ts +29 -28
  125. package/lib/Utils/generics.js +210 -180
  126. package/lib/Utils/history.d.ts +9 -18
  127. package/lib/Utils/history.js +55 -93
  128. package/lib/Utils/index.d.ts +17 -22
  129. package/lib/Utils/index.js +33 -22
  130. package/lib/Utils/link-preview.d.ts +5 -5
  131. package/lib/Utils/link-preview.js +24 -16
  132. package/lib/Utils/logger.d.ts +3 -11
  133. package/lib/Utils/logger.js +7 -3
  134. package/lib/Utils/lt-hash.d.ts +12 -8
  135. package/lib/Utils/lt-hash.js +46 -3
  136. package/lib/Utils/make-mutex.d.ts +2 -4
  137. package/lib/Utils/make-mutex.js +34 -24
  138. package/lib/Utils/messages-media.d.ts +44 -61
  139. package/lib/Utils/messages-media.js +482 -451
  140. package/lib/Utils/messages.d.ts +18 -32
  141. package/lib/Utils/messages.js +369 -458
  142. package/lib/Utils/noise-handler.d.ts +14 -13
  143. package/lib/Utils/noise-handler.js +99 -145
  144. package/lib/Utils/process-message.d.ts +12 -31
  145. package/lib/Utils/process-message.js +150 -459
  146. package/lib/Utils/signal.d.ts +5 -20
  147. package/lib/Utils/signal.js +72 -120
  148. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -2
  149. package/lib/Utils/use-multi-file-auth-state.js +27 -29
  150. package/lib/Utils/validate-connection.d.ts +7 -7
  151. package/lib/Utils/validate-connection.js +99 -73
  152. package/lib/WABinary/constants.d.ts +27 -25
  153. package/lib/WABinary/constants.js +20 -1281
  154. package/lib/WABinary/decode.d.ts +5 -5
  155. package/lib/WABinary/decode.js +42 -52
  156. package/lib/WABinary/encode.d.ts +3 -3
  157. package/lib/WABinary/encode.js +155 -110
  158. package/lib/WABinary/generic-utils.d.ts +7 -8
  159. package/lib/WABinary/generic-utils.js +49 -48
  160. package/lib/WABinary/index.d.ts +5 -6
  161. package/lib/WABinary/index.js +21 -6
  162. package/lib/WABinary/jid-utils.d.ts +8 -25
  163. package/lib/WABinary/jid-utils.js +40 -74
  164. package/lib/WABinary/types.d.ts +1 -2
  165. package/lib/WABinary/types.js +2 -2
  166. package/lib/WAM/BinaryInfo.d.ts +11 -3
  167. package/lib/WAM/BinaryInfo.js +5 -2
  168. package/lib/WAM/constants.d.ts +3 -5
  169. package/lib/WAM/constants.js +11958 -19461
  170. package/lib/WAM/encode.d.ts +3 -3
  171. package/lib/WAM/encode.js +22 -17
  172. package/lib/WAM/index.d.ts +3 -4
  173. package/lib/WAM/index.js +19 -4
  174. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +3 -4
  175. package/lib/WAUSync/Protocols/USyncContactProtocol.js +13 -33
  176. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -3
  177. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +14 -11
  178. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -3
  179. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +12 -9
  180. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -3
  181. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +13 -9
  182. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +3 -4
  183. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +22 -20
  184. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +3 -5
  185. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +8 -13
  186. package/lib/WAUSync/Protocols/index.d.ts +4 -6
  187. package/lib/WAUSync/Protocols/index.js +20 -6
  188. package/lib/WAUSync/USyncQuery.d.ts +4 -6
  189. package/lib/WAUSync/USyncQuery.js +35 -44
  190. package/lib/WAUSync/USyncUser.d.ts +5 -10
  191. package/lib/WAUSync/USyncUser.js +5 -10
  192. package/lib/WAUSync/index.js +19 -4
  193. package/lib/index.d.ts +9 -10
  194. package/lib/index.js +34 -12
  195. package/package.json +50 -83
  196. package/WAProto/GenerateStatics.sh +0 -3
  197. package/WAProto/WAProto.proto +0 -5479
  198. package/WAProto/fix-imports.js +0 -85
  199. package/WAProto/index.d.ts +0 -14017
  200. package/lib/Signal/lid-mapping.d.ts +0 -23
  201. package/lib/Signal/lid-mapping.js +0 -277
  202. package/lib/Socket/Client/types.js +0 -11
  203. package/lib/Socket/Client/websocket.js +0 -54
  204. package/lib/Socket/mex.d.ts +0 -3
  205. package/lib/Socket/mex.js +0 -42
  206. package/lib/Store/keyed-db.d.ts +0 -22
  207. package/lib/Store/keyed-db.js +0 -108
  208. package/lib/Types/Bussines.d.ts +0 -25
  209. package/lib/Types/Bussines.js +0 -2
  210. package/lib/Types/Mex.d.ts +0 -141
  211. package/lib/Types/Mex.js +0 -37
  212. package/lib/Utils/browser-utils.d.ts +0 -4
  213. package/lib/Utils/browser-utils.js +0 -28
  214. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  215. package/lib/Utils/companion-reg-client-utils.js +0 -35
  216. package/lib/Utils/identity-change-handler.d.ts +0 -44
  217. package/lib/Utils/identity-change-handler.js +0 -50
  218. package/lib/Utils/message-retry-manager.d.ts +0 -115
  219. package/lib/Utils/message-retry-manager.js +0 -265
  220. package/lib/Utils/offline-node-processor.d.ts +0 -17
  221. package/lib/Utils/offline-node-processor.js +0 -40
  222. package/lib/Utils/pre-key-manager.d.ts +0 -28
  223. package/lib/Utils/pre-key-manager.js +0 -106
  224. package/lib/Utils/reporting-utils.d.ts +0 -11
  225. package/lib/Utils/reporting-utils.js +0 -258
  226. package/lib/Utils/stanza-ack.d.ts +0 -11
  227. package/lib/Utils/stanza-ack.js +0 -38
  228. package/lib/Utils/sync-action-utils.d.ts +0 -19
  229. package/lib/Utils/sync-action-utils.js +0 -49
  230. package/lib/Utils/tc-token-utils.d.ts +0 -37
  231. package/lib/Utils/tc-token-utils.js +0 -163
  232. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  233. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  234. package/lib/WAUSync/index.d.ts +0 -4
@@ -1,56 +1,30 @@
1
- import NodeCache from '@cacheable/node-cache';
2
- import { Boom } from '@hapi/boom';
3
- import { proto } from '../../WAProto/index.js';
4
- import { DEFAULT_CACHE_TTLS, HISTORY_SYNC_PAUSED_TIMEOUT_MS, PROCESSABLE_HISTORY_TYPES } from '../Defaults/index.js';
5
- import { ALL_WA_PATCH_NAMES } from '../Types/index.js';
6
- import { SyncState } from '../Types/State.js';
7
- import { chatModificationToAppPatch, decodePatches, decodeSyncdSnapshot, encodeSyncdPatch, ensureLTHashStateVersion, extractSyncdPatches, generateProfilePicture, getHistoryMsg, isAppStateSyncIrrecoverable, isMissingKeyError, MAX_SYNC_ATTEMPTS, newLTHashState, processSyncAction } from '../Utils/index.js';
8
- import { makeMutex } from '../Utils/make-mutex.js';
9
- import processMessage from '../Utils/process-message.js';
10
- import { buildTcTokenFromJid } from '../Utils/tc-token-utils.js';
11
- import { getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isLidUser, isPnUser, jidDecode, jidNormalizedUser, reduceBinaryNodeToDictionary, S_WHATSAPP_NET } from '../WABinary/index.js';
12
- import { USyncQuery, USyncUser } from '../WAUSync/index.js';
13
- import { makeSocket } from './socket.js';
14
- export const makeChatsSocket = (config) => {
15
- const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
16
- const sock = makeSocket(config);
17
- const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession, registerSocketEndHandler } = sock;
18
- const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeChatsSocket = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const WAProto_1 = require("../../WAProto");
9
+ const Defaults_1 = require("../Defaults");
10
+ const Types_1 = require("../Types");
11
+ const Utils_1 = require("../Utils");
12
+ const make_mutex_1 = require("../Utils/make-mutex");
13
+ const process_message_1 = __importDefault(require("../Utils/process-message"));
14
+ const WABinary_1 = require("../WABinary");
15
+ const socket_1 = require("./socket");
16
+ const WAUSync_1 = require("../WAUSync");
17
+ const usync_1 = require("./usync");
18
+ const MAX_SYNC_ATTEMPTS = 2;
19
+ const makeChatsSocket = (config) => {
20
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config;
21
+ const sock = (0, usync_1.makeUSyncSocket)(config);
22
+ const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, } = sock;
19
23
  let privacySettings;
20
- /** Server-assigned AB props for protocol behavior. */
21
- const serverProps = {
22
- /** AB prop 10518: gate tctoken on 1:1 messages. Default true (safe: avoids 463). */
23
- privacyTokenOn1to1: true,
24
- /** AB prop 9666: gate tctoken on profile picture IQs. WA Web default: true. */
25
- profilePicPrivacyToken: true,
26
- /** AB prop 14303: issue tctokens to LID instead of PN. WA Web default: false. */
27
- lidTrustedTokenIssueToLid: false
28
- };
29
- let syncState = SyncState.Connecting;
30
- /** this mutex ensures that messages are processed in order */
31
- const messageMutex = makeMutex();
32
- /** this mutex ensures that receipts are processed in order */
33
- const receiptMutex = makeMutex();
34
- /** this mutex ensures that app state patches are processed in order */
35
- const appStatePatchMutex = makeMutex();
36
- /** this mutex ensures that notifications are processed in order */
37
- const notificationMutex = makeMutex();
38
- // Timeout for AwaitingInitialSync state
39
- let awaitingSyncTimeout;
40
- // In-memory history sync completion tracking (resets on reconnection)
41
- const historySyncStatus = {
42
- initialBootstrapComplete: false,
43
- recentSyncComplete: false
44
- };
45
- let historySyncPausedTimeout;
46
- // Collections blocked on missing app state sync keys (mirrors WA Web's "Blocked" state).
47
- // When a key arrives via APP_STATE_SYNC_KEY_SHARE, these are re-synced.
48
- const blockedCollections = new Set();
49
- const placeholderResendCache = config.placeholderResendCache ||
50
- new NodeCache({
51
- stdTTL: DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
52
- useClones: false
53
- });
24
+ let needToFlushWithAppStateSync = false;
25
+ let pendingAppStateSync = false;
26
+ /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
27
+ const processingMutex = (0, make_mutex_1.makeMutex)();
54
28
  /** helper function to fetch the given app state sync key */
55
29
  const getAppStateSyncKey = async (keyId) => {
56
30
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
@@ -62,12 +36,14 @@ export const makeChatsSocket = (config) => {
62
36
  tag: 'iq',
63
37
  attrs: {
64
38
  xmlns: 'privacy',
65
- to: S_WHATSAPP_NET,
39
+ to: WABinary_1.S_WHATSAPP_NET,
66
40
  type: 'get'
67
41
  },
68
- content: [{ tag: 'privacy', attrs: {} }]
42
+ content: [
43
+ { tag: 'privacy', attrs: {} }
44
+ ]
69
45
  });
70
- privacySettings = reduceBinaryNodeToDictionary(content?.[0], 'category');
46
+ privacySettings = (0, WABinary_1.reduceBinaryNodeToDictionary)(content === null || content === void 0 ? void 0 : content[0], 'category');
71
47
  }
72
48
  return privacySettings;
73
49
  };
@@ -77,11 +53,10 @@ export const makeChatsSocket = (config) => {
77
53
  tag: 'iq',
78
54
  attrs: {
79
55
  xmlns: 'privacy',
80
- to: S_WHATSAPP_NET,
56
+ to: WABinary_1.S_WHATSAPP_NET,
81
57
  type: 'set'
82
58
  },
83
- content: [
84
- {
59
+ content: [{
85
60
  tag: 'privacy',
86
61
  attrs: {},
87
62
  content: [
@@ -90,16 +65,9 @@ export const makeChatsSocket = (config) => {
90
65
  attrs: { name, value }
91
66
  }
92
67
  ]
93
- }
94
- ]
68
+ }]
95
69
  });
96
70
  };
97
- const updateMessagesPrivacy = async (value) => {
98
- await privacyQuery('messages', value);
99
- };
100
- const updateCallPrivacy = async (value) => {
101
- await privacyQuery('calladd', value);
102
- };
103
71
  const updateLastSeenPrivacy = async (value) => {
104
72
  await privacyQuery('last', value);
105
73
  };
@@ -118,95 +86,259 @@ export const makeChatsSocket = (config) => {
118
86
  const updateGroupsAddPrivacy = async (value) => {
119
87
  await privacyQuery('groupadd', value);
120
88
  };
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
+ }
156
+ };
121
157
  const updateDefaultDisappearingMode = async (duration) => {
122
158
  await query({
123
159
  tag: 'iq',
124
160
  attrs: {
125
161
  xmlns: 'disappearing_mode',
126
- to: S_WHATSAPP_NET,
162
+ to: WABinary_1.S_WHATSAPP_NET,
127
163
  type: 'set'
128
164
  },
129
- content: [
130
- {
165
+ content: [{
131
166
  tag: 'disappearing_mode',
132
167
  attrs: {
133
168
  duration: duration.toString()
134
169
  }
135
- }
136
- ]
170
+ }]
137
171
  });
138
172
  };
139
- const getBotListV2 = async () => {
140
- const resp = await query({
173
+ /** helper function to run a generic IQ query */
174
+ const interactiveQuery = async (userNodes, queryNode) => {
175
+ const result = await query({
141
176
  tag: 'iq',
142
177
  attrs: {
143
- xmlns: 'bot',
144
- to: S_WHATSAPP_NET,
145
- type: 'get'
178
+ to: WABinary_1.S_WHATSAPP_NET,
179
+ type: 'get',
180
+ xmlns: 'usync',
146
181
  },
147
182
  content: [
148
183
  {
149
- tag: 'bot',
184
+ tag: 'usync',
150
185
  attrs: {
151
- v: '2'
152
- }
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
+ ]
153
204
  }
154
- ]
205
+ ],
155
206
  });
156
- const botNode = getBinaryNodeChild(resp, 'bot');
157
- const botList = [];
158
- for (const section of getBinaryNodeChildren(botNode, 'section')) {
159
- if (section.attrs.type === 'all') {
160
- for (const bot of getBinaryNodeChildren(section, 'bot')) {
161
- botList.push({
162
- jid: bot.attrs.jid,
163
- personaId: bot.attrs['persona_id']
164
- });
165
- }
166
- }
167
- }
168
- return botList;
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;
169
211
  };
170
- const fetchStatus = async (...jids) => {
171
- const usyncQuery = new USyncQuery().withStatusProtocol();
172
- for (const jid of jids) {
173
- usyncQuery.withUser(new USyncUser().withId(jid));
174
- }
175
- const result = await sock.executeUSyncQuery(usyncQuery);
176
- if (result) {
177
- return result.list;
212
+ const getBusinessProfile = async (jid) => {
213
+ var _a, _b, _c, _d, _e, _f, _g;
214
+ const results = await query({
215
+ tag: 'iq',
216
+ attrs: {
217
+ to: 's.whatsapp.net',
218
+ xmlns: 'w:biz',
219
+ type: 'get'
220
+ },
221
+ content: [{
222
+ tag: 'business_profile',
223
+ attrs: { v: '244' },
224
+ content: [{
225
+ tag: 'profile',
226
+ attrs: { jid }
227
+ }]
228
+ }]
229
+ });
230
+ const profileNode = (0, WABinary_1.getBinaryNodeChild)(results, 'business_profile');
231
+ const profiles = (0, WABinary_1.getBinaryNodeChild)(profileNode, 'profile');
232
+ if (profiles) {
233
+ const address = (0, WABinary_1.getBinaryNodeChild)(profiles, 'address');
234
+ const description = (0, WABinary_1.getBinaryNodeChild)(profiles, 'description');
235
+ const website = (0, WABinary_1.getBinaryNodeChild)(profiles, 'website');
236
+ const email = (0, WABinary_1.getBinaryNodeChild)(profiles, 'email');
237
+ const category = (0, WABinary_1.getBinaryNodeChild)((0, WABinary_1.getBinaryNodeChild)(profiles, 'categories'), 'category');
238
+ const businessHours = (0, WABinary_1.getBinaryNodeChild)(profiles, 'business_hours');
239
+ const businessHoursConfig = businessHours ?
240
+ (0, WABinary_1.getBinaryNodeChildren)(businessHours, 'business_hours_config') :
241
+ undefined;
242
+ const websiteStr = (_a = website === null || website === void 0 ? void 0 : website.content) === null || _a === void 0 ? void 0 : _a.toString();
243
+ return {
244
+ wid: (_b = profiles.attrs) === null || _b === void 0 ? void 0 : _b.jid,
245
+ address: (_c = address === null || address === void 0 ? void 0 : address.content) === null || _c === void 0 ? void 0 : _c.toString(),
246
+ description: ((_d = description === null || description === void 0 ? void 0 : description.content) === null || _d === void 0 ? void 0 : _d.toString()) || '',
247
+ website: websiteStr ? [websiteStr] : [],
248
+ email: (_e = email === null || email === void 0 ? void 0 : email.content) === null || _e === void 0 ? void 0 : _e.toString(),
249
+ category: (_f = category === null || category === void 0 ? void 0 : category.content) === null || _f === void 0 ? void 0 : _f.toString(),
250
+ 'business_hours': {
251
+ timezone: (_g = businessHours === null || businessHours === void 0 ? void 0 : businessHours.attrs) === null || _g === void 0 ? void 0 : _g.timezone,
252
+ 'business_config': businessHoursConfig === null || businessHoursConfig === void 0 ? void 0 : businessHoursConfig.map(({ attrs }) => attrs)
253
+ }
254
+ };
178
255
  }
179
256
  };
180
- const fetchDisappearingDuration = async (...jids) => {
181
- const usyncQuery = new USyncQuery().withDisappearingModeProtocol();
257
+ const onWhatsApp = async (...jids) => {
258
+ const usyncQuery = new WAUSync_1.USyncQuery()
259
+ .withContactProtocol()
260
+ .withLIDProtocol();
261
+
182
262
  for (const jid of jids) {
183
- usyncQuery.withUser(new USyncUser().withId(jid));
184
- }
185
- const result = await sock.executeUSyncQuery(usyncQuery);
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;
305
+ }
306
+ };
307
+ const toLid = async (jid) => {
308
+ const result = await onWhatsApp(jid);
309
+ let lidResult = result[0].lid;
310
+ if (!result[0].exist) {
311
+ lidResult = jid + "doesnt exist";
312
+ }
313
+ return lidResult
314
+ }
315
+ const fetchStatus = async (jid) => {
316
+ const [result] = await interactiveQuery([{ tag: 'user', attrs: { jid } }], { tag: 'status', attrs: {} });
186
317
  if (result) {
187
- return result.list;
318
+ const status = (0, WABinary_1.getBinaryNodeChild)(result, 'status');
319
+ return {
320
+ status: status === null || status === void 0 ? void 0 : status.content.toString(),
321
+ setAt: new Date(+((status === null || status === void 0 ? void 0 : status.attrs.t) || 0) * 1000)
322
+ };
188
323
  }
189
324
  };
190
325
  /** update the profile picture for yourself or a group */
191
- const updateProfilePicture = async (jid, content, dimensions) => {
326
+ const updateProfilePicture = async (jid, content) => {
192
327
  let targetJid;
193
328
  if (!jid) {
194
- throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
329
+ 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');
195
330
  }
196
- if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
197
- targetJid = jidNormalizedUser(jid); // in case it is someone other than us
331
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
332
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
198
333
  }
199
- else {
200
- targetJid = undefined;
201
- }
202
- const { img } = await generateProfilePicture(content, dimensions);
334
+ const { img } = await (0, Utils_1.generateProfilePicture)(content);
203
335
  await query({
204
336
  tag: 'iq',
205
337
  attrs: {
206
- to: S_WHATSAPP_NET,
338
+ target: targetJid,
339
+ to: WABinary_1.S_WHATSAPP_NET,
207
340
  type: 'set',
208
- xmlns: 'w:profile:picture',
209
- ...(targetJid ? { target: targetJid } : {})
341
+ xmlns: 'w:profile:picture'
210
342
  },
211
343
  content: [
212
344
  {
@@ -221,21 +353,18 @@ export const makeChatsSocket = (config) => {
221
353
  const removeProfilePicture = async (jid) => {
222
354
  let targetJid;
223
355
  if (!jid) {
224
- throw new Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
356
+ 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');
225
357
  }
226
- if (jidNormalizedUser(jid) !== jidNormalizedUser(authState.creds.me.id)) {
227
- targetJid = jidNormalizedUser(jid); // in case it is someone other than us
228
- }
229
- else {
230
- targetJid = undefined;
358
+ if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
359
+ targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
231
360
  }
232
361
  await query({
233
362
  tag: 'iq',
234
363
  attrs: {
235
- to: S_WHATSAPP_NET,
364
+ target: targetJid,
365
+ to: WABinary_1.S_WHATSAPP_NET,
236
366
  type: 'set',
237
- xmlns: 'w:profile:picture',
238
- ...(targetJid ? { target: targetJid } : {})
367
+ xmlns: 'w:profile:picture'
239
368
  }
240
369
  });
241
370
  };
@@ -244,7 +373,7 @@ export const makeChatsSocket = (config) => {
244
373
  await query({
245
374
  tag: 'iq',
246
375
  attrs: {
247
- to: S_WHATSAPP_NET,
376
+ to: WABinary_1.S_WHATSAPP_NET,
248
377
  type: 'set',
249
378
  xmlns: 'status'
250
379
  },
@@ -265,129 +394,49 @@ export const makeChatsSocket = (config) => {
265
394
  tag: 'iq',
266
395
  attrs: {
267
396
  xmlns: 'blocklist',
268
- to: S_WHATSAPP_NET,
397
+ to: WABinary_1.S_WHATSAPP_NET,
269
398
  type: 'get'
270
399
  }
271
400
  });
272
- const listNode = getBinaryNodeChild(result, 'list');
273
- return getBinaryNodeChildren(listNode, 'item').map(n => n.attrs.jid);
401
+ const listNode = (0, WABinary_1.getBinaryNodeChild)(result, 'list');
402
+ return (0, WABinary_1.getBinaryNodeChildren)(listNode, 'item')
403
+ .map(n => n.attrs.jid);
274
404
  };
275
405
  const updateBlockStatus = async (jid, action) => {
276
- const normalizedJid = jidNormalizedUser(jid);
277
- let lid;
278
- let pn_jid;
279
- if (isLidUser(normalizedJid) || isHostedLidUser(normalizedJid)) {
280
- lid = normalizedJid;
281
- if (action === 'block') {
282
- const pn = await signalRepository.lidMapping.getPNForLID(normalizedJid);
283
- if (!pn) {
284
- throw new Boom(`Unable to resolve PN JID for LID: ${jid}`, { statusCode: 400 });
285
- }
286
- pn_jid = jidNormalizedUser(pn);
287
- }
288
- }
289
- else if (isPnUser(normalizedJid) || isHostedPnUser(normalizedJid)) {
290
- const mapped = await signalRepository.lidMapping.getLIDForPN(normalizedJid);
291
- if (!mapped) {
292
- throw new Boom(`Unable to resolve LID for PN JID: ${jid}`, { statusCode: 400 });
293
- }
294
- lid = mapped;
295
- if (action === 'block') {
296
- pn_jid = jidNormalizedUser(normalizedJid);
297
- }
298
- }
299
- else {
300
- throw new Boom(`Invalid jid: ${jid}`, { statusCode: 400 });
301
- }
302
- const itemAttrs = {
303
- action,
304
- jid: lid
305
- };
306
- if (action === 'block') {
307
- if (!pn_jid) {
308
- throw new Boom(`pn_jid required for block: ${jid}`, { statusCode: 400 });
309
- }
310
- itemAttrs.pn_jid = pn_jid;
311
- }
312
406
  await query({
313
407
  tag: 'iq',
314
408
  attrs: {
315
409
  xmlns: 'blocklist',
316
- to: S_WHATSAPP_NET,
410
+ to: WABinary_1.S_WHATSAPP_NET,
317
411
  type: 'set'
318
412
  },
319
413
  content: [
320
414
  {
321
415
  tag: 'item',
322
- attrs: itemAttrs
323
- }
324
- ]
325
- });
326
- };
327
- const getBusinessProfile = async (jid) => {
328
- const results = await query({
329
- tag: 'iq',
330
- attrs: {
331
- to: 's.whatsapp.net',
332
- xmlns: 'w:biz',
333
- type: 'get'
334
- },
335
- content: [
336
- {
337
- tag: 'business_profile',
338
- attrs: { v: '244' },
339
- content: [
340
- {
341
- tag: 'profile',
342
- attrs: { jid }
343
- }
344
- ]
416
+ attrs: {
417
+ action,
418
+ jid
419
+ }
345
420
  }
346
421
  ]
347
422
  });
348
- const profileNode = getBinaryNodeChild(results, 'business_profile');
349
- const profiles = getBinaryNodeChild(profileNode, 'profile');
350
- if (profiles) {
351
- const address = getBinaryNodeChild(profiles, 'address');
352
- const description = getBinaryNodeChild(profiles, 'description');
353
- const website = getBinaryNodeChild(profiles, 'website');
354
- const email = getBinaryNodeChild(profiles, 'email');
355
- const category = getBinaryNodeChild(getBinaryNodeChild(profiles, 'categories'), 'category');
356
- const businessHours = getBinaryNodeChild(profiles, 'business_hours');
357
- const businessHoursConfig = businessHours
358
- ? getBinaryNodeChildren(businessHours, 'business_hours_config')
359
- : undefined;
360
- const websiteStr = website?.content?.toString();
361
- return {
362
- wid: profiles.attrs?.jid,
363
- address: address?.content?.toString(),
364
- description: description?.content?.toString() || '',
365
- website: websiteStr ? [websiteStr] : [],
366
- email: email?.content?.toString(),
367
- category: category?.content?.toString(),
368
- business_hours: {
369
- timezone: businessHours?.attrs?.timezone,
370
- business_config: businessHoursConfig?.map(({ attrs }) => attrs)
371
- }
372
- };
373
- }
374
423
  };
375
424
  const cleanDirtyBits = async (type, fromTimestamp) => {
376
425
  logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
377
426
  await sendNode({
378
427
  tag: 'iq',
379
428
  attrs: {
380
- to: S_WHATSAPP_NET,
429
+ to: WABinary_1.S_WHATSAPP_NET,
381
430
  type: 'set',
382
431
  xmlns: 'urn:xmpp:whatsapp:dirty',
383
- id: generateMessageTag()
432
+ id: generateMessageTag(),
384
433
  },
385
434
  content: [
386
435
  {
387
436
  tag: 'clean',
388
437
  attrs: {
389
438
  type,
390
- ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
439
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
391
440
  }
392
441
  }
393
442
  ]
@@ -396,31 +445,20 @@ export const makeChatsSocket = (config) => {
396
445
  const newAppStateChunkHandler = (isInitialSync) => {
397
446
  return {
398
447
  onMutation(mutation) {
399
- processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
448
+ (0, Utils_1.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
400
449
  }
401
450
  };
402
451
  };
403
452
  const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
404
- const appStateSyncKeyCache = new Map();
405
- const getCachedAppStateSyncKey = async (keyId) => {
406
- if (appStateSyncKeyCache.has(keyId)) {
407
- return appStateSyncKeyCache.get(keyId) ?? undefined;
408
- }
409
- const key = await getAppStateSyncKey(keyId);
410
- appStateSyncKeyCache.set(keyId, key ?? null);
411
- return key;
412
- };
413
453
  // we use this to determine which events to fire
414
454
  // otherwise when we resync from scratch -- all notifications will fire
415
455
  const initialVersionMap = {};
416
456
  const globalMutationMap = {};
417
457
  await authState.keys.transaction(async () => {
458
+ var _a;
418
459
  const collectionsToHandle = new Set(collections);
419
460
  // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
420
461
  const attemptsMap = {};
421
- // collections that failed and need a full snapshot on retry
422
- // mirrors WA Web's ErrorFatal -> force snapshot behavior
423
- const forceSnapshotCollections = new Set();
424
462
  // keep executing till all collections are done
425
463
  // sometimes a single patch request will not return all the patches (God knows why)
426
464
  // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
@@ -431,34 +469,29 @@ export const makeChatsSocket = (config) => {
431
469
  const result = await authState.keys.get('app-state-sync-version', [name]);
432
470
  let state = result[name];
433
471
  if (state) {
434
- state = ensureLTHashStateVersion(state);
435
472
  if (typeof initialVersionMap[name] === 'undefined') {
436
473
  initialVersionMap[name] = state.version;
437
474
  }
438
475
  }
439
476
  else {
440
- state = newLTHashState();
477
+ state = (0, Utils_1.newLTHashState)();
441
478
  }
442
479
  states[name] = state;
443
- const shouldForceSnapshot = forceSnapshotCollections.has(name);
444
- if (shouldForceSnapshot) {
445
- forceSnapshotCollections.delete(name);
446
- }
447
- logger.info(`resyncing ${name} from v${state.version}${shouldForceSnapshot ? ' (forcing snapshot)' : ''}`);
480
+ logger.info(`resyncing ${name} from v${state.version}`);
448
481
  nodes.push({
449
482
  tag: 'collection',
450
483
  attrs: {
451
484
  name,
452
485
  version: state.version.toString(),
453
- // return snapshot if syncing from scratch or forcing after a failed attempt
454
- return_snapshot: (shouldForceSnapshot || !state.version).toString()
486
+ // return snapshot if being synced from scratch
487
+ 'return_snapshot': (!state.version).toString()
455
488
  }
456
489
  });
457
490
  }
458
491
  const result = await query({
459
492
  tag: 'iq',
460
493
  attrs: {
461
- to: S_WHATSAPP_NET,
494
+ to: WABinary_1.S_WHATSAPP_NET,
462
495
  xmlns: 'w:sync:app:state',
463
496
  type: 'set'
464
497
  },
@@ -471,22 +504,26 @@ export const makeChatsSocket = (config) => {
471
504
  ]
472
505
  });
473
506
  // extract from binary node
474
- const decoded = await extractSyncdPatches(result, config?.options);
507
+ const decoded = await (0, Utils_1.extractSyncdPatches)(result, config === null || config === void 0 ? void 0 : config.options);
475
508
  for (const key in decoded) {
476
509
  const name = key;
477
510
  const { patches, hasMorePatches, snapshot } = decoded[name];
478
511
  try {
479
512
  if (snapshot) {
480
- const { state: newState, mutationMap } = await decodeSyncdSnapshot(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot, logger);
513
+ const { state: newState, mutationMap } = await (0, Utils_1.decodeSyncdSnapshot)(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
481
514
  states[name] = newState;
482
515
  Object.assign(globalMutationMap, mutationMap);
483
516
  logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
484
- await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
517
+ await authState.keys.set({ 'app-state-sync-version': {
518
+ [name]: newState
519
+ } });
485
520
  }
486
521
  // only process if there are syncd patches
487
522
  if (patches.length) {
488
- const { state: newState, mutationMap } = await decodePatches(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
489
- await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
523
+ const { state: newState, mutationMap } = await (0, Utils_1.decodePatches)(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
524
+ await authState.keys.set({ 'app-state-sync-version': {
525
+ [name]: newState
526
+ } });
490
527
  logger.info(`synced ${name} to v${newState.version}`);
491
528
  initialVersionMap[name] = newState.version;
492
529
  Object.assign(globalMutationMap, mutationMap);
@@ -494,47 +531,30 @@ export const makeChatsSocket = (config) => {
494
531
  if (hasMorePatches) {
495
532
  logger.info(`${name} has more patches...`);
496
533
  }
497
- else {
498
- // collection is done with sync
534
+ else { // collection is done with sync
499
535
  collectionsToHandle.delete(name);
500
536
  }
501
537
  }
502
538
  catch (error) {
539
+ // if retry attempts overshoot
540
+ // or key not found
541
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
542
+ ((_a = error.output) === null || _a === void 0 ? void 0 : _a.statusCode) === 404 ||
543
+ error.name === 'TypeError';
544
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
545
+ await authState.keys.set({ 'app-state-sync-version': {
546
+ [name]: null
547
+ } });
548
+ // increment number of retries
503
549
  attemptsMap[name] = (attemptsMap[name] || 0) + 1;
504
- const logData = {
505
- name,
506
- attempt: attemptsMap[name],
507
- version: states[name].version,
508
- statusCode: error.output?.statusCode,
509
- errorType: error.name,
510
- error: error.stack
511
- };
512
- if (isMissingKeyError(error) && attemptsMap[name] >= MAX_SYNC_ATTEMPTS) {
513
- // WA Web treats missing keys as "Blocked" — park the collection
514
- // until the key arrives via APP_STATE_SYNC_KEY_SHARE.
515
- logger.warn(logData, `${name} blocked on missing key from v${states[name].version}, parking after ${attemptsMap[name]} attempts`);
516
- blockedCollections.add(name);
517
- collectionsToHandle.delete(name);
518
- }
519
- else if (isMissingKeyError(error)) {
520
- // Retry with a snapshot which may use a different key.
521
- logger.info(logData, `${name} blocked on missing key from v${states[name].version}, retrying with snapshot`);
522
- forceSnapshotCollections.add(name);
523
- }
524
- else if (isAppStateSyncIrrecoverable(error, attemptsMap[name])) {
525
- logger.warn(logData, `failed to sync ${name} from v${states[name].version}, giving up`);
550
+ if (isIrrecoverableError) {
551
+ // stop retrying
526
552
  collectionsToHandle.delete(name);
527
553
  }
528
- else {
529
- logger.info(logData, `failed to sync ${name} from v${states[name].version}, forcing snapshot retry`);
530
- // force a full snapshot on retry to recover from
531
- // corrupted local state (e.g. LTHash MAC mismatch)
532
- forceSnapshotCollections.add(name);
533
- }
534
554
  }
535
555
  }
536
556
  }
537
- }, authState?.creds?.me?.id || 'resync-app-state');
557
+ });
538
558
  const { onMutation } = newAppStateChunkHandler(isInitialSync);
539
559
  for (const key in globalMutationMap) {
540
560
  onMutation(globalMutationMap[key]);
@@ -546,83 +566,47 @@ export const makeChatsSocket = (config) => {
546
566
  * type = "image for the high res picture"
547
567
  */
548
568
  const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
549
- const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
550
- // WA Web only includes tctoken for user JIDs (not groups/newsletters)
551
- // and never for own profile pic (Chat model for self has no tcToken).
552
- // Including tctoken for own JID causes the server to never respond.
553
- const normalizedJid = jidNormalizedUser(jid);
554
- const isUserJid = isPnUser(normalizedJid) || isLidUser(normalizedJid);
555
- const me = authState.creds.me;
556
- const isSelf = me && (normalizedJid === jidNormalizedUser(me.id) || (me.lid && normalizedJid === jidNormalizedUser(me.lid)));
557
- let content = baseContent;
558
- if (serverProps.profilePicPrivacyToken && isUserJid && !isSelf) {
559
- content = await buildTcTokenFromJid({
560
- authState,
561
- jid: normalizedJid,
562
- baseContent,
563
- getLIDForPN
564
- });
565
- }
566
- jid = jidNormalizedUser(jid);
569
+ var _a;
570
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
567
571
  const result = await query({
568
572
  tag: 'iq',
569
573
  attrs: {
570
574
  target: jid,
571
- to: S_WHATSAPP_NET,
575
+ to: WABinary_1.S_WHATSAPP_NET,
572
576
  type: 'get',
573
577
  xmlns: 'w:profile:picture'
574
578
  },
575
- content
576
- }, timeoutMs);
577
- const child = getBinaryNodeChild(result, 'picture');
578
- return child?.attrs?.url;
579
- };
580
- const createCallLink = async (type, event, timeoutMs) => {
581
- const result = await query({
582
- tag: 'call',
583
- attrs: {
584
- id: generateMessageTag(),
585
- to: '@call'
586
- },
587
579
  content: [
588
- {
589
- tag: 'link_create',
590
- attrs: { media: type },
591
- content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
592
- }
580
+ { tag: 'picture', attrs: { type, query: 'url' } }
593
581
  ]
594
582
  }, timeoutMs);
595
- const child = getBinaryNodeChild(result, 'link_create');
596
- return child?.attrs?.token;
583
+ const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
584
+ return (_a = child === null || child === void 0 ? void 0 : child.attrs) === null || _a === void 0 ? void 0 : _a.url;
597
585
  };
598
586
  const sendPresenceUpdate = async (type, toJid) => {
599
587
  const me = authState.creds.me;
600
- const isAvailableType = type === 'available';
601
- if (isAvailableType || type === 'unavailable') {
588
+ if (type === 'available' || type === 'unavailable') {
602
589
  if (!me.name) {
603
590
  logger.warn('no name present, ignoring presence update request...');
604
591
  return;
605
592
  }
606
- ev.emit('connection.update', { isOnline: isAvailableType });
607
- if (isAvailableType) {
608
- void sendUnifiedSession();
609
- }
593
+ ev.emit('connection.update', { isOnline: type === 'available' });
610
594
  await sendNode({
611
595
  tag: 'presence',
612
596
  attrs: {
613
- name: me.name.replace(/@/g, ''),
597
+ name: me.name,
614
598
  type
615
599
  }
616
600
  });
617
601
  }
618
602
  else {
619
- const { server } = jidDecode(toJid);
603
+ const { server } = (0, WABinary_1.jidDecode)(toJid);
620
604
  const isLid = server === 'lid';
621
605
  await sendNode({
622
606
  tag: 'chatstate',
623
607
  attrs: {
624
608
  from: isLid ? me.lid : me.id,
625
- to: toJid
609
+ to: toJid,
626
610
  },
627
611
  content: [
628
612
  {
@@ -637,35 +621,35 @@ export const makeChatsSocket = (config) => {
637
621
  * @param toJid the jid to subscribe to
638
622
  * @param tcToken token for subscription, use if present
639
623
  */
640
- const presenceSubscribe = async (toJid) => {
641
- // Only include tctoken for user JIDs — groups/newsletters don't use tctokens
642
- const normalizedToJid = jidNormalizedUser(toJid);
643
- const isUserJid = isPnUser(normalizedToJid) || isLidUser(normalizedToJid);
644
- const tcTokenContent = isUserJid
645
- ? await buildTcTokenFromJid({ authState, jid: normalizedToJid, getLIDForPN })
646
- : undefined;
647
- return sendNode({
648
- tag: 'presence',
649
- attrs: {
650
- to: toJid,
651
- id: generateMessageTag(),
652
- type: 'subscribe'
653
- },
654
- content: tcTokenContent
655
- });
656
- };
624
+ const presenceSubscribe = (toJid, tcToken) => (sendNode({
625
+ tag: 'presence',
626
+ attrs: {
627
+ to: toJid,
628
+ id: generateMessageTag(),
629
+ type: 'subscribe'
630
+ },
631
+ content: tcToken ?
632
+ [
633
+ {
634
+ tag: 'tctoken',
635
+ attrs: {},
636
+ content: tcToken
637
+ }
638
+ ] :
639
+ undefined
640
+ }));
657
641
  const handlePresenceUpdate = ({ tag, attrs, content }) => {
642
+ var _a;
658
643
  let presence;
659
644
  const jid = attrs.from;
660
645
  const participant = attrs.participant || attrs.from;
661
- if (shouldIgnoreJid(jid) && jid !== S_WHATSAPP_NET) {
646
+ if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
662
647
  return;
663
648
  }
664
649
  if (tag === 'presence') {
665
650
  presence = {
666
651
  lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
667
- lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined,
668
- groupOnlineCount: attrs.count ? +attrs.count : undefined
652
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
669
653
  };
670
654
  }
671
655
  else if (Array.isArray(content)) {
@@ -674,7 +658,7 @@ export const makeChatsSocket = (config) => {
674
658
  if (type === 'paused') {
675
659
  type = 'available';
676
660
  }
677
- if (firstChild.attrs?.media === 'audio') {
661
+ if (((_a = firstChild.attrs) === null || _a === void 0 ? void 0 : _a.media) === 'audio') {
678
662
  type = 'recording';
679
663
  }
680
664
  presence = { lastKnownPresence: type };
@@ -683,29 +667,31 @@ export const makeChatsSocket = (config) => {
683
667
  logger.error({ tag, attrs, content }, 'recv invalid presence node');
684
668
  }
685
669
  if (presence) {
686
- ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
670
+ ev.emit('presence.update', { id: jid, presences: {
671
+ [participant]: presence
672
+ } });
687
673
  }
688
674
  };
689
675
  const appPatch = async (patchCreate) => {
690
676
  const name = patchCreate.type;
691
677
  const myAppStateKeyId = authState.creds.myAppStateKeyId;
692
678
  if (!myAppStateKeyId) {
693
- throw new Boom('App state key not present!', { statusCode: 400 });
679
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
694
680
  }
695
681
  let initial;
696
682
  let encodeResult;
697
- await appStatePatchMutex.mutex(async () => {
683
+ await processingMutex.mutex(async () => {
698
684
  await authState.keys.transaction(async () => {
699
685
  logger.debug({ patch: patchCreate }, 'applying app patch');
700
686
  await resyncAppState([name], false);
701
687
  const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
702
- initial = currentSyncVersion ? ensureLTHashStateVersion(currentSyncVersion) : newLTHashState();
703
- encodeResult = await encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
688
+ initial = currentSyncVersion || (0, Utils_1.newLTHashState)();
689
+ encodeResult = await (0, Utils_1.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
704
690
  const { patch, state } = encodeResult;
705
691
  const node = {
706
692
  tag: 'iq',
707
693
  attrs: {
708
- to: S_WHATSAPP_NET,
694
+ to: WABinary_1.S_WHATSAPP_NET,
709
695
  type: 'set',
710
696
  xmlns: 'w:sync:app:state'
711
697
  },
@@ -719,13 +705,13 @@ export const makeChatsSocket = (config) => {
719
705
  attrs: {
720
706
  name,
721
707
  version: (state.version - 1).toString(),
722
- return_snapshot: 'false'
708
+ 'return_snapshot': 'false'
723
709
  },
724
710
  content: [
725
711
  {
726
712
  tag: 'patch',
727
713
  attrs: {},
728
- content: proto.SyncdPatch.encode(patch).finish()
714
+ content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
729
715
  }
730
716
  ]
731
717
  }
@@ -734,60 +720,47 @@ export const makeChatsSocket = (config) => {
734
720
  ]
735
721
  };
736
722
  await query(node);
737
- await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
738
- }, authState?.creds?.me?.id || 'app-patch');
723
+ await authState.keys.set({ 'app-state-sync-version': {
724
+ [name]: state
725
+ } });
726
+ });
739
727
  });
740
728
  if (config.emitOwnEvents) {
741
729
  const { onMutation } = newAppStateChunkHandler(false);
742
- const { mutationMap } = await decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
730
+ const { mutationMap } = await (0, Utils_1.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger);
743
731
  for (const key in mutationMap) {
744
732
  onMutation(mutationMap[key]);
745
733
  }
746
734
  }
747
735
  };
748
- /** fetch AB props */
736
+ /** sending non-abt props may fix QR scan fail if server expects */
749
737
  const fetchProps = async () => {
738
+ var _a, _b;
750
739
  const resultNode = await query({
751
740
  tag: 'iq',
752
741
  attrs: {
753
- to: S_WHATSAPP_NET,
754
- xmlns: 'abt',
755
- type: 'get'
742
+ to: WABinary_1.S_WHATSAPP_NET,
743
+ xmlns: 'w',
744
+ type: 'get',
756
745
  },
757
746
  content: [
758
747
  {
759
748
  tag: 'props',
760
749
  attrs: {
761
- protocol: '1',
762
- ...(authState?.creds?.lastPropHash ? { hash: authState.creds.lastPropHash } : {})
750
+ protocol: '2',
751
+ hash: ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.lastPropHash) || ''
763
752
  }
764
753
  }
765
754
  ]
766
755
  });
767
- const propsNode = getBinaryNodeChild(resultNode, 'props');
756
+ const propsNode = (0, WABinary_1.getBinaryNodeChild)(resultNode, 'props');
768
757
  let props = {};
769
758
  if (propsNode) {
770
- if (propsNode.attrs?.hash) {
771
- // on some clients, the hash is returning as undefined
772
- authState.creds.lastPropHash = propsNode?.attrs?.hash;
773
- ev.emit('creds.update', authState.creds);
774
- }
775
- props = reduceBinaryNodeToDictionary(propsNode, 'prop');
776
- }
777
- // Extract protocol-relevant AB props (only the ones we need)
778
- const privacyTokenProp = props['10518'] ?? props['privacy_token_sending_on_all_1_on_1_messages'];
779
- if (privacyTokenProp !== undefined) {
780
- serverProps.privacyTokenOn1to1 = privacyTokenProp === 'true' || privacyTokenProp === '1';
781
- }
782
- const profilePicProp = props['9666'] ?? props['profile_scraping_privacy_token_in_photo_iq'];
783
- if (profilePicProp !== undefined) {
784
- serverProps.profilePicPrivacyToken = profilePicProp === 'true' || profilePicProp === '1';
759
+ authState.creds.lastPropHash = (_b = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash;
760
+ ev.emit('creds.update', authState.creds);
761
+ props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');
785
762
  }
786
- const lidIssueProp = props['14303'] ?? props['lid_trusted_token_issue_to_lid'];
787
- if (lidIssueProp !== undefined) {
788
- serverProps.lidTrustedTokenIssueToLid = lidIssueProp === 'true' || lidIssueProp === '1';
789
- }
790
- logger.debug({ serverProps }, 'fetched props');
763
+ logger.debug('fetched props');
791
764
  return props;
792
765
  };
793
766
  /**
@@ -796,17 +769,9 @@ export const makeChatsSocket = (config) => {
796
769
  * requires the last messages till the last message received; required for archive & unread
797
770
  */
798
771
  const chatModify = (mod, jid) => {
799
- const patch = chatModificationToAppPatch(mod, jid);
772
+ const patch = (0, Utils_1.chatModificationToAppPatch)(mod, jid);
800
773
  return appPatch(patch);
801
774
  };
802
- /**
803
- * Enable/Disable link preview privacy, not related to baileys link preview generation
804
- */
805
- const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
806
- return chatModify({
807
- disableLinkPreviews: { isPreviewsDisabled }
808
- }, '');
809
- };
810
775
  /**
811
776
  * Star or Unstar a message
812
777
  */
@@ -818,32 +783,6 @@ export const makeChatsSocket = (config) => {
818
783
  }
819
784
  }, jid);
820
785
  };
821
- /**
822
- * Add or Edit Contact
823
- */
824
- const addOrEditContact = (jid, contact) => {
825
- return chatModify({
826
- contact
827
- }, jid);
828
- };
829
- /**
830
- * Remove Contact
831
- */
832
- const removeContact = (jid) => {
833
- return chatModify({
834
- contact: null
835
- }, jid);
836
- };
837
- /**
838
- * Adds label
839
- */
840
- const addLabel = (jid, labels) => {
841
- return chatModify({
842
- addLabel: {
843
- ...labels
844
- }
845
- }, jid);
846
- };
847
786
  /**
848
787
  * Adds label for the chats
849
788
  */
@@ -887,146 +826,92 @@ export const makeChatsSocket = (config) => {
887
826
  }, jid);
888
827
  };
889
828
  /**
890
- * Add or Edit Quick Reply
891
- */
892
- const addOrEditQuickReply = (quickReply) => {
829
+ * Deleting all chat by key message
830
+ * usage: sock.deleteChat(m.chat, m.key)
831
+ */
832
+ const deleteChat = async (jid, key) => {
893
833
  return chatModify({
894
- quickReply
895
- }, '');
896
- };
897
- /**
898
- * Remove Quick Reply
899
- */
900
- const removeQuickReply = (timestamp) => {
901
- return chatModify({
902
- quickReply: { timestamp, deleted: true }
903
- }, '');
904
- };
834
+ delete: true,
835
+ lastMessages: [{
836
+ key: key,
837
+ messageTimestamp: Math.floor(Date.now() / 1000)
838
+ }],
839
+ }, jid);
840
+ }
905
841
  /**
906
842
  * queries need to be fired on connection open
907
843
  * help ensure parity with WA Web
908
844
  * */
909
845
  const executeInitQueries = async () => {
910
- await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
846
+ await Promise.all([
847
+ fetchProps(),
848
+ fetchBlocklist(),
849
+ fetchPrivacySettings(),
850
+ ]);
911
851
  };
912
852
  const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
853
+ var _a, _b, _c;
913
854
  ev.emit('messages.upsert', { messages: [msg], type });
914
855
  if (!!msg.pushName) {
915
- let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
916
- jid = jidNormalizedUser(jid);
856
+ let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
857
+ jid = (0, WABinary_1.jidNormalizedUser)(jid);
917
858
  if (!msg.key.fromMe) {
918
859
  ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
919
860
  }
920
861
  // update our pushname too
921
- if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
862
+ if (msg.key.fromMe && msg.pushName && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
922
863
  ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
923
864
  }
924
865
  }
925
- const historyMsg = getHistoryMsg(msg.message);
926
- const shouldProcessHistoryMsg = historyMsg
927
- ? shouldSyncHistoryMessage(historyMsg) &&
928
- PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
929
- : false;
930
- if (historyMsg && shouldProcessHistoryMsg) {
931
- const syncType = historyMsg.syncType;
932
- // INITIAL_BOOTSTRAP — fire immediately, no progress check (same as WA Web K function)
933
- if (syncType === proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP &&
934
- !historySyncStatus.initialBootstrapComplete) {
935
- historySyncStatus.initialBootstrapComplete = true;
936
- ev.emit('messaging-history.status', {
937
- syncType,
938
- status: 'complete',
939
- explicit: true
940
- });
941
- }
942
- // RECENT with progress === 100 — explicit completion
943
- if (syncType === proto.HistorySync.HistorySyncType.RECENT &&
944
- historyMsg.progress === 100 &&
945
- !historySyncStatus.recentSyncComplete) {
946
- historySyncStatus.recentSyncComplete = true;
947
- clearTimeout(historySyncPausedTimeout);
948
- historySyncPausedTimeout = undefined;
949
- ev.emit('messaging-history.status', {
950
- syncType,
951
- status: 'complete',
952
- explicit: true
953
- });
954
- }
955
- // Reset 120s paused timeout on any RECENT chunk (like WA Web's handleChunkProgress)
956
- if (syncType === proto.HistorySync.HistorySyncType.RECENT && !historySyncStatus.recentSyncComplete) {
957
- clearTimeout(historySyncPausedTimeout);
958
- historySyncPausedTimeout = setTimeout(() => {
959
- if (!historySyncStatus.recentSyncComplete) {
960
- historySyncStatus.recentSyncComplete = true;
961
- ev.emit('messaging-history.status', {
962
- syncType: proto.HistorySync.HistorySyncType.RECENT,
963
- status: 'paused',
964
- explicit: false
965
- });
966
- }
967
- historySyncPausedTimeout = undefined;
968
- }, HISTORY_SYNC_PAUSED_TIMEOUT_MS);
969
- }
970
- }
971
- // State machine: decide on sync and flush
972
- if (historyMsg && syncState === SyncState.AwaitingInitialSync) {
973
- if (awaitingSyncTimeout) {
974
- clearTimeout(awaitingSyncTimeout);
975
- awaitingSyncTimeout = undefined;
976
- }
977
- if (shouldProcessHistoryMsg) {
978
- syncState = SyncState.Syncing;
979
- logger.info('Transitioned to Syncing state');
980
- // Let doAppStateSync handle the final flush after it's done
981
- }
982
- else {
983
- syncState = SyncState.Online;
984
- logger.info('History sync skipped, transitioning to Online state and flushing buffer');
985
- ev.flush();
986
- }
866
+ const historyMsg = (0, Utils_1.getHistoryMsg)(msg.message);
867
+ const shouldProcessHistoryMsg = historyMsg ?
868
+ (shouldSyncHistoryMessage(historyMsg) &&
869
+ Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)) :
870
+ false;
871
+ if (historyMsg && !authState.creds.myAppStateKeyId) {
872
+ logger.warn('skipping app state sync, as myAppStateKeyId is not set');
873
+ pendingAppStateSync = true;
987
874
  }
988
- const doAppStateSync = async () => {
989
- if (syncState === SyncState.Syncing) {
990
- // All collections will be synced, so clear any blocked ones
991
- blockedCollections.clear();
992
- logger.info('Doing app state sync');
993
- await resyncAppState(ALL_WA_PATCH_NAMES, true);
994
- // Sync is complete, go online and flush everything
995
- syncState = SyncState.Online;
996
- logger.info('App state sync complete, transitioning to Online state and flushing buffer');
997
- ev.flush();
998
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
999
- ev.emit('creds.update', { accountSyncCounter });
1000
- }
1001
- };
1002
875
  await Promise.all([
1003
876
  (async () => {
1004
- if (shouldProcessHistoryMsg) {
877
+ if (historyMsg &&
878
+ authState.creds.myAppStateKeyId) {
879
+ pendingAppStateSync = false;
1005
880
  await doAppStateSync();
1006
881
  }
1007
882
  })(),
1008
- processMessage(msg, {
1009
- signalRepository,
883
+ (0, process_message_1.default)(msg, {
1010
884
  shouldProcessHistoryMsg,
1011
- placeholderResendCache,
1012
885
  ev,
1013
886
  creds: authState.creds,
1014
887
  keyStore: authState.keys,
1015
888
  logger,
1016
889
  options: config.options,
1017
- getMessage
890
+ getMessage: config.getMessage,
1018
891
  })
1019
892
  ]);
1020
- // If the app state key arrives and we are waiting to sync, trigger the sync now.
1021
- if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === SyncState.Syncing) {
1022
- logger.info('App state sync key arrived, triggering app state sync');
893
+ if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.appStateSyncKeyShare) &&
894
+ pendingAppStateSync) {
1023
895
  await doAppStateSync();
896
+ pendingAppStateSync = false;
897
+ }
898
+ async function doAppStateSync() {
899
+ if (!authState.creds.accountSyncCounter) {
900
+ logger.info('doing initial app state sync');
901
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true);
902
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
903
+ ev.emit('creds.update', { accountSyncCounter });
904
+ if (needToFlushWithAppStateSync) {
905
+ logger.debug('flushing with app state sync');
906
+ ev.flush();
907
+ }
908
+ }
1024
909
  }
1025
910
  });
1026
911
  ws.on('CB:presence', handlePresenceUpdate);
1027
912
  ws.on('CB:chatstate', handlePresenceUpdate);
1028
913
  ws.on('CB:ib,,dirty', async (node) => {
1029
- const { attrs } = getBinaryNodeChild(node, 'dirty');
914
+ const { attrs } = (0, WABinary_1.getBinaryNodeChild)(node, 'dirty');
1030
915
  const type = attrs.type;
1031
916
  switch (type) {
1032
917
  case 'account_sync':
@@ -1048,124 +933,43 @@ export const makeChatsSocket = (config) => {
1048
933
  }
1049
934
  });
1050
935
  ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1051
- if (connection === 'close') {
1052
- blockedCollections.clear();
1053
- clearTimeout(historySyncPausedTimeout);
1054
- historySyncPausedTimeout = undefined;
1055
- }
936
+ var _a;
1056
937
  if (connection === 'open') {
1057
938
  if (fireInitQueries) {
1058
- executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
939
+ executeInitQueries()
940
+ .catch(error => onUnexpectedError(error, 'init queries'));
1059
941
  }
1060
- sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
1061
- }
1062
- if (!receivedPendingNotifications || syncState !== SyncState.Connecting) {
1063
- return;
1064
- }
1065
- historySyncStatus.initialBootstrapComplete = false;
1066
- historySyncStatus.recentSyncComplete = false;
1067
- clearTimeout(historySyncPausedTimeout);
1068
- historySyncPausedTimeout = undefined;
1069
- syncState = SyncState.AwaitingInitialSync;
1070
- logger.info('Connection is now AwaitingInitialSync, buffering events');
1071
- ev.buffer();
1072
- const willSyncHistory = shouldSyncHistoryMessage(proto.Message.HistorySyncNotification.create({
1073
- syncType: proto.HistorySync.HistorySyncType.RECENT
1074
- }));
1075
- if (!willSyncHistory) {
1076
- logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
1077
- syncState = SyncState.Online;
1078
- setTimeout(() => ev.flush(), 0);
1079
- return;
1080
- }
1081
- // On reconnection (accountSyncCounter > 0), the server does not push
1082
- // history sync notifications — the device already has its data.
1083
- // Skip the 20s wait and go online immediately.
1084
- if (authState.creds.accountSyncCounter > 0) {
1085
- logger.info('Reconnection with existing sync data, skipping history sync wait. Transitioning to Online.');
1086
- syncState = SyncState.Online;
1087
- setTimeout(() => ev.flush(), 0);
1088
- return;
942
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
943
+ .catch(error => onUnexpectedError(error, 'presence update requests'));
1089
944
  }
1090
- logger.info('First connection, awaiting history sync notification with a 20s timeout.');
1091
- if (awaitingSyncTimeout) {
1092
- clearTimeout(awaitingSyncTimeout);
1093
- }
1094
- awaitingSyncTimeout = setTimeout(() => {
1095
- if (syncState === SyncState.AwaitingInitialSync) {
1096
- logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1097
- syncState = SyncState.Online;
1098
- ev.flush();
1099
- // Increment so subsequent reconnections skip the 20s wait.
1100
- // Late-arriving history is still processed via processMessage
1101
- // regardless of the state machine phase.
1102
- const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
1103
- ev.emit('creds.update', { accountSyncCounter });
945
+ if (receivedPendingNotifications) {
946
+ // if we don't have the app state key
947
+ // we keep buffering events until we finally have
948
+ // the key and can sync the messages
949
+ if (!((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId) && !config.mobile) {
950
+ ev.buffer();
951
+ needToFlushWithAppStateSync = true;
1104
952
  }
1105
- }, 20000);
1106
- });
1107
- // When an app state sync key arrives (myAppStateKeyId is set) and there are
1108
- // collections blocked on a missing key, trigger a re-sync for just those collections.
1109
- // This mirrors WA Web's Blocked → retry-on-key-arrival behavior.
1110
- ev.on('creds.update', ({ myAppStateKeyId }) => {
1111
- if (!myAppStateKeyId || blockedCollections.size === 0) {
1112
- return;
1113
- }
1114
- // If we're in the middle of a full sync, doAppStateSync handles all collections
1115
- if (syncState === SyncState.Syncing) {
1116
- blockedCollections.clear();
1117
- return;
1118
- }
1119
- const collections = [...blockedCollections];
1120
- blockedCollections.clear();
1121
- logger.info({ collections }, 'app state sync key arrived, re-syncing blocked collections');
1122
- resyncAppState(collections, false).catch(error => onUnexpectedError(error, 'blocked collections resync'));
1123
- });
1124
- ev.on('lid-mapping.update', async ({ lid, pn }) => {
1125
- try {
1126
- await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
1127
- }
1128
- catch (error) {
1129
- logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
1130
- }
1131
- });
1132
- registerSocketEndHandler(() => {
1133
- if (awaitingSyncTimeout) {
1134
- clearTimeout(awaitingSyncTimeout);
1135
- awaitingSyncTimeout = undefined;
1136
- }
1137
- if (!config.placeholderResendCache && placeholderResendCache.close) {
1138
- placeholderResendCache.close();
1139
953
  }
1140
- syncState = SyncState.Connecting;
1141
- privacySettings = undefined;
1142
954
  });
1143
955
  return {
1144
956
  ...sock,
1145
- serverProps,
1146
- createCallLink,
1147
- getBotListV2,
1148
- messageMutex,
1149
- receiptMutex,
1150
- appStatePatchMutex,
1151
- notificationMutex,
957
+ processingMutex,
1152
958
  fetchPrivacySettings,
1153
959
  upsertMessage,
1154
960
  appPatch,
1155
961
  sendPresenceUpdate,
1156
962
  presenceSubscribe,
1157
963
  profilePictureUrl,
964
+ onWhatsApp,
965
+ toLid,
1158
966
  fetchBlocklist,
1159
967
  fetchStatus,
1160
- fetchDisappearingDuration,
1161
968
  updateProfilePicture,
1162
969
  removeProfilePicture,
1163
970
  updateProfileStatus,
1164
971
  updateProfileName,
1165
972
  updateBlockStatus,
1166
- updateDisableLinkPreviewsPrivacy,
1167
- updateCallPrivacy,
1168
- updateMessagesPrivacy,
1169
973
  updateLastSeenPrivacy,
1170
974
  updateOnlinePrivacy,
1171
975
  updateProfilePicturePrivacy,
@@ -1177,17 +981,13 @@ export const makeChatsSocket = (config) => {
1177
981
  resyncAppState,
1178
982
  chatModify,
1179
983
  cleanDirtyBits,
1180
- addOrEditContact,
1181
- removeContact,
1182
- placeholderResendCache,
1183
- addLabel,
1184
984
  addChatLabel,
1185
985
  removeChatLabel,
1186
986
  addMessageLabel,
987
+ deleteChat,
988
+ checkStatusWA,
1187
989
  removeMessageLabel,
1188
- star,
1189
- addOrEditQuickReply,
1190
- removeQuickReply
990
+ star
1191
991
  };
1192
992
  };
1193
- //# sourceMappingURL=chats.js.map
993
+ exports.makeChatsSocket = makeChatsSocket;