@hbmodsofc/baileys 1.5.0 → 1.7.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 (156) hide show
  1. package/LICENSE +1 -1
  2. package/WAProto/index.js +19671 -152026
  3. package/engine-requirements.js +4 -4
  4. package/lib/Defaults/index.d.ts +12 -8
  5. package/lib/Defaults/index.js +90 -124
  6. package/lib/Signal/Group/group_cipher.d.ts +0 -1
  7. package/lib/Signal/Group/group_cipher.js +28 -39
  8. package/lib/Signal/Group/sender-chain-key.d.ts +1 -1
  9. package/lib/Signal/Group/sender-chain-key.js +9 -2
  10. package/lib/Signal/Group/sender-key-distribution-message.js +3 -3
  11. package/lib/Signal/Group/sender-key-message.js +3 -3
  12. package/lib/Signal/Group/sender-key-state.d.ts +4 -4
  13. package/lib/Signal/Group/sender-key-state.js +47 -16
  14. package/lib/Signal/libsignal.d.ts +7 -3
  15. package/lib/Signal/libsignal.js +224 -39
  16. package/lib/Signal/lid-mapping.d.ts +26 -0
  17. package/lib/Signal/lid-mapping.js +146 -0
  18. package/lib/Socket/Client/index.d.ts +2 -3
  19. package/lib/Socket/Client/index.js +2 -3
  20. package/lib/Socket/Client/{abstract-socket-client.d.ts → types.d.ts} +1 -3
  21. package/lib/Socket/Client/{web-socket-client.d.ts → websocket.d.ts} +1 -1
  22. package/lib/Socket/Client/{web-socket-client.js → websocket.js} +10 -16
  23. package/lib/Socket/business.d.ts +94 -78
  24. package/lib/Socket/business.js +130 -11
  25. package/lib/Socket/chats.d.ts +63 -233
  26. package/lib/Socket/chats.js +234 -184
  27. package/lib/Socket/communities.d.ts +232 -0
  28. package/lib/Socket/communities.js +402 -0
  29. package/lib/Socket/groups.d.ts +62 -41
  30. package/lib/Socket/groups.js +76 -64
  31. package/lib/Socket/index.d.ts +129 -83
  32. package/lib/Socket/index.js +13 -6
  33. package/lib/Socket/messages-recv.d.ts +59 -48
  34. package/lib/Socket/messages-recv.js +516 -371
  35. package/lib/Socket/messages-send.d.ts +86 -67
  36. package/lib/Socket/messages-send.js +1091 -1
  37. package/lib/Socket/mex.d.ts +2 -0
  38. package/lib/Socket/mex.js +45 -0
  39. package/lib/Socket/newsletter.d.ts +76 -64
  40. package/lib/Socket/newsletter.js +184 -1
  41. package/lib/Socket/socket.d.ts +19 -13
  42. package/lib/Socket/socket.js +805 -1
  43. package/lib/Types/Auth.d.ts +4 -10
  44. package/lib/Types/Bussines.d.ts +24 -0
  45. package/lib/Types/Bussines.js +2 -0
  46. package/lib/Types/Call.d.ts +1 -1
  47. package/lib/Types/Chat.d.ts +29 -9
  48. package/lib/Types/Chat.js +7 -1
  49. package/lib/Types/Contact.d.ts +5 -1
  50. package/lib/Types/Events.d.ts +55 -14
  51. package/lib/Types/GroupMetadata.d.ts +15 -5
  52. package/lib/Types/Label.d.ts +11 -0
  53. package/lib/Types/Label.js +1 -1
  54. package/lib/Types/LabelAssociation.js +1 -1
  55. package/lib/Types/Message.d.ts +75 -49
  56. package/lib/Types/Message.js +10 -7
  57. package/lib/Types/Newsletter.d.ts +129 -98
  58. package/lib/Types/Newsletter.js +33 -38
  59. package/lib/Types/Product.d.ts +1 -1
  60. package/lib/Types/Signal.d.ts +29 -1
  61. package/lib/Types/Socket.d.ts +48 -22
  62. package/lib/Types/State.d.ts +13 -2
  63. package/lib/Types/State.js +12 -0
  64. package/lib/Types/USync.d.ts +1 -1
  65. package/lib/Types/index.d.ts +10 -3
  66. package/lib/Types/index.js +2 -2
  67. package/lib/Utils/auth-utils.d.ts +3 -3
  68. package/lib/Utils/auth-utils.js +378 -102
  69. package/lib/Utils/baileys-event-stream.js +1 -1
  70. package/lib/Utils/business.d.ts +2 -2
  71. package/lib/Utils/business.js +19 -13
  72. package/lib/Utils/chat-utils.d.ts +21 -22
  73. package/lib/Utils/chat-utils.js +201 -154
  74. package/lib/Utils/crypto.d.ts +18 -19
  75. package/lib/Utils/crypto.js +78 -37
  76. package/lib/Utils/decode-wa-message.d.ts +34 -7
  77. package/lib/Utils/decode-wa-message.js +138 -66
  78. package/lib/Utils/event-buffer.d.ts +6 -8
  79. package/lib/Utils/event-buffer.js +81 -43
  80. package/lib/Utils/generics.d.ts +27 -27
  81. package/lib/Utils/generics.js +128 -133
  82. package/lib/Utils/history.d.ts +9 -5
  83. package/lib/Utils/history.js +17 -23
  84. package/lib/Utils/index.d.ts +2 -0
  85. package/lib/Utils/index.js +2 -0
  86. package/lib/Utils/lidToJid-test.d.ts +11 -0
  87. package/lib/Utils/lidToJid-test.js +27 -0
  88. package/lib/Utils/link-preview.d.ts +4 -4
  89. package/lib/Utils/link-preview.js +40 -12
  90. package/lib/Utils/logger.d.ts +11 -3
  91. package/lib/Utils/lt-hash.d.ts +8 -8
  92. package/lib/Utils/lt-hash.js +23 -24
  93. package/lib/Utils/make-mutex.d.ts +2 -2
  94. package/lib/Utils/make-mutex.js +3 -2
  95. package/lib/Utils/message-retry-manager.d.ts +81 -0
  96. package/lib/Utils/message-retry-manager.js +152 -0
  97. package/lib/Utils/messages-media.d.ts +37 -41
  98. package/lib/Utils/messages-media.js +252 -368
  99. package/lib/Utils/messages.d.ts +13 -15
  100. package/lib/Utils/messages.js +274 -261
  101. package/lib/Utils/noise-handler.d.ts +13 -15
  102. package/lib/Utils/noise-handler.js +20 -26
  103. package/lib/Utils/process-message.d.ts +9 -8
  104. package/lib/Utils/process-message.js +157 -93
  105. package/lib/Utils/signal.d.ts +6 -5
  106. package/lib/Utils/signal.js +37 -29
  107. package/lib/Utils/use-multi-file-auth-state.d.ts +1 -2
  108. package/lib/Utils/use-multi-file-auth-state.js +12 -7
  109. package/lib/Utils/validate-connection.d.ts +5 -6
  110. package/lib/Utils/validate-connection.js +39 -97
  111. package/lib/WABinary/constants.d.ts +24 -27
  112. package/lib/WABinary/constants.js +1276 -13
  113. package/lib/WABinary/decode.d.ts +3 -4
  114. package/lib/WABinary/decode.js +28 -14
  115. package/lib/WABinary/encode.d.ts +1 -2
  116. package/lib/WABinary/encode.js +134 -147
  117. package/lib/WABinary/generic-utils.d.ts +4 -7
  118. package/lib/WABinary/generic-utils.js +40 -125
  119. package/lib/WABinary/jid-utils.d.ts +13 -8
  120. package/lib/WABinary/jid-utils.js +27 -16
  121. package/lib/WAM/BinaryInfo.d.ts +2 -11
  122. package/lib/WAM/constants.d.ts +3 -2
  123. package/lib/WAM/constants.js +2252 -2359
  124. package/lib/WAM/encode.d.ts +1 -2
  125. package/lib/WAM/encode.js +8 -11
  126. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +2 -2
  127. package/lib/WAUSync/Protocols/USyncContactProtocol.js +3 -4
  128. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -2
  129. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +5 -5
  130. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -2
  131. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +5 -5
  132. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -2
  133. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +5 -6
  134. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +2 -2
  135. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +1 -1
  136. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +4 -3
  137. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +11 -3
  138. package/lib/WAUSync/USyncQuery.d.ts +2 -2
  139. package/lib/WAUSync/USyncQuery.js +19 -15
  140. package/lib/WAUSync/USyncUser.d.ts +5 -5
  141. package/lib/WAUSync/index.d.ts +1 -1
  142. package/lib/WAUSync/index.js +1 -1
  143. package/package.json +102 -102
  144. package/lib/Defaults/baileys-version.json +0 -3
  145. package/lib/Defaults/phonenumber-mcc.json +0 -223
  146. package/lib/Signal/Group/queue-job.d.ts +0 -1
  147. package/lib/Signal/Group/queue-job.js +0 -57
  148. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  149. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  150. package/lib/Socket/hbmods.d.ts +0 -253
  151. package/lib/Socket/hbmods.js +0 -1
  152. package/lib/Socket/registration.d.ts +0 -267
  153. package/lib/Socket/registration.js +0 -166
  154. package/lib/Socket/usync.d.ts +0 -36
  155. package/lib/Socket/usync.js +0 -70
  156. /package/lib/Socket/Client/{abstract-socket-client.js → types.js} +0 -0
