jagproject 26.3.23 → 26.3.26

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 (209) hide show
  1. package/WAProto/GenerateStatics.sh +3 -4
  2. package/WAProto/WAProto.proto +1215 -511
  3. package/WAProto/fix-imports.js +73 -0
  4. package/WAProto/index.d.ts +14017 -0
  5. package/WAProto/index.js +64857 -145167
  6. package/engine-requirements.js +4 -7
  7. package/lib/Defaults/index.d.ts +74 -0
  8. package/lib/Defaults/index.js +49 -35
  9. package/lib/Defaults/phonenumber-mcc.json +223 -0
  10. package/lib/Defaults/wileys-version.json +2 -2
  11. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  12. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  13. package/lib/Signal/Group/group-session-builder.js +5 -3
  14. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  15. package/lib/Signal/Group/group_cipher.js +35 -46
  16. package/lib/Signal/Group/index.d.ts +12 -0
  17. package/lib/Signal/Group/index.js +21 -21
  18. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  19. package/lib/Signal/Group/keyhelper.js +2 -2
  20. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  21. package/lib/Signal/Group/sender-chain-key.js +5 -10
  22. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  23. package/lib/Signal/Group/sender-key-distribution-message.js +7 -7
  24. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  25. package/lib/Signal/Group/sender-key-message.js +8 -8
  26. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  27. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  28. package/lib/Signal/Group/sender-key-record.js +7 -16
  29. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  30. package/lib/Signal/Group/sender-key-state.js +25 -37
  31. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  32. package/lib/Signal/Group/sender-message-key.js +2 -2
  33. package/lib/Signal/libsignal.d.ts +5 -0
  34. package/lib/Signal/libsignal.js +358 -54
  35. package/lib/Signal/lid-mapping.d.ts +19 -0
  36. package/lib/Signal/lid-mapping.js +274 -0
  37. package/lib/Socket/Client/index.d.ts +3 -0
  38. package/lib/Socket/Client/index.js +2 -2
  39. package/lib/Socket/Client/types.d.ts +16 -0
  40. package/lib/Socket/Client/types.js +1 -0
  41. package/lib/Socket/Client/websocket.d.ts +13 -0
  42. package/lib/Socket/Client/websocket.js +18 -30
  43. package/lib/Socket/business.d.ts +202 -0
  44. package/lib/Socket/business.js +160 -38
  45. package/lib/Socket/chats.d.ts +111 -0
  46. package/lib/Socket/chats.js +497 -314
  47. package/lib/Socket/communities.d.ts +258 -0
  48. package/lib/Socket/communities.js +438 -0
  49. package/lib/Socket/community.js +333 -0
  50. package/lib/Socket/groups.d.ts +150 -0
  51. package/lib/Socket/groups.js +229 -91
  52. package/lib/Socket/index.d.ts +245 -0
  53. package/lib/Socket/index.js +9 -6
  54. package/lib/Socket/messages-recv.d.ts +187 -0
  55. package/lib/Socket/messages-recv.js +1105 -501
  56. package/lib/Socket/messages-send.d.ts +183 -0
  57. package/lib/Socket/messages-send.js +1181 -501
  58. package/lib/Socket/mex.d.ts +3 -0
  59. package/lib/Socket/mex.js +45 -0
  60. package/lib/Socket/newsletter.d.ts +160 -0
  61. package/lib/Socket/newsletter.js +227 -200
  62. package/lib/Socket/socket.d.ts +55 -0
  63. package/lib/Socket/socket.js +507 -206
  64. package/lib/Socket/usync.js +6 -6
  65. package/lib/Store/index.js +17 -5
  66. package/lib/Store/make-cache-manager-store.js +83 -0
  67. package/lib/Store/make-in-memory-store.js +48 -89
  68. package/lib/Store/make-ordered-dictionary.js +1 -1
  69. package/lib/Types/Auth.d.ts +116 -0
  70. package/lib/Types/Bussines.d.ts +25 -0
  71. package/lib/Types/Bussines.js +2 -0
  72. package/lib/Types/Call.d.ts +15 -0
  73. package/lib/Types/Chat.d.ts +123 -0
  74. package/lib/Types/Chat.js +7 -1
  75. package/lib/Types/Contact.d.ts +24 -0
  76. package/lib/Types/Events.d.ts +237 -0
  77. package/lib/Types/Events.js +1 -0
  78. package/lib/Types/GroupMetadata.d.ts +67 -0
  79. package/lib/Types/Label.d.ts +47 -0
  80. package/lib/Types/Label.js +1 -3
  81. package/lib/Types/LabelAssociation.d.ts +30 -0
  82. package/lib/Types/LabelAssociation.js +1 -3
  83. package/lib/Types/Message.d.ts +305 -0
  84. package/lib/Types/Message.js +9 -5
  85. package/lib/Types/MexUpdates.js +11 -0
  86. package/lib/Types/Newsletter.d.ts +135 -0
  87. package/lib/Types/Newsletter.js +36 -11
  88. package/lib/Types/Product.d.ts +79 -0
  89. package/lib/Types/Signal.d.ts +76 -0
  90. package/lib/Types/Signal.js +1 -0
  91. package/lib/Types/Socket.d.ts +133 -0
  92. package/lib/Types/Socket.js +1 -0
  93. package/lib/Types/State.d.ts +39 -0
  94. package/lib/Types/State.js +12 -0
  95. package/lib/Types/USync.d.ts +26 -0
  96. package/lib/Types/USync.js +1 -0
  97. package/lib/Types/index.d.ts +65 -0
  98. package/lib/Types/index.js +14 -14
  99. package/lib/Utils/audioToBuffer.js +31 -0
  100. package/lib/Utils/auth-utils.d.ts +19 -0
  101. package/lib/Utils/auth-utils.js +222 -123
  102. package/lib/Utils/baileys-event-stream.js +60 -0
  103. package/lib/Utils/bridge-runtime.d.ts +1 -0
  104. package/lib/Utils/bridge-runtime.js +14 -0
  105. package/lib/Utils/browser-utils.d.ts +4 -0
  106. package/lib/Utils/browser-utils.js +38 -29
  107. package/lib/Utils/business.d.ts +23 -0
  108. package/lib/Utils/business.js +54 -48
  109. package/lib/Utils/chat-utils.d.ts +70 -0
  110. package/lib/Utils/chat-utils.js +284 -189
  111. package/lib/Utils/crypto.d.ts +37 -0
  112. package/lib/Utils/crypto.js +16 -41
  113. package/lib/Utils/decode-wa-message.d.ts +48 -0
  114. package/lib/Utils/decode-wa-message.js +128 -48
  115. package/lib/Utils/event-buffer.d.ts +34 -0
  116. package/lib/Utils/event-buffer.js +124 -62
  117. package/lib/Utils/generics.d.ts +91 -0
  118. package/lib/Utils/generics.js +154 -138
  119. package/lib/Utils/history.d.ts +22 -0
  120. package/lib/Utils/history.js +77 -34
  121. package/lib/Utils/identity-change-handler.d.ts +37 -0
  122. package/lib/Utils/identity-change-handler.js +54 -0
  123. package/lib/Utils/index.d.ts +22 -0
  124. package/lib/Utils/index.js +32 -19
  125. package/lib/Utils/link-preview.d.ts +21 -0
  126. package/lib/Utils/link-preview.js +12 -17
  127. package/lib/Utils/logger.d.ts +13 -0
  128. package/lib/Utils/lt-hash.d.ts +8 -0
  129. package/lib/Utils/lt-hash.js +2 -43
  130. package/lib/Utils/make-mutex.d.ts +9 -0
  131. package/lib/Utils/make-mutex.js +21 -27
  132. package/lib/Utils/message-retry-manager.d.ts +110 -0
  133. package/lib/Utils/message-retry-manager.js +143 -45
  134. package/lib/Utils/messages-media.d.ts +130 -0
  135. package/lib/Utils/messages-media.js +429 -502
  136. package/lib/Utils/messages-newsletter.d.ts +84 -0
  137. package/lib/Utils/messages-newsletter.js +295 -0
  138. package/lib/Utils/messages.d.ts +92 -0
  139. package/lib/Utils/messages.js +1025 -674
  140. package/lib/Utils/noise-handler.d.ts +20 -0
  141. package/lib/Utils/noise-handler.js +145 -91
  142. package/lib/Utils/pre-key-manager.d.ts +28 -0
  143. package/lib/Utils/pre-key-manager.js +112 -0
  144. package/lib/Utils/process-message.d.ts +60 -0
  145. package/lib/Utils/process-message.js +316 -184
  146. package/lib/Utils/reporting-utils.d.ts +11 -0
  147. package/lib/Utils/reporting-utils.js +262 -0
  148. package/lib/Utils/resolve-jid.d.ts +43 -0
  149. package/lib/Utils/resolve-jid.js +95 -0
  150. package/lib/Utils/rust-bridge-shim.d.ts +22 -0
  151. package/lib/Utils/rust-bridge-shim.js +70 -0
  152. package/lib/Utils/serial-task-queue.js +29 -0
  153. package/lib/Utils/signal.d.ts +34 -0
  154. package/lib/Utils/signal.js +56 -39
  155. package/lib/Utils/streamToBuffer.js +17 -0
  156. package/lib/Utils/sync-action-utils.d.ts +19 -0
  157. package/lib/Utils/sync-action-utils.js +52 -0
  158. package/lib/Utils/tc-token-utils.d.ts +12 -0
  159. package/lib/Utils/tc-token-utils.js +20 -0
  160. package/lib/Utils/use-mongo-file-auth-state.js +71 -0
  161. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  162. package/lib/Utils/use-multi-file-auth-state.js +11 -12
  163. package/lib/Utils/use-single-file-auth-state.js +73 -0
  164. package/lib/Utils/validate-connection.d.ts +11 -0
  165. package/lib/Utils/validate-connection.js +59 -82
  166. package/lib/Utils/wileys-event-stream.js +1 -61
  167. package/lib/WABinary/constants.d.ts +28 -0
  168. package/lib/WABinary/decode.d.ts +7 -0
  169. package/lib/WABinary/decode.js +39 -4
  170. package/lib/WABinary/encode.d.ts +3 -0
  171. package/lib/WABinary/encode.js +17 -11
  172. package/lib/WABinary/generic-utils.d.ts +15 -0
  173. package/lib/WABinary/generic-utils.js +46 -18
  174. package/lib/WABinary/index.d.ts +6 -0
  175. package/lib/WABinary/index.js +9 -5
  176. package/lib/WABinary/jid-utils.d.ts +48 -0
  177. package/lib/WABinary/jid-utils.js +67 -37
  178. package/lib/WABinary/types.d.ts +19 -0
  179. package/lib/WABinary/types.js +34 -0
  180. package/lib/WAM/BinaryInfo.d.ts +9 -0
  181. package/lib/WAM/constants.d.ts +40 -0
  182. package/lib/WAM/constants.js +19183 -11678
  183. package/lib/WAM/encode.d.ts +3 -0
  184. package/lib/WAM/encode.js +15 -17
  185. package/lib/WAM/index.d.ts +4 -0
  186. package/lib/WAM/index.js +3 -3
  187. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  188. package/lib/WAUSync/Protocols/USyncContactProtocol.js +6 -6
  189. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  190. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +9 -9
  191. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  192. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +6 -6
  193. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  194. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +7 -8
  195. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  196. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +18 -17
  197. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  198. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +11 -3
  199. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  200. package/lib/WAUSync/Protocols/index.js +6 -4
  201. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  202. package/lib/WAUSync/USyncQuery.js +38 -30
  203. package/lib/WAUSync/USyncUser.d.ts +13 -0
  204. package/lib/WAUSync/index.d.ts +4 -0
  205. package/lib/WAUSync/index.js +3 -3
  206. package/lib/index.d.ts +12 -0
  207. package/lib/index.js +3 -5
  208. package/package.json +7 -4
  209. package/LICENSE +0 -21