@@ -1,50 +1,58 @@
1
- "use strict";
1
+ "use strict";
2
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.bytesToCrockford = exports.trimUndefined = exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.bindWaitForEvent = exports.generateMessageID = exports.generateMessageIDV2 = exports.promiseTimeout = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.Browsers = void 0;
6
+ exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestBaileysVersion = exports.bindWaitForConnectionUpdate = exports.generateMessageID = exports.generateMessageIDV2 = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeWAMessage = exports.generateParticipantHashV2 = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.getPlatformId = exports.Browsers = void 0;
7
+ exports.promiseTimeout = promiseTimeout;
8
+ exports.bindWaitForEvent = bindWaitForEvent;
9
+ exports.trimUndefined = trimUndefined;
10
+ exports.bytesToCrockford = bytesToCrockford;
11
+ exports.encodeNewsletterMessage = encodeNewsletterMessage;
7
12
  const boom_1 = require("@hapi/boom");
8
13
  const axios_1 = __importDefault(require("axios"));
9
14
  const crypto_1 = require("crypto");
10
15
  const os_1 = require("os");
11
- const fetch_1 = require("node-fetch")
12
- const WAProto_1 = require("../../WAProto");
13
- const baileys_version_json_1 = require("../Defaults/baileys-version.json");
16
+ const index_js_1 = require("../../WAProto/index.js");
17
+ const baileysVersion = [2, 3000, 1023223821];
14
18
  const Types_1 = require("../Types");
15
19
  const WABinary_1 = require("../WABinary");
16
- const baileysVersion = [2, 3000, 1027934701]
20
+ const crypto_2 = require("./crypto");
17
21
  const PLATFORM_MAP = {
18
- 'aix': 'AIX',
19
- 'darwin': 'Mac OS',
20
- 'win32': 'Windows',
21
- 'android': 'Android',
22
- 'freebsd': 'FreeBSD',
23
- 'openbsd': 'OpenBSD',
24
- 'sunos': 'Solaris',
25
- 'linux': undefined,
26
- 'haiku': undefined,
27
- 'cygwin': undefined,
28
- 'netbsd': undefined
22
+ aix: 'AIX',
23
+ darwin: 'Mac OS',
24
+ win32: 'Windows',
25
+ android: 'Android',
26
+ freebsd: 'FreeBSD',
27
+ openbsd: 'OpenBSD',
28
+ sunos: 'Solaris',
29
+ linux: undefined,
30
+ haiku: undefined,
31
+ cygwin: undefined,
32
+ netbsd: undefined
29
33
  };
30
- exports.Browsers = (browser) => {
31
- const osName = PLATFORM_MAP[os_1.platform()] || 'Ubuntu';
32
- const osRelease = os_1.release();
33
- return [osName, browser, osRelease];
34
+ exports.Browsers = {
35
+ ubuntu: browser => ['Ubuntu', browser, '22.04.4'],
36
+ macOS: browser => ['Mac OS', browser, '14.4.1'],
37
+ baileys: browser => ['Baileys', browser, '6.5.0'],
38
+ windows: browser => ['Windows', browser, '10.0.22631'],
39
+ /** The appropriate browser based on your OS & release */
40
+ appropriate: browser => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
34
41
  };
35
-
36
42
  const getPlatformId = (browser) => {
37
- const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
43
+ const platformType = index_js_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
38
44
  return platformType ? platformType.toString() : '1'; //chrome
39
45
  };
40
46
  exports.getPlatformId = getPlatformId;
41
47
  exports.BufferJSON = {
48
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
49
  replacer: (k, value) => {
43
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
44
- return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
50
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
51
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
45
52
  }
46
53
  return value;
47
54
  },
55
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
48
56
  reviver: (_, value) => {
49
57
  if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
50
58
  const val = value.data || value.value;
@@ -53,15 +61,12 @@ exports.BufferJSON = {
53
61
  return value;
54
62
  }
55
63
  };
56
- const getKeyAuthor = (key, meId = 'me') => (((key === null || key === void 0 ? void 0 : key.fromMe) ? meId : (key === null || key === void 0 ? void 0 : key.participant) || (key === null || key === void 0 ? void 0 : key.remoteJid)) || '');
64
+ const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participant || key?.remoteJid) || '';
57
65
  exports.getKeyAuthor = getKeyAuthor;