@@ -0,0 +1,274 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LIDMappingStore = void 0;
4
+ const lru_cache_1 = require("lru-cache");
5
+ const index_js_1 = require("../WABinary/index.js");
6
+ class LIDMappingStore {
7
+ constructor(keys, logger, pnToLIDFunc) {
8
+ this.mappingCache = new lru_cache_1.LRUCache({
9
+ ttl: 3 * 24 * 60 * 60 * 1000, // 7 days
10
+ ttlAutopurge: true,
11
+ updateAgeOnGet: true
12
+ });
13
+ this.inflightLIDLookups = new Map();
14
+ this.inflightPNLookups = new Map();
15
+ this.keys = keys;
16
+ this.pnToLIDFunc = pnToLIDFunc;
17
+ this.logger = logger;
18
+ }
19
+ async storeLIDPNMappings(pairs) {
20
+ if (pairs.length === 0)
21
+ return;
22
+ const validatedPairs = [];
23
+ for (const { lid, pn } of pairs) {
24
+ if (!(((0, index_js_1.isLidUser)(lid) && (0, index_js_1.isPnUser)(pn)) || ((0, index_js_1.isPnUser)(lid) && (0, index_js_1.isLidUser)(pn)))) {
25
+ this.logger.warn(`Invalid LID-PN mapping: ${lid}, ${pn}`);
26
+ continue;
27
+ }
28
+ const lidDecoded = (0, index_js_1.jidDecode)(lid);
29
+ const pnDecoded = (0, index_js_1.jidDecode)(pn);
30
+ if (!lidDecoded || !pnDecoded)
31
+ continue;
32
+ validatedPairs.push({ pnUser: pnDecoded.user, lidUser: lidDecoded.user });
33
+ }
34
+ if (validatedPairs.length === 0)
35
+ return;
36
+ const cacheMissSet = new Set();
37
+ const existingMappings = new Map();
38
+ for (const { pnUser } of validatedPairs) {
39
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
40
+ if (cached) {
41
+ existingMappings.set(pnUser, cached);
42
+ }
43
+ else {
44
+ cacheMissSet.add(pnUser);
45
+ }
46
+ }
47
+ if (cacheMissSet.size > 0) {
48
+ const cacheMisses = [...cacheMissSet];
49
+ this.logger.trace(`Batch fetching ${cacheMisses.length} LID mappings from database`);
50
+ const stored = await this.keys.get('lid-mapping', cacheMisses);
51
+ for (const pnUser of cacheMisses) {
52
+ const existingLidUser = stored[pnUser];
53
+ if (existingLidUser) {
54
+ existingMappings.set(pnUser, existingLidUser);
55
+ this.mappingCache.set(`pn:${pnUser}`, existingLidUser);
56
+ this.mappingCache.set(`lid:${existingLidUser}`, pnUser);
57
+ }
58
+ }
59
+ }
60
+ const pairMap = {};
61
+ for (const { pnUser, lidUser } of validatedPairs) {
62
+ const existingLidUser = existingMappings.get(pnUser);
63
+ if (existingLidUser === lidUser) {
64
+ this.logger.debug({ pnUser, lidUser }, 'LID mapping already exists, skipping');
65
+ continue;
66
+ }
67
+ pairMap[pnUser] = lidUser;
68
+ }
69
+ if (Object.keys(pairMap).length === 0)
70
+ return;
71
+ this.logger.trace({ pairMap }, `Storing ${Object.keys(pairMap).length} pn mappings`);
72
+ const batchData = {};
73
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
74
+ batchData[pnUser] = lidUser;
75
+ batchData[`${lidUser}_reverse`] = pnUser;
76
+ }
77
+ await this.keys.transaction(async () => {
78
+ await this.keys.set({ 'lid-mapping': batchData });
79
+ }, 'lid-mapping');
80
+ // Update cache after successful DB write
81
+ for (const [pnUser, lidUser] of Object.entries(pairMap)) {
82
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
83
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
84
+ }
85
+ }
86
+ async getLIDForPN(pn) {
87
+ return (await this.getLIDsForPNs([pn]))?.[0]?.lid || null;
88
+ }
89
+ async getLIDsForPNs(pns) {
90
+ if (pns.length === 0)
91
+ return null;
92
+ const sortedPns = [...new Set(pns)].sort();
93
+ const cacheKey = sortedPns.join(',');
94
+ const inflight = this.inflightLIDLookups.get(cacheKey);
95
+ if (inflight) {
96
+ this.logger.trace(`Coalescing getLIDsForPNs request for ${sortedPns.length} PNs`);
97
+ return inflight;
98
+ }
99
+ const promise = this._getLIDsForPNsImpl(pns);
100
+ this.inflightLIDLookups.set(cacheKey, promise);
101
+ try {
102
+ return await promise;
103
+ }
104
+ finally {
105
+ this.inflightLIDLookups.delete(cacheKey);
106
+ }
107
+ }
108
+ async _getLIDsForPNsImpl(pns) {
109
+ const usyncFetch = {};
110
+ const successfulPairs = {};
111
+ const pending = [];
112
+ const addResolvedPair = (pn, decoded, lidUser) => {
113
+ const normalizedLidUser = lidUser.toString();
114
+ if (!normalizedLidUser) {
115
+ this.logger.warn(`Invalid or empty LID user for PN ${pn}: lidUser = "${lidUser}"`);
116
+ return false;
117
+ }
118
+ // Push the PN device ID to the LID to maintain device separation
119
+ const pnDevice = decoded.device !== undefined ? decoded.device : 0;
120
+ const deviceSpecificLid = `${normalizedLidUser}${!!pnDevice ? `:${pnDevice}` : ``}@${decoded.server === 'hosted' ? 'hosted.lid' : 'lid'}`;
121
+ this.logger.trace(`getLIDForPN: ${pn} → ${deviceSpecificLid} (user mapping with device ${pnDevice})`);
122
+ successfulPairs[pn] = { lid: deviceSpecificLid, pn };
123
+ return true;
124
+ };
125
+ for (const pn of pns) {
126
+ if (!(0, index_js_1.isPnUser)(pn) && !(0, index_js_1.isHostedPnUser)(pn))
127
+ continue;
128
+ const decoded = (0, index_js_1.jidDecode)(pn);
129
+ if (!decoded)
130
+ continue;
131
+ const pnUser = decoded.user;
132
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
133
+ if (cached && typeof cached === 'string') {
134
+ if (!addResolvedPair(pn, decoded, cached)) {
135
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
136
+ continue;
137
+ }
138
+ continue;
139
+ }
140
+ pending.push({ pn, pnUser, decoded });
141
+ }
142
+ if (pending.length) {
143
+ const pnUsers = [...new Set(pending.map(item => item.pnUser))];
144
+ const stored = await this.keys.get('lid-mapping', pnUsers);
145
+ for (const pnUser of pnUsers) {
146
+ const lidUser = stored[pnUser];
147
+ if (lidUser && typeof lidUser === 'string') {
148
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
149
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
150
+ }
151
+ }
152
+ for (const { pn, pnUser, decoded } of pending) {
153
+ const cached = this.mappingCache.get(`pn:${pnUser}`);
154
+ if (cached && typeof cached === 'string') {
155
+ if (!addResolvedPair(pn, decoded, cached)) {
156
+ this.logger.warn(`Invalid entry for ${pn} (pair not resolved)`);
157
+ continue;
158
+ }
159
+ }
160
+ else {
161
+ this.logger.trace(`No LID mapping found for PN user ${pnUser}; batch getting from USync`);
162
+ const device = decoded.device || 0;
163
+ let normalizedPn = (0, index_js_1.jidNormalizedUser)(pn);
164
+ if ((0, index_js_1.isHostedPnUser)(normalizedPn)) {
165
+ normalizedPn = `${pnUser}@s.whatsapp.net`;
166
+ }
167
+ if (!usyncFetch[normalizedPn]) {
168
+ usyncFetch[normalizedPn] = [device];
169
+ }
170
+ else {
171
+ usyncFetch[normalizedPn]?.push(device);
172
+ }
173
+ }
174
+ }
175
+ }
176
+ if (Object.keys(usyncFetch).length > 0) {
177
+ const result = await this.pnToLIDFunc?.(Object.keys(usyncFetch)); // this function already adds LIDs to mapping
178
+ if (result && result.length > 0) {
179
+ await this.storeLIDPNMappings(result);
180
+ for (const pair of result) {
181
+ const pnDecoded = (0, index_js_1.jidDecode)(pair.pn);
182
+ const pnUser = pnDecoded?.user;
183
+ if (!pnUser)
184
+ continue;
185
+ const lidUser = (0, index_js_1.jidDecode)(pair.lid)?.user;
186
+ if (!lidUser)
187
+ continue;
188
+ for (const device of usyncFetch[pair.pn]) {
189
+ const deviceSpecificLid = `${lidUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted.lid' : 'lid'}`;
190
+ this.logger.trace(`getLIDForPN: USYNC success for ${pair.pn} → ${deviceSpecificLid} (user mapping with device ${device})`);
191
+ const deviceSpecificPn = `${pnUser}${!!device ? `:${device}` : ``}@${device === 99 ? 'hosted' : 's.whatsapp.net'}`;
192
+ successfulPairs[deviceSpecificPn] = { lid: deviceSpecificLid, pn: deviceSpecificPn };
193
+ }
194
+ }
195
+ }
196
+ else {
197
+ this.logger.warn('USync fetch yielded no results for pending PNs');
198
+ }
199
+ }
200
+ return Object.values(successfulPairs).length > 0 ? Object.values(successfulPairs) : null;
201
+ }
202
+ async getPNForLID(lid) {
203
+ return (await this.getPNsForLIDs([lid]))?.[0]?.pn || null;
204
+ }
205
+ async getPNsForLIDs(lids) {
206
+ if (lids.length === 0)
207
+ return null;
208
+ const sortedLids = [...new Set(lids)].sort();
209
+ const cacheKey = sortedLids.join(',');
210
+ const inflight = this.inflightPNLookups.get(cacheKey);
211
+ if (inflight) {
212
+ this.logger.trace(`Coalescing getPNsForLIDs request for ${sortedLids.length} LIDs`);
213
+ return inflight;
214
+ }
215
+ const promise = this._getPNsForLIDsImpl(lids);
216
+ this.inflightPNLookups.set(cacheKey, promise);
217
+ try {
218
+ return await promise;
219
+ }
220
+ finally {
221
+ this.inflightPNLookups.delete(cacheKey);
222
+ }
223
+ }
224
+ async _getPNsForLIDsImpl(lids) {
225
+ const successfulPairs = {};
226
+ const pending = [];
227
+ const addResolvedPair = (lid, decoded, pnUser) => {
228
+ if (!pnUser || typeof pnUser !== 'string') {
229
+ return false;
230
+ }
231
+ const lidDevice = decoded.device !== undefined ? decoded.device : 0;
232
+ const pnJid = `${pnUser}:${lidDevice}@${decoded.domainType === index_js_1.WAJIDDomains.HOSTED_LID ? 'hosted' : 's.whatsapp.net'}`;
233
+ this.logger.trace(`Found reverse mapping: ${lid} → ${pnJid}`);
234
+ successfulPairs[lid] = { lid, pn: pnJid };
235
+ return true;
236
+ };
237
+ for (const lid of lids) {
238
+ if (!(0, index_js_1.isLidUser)(lid))
239
+ continue;
240
+ const decoded = (0, index_js_1.jidDecode)(lid);
241
+ if (!decoded)
242
+ continue;
243
+ const lidUser = decoded.user;
244
+ const cached = this.mappingCache.get(`lid:${lidUser}`);
245
+ if (cached && typeof cached === 'string') {
246
+ addResolvedPair(lid, decoded, cached);
247
+ continue;
248
+ }
249
+ pending.push({ lid, lidUser, decoded });
250
+ }
251
+ if (pending.length) {
252
+ const reverseKeys = [...new Set(pending.map(item => `${item.lidUser}_reverse`))];
253
+ const stored = await this.keys.get('lid-mapping', reverseKeys);
254
+ for (const { lid, lidUser, decoded } of pending) {
255
+ let pnUser = this.mappingCache.get(`lid:${lidUser}`);
256
+ if (!pnUser || typeof pnUser !== 'string') {
257
+ pnUser = stored[`${lidUser}_reverse`];
258
+ if (pnUser && typeof pnUser === 'string') {
259
+ this.mappingCache.set(`lid:${lidUser}`, pnUser);
260
+ this.mappingCache.set(`pn:${pnUser}`, lidUser);
261
+ }
262
+ }
263
+ if (pnUser && typeof pnUser === 'string') {
264
+ addResolvedPair(lid, decoded, pnUser);
265
+ }
266
+ else {
267
+ this.logger.trace(`No reverse mapping found for LID user: ${lidUser}`);
268
+ }
269
+ }
270
+ }
271
+ return Object.values(successfulPairs).length ? Object.values(successfulPairs) : null;
272
+ }
273
+ }
274
+ exports.LIDMappingStore = LIDMappingStore;
@@ -0,0 +1,3 @@
1
+ export * from './types.js';
2
+ export * from './websocket.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -14,5 +14,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./types"), exports);
18
- __exportStar(require("./websocket"), exports);
17
+ __exportStar(require("./types.js"), exports);
18
+ __exportStar(require("./websocket.js"), exports);
@@ -0,0 +1,16 @@
1
+ import { EventEmitter } from 'events';
2
+ import { URL } from 'url';
3
+ import type { SocketConfig } from '../../Types/index.js';
4
+ export declare abstract class AbstractSocketClient extends EventEmitter {
5
+ url: URL;
6
+ config: SocketConfig;
7
+ abstract get isOpen(): boolean;
8
+ abstract get isClosed(): boolean;
9
+ abstract get isClosing(): boolean;
10
+ abstract get isConnecting(): boolean;
11
+ constructor(url: URL, config: SocketConfig);
12
+ abstract connect(): void;
13
+ abstract close(): void;
14
+ abstract send(str: Uint8Array | string, cb?: (err?: Error) => void): boolean;
15
+ }
16
+ //# sourceMappingURL=types.d.ts.map
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AbstractSocketClient = void 0;
4
4
  const events_1 = require("events");
5
+ const url_1 = require("url");
5
6
  class AbstractSocketClient extends events_1.EventEmitter {
6
7
  constructor(url, config) {
7
8
  super();
@@ -0,0 +1,13 @@
1
+ import WebSocket from 'ws';
2
+ import { AbstractSocketClient } from './types.js';
3
+ export declare class WebSocketClient extends AbstractSocketClient {
4
+ protected socket: WebSocket | null;
5
+ get isOpen(): boolean;
6
+ get isClosed(): boolean;
7
+ get isClosing(): boolean;
8
+ get isConnecting(): boolean;
9
+ connect(): void;
10
+ close(): Promise<void>;
11
+ send(str: string | Uint8Array, cb?: (err?: Error) => void): boolean;
12
+ }
13
+ //# sourceMappingURL=websocket.d.ts.map
@@ -5,68 +5,56 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.WebSocketClient = void 0;
7
7
  const ws_1 = __importDefault(require("ws"));
8
- const Defaults_1 = require("../../Defaults");
9
- const types_1 = require("./types");
10
- class WebSocketClient extends types_1.AbstractSocketClient {
8
+ const index_js_1 = require("../../Defaults/index.js");
9
+ const types_js_1 = require("./types.js");
10
+ class WebSocketClient extends types_js_1.AbstractSocketClient {
11
11
  constructor() {
12
12
  super(...arguments);
13
13
  this.socket = null;
14
14
  }
15
15
  get isOpen() {
16
- var _a;
17
- return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.OPEN;
16
+ return this.socket?.readyState === ws_1.default.OPEN;
18
17
  }
19
18
  get isClosed() {
20
- var _a;
21
- return this.socket === null || ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.CLOSED;
19
+ return this.socket === null || this.socket?.readyState === ws_1.default.CLOSED;
22
20
  }
23
21
  get isClosing() {
24
- var _a;
25
- return this.socket === null || ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.CLOSING;
22
+ return this.socket === null || this.socket?.readyState === ws_1.default.CLOSING;
26
23
  }
27
24
  get isConnecting() {
28
- var _a;
29
- return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.CONNECTING;
25
+ return this.socket?.readyState === ws_1.default.CONNECTING;
30
26
  }
31
- async connect() {
32
- var _a, _b;
27
+ connect() {
33
28
  if (this.socket) {
34
29
  return;
35
30
  }
36
31
  this.socket = new ws_1.default(this.url, {
37
- origin: Defaults_1.DEFAULT_ORIGIN,
38
- headers: (_a = this.config.options) === null || _a === void 0 ? void 0 : _a.headers,
32
+ origin: index_js_1.DEFAULT_ORIGIN,
33
+ headers: this.config.options?.headers,
39
34
  handshakeTimeout: this.config.connectTimeoutMs,
40
35
  timeout: this.config.connectTimeoutMs,
41
- agent: this.config.agent,
36
+ agent: this.config.agent
42
37
  });
43
38
  this.socket.setMaxListeners(0);
44
39
  const events = ['close', 'error', 'upgrade', 'message', 'open', 'ping', 'pong', 'unexpected-response'];
45
40
  for (const event of events) {
46
- (_b = this.socket) === null || _b === void 0 ? void 0 : _b.on(event, (...args) => this.emit(event, ...args));
41
+ this.socket?.on(event, (...args) => this.emit(event, ...args));
47
42
  }
48
43
  }
49
44
  async close() {
50
45
  if (!this.socket) {
51
46
  return;
52
47
  }
48
+ const closePromise = new Promise(resolve => {
49
+ this.socket?.once('close', resolve);
50
+ });
53
51
  this.socket.close();
52
+ await closePromise;
54
53
  this.socket = null;
55
54
  }
56
- async restart() {
57
- if (this.socket) {
58
- await new Promise(resolve => {
59
- this.socket.once('close', resolve);
60
- this.socket.terminate();
61
- });
62
- this.socket = null;
63
- }
64
- await this.connect();
65
- }
66
55
  send(str, cb) {
67
- var _a;
68
- (_a = this.socket) === null || _a === void 0 ? void 0 : _a.send(str, cb);
69
- return true;
56
+ this.socket?.send(str, cb);
57
+ return Boolean(this.socket);
70
58
  }
71
59
  }
72
60
  exports.WebSocketClient = WebSocketClient;
@@ -0,0 +1,202 @@
1
+ import type { GetCatalogOptions, ProductCreate, ProductUpdate, SocketConfig, WAMediaUpload } from '../Types/index.js';
2
+ import type { UpdateBussinesProfileProps } from '../Types/Bussines.js';
3
+ import { type BinaryNode } from '../WABinary/index.js';
4
+ export declare const makeBusinessSocket: (config: SocketConfig) => {
5
+ logger: import("../Utils/logger.js").ILogger;
6
+ getOrderDetails: (orderId: string, tokenBase64: string) => Promise<import("../index.js").OrderDetails>;
7
+ getCatalog: ({ jid, limit, cursor }: GetCatalogOptions) => Promise<{
8
+ products: import("../index.js").Product[];
9
+ nextPageCursor: string | undefined;
10
+ }>;
11
+ getCollections: (jid?: string, limit?: number) => Promise<{
12
+ collections: import("../index.js").CatalogCollection[];
13
+ }>;
14
+ productCreate: (create: ProductCreate) => Promise<import("../index.js").Product>;
15
+ productDelete: (productIds: string[]) => Promise<{
16
+ deleted: number;
17
+ }>;
18
+ productUpdate: (productId: string, update: ProductUpdate) => Promise<import("../index.js").Product>;
19
+ updateBussinesProfile: (args: UpdateBussinesProfileProps) => Promise<any>;
20
+ updateCoverPhoto: (photo: WAMediaUpload) => Promise<number>;
21
+ removeCoverPhoto: (id: string) => Promise<any>;
22
+ sendMessageAck: ({ tag, attrs, content }: BinaryNode, errorCode?: number) => Promise<void>;
23
+ sendRetryRequest: (node: BinaryNode, forceIncludeKeys?: boolean) => Promise<void>;
24
+ rejectCall: (callId: string, callFrom: string) => Promise<void>;
25
+ fetchMessageHistory: (count: number, oldestMsgKey: import("../index.js").WAMessageKey, oldestMsgTimestamp: number | import("long").default) => Promise<string>;
26
+ requestPlaceholderResend: (messageKey: import("../index.js").WAMessageKey, msgData?: Partial<import("../index.js").WAMessage>) => Promise<string | undefined>;
27
+ messageRetryManager: import("../index.js").MessageRetryManager | null;
28
+ getPrivacyTokens: (jids: string[]) => Promise<any>;
29
+ assertSessions: (jids: string[], force?: boolean) => Promise<boolean>;
30
+ relayMessage: (jid: string, message: import("../index.js").proto.IMessage, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }: import("../index.js").MessageRelayOptions) => Promise<string>;
31
+ sendReceipt: (jid: string, participant: string | undefined, messageIds: string[], type: import("../index.js").MessageReceiptType) => Promise<void>;
32
+ sendReceipts: (keys: import("../index.js").WAMessageKey[], type: import("../index.js").MessageReceiptType) => Promise<void>;
33
+ readMessages: (keys: import("../index.js").WAMessageKey[]) => Promise<void>;
34
+ refreshMediaConn: (forceGet?: boolean) => Promise<import("../index.js").MediaConnInfo>;
35
+ waUploadToServer: import("../index.js").WAMediaUploadFunction;
36
+ fetchPrivacySettings: (force?: boolean) => Promise<{
37
+ [_: string]: string;
38
+ }>;
39
+ sendPeerDataOperationMessage: (pdoMessage: import("../index.js").proto.Message.IPeerDataOperationRequestMessage) => Promise<string>;
40
+ createParticipantNodes: (recipientJids: string[], message: import("../index.js").proto.IMessage, extraAttrs?: BinaryNode["attrs"], dsmMessage?: import("../index.js").proto.IMessage) => Promise<{
41
+ nodes: BinaryNode[];
42
+ shouldIncludeDeviceIdentity: boolean;
43
+ }>;
44
+ getUSyncDevices: (jids: string[], useCache: boolean, ignoreZeroDevices: boolean) => Promise<(import("../index.js").JidWithDevice & {
45
+ jid: string;
46
+ })[]>;
47
+ updateMemberLabel: (jid: string, memberLabel: string) => Promise<string>;
48
+ updateMediaMessage: (message: import("../index.js").WAMessage) => Promise<import("../index.js").WAMessage>;
49
+ sendMessage: (jid: string, content: import("../index.js").AnyMessageContent, options?: import("../index.js").MiscMessageGenerationOptions) => Promise<import("../index.js").WAMessage | undefined>;
50
+ newsletterCreate: (name: string, description?: string) => Promise<import("../index.js").NewsletterMetadata>;
51
+ newsletterUpdate: (jid: string, updates: import("../index.js").NewsletterUpdate) => Promise<unknown>;
52
+ newsletterSubscribers: (jid: string) => Promise<{
53
+ subscribers: number;
54
+ }>;
55
+ newsletterMetadata: (type: "invite" | "jid", key: string) => Promise<import("../index.js").NewsletterMetadata | null>;
56
+ newsletterFollow: (jid: string) => Promise<unknown>;
57
+ newsletterUnfollow: (jid: string) => Promise<unknown>;
58
+ newsletterMute: (jid: string) => Promise<unknown>;
59
+ newsletterUnmute: (jid: string) => Promise<unknown>;
60
+ newsletterUpdateName: (jid: string, name: string) => Promise<unknown>;
61
+ newsletterUpdateDescription: (jid: string, description: string) => Promise<unknown>;
62
+ newsletterUpdatePicture: (jid: string, content: WAMediaUpload) => Promise<unknown>;
63
+ newsletterRemovePicture: (jid: string) => Promise<unknown>;
64
+ newsletterReactMessage: (jid: string, serverId: string, reaction?: string) => Promise<void>;
65
+ newsletterFetchMessages: (jid: string, count: number, since: number, after: number) => Promise<any>;
66
+ subscribeNewsletterUpdates: (jid: string) => Promise<{
67
+ duration: string;
68
+ } | null>;
69
+ newsletterAdminCount: (jid: string) => Promise<number>;
70
+ newsletterChangeOwner: (jid: string, newOwnerJid: string) => Promise<void>;
71
+ newsletterDemote: (jid: string, userJid: string) => Promise<void>;
72
+ newsletterDelete: (jid: string) => Promise<void>;
73
+ groupMetadata: (jid: string) => Promise<import("../index.js").GroupMetadata>;
74
+ groupCreate: (subject: string, participants: string[]) => Promise<import("../index.js").GroupMetadata>;
75
+ groupLeave: (id: string) => Promise<void>;
76
+ groupUpdateSubject: (jid: string, subject: string) => Promise<void>;
77
+ groupRequestParticipantsList: (jid: string) => Promise<{
78
+ [key: string]: string;
79
+ }[]>;
80
+ groupRequestParticipantsUpdate: (jid: string, participants: string[], action: "approve" | "reject") => Promise<{
81
+ status: string;
82
+ jid: string | undefined;
83
+ }[]>;
84
+ groupParticipantsUpdate: (jid: string, participants: string[], action: import("../index.js").ParticipantAction) => Promise<{
85
+ status: string;
86
+ jid: string | undefined;
87
+ content: BinaryNode;
88
+ }[]>;
89
+ groupUpdateDescription: (jid: string, description?: string) => Promise<void>;
90
+ groupInviteCode: (jid: string) => Promise<string | undefined>;
91
+ groupRevokeInvite: (jid: string) => Promise<string | undefined>;
92
+ groupAcceptInvite: (code: string) => Promise<string | undefined>;
93
+ groupRevokeInviteV4: (groupJid: string, invitedJid: string) => Promise<boolean>;
94
+ groupAcceptInviteV4: (key: string | import("../index.js").WAMessageKey, inviteMessage: import("../index.js").proto.Message.IGroupInviteMessage) => Promise<any>;
95
+ groupGetInviteInfo: (code: string) => Promise<import("../index.js").GroupMetadata>;
96
+ groupToggleEphemeral: (jid: string, ephemeralExpiration: number) => Promise<void>;
97
+ groupSettingUpdate: (jid: string, setting: "announcement" | "not_announcement" | "locked" | "unlocked") => Promise<void>;
98
+ groupMemberAddMode: (jid: string, mode: "admin_add" | "all_member_add") => Promise<void>;
99
+ groupJoinApprovalMode: (jid: string, mode: "on" | "off") => Promise<void>;
100
+ groupFetchAllParticipating: () => Promise<{
101
+ [_: string]: import("../index.js").GroupMetadata;
102
+ }>;
103
+ createCallLink: (type: "audio" | "video", event?: {
104
+ startTime: number;
105
+ }, timeoutMs?: number) => Promise<string | undefined>;
106
+ getBotListV2: () => Promise<import("../index.js").BotListInfo[]>;
107
+ messageMutex: {
108
+ mutex<T>(code: () => Promise<T> | T): Promise<T>;
109
+ };
110
+ receiptMutex: {
111
+ mutex<T>(code: () => Promise<T> | T): Promise<T>;
112
+ };
113
+ appStatePatchMutex: {
114
+ mutex<T>(code: () => Promise<T> | T): Promise<T>;
115
+ };
116
+ notificationMutex: {
117
+ mutex<T>(code: () => Promise<T> | T): Promise<T>;
118
+ };
119
+ upsertMessage: (msg: import("../index.js").WAMessage, type: import("../index.js").MessageUpsertType) => Promise<void>;
120
+ appPatch: (patchCreate: import("../index.js").WAPatchCreate) => Promise<void>;
121
+ sendPresenceUpdate: (type: import("../index.js").WAPresence, toJid?: string) => Promise<void>;
122
+ presenceSubscribe: (toJid: string) => Promise<void>;
123
+ profilePictureUrl: (jid: string, type?: "preview" | "image", timeoutMs?: number) => Promise<string | undefined>;
124
+ fetchBlocklist: () => Promise<(string | undefined)[]>;
125
+ fetchStatus: (...jids: string[]) => Promise<import("../index.js").USyncQueryResultList[] | undefined>;
126
+ fetchDisappearingDuration: (...jids: string[]) => Promise<import("../index.js").USyncQueryResultList[] | undefined>;
127
+ updateProfilePicture: (jid: string, content: WAMediaUpload, dimensions?: {
128
+ width: number;
129
+ height: number;
130
+ }) => Promise<void>;
131
+ removeProfilePicture: (jid: string) => Promise<void>;
132
+ updateProfileStatus: (status: string) => Promise<void>;
133
+ updateProfileName: (name: string) => Promise<void>;
134
+ updateBlockStatus: (jid: string, action: "block" | "unblock") => Promise<void>;
135
+ updateDisableLinkPreviewsPrivacy: (isPreviewsDisabled: boolean) => Promise<void>;
136
+ updateCallPrivacy: (value: import("../index.js").WAPrivacyCallValue) => Promise<void>;
137
+ updateMessagesPrivacy: (value: import("../index.js").WAPrivacyMessagesValue) => Promise<void>;
138
+ updateLastSeenPrivacy: (value: import("../index.js").WAPrivacyValue) => Promise<void>;
139
+ updateOnlinePrivacy: (value: import("../index.js").WAPrivacyOnlineValue) => Promise<void>;
140
+ updateProfilePicturePrivacy: (value: import("../index.js").WAPrivacyValue) => Promise<void>;
141
+ updateStatusPrivacy: (value: import("../index.js").WAPrivacyValue) => Promise<void>;
142
+ updateReadReceiptsPrivacy: (value: import("../index.js").WAReadReceiptsValue) => Promise<void>;
143
+ updateGroupsAddPrivacy: (value: import("../index.js").WAPrivacyGroupAddValue) => Promise<void>;
144
+ updateDefaultDisappearingMode: (duration: number) => Promise<void>;
145
+ getBusinessProfile: (jid: string) => Promise<import("../index.js").WABusinessProfile | void>;
146
+ resyncAppState: (collections: readonly ("critical_unblock_low" | "regular_high" | "regular_low" | "critical_block" | "regular")[], isInitialSync: boolean) => Promise<void>;
147
+ chatModify: (mod: import("../index.js").ChatModification, jid: string) => Promise<void>;
148
+ cleanDirtyBits: (type: "account_sync" | "groups", fromTimestamp?: number | string) => Promise<void>;
149
+ addOrEditContact: (jid: string, contact: import("../index.js").proto.SyncActionValue.IContactAction) => Promise<void>;
150
+ removeContact: (jid: string) => Promise<void>;
151
+ addLabel: (jid: string, labels: import("../Types/Label.js").LabelActionBody) => Promise<void>;
152
+ addChatLabel: (jid: string, labelId: string) => Promise<void>;
153
+ removeChatLabel: (jid: string, labelId: string) => Promise<void>;
154
+ addMessageLabel: (jid: string, messageId: string, labelId: string) => Promise<void>;
155
+ removeMessageLabel: (jid: string, messageId: string, labelId: string) => Promise<void>;
156
+ star: (jid: string, messages: {
157
+ id: string;
158
+ fromMe?: boolean;
159
+ }[], star: boolean) => Promise<void>;
160
+ addOrEditQuickReply: (quickReply: import("../Types/Bussines.js").QuickReplyAction) => Promise<void>;
161
+ removeQuickReply: (timestamp: string) => Promise<void>;
162
+ type: "md";
163
+ ws: import("./Client/index.js").WebSocketClient;
164
+ ev: import("../index.js").BaileysEventEmitter & {
165
+ process(handler: (events: Partial<import("../index.js").BaileysEventMap>) => void | Promise<void>): () => void;
166
+ buffer(): void;
167
+ createBufferedFunction<A extends any[], T>(work: (...args: A) => Promise<T>): (...args: A) => Promise<T>;
168
+ flush(): boolean;
169
+ isBuffering(): boolean;
170
+ };
171
+ authState: {
172
+ creds: import("../index.js").AuthenticationCreds;
173
+ keys: import("../index.js").SignalKeyStoreWithTransaction;
174
+ };
175
+ signalRepository: import("../index.js").SignalRepositoryWithLIDStore;
176
+ user: import("../index.js").Contact | undefined;
177
+ generateMessageTag: () => string;
178
+ query: (node: BinaryNode, timeoutMs?: number) => Promise<any>;
179
+ waitForMessage: <T>(msgId: string, timeoutMs?: number | undefined) => Promise<T | undefined>;
180
+ waitForSocketOpen: () => Promise<void>;
181
+ sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
182
+ sendNode: (frame: BinaryNode) => Promise<void>;
183
+ logout: (msg?: string) => Promise<void>;
184
+ end: (error: Error | undefined) => Promise<void>;
185
+ onUnexpectedError: (err: Error | import("@hapi/boom").Boom, msg: string) => void;
186
+ uploadPreKeys: (count?: number, retryCount?: number) => Promise<void>;
187
+ uploadPreKeysToServerIfRequired: () => Promise<void>;
188
+ digestKeyBundle: () => Promise<void>;
189
+ rotateSignedPreKey: () => Promise<void>;
190
+ requestPairingCode: (phoneNumber: string, customPairingCode?: string) => Promise<string>;
191
+ updateServerTimeOffset: ({ attrs }: BinaryNode) => void;
192
+ sendUnifiedSession: () => Promise<void>;
193
+ wamBuffer: import("../index.js").BinaryInfo;
194
+ waitForConnectionUpdate: (check: (u: Partial<import("../index.js").ConnectionState>) => Promise<boolean | undefined>, timeoutMs?: number) => Promise<void>;
195
+ sendWAMBuffer: (wamBuffer: Buffer) => Promise<any>;
196
+ executeUSyncQuery: (usyncQuery: import("../index.js").USyncQuery) => Promise<import("../index.js").USyncQueryResult | undefined>;
197
+ onWhatsApp: (...phoneNumber: string[]) => Promise<{
198
+ jid: string;
199
+ exists: boolean;
200
+ }[] | undefined>;
201
+ };
202
+ //# sourceMappingURL=business.d.ts.map