58
66
  const writeRandomPadMax16 = (msg) => {
59
67
  const pad = (0, crypto_1.randomBytes)(1);
60
- pad[0] &= 0xf;
61
- if (!pad[0]) {
62
- pad[0] = 0xf;
63
- }
64
- return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
68
+ const padLength = (pad[0] & 0x0f) + 1;
69
+ return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
65
70
  };
66
71
  exports.writeRandomPadMax16 = writeRandomPadMax16;
67
72
  const unpadRandomMax16 = (e) => {
@@ -76,7 +81,14 @@ const unpadRandomMax16 = (e) => {
76
81
  return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
77
82
  };
78
83
  exports.unpadRandomMax16 = unpadRandomMax16;
79
- const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
84
+ // code is inspired by whatsmeow
85
+ const generateParticipantHashV2 = (participants) => {
86
+ participants.sort();
87
+ const sha256Hash = (0, crypto_2.sha256)(Buffer.from(participants.join(''))).toString('base64');
88
+ return '2:' + sha256Hash.slice(0, 6);
89
+ };
90
+ exports.generateParticipantHashV2 = generateParticipantHashV2;
91
+ const encodeWAMessage = (message) => (0, exports.writeRandomPadMax16)(index_js_1.proto.Message.encode(message).finish());
80
92
  exports.encodeWAMessage = encodeWAMessage;
81
93
  const generateRegistrationId = () => {
82
94
  return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
@@ -92,7 +104,7 @@ const encodeBigEndian = (e, t = 4) => {
92
104
  return a;
93
105
  };
94
106
  exports.encodeBigEndian = encodeBigEndian;
95
- const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
107
+ const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
96
108
  exports.toNumber = toNumber;
97
109
  /** unix timestamp of a date in seconds */
98
110
  const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
@@ -104,14 +116,14 @@ const debouncedTimeout = (intervalMs = 1000, task) => {
104
116
  task = newTask || task;
105
117
  intervalMs = newIntervalMs || intervalMs;
106
118
  timeout && clearTimeout(timeout);
107
- timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
119
+ timeout = setTimeout(() => task?.(), intervalMs);
108
120
  },
109
121
  cancel: () => {
110
122
  timeout && clearTimeout(timeout);
111
123
  timeout = undefined;
112
124
  },
113
- setTask: (newTask) => task = newTask,
114
- setInterval: (newInterval) => intervalMs = newInterval
125
+ setTask: (newTask) => (task = newTask),
126
+ setInterval: (newInterval) => (intervalMs = newInterval)
115
127
  };
116
128
  };
117
129
  exports.debouncedTimeout = debouncedTimeout;
@@ -154,17 +166,17 @@ async function promiseTimeout(ms, promise) {
154
166
  })))
155
167
  .catch(err => reject(err));
156
168
  promise(resolve, reject);
157
- })
158
- .finally(cancel);
169
+ }).finally(cancel);
159
170
  return p;
160
171
  }
161
- exports.promiseTimeout = promiseTimeout;
172
+ // inspired from whatsmeow code
173
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
162
174
  const generateMessageIDV2 = (userId) => {
163
175
  const data = Buffer.alloc(8 + 20 + 16);
164
176
  data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
165
177
  if (userId) {
166
178
  const id = (0, WABinary_1.jidDecode)(userId);
167
- if (id === null || id === void 0 ? void 0 : id.user) {
179
+ if (id?.user) {
168
180
  data.write(id.user, 8);
169
181
  data.write('@c.us', 8 + id.user.length);
170
182
  }
@@ -176,123 +188,104 @@ const generateMessageIDV2 = (userId) => {
176
188
  };
177
189
  exports.generateMessageIDV2 = generateMessageIDV2;
178
190
  // generate a random ID to attach to a message
179
- const generateMessageID = () => 'ILSYM-' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
191
+ const generateMessageID = () => '3EB0' + (0, crypto_1.randomBytes)(18).toString('hex').toUpperCase();
180
192
  exports.generateMessageID = generateMessageID;
181
193
  function bindWaitForEvent(ev, event) {
182
194
  return async (check, timeoutMs) => {
183
195
  let listener;
184
196
  let closeListener;
185
- await (promiseTimeout(timeoutMs, (resolve, reject) => {
197
+ await promiseTimeout(timeoutMs, (resolve, reject) => {
186
198
  closeListener = ({ connection, lastDisconnect }) => {
187
199
  if (connection === 'close') {
188
- reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
189
- || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
200
+ reject(lastDisconnect?.error || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
190
201
  }
191
202
  };
192
203
  ev.on('connection.update', closeListener);
193
- listener = (update) => {
194
- if (check(update)) {
204
+ listener = async (update) => {
205
+ if (await check(update)) {
195
206
  resolve();
196
207
  }
197
208
  };
198
209
  ev.on(event, listener);
199
- })
200
- .finally(() => {
210
+ }).finally(() => {
201
211
  ev.off(event, listener);
202
212
  ev.off('connection.update', closeListener);
203
- }));
213
+ });
204
214
  };
205
215
  }
206
- exports.bindWaitForEvent = bindWaitForEvent;
207
216
  const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
208
217
  exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
209
- const printQRIfNecessaryListener = (ev, logger) => {
210
- ev.on('connection.update', async ({ qr }) => {
211
- if (qr) {
212
- const QR = await import('qrcode-terminal')
213
- .then(m => m.default || m)
214
- .catch(() => {
215
- logger.error('QR code terminal not added as dependency');
216
- });
217
- QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
218
- }
219
- });
220
- };
221
- exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
222
218
  /**
223
219
  * utility that fetches latest baileys version from the master branch.
224
220
  * Use to ensure your WA connection is always on the latest version
225
221
  */
226
- const fetchLatestWaWebVersion = async (options = {}) => {
227
- try {
228
- const defaultHeaders = {
229
- 'User-Agent':
230
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
231
- 'Accept': '*/*'
232
- }
233
-
234
- const headers = { ...defaultHeaders, ...options.headers }
235
-
236
- const response = await fetch_1('https://web.whatsapp.com/sw.js', {
237
- method: 'GET',
238
- headers
239
- })
240
-
241
- if (!response.ok) {
242
- throw new Error(`Failed to fetch sw.js: ${response.status} ${response.statusText}`)
243
- }
244
-
245
- const data = await response.text()
246
- const regex = /"client_revision":\s*(\d+)/ // regex cukup begini untuk Node
247
- const match = data.match(regex)
248
-
249
- if (!match || !match[1]) {
250
- return {
251
- version: baileysVersion,
252
- isLatest: false,
253
- error: { message: 'Client revision not found' }
254
- }
255
- }
256
-
257
- const clientRevision = match[1]
258
- return {
259
- version: [2, 3000, +clientRevision],
260
- isLatest: true
261
- }
262
- } catch (error) {
263
- return {
264
- version: baileysVersion,
265
- isLatest: false,
266
- error
267
- }
268
- }
269
- }
270
- exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
222
+ const fetchLatestBaileysVersion = async (options = {}) => {
223
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts';
224
+ try {
225
+ const result = await axios_1.default.get(URL, {
226
+ ...options,
227
+ responseType: 'text'
228
+ });
229
+ // Extract version from line 7 (const version = [...])
230
+ const lines = result.data.split('\n');
231
+ const versionLine = lines[6]; // Line 7 (0-indexed)
232
+ const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
233
+ if (versionMatch) {
234
+ const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
235
+ return {
236
+ version,
237
+ isLatest: true
238
+ };
239
+ }
240
+ else {
241
+ throw new Error('Could not parse version from Defaults/index.ts');
242
+ }
243
+ }
244
+ catch (error) {
245
+ return {
246
+ version: baileysVersion,
247
+ isLatest: false,
248
+ error
249
+ };
250
+ }
251
+ };
252
+ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
271
253
  /**
272
- * utility that fetches latest baileys version from the master branch.
254
+ * A utility that fetches the latest web version of whatsapp.
273
255
  * Use to ensure your WA connection is always on the latest version
274
256
  */
275
- const fetchLatestBaileysVersion = async (options = {}) => {
276
- const URL = 'https://raw.githubusercontent.com/kiuur/bails/master/src/Defaults/baileys-version.json';
257
+ const fetchLatestWaWebVersion = async (options) => {
277
258
  try {
278
- const result = await axios_1.default.get(URL, {
259
+ const { data } = await axios_1.default.get('https://web.whatsapp.com/sw.js', {
279
260
  ...options,
280
261
  responseType: 'json'
281
262
  });
263
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
264
+ const match = data.match(regex);
265
+ if (!match?.[1]) {
266
+ return {
267
+ version: baileysVersion,
268
+ isLatest: false,
269
+ error: {
270
+ message: 'Could not find client revision in the fetched content'
271
+ }
272
+ };
273
+ }
274
+ const clientRevision = match[1];
282
275
  return {
283
- version: result.data.version,
276
+ version: [2, 3000, +clientRevision],
284
277
  isLatest: true
285
278
  };
286
279
  }
287
280
  catch (error) {
288
281
  return {
289
- version: baileys_version_json_1.version,
282
+ version: baileysVersion,
290
283
  isLatest: false,
291
284
  error
292
285
  };
293
286
  }
294
287
  };
295
- exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
288
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
296
289
  /** unique message tag prefix for MD clients */
297
290
  const generateMdTagPrefix = () => {
298
291
  const bytes = (0, crypto_1.randomBytes)(4);
@@ -300,9 +293,10 @@ const generateMdTagPrefix = () => {
300
293
  };
301
294
  exports.generateMdTagPrefix = generateMdTagPrefix;
302
295
  const STATUS_MAP = {
303
- 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
304
- 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
305
- 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
296
+ sender: index_js_1.proto.WebMessageInfo.Status.SERVER_ACK,
297
+ played: index_js_1.proto.WebMessageInfo.Status.PLAYED,
298
+ read: index_js_1.proto.WebMessageInfo.Status.READ,
299
+ 'read-self': index_js_1.proto.WebMessageInfo.Status.READ
306
300
  };
307
301
  /**
308
302
  * Given a type of receipt, returns what the new status of the message should be
@@ -311,7 +305,7 @@ const STATUS_MAP = {
311
305
  const getStatusFromReceiptType = (type) => {
312
306
  const status = STATUS_MAP[type];
313
307
  if (typeof type === 'undefined') {
314
- return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
308
+ return index_js_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
315
309
  }
316
310
  return status;
317
311
  };
@@ -325,7 +319,7 @@ const CODE_MAP = {
325
319
  */
326
320
  const getErrorCodeFromStreamError = (node) => {
327
321
  const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
328
- let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
322
+ let reason = reasonNode?.tag || 'unknown';
329
323
  const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
330
324
  if (statusCode === Types_1.DisconnectReason.restartRequired) {
331
325
  reason = 'restart required';
@@ -348,7 +342,8 @@ const getCallStatusFromNode = ({ tag, attrs }) => {
348
342
  status = 'timeout';
349
343
  }
350
344
  else {
351
- status = 'reject';
345
+ //fired when accepted/rejected/timeout/caller hangs up
346
+ status = 'terminate';
352
347
  }
353
348
  break;
354
349
  case 'reject':
@@ -366,16 +361,18 @@ const getCallStatusFromNode = ({ tag, attrs }) => {
366
361
  exports.getCallStatusFromNode = getCallStatusFromNode;
367
362
  const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
368
363
  const getCodeFromWSError = (error) => {
369
- var _a, _b, _c;
370
364
  let statusCode = 500;
371
- if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
372
- const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
365
+ if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
366
+ const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
373
367
  if (!Number.isNaN(code) && code >= 400) {
374
368
  statusCode = code;
375
369
  }
376
370
  }
377
- else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
378
- || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
371
+ else if (
372
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
373
+ error?.code?.startsWith('E') ||
374
+ error?.message?.includes('timed out')) {
375
+ // handle ETIMEOUT, ENOTFOUND etc
379
376
  statusCode = 408;
380
377
  }
381
378
  return statusCode;
@@ -389,6 +386,7 @@ const isWABusinessPlatform = (platform) => {
389
386
  return platform === 'smbi' || platform === 'smba';
390
387
  };
391
388
  exports.isWABusinessPlatform = isWABusinessPlatform;
389
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
392
390
  function trimUndefined(obj) {
393
391
  for (const key in obj) {
394
392
  if (typeof obj[key] === 'undefined') {
@@ -397,14 +395,13 @@ function trimUndefined(obj) {
397
395
  }
398
396
  return obj;
399
397
  }
400
- exports.trimUndefined = trimUndefined;
401
398
  const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
402
399
  function bytesToCrockford(buffer) {
403
400
  let value = 0;
404
401
  let bitCount = 0;
405
402
  const crockford = [];
406
- for (let i = 0; i < buffer.length; i++) {
407
- value = (value << 8) | (buffer[i] & 0xff);
403
+ for (const element of buffer) {
404
+ value = (value << 8) | (element & 0xff);
408
405
  bitCount += 8;
409
406
  while (bitCount >= 5) {
410
407
  crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
@@ -416,8 +413,6 @@ function bytesToCrockford(buffer) {
416
413
  }
417
414
  return crockford.join('');
418
415
  }
419
- exports.bytesToCrockford = bytesToCrockford;
420
- const encodeNewsletterMessage = (message) => {
421
- return WAProto_1.proto.Message.encode(message).finish()
416
+ function encodeNewsletterMessage(message) {
417
+ return index_js_1.proto.Message.encode(message).finish();
422
418
  }
423
- exports.encodeNewsletterMessage = encodeNewsletterMessage;
@@ -1,15 +1,19 @@
1
- import { AxiosRequestConfig } from 'axios';
2
- import { proto } from '../../WAProto';
3
- import { Chat, Contact } from '../Types';
4
- export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<proto.HistorySync>;
1
+ import type { AxiosRequestConfig } from 'axios';
2
+ import { proto } from '../../WAProto/index.js';
3
+ import type { Chat, Contact } from '../Types';
4
+ export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<{}>) => Promise<proto.HistorySync>;
5
5
  export declare const processHistoryMessage: (item: proto.IHistorySync) => {
6
6
  chats: Chat[];
7
7
  contacts: Contact[];
8
8
  messages: proto.IWebMessageInfo[];
9
+ syncType: proto.HistorySync.HistorySyncType;
10
+ progress: number | null | undefined;
9
11
  };
10
- export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<{
12
+ export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<{}>) => Promise<{
11
13
  chats: Chat[];
12
14
  contacts: Contact[];
13
15
  messages: proto.IWebMessageInfo[];
16
+ syncType: proto.HistorySync.HistorySyncType;
17
+ progress: number | null | undefined;
14
18
  }>;
15
19
  export declare const getHistoryMsg: (message: proto.IMessage) => proto.Message.IHistorySyncNotification | null | undefined;
@@ -3,9 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getHistoryMsg = exports.downloadAndProcessHistorySyncNotification = exports.processHistoryMessage = exports.downloadHistory = void 0;
4
4
  const util_1 = require("util");
5
5
  const zlib_1 = require("zlib");
6
- const WAProto_1 = require("../../WAProto");
6
+ const index_js_1 = require("../../WAProto/index.js");
7
7
  const Types_1 = require("../Types");
8
- const WABinary_1 = require("../WABinary");
9
8
  const generics_1 = require("./generics");
10
9
  const messages_1 = require("./messages");
11
10
  const messages_media_1 = require("./messages-media");
@@ -19,57 +18,51 @@ const downloadHistory = async (msg, options) => {
19
18
  let buffer = Buffer.concat(bufferArray);
20
19
  // decompress buffer
21
20
  buffer = await inflatePromise(buffer);
22
- const syncData = WAProto_1.proto.HistorySync.decode(buffer);
21
+ const syncData = index_js_1.proto.HistorySync.decode(buffer);
23
22
  return syncData;
24
23
  };
25
24
  exports.downloadHistory = downloadHistory;
26
25
  const processHistoryMessage = (item) => {
27
- var _a, _b, _c;
28
26
  const messages = [];
29
27
  const contacts = [];
30
28
  const chats = [];
31
29
  switch (item.syncType) {
32
- case WAProto_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
33
- case WAProto_1.proto.HistorySync.HistorySyncType.RECENT:
34
- case WAProto_1.proto.HistorySync.HistorySyncType.FULL:
30
+ case index_js_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
31
+ case index_js_1.proto.HistorySync.HistorySyncType.RECENT:
32
+ case index_js_1.proto.HistorySync.HistorySyncType.FULL:
33
+ case index_js_1.proto.HistorySync.HistorySyncType.ON_DEMAND:
35
34
  for (const chat of item.conversations) {
36
- contacts.push({
35
+ contacts.push({
37
36
  id: chat.id,
38
37
  name: chat.name || undefined,
39
38
  lid: chat.lidJid || undefined,
40
- jid: (0, WABinary_1.isJidUser)(chat.id) ? chat.id : undefined
39
+ phoneNumber: chat.pnJid || undefined
41
40
  });
42
41
  const msgs = chat.messages || [];
43
42
  delete chat.messages;
44
- delete chat.archived;
45
- delete chat.muteEndTime;
46
- delete chat.pinned;
47
43
  for (const item of msgs) {
48
44
  const message = item.message;
49
45
  messages.push(message);
50
- if (!((_a = chat.messages) === null || _a === void 0 ? void 0 : _a.length)) {
46
+ if (!chat.messages?.length) {
51
47
  // keep only the most recent message in the chat array
52
48
  chat.messages = [{ message }];
53
49
  }
54
50
  if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
55
51
  chat.lastMessageRecvTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
56
52
  }
57
- if ((message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP
58
- || message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB)
59
- && ((_b = message.messageStubParameters) === null || _b === void 0 ? void 0 : _b[0])) {
53
+ if ((message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP ||
54
+ message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB) &&
55
+ message.messageStubParameters?.[0]) {
60
56
  contacts.push({
61
57
  id: message.key.participant || message.key.remoteJid,
62
- verifiedName: (_c = message.messageStubParameters) === null || _c === void 0 ? void 0 : _c[0],
58
+ verifiedName: message.messageStubParameters?.[0]
63
59
  });
64
60
  }
65
61
  }
66
- if ((0, WABinary_1.isJidUser)(chat.id) && chat.readOnly && chat.archived) {
67
- delete chat.readOnly;
68
- }
69
62
  chats.push({ ...chat });
70
63
  }
71
64
  break;
72
- case WAProto_1.proto.HistorySync.HistorySyncType.PUSH_NAME:
65
+ case index_js_1.proto.HistorySync.HistorySyncType.PUSH_NAME:
73
66
  for (const c of item.pushnames) {
74
67
  contacts.push({ id: c.id, notify: c.pushname });
75
68
  }
@@ -79,6 +72,8 @@ const processHistoryMessage = (item) => {
79
72
  chats,
80
73
  contacts,
81
74
  messages,
75
+ syncType: item.syncType,
76
+ progress: item.progress
82
77
  };
83
78
  };
84
79
  exports.processHistoryMessage = processHistoryMessage;
@@ -88,9 +83,8 @@ const downloadAndProcessHistorySyncNotification = async (msg, options) => {
88
83
  };
89
84
  exports.downloadAndProcessHistorySyncNotification = downloadAndProcessHistorySyncNotification;
90
85
  const getHistoryMsg = (message) => {
91
- var _a;
92
86
  const normalizedContent = !!message ? (0, messages_1.normalizeMessageContent)(message) : undefined;
93
- const anyHistoryMsg = (_a = normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage) === null || _a === void 0 ? void 0 : _a.historySyncNotification;
87
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification;
94
88
  return anyHistoryMsg;
95
89
  };
96
90
  exports.getHistoryMsg = getHistoryMsg;
@@ -15,3 +15,5 @@ export * from './use-multi-file-auth-state';
15
15
  export * from './link-preview';
16
16
  export * from './event-buffer';
17
17
  export * from './process-message';
18
+ export * from './message-retry-manager';
19
+ export * from './lidToJid-test';
@@ -31,3 +31,5 @@ __exportStar(require("./use-multi-file-auth-state"), exports);
31
31
  __exportStar(require("./link-preview"), exports);
32
32
  __exportStar(require("./event-buffer"), exports);
33
33
  __exportStar(require("./process-message"), exports);
34
+ __exportStar(require("./message-retry-manager"), exports);
35
+ __exportStar(require("./lidToJid-test"), exports);
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Convert a WhatsApp LID (or raw number) into a full JID string.
3
+ *
4
+ * @param lid - Bisa berupa:
5
+ * • string seperti "6281234567890"
6
+ * • number (akan di-cast ke string)
7
+ * • sudah berformat JID (mis. "6281234567890@s.whatsapp.net")
8
+ *
9
+ * @returns string JID yang valid (mis. "6281234567890@s.whatsapp.net")
10
+ */
11
+ export declare function lidToJid(lid: string | number): string;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.lidToJid = lidToJid;
4
+ /**
5
+ * Convert a WhatsApp LID (or raw number) into a full JID string.
6
+ *
7
+ * @param lid - Bisa berupa:
8
+ * • string seperti "6281234567890"
9
+ * • number (akan di-cast ke string)
10
+ * • sudah berformat JID (mis. "6281234567890@s.whatsapp.net")
11
+ *
12
+ * @returns string JID yang valid (mis. "6281234567890@s.whatsapp.net")
13
+ */
14
+ function lidToJid(lid) {
15
+ if (!lid)
16
+ throw new Error("lidToJid: parameter 'lid' wajib diisi");
17
+ let id = String(lid).trim();
18
+ // Jika sudah berakhiran @s.whatsapp.net atau @g.us, langsung kembalikan
19
+ if (/@(s\.whatsapp\.net|g\.us)$/.test(id)) {
20
+ return id;
21
+ }
22
+ // Buang karakter non-digit (jaga-jaga jika ada spasi/tanda plus)
23
+ id = id.replace(/[^\d]/g, "");
24
+ if (!id.length)
25
+ throw new Error("lidToJid: format LID tidak valid");
26
+ return `${id}@s.whatsapp.net`;
27
+ }
@@ -1,6 +1,6 @@
1
- import { AxiosRequestConfig } from 'axios';
2
- import { Logger } from 'pino';
3
- import { WAMediaUploadFunction, WAUrlInfo } from '../Types';
1
+ import type { AxiosRequestConfig } from 'axios';
2
+ import type { WAMediaUploadFunction, WAUrlInfo } from '../Types';
3
+ import type { ILogger } from './logger';
4
4
  export type URLGenerationOptions = {
5
5
  thumbnailWidth: number;
6
6
  fetchOpts: {
@@ -10,7 +10,7 @@ export type URLGenerationOptions = {
10
10
  headers?: AxiosRequestConfig<{}>['headers'];
11
11
  };
12
12
  uploadImage?: WAMediaUploadFunction;
13
- logger?: Logger;
13
+ logger?: ILogger;
14
14
  };
15
15
  /**
16
16
  * Given a piece of text, checks for any URL present, generates link preview for the same and returns it