@d0v3riz/baileys 6.7.12 → 6.7.17

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 (161) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +35 -1267
  3. package/WAProto/index.d.ts +16106 -2739
  4. package/WAProto/index.js +128593 -73944
  5. package/engine-requirements.js +10 -0
  6. package/lib/Defaults/baileys-version.json +3 -3
  7. package/lib/Defaults/index.d.ts +51 -53
  8. package/lib/Defaults/index.js +105 -106
  9. package/lib/Signal/libsignal.d.ts +3 -3
  10. package/lib/Signal/libsignal.js +161 -152
  11. package/lib/Socket/Client/index.d.ts +2 -2
  12. package/lib/Socket/Client/index.js +18 -18
  13. package/lib/Socket/Client/types.d.ts +15 -17
  14. package/lib/Socket/Client/types.js +13 -13
  15. package/lib/Socket/Client/websocket.d.ts +12 -12
  16. package/lib/Socket/Client/websocket.js +62 -62
  17. package/lib/Socket/business.d.ts +146 -148
  18. package/lib/Socket/business.js +260 -260
  19. package/lib/Socket/chats.d.ts +85 -84
  20. package/lib/Socket/chats.js +880 -846
  21. package/lib/Socket/groups.d.ts +124 -123
  22. package/lib/Socket/groups.js +314 -314
  23. package/lib/Socket/index.d.ts +146 -148
  24. package/lib/Socket/index.js +10 -10
  25. package/lib/Socket/messages-recv.d.ts +135 -135
  26. package/lib/Socket/messages-recv.js +920 -913
  27. package/lib/Socket/messages-send.d.ts +130 -129
  28. package/lib/Socket/messages-send.js +683 -673
  29. package/lib/Socket/socket.d.ts +42 -45
  30. package/lib/Socket/socket.js +622 -622
  31. package/lib/Socket/usync.d.ts +36 -38
  32. package/lib/Socket/usync.js +70 -70
  33. package/lib/Types/Auth.d.ts +103 -105
  34. package/lib/Types/Auth.js +2 -2
  35. package/lib/Types/Call.d.ts +13 -13
  36. package/lib/Types/Call.js +2 -2
  37. package/lib/Types/Chat.d.ts +112 -107
  38. package/lib/Types/Chat.js +4 -4
  39. package/lib/Types/Contact.d.ts +19 -19
  40. package/lib/Types/Contact.js +2 -2
  41. package/lib/Types/Events.d.ts +172 -172
  42. package/lib/Types/Events.js +2 -2
  43. package/lib/Types/GroupMetadata.d.ts +56 -56
  44. package/lib/Types/GroupMetadata.js +2 -2
  45. package/lib/Types/Label.d.ts +46 -46
  46. package/lib/Types/Label.js +27 -27
  47. package/lib/Types/LabelAssociation.d.ts +29 -29
  48. package/lib/Types/LabelAssociation.js +9 -9
  49. package/lib/Types/Message.d.ts +269 -273
  50. package/lib/Types/Message.js +7 -9
  51. package/lib/Types/Product.d.ts +78 -78
  52. package/lib/Types/Product.js +2 -2
  53. package/lib/Types/Signal.d.ts +57 -57
  54. package/lib/Types/Signal.js +2 -2
  55. package/lib/Types/Socket.d.ts +121 -118
  56. package/lib/Types/Socket.js +2 -2
  57. package/lib/Types/State.d.ts +27 -27
  58. package/lib/Types/State.js +2 -2
  59. package/lib/Types/USync.d.ts +25 -25
  60. package/lib/Types/USync.js +2 -2
  61. package/lib/Types/index.d.ts +63 -63
  62. package/lib/Types/index.js +41 -41
  63. package/lib/Utils/auth-utils.d.ts +18 -18
  64. package/lib/Utils/auth-utils.js +200 -200
  65. package/lib/Utils/baileys-event-stream.d.ts +16 -16
  66. package/lib/Utils/baileys-event-stream.js +63 -63
  67. package/lib/Utils/business.d.ts +22 -22
  68. package/lib/Utils/business.js +234 -234
  69. package/lib/Utils/chat-utils.d.ts +70 -72
  70. package/lib/Utils/chat-utils.js +745 -745
  71. package/lib/Utils/crypto.d.ts +40 -42
  72. package/lib/Utils/crypto.js +193 -153
  73. package/lib/Utils/decode-wa-message.d.ts +36 -36
  74. package/lib/Utils/decode-wa-message.js +205 -205
  75. package/lib/Utils/event-buffer.d.ts +35 -35
  76. package/lib/Utils/event-buffer.js +520 -520
  77. package/lib/Utils/generics.d.ts +90 -94
  78. package/lib/Utils/generics.js +398 -421
  79. package/lib/Utils/history.d.ts +19 -19
  80. package/lib/Utils/history.js +94 -94
  81. package/lib/Utils/index.d.ts +17 -17
  82. package/lib/Utils/index.js +33 -33
  83. package/lib/Utils/link-preview.d.ts +21 -21
  84. package/lib/Utils/link-preview.js +126 -116
  85. package/lib/Utils/logger.d.ts +11 -4
  86. package/lib/Utils/logger.js +7 -7
  87. package/lib/Utils/lt-hash.d.ts +12 -12
  88. package/lib/Utils/lt-hash.js +51 -51
  89. package/lib/Utils/make-mutex.d.ts +7 -7
  90. package/lib/Utils/make-mutex.js +44 -44
  91. package/lib/Utils/messages-media.d.ts +104 -108
  92. package/lib/Utils/messages-media.js +677 -667
  93. package/lib/Utils/messages.d.ts +75 -78
  94. package/lib/Utils/messages.js +765 -762
  95. package/lib/Utils/noise-handler.d.ts +19 -21
  96. package/lib/Utils/noise-handler.js +150 -150
  97. package/lib/Utils/process-message.d.ts +41 -42
  98. package/lib/Utils/process-message.js +382 -371
  99. package/lib/Utils/signal.d.ts +33 -33
  100. package/lib/Utils/signal.js +153 -153
  101. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -12
  102. package/lib/Utils/use-multi-file-auth-state.js +125 -94
  103. package/lib/Utils/validate-connection.d.ts +10 -10
  104. package/lib/Utils/validate-connection.js +175 -175
  105. package/lib/WABinary/constants.d.ts +27 -27
  106. package/lib/WABinary/constants.js +40 -40
  107. package/lib/WABinary/decode.d.ts +6 -8
  108. package/lib/WABinary/decode.js +264 -254
  109. package/lib/WABinary/encode.d.ts +2 -4
  110. package/lib/WABinary/encode.js +252 -234
  111. package/lib/WABinary/generic-utils.d.ts +14 -16
  112. package/lib/WABinary/generic-utils.js +110 -110
  113. package/lib/WABinary/index.d.ts +5 -5
  114. package/lib/WABinary/index.js +21 -21
  115. package/lib/WABinary/jid-utils.d.ts +33 -31
  116. package/lib/WABinary/jid-utils.js +66 -62
  117. package/lib/WABinary/types.d.ts +18 -18
  118. package/lib/WABinary/types.js +2 -2
  119. package/lib/WAM/BinaryInfo.d.ts +8 -18
  120. package/lib/WAM/BinaryInfo.js +13 -13
  121. package/lib/WAM/constants.d.ts +39 -39
  122. package/lib/WAM/constants.js +15350 -15350
  123. package/lib/WAM/encode.d.ts +2 -4
  124. package/lib/WAM/encode.js +155 -155
  125. package/lib/WAM/index.d.ts +3 -3
  126. package/lib/WAM/index.js +19 -19
  127. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -9
  128. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -32
  129. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -22
  130. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -57
  131. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -12
  132. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -30
  133. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -12
  134. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -42
  135. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  136. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  137. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  138. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  139. package/lib/WAUSync/Protocols/index.d.ts +4 -4
  140. package/lib/WAUSync/Protocols/index.js +20 -20
  141. package/lib/WAUSync/USyncQuery.d.ts +28 -26
  142. package/lib/WAUSync/USyncQuery.js +89 -79
  143. package/lib/WAUSync/USyncUser.d.ts +12 -10
  144. package/lib/WAUSync/USyncUser.js +26 -22
  145. package/lib/WAUSync/index.d.ts +3 -3
  146. package/lib/WAUSync/index.js +19 -19
  147. package/lib/index.d.ts +11 -12
  148. package/lib/index.js +30 -31
  149. package/package.json +27 -35
  150. package/WAProto/GenerateStatics.sh +0 -4
  151. package/WAProto/WAProto.proto +0 -3344
  152. package/lib/Store/index.d.ts +0 -3
  153. package/lib/Store/index.js +0 -10
  154. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  155. package/lib/Store/make-cache-manager-store.js +0 -83
  156. package/lib/Store/make-in-memory-store.d.ts +0 -118
  157. package/lib/Store/make-in-memory-store.js +0 -420
  158. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  159. package/lib/Store/make-ordered-dictionary.js +0 -81
  160. package/lib/Store/object-repository.d.ts +0 -10
  161. package/lib/Store/object-repository.js +0 -27
@@ -1,421 +1,398 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- 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.getPlatformId = exports.Browsers = void 0;
30
- const boom_1 = require("@hapi/boom");
31
- const axios_1 = __importDefault(require("axios"));
32
- const crypto_1 = require("crypto");
33
- const os_1 = require("os");
34
- const WAProto_1 = require("../../WAProto");
35
- const baileys_version_json_1 = require("../Defaults/baileys-version.json");
36
- const Types_1 = require("../Types");
37
- const WABinary_1 = require("../WABinary");
38
- const PLATFORM_MAP = {
39
- 'aix': 'AIX',
40
- 'darwin': 'Mac OS',
41
- 'win32': 'Windows',
42
- 'android': 'Android',
43
- 'freebsd': 'FreeBSD',
44
- 'openbsd': 'OpenBSD',
45
- 'sunos': 'Solaris'
46
- };
47
- exports.Browsers = {
48
- ubuntu: (browser) => ['Ubuntu', browser, '22.04.4'],
49
- macOS: (browser) => ['Mac OS', browser, '14.4.1'],
50
- baileys: (browser) => ['Baileys', browser, '6.5.0'],
51
- windows: (browser) => ['Windows', browser, '10.0.22631'],
52
- /** The appropriate browser based on your OS & release */
53
- appropriate: (browser) => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
54
- };
55
- const getPlatformId = (browser) => {
56
- const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
57
- return platformType ? platformType.toString().charCodeAt(0).toString() : '49'; //chrome
58
- };
59
- exports.getPlatformId = getPlatformId;
60
- exports.BufferJSON = {
61
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
62
- replacer: (k, value) => {
63
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
64
- return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
65
- }
66
- return value;
67
- },
68
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
69
- reviver: (_, value) => {
70
- if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
71
- const val = value.data || value.value;
72
- return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
73
- }
74
- return value;
75
- }
76
- };
77
- 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)) || '');
78
- exports.getKeyAuthor = getKeyAuthor;
79
- const writeRandomPadMax16 = (msg) => {
80
- const pad = (0, crypto_1.randomBytes)(1);
81
- pad[0] &= 0xf;
82
- if (!pad[0]) {
83
- pad[0] = 0xf;
84
- }
85
- return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
86
- };
87
- exports.writeRandomPadMax16 = writeRandomPadMax16;
88
- const unpadRandomMax16 = (e) => {
89
- const t = new Uint8Array(e);
90
- if (0 === t.length) {
91
- throw new Error('unpadPkcs7 given empty bytes');
92
- }
93
- var r = t[t.length - 1];
94
- if (r > t.length) {
95
- throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
96
- }
97
- return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
98
- };
99
- exports.unpadRandomMax16 = unpadRandomMax16;
100
- const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
101
- exports.encodeWAMessage = encodeWAMessage;
102
- const generateRegistrationId = () => {
103
- return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
104
- };
105
- exports.generateRegistrationId = generateRegistrationId;
106
- const encodeBigEndian = (e, t = 4) => {
107
- let r = e;
108
- const a = new Uint8Array(t);
109
- for (let i = t - 1; i >= 0; i--) {
110
- a[i] = 255 & r;
111
- r >>>= 8;
112
- }
113
- return a;
114
- };
115
- exports.encodeBigEndian = encodeBigEndian;
116
- const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0);
117
- exports.toNumber = toNumber;
118
- /** unix timestamp of a date in seconds */
119
- const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
120
- exports.unixTimestampSeconds = unixTimestampSeconds;
121
- const debouncedTimeout = (intervalMs = 1000, task) => {
122
- let timeout;
123
- return {
124
- start: (newIntervalMs, newTask) => {
125
- task = newTask || task;
126
- intervalMs = newIntervalMs || intervalMs;
127
- timeout && clearTimeout(timeout);
128
- timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
129
- },
130
- cancel: () => {
131
- timeout && clearTimeout(timeout);
132
- timeout = undefined;
133
- },
134
- setTask: (newTask) => task = newTask,
135
- setInterval: (newInterval) => intervalMs = newInterval
136
- };
137
- };
138
- exports.debouncedTimeout = debouncedTimeout;
139
- const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
140
- exports.delay = delay;
141
- const delayCancellable = (ms) => {
142
- const stack = new Error().stack;
143
- let timeout;
144
- let reject;
145
- const delay = new Promise((resolve, _reject) => {
146
- timeout = setTimeout(resolve, ms);
147
- reject = _reject;
148
- });
149
- const cancel = () => {
150
- clearTimeout(timeout);
151
- reject(new boom_1.Boom('Cancelled', {
152
- statusCode: 500,
153
- data: {
154
- stack
155
- }
156
- }));
157
- };
158
- return { delay, cancel };
159
- };
160
- exports.delayCancellable = delayCancellable;
161
- async function promiseTimeout(ms, promise) {
162
- if (!ms) {
163
- return new Promise(promise);
164
- }
165
- const stack = new Error().stack;
166
- // Create a promise that rejects in <ms> milliseconds
167
- const { delay, cancel } = (0, exports.delayCancellable)(ms);
168
- const p = new Promise((resolve, reject) => {
169
- delay
170
- .then(() => reject(new boom_1.Boom('Timed Out', {
171
- statusCode: Types_1.DisconnectReason.timedOut,
172
- data: {
173
- stack
174
- }
175
- })))
176
- .catch(err => reject(err));
177
- promise(resolve, reject);
178
- })
179
- .finally(cancel);
180
- return p;
181
- }
182
- exports.promiseTimeout = promiseTimeout;
183
- // inspired from whatsmeow code
184
- // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
185
- const generateMessageIDV2 = (userId) => {
186
- const data = Buffer.alloc(8 + 20 + 16);
187
- data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
188
- if (userId) {
189
- const id = (0, WABinary_1.jidDecode)(userId);
190
- if (id === null || id === void 0 ? void 0 : id.user) {
191
- data.write(id.user, 8);
192
- data.write('@c.us', 8 + id.user.length);
193
- }
194
- }
195
- const random = (0, crypto_1.randomBytes)(16);
196
- random.copy(data, 28);
197
- const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
198
- return (process.env.WHATSAPP_CONN_IDMSG || 'WHPI') + hash.toString('hex').toUpperCase().substring(0, 18);
199
- };
200
- exports.generateMessageIDV2 = generateMessageIDV2;
201
- // generate a random ID to attach to a message
202
- const generateMessageID = () => (process.env.WHATSAPP_CONN_IDMSG || 'WHPI') + (0, crypto_1.randomBytes)(18).toString('hex').toUpperCase();
203
- exports.generateMessageID = generateMessageID;
204
- function bindWaitForEvent(ev, event) {
205
- return async (check, timeoutMs) => {
206
- let listener;
207
- let closeListener;
208
- await (promiseTimeout(timeoutMs, (resolve, reject) => {
209
- closeListener = ({ connection, lastDisconnect }) => {
210
- if (connection === 'close') {
211
- reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
212
- || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
213
- }
214
- };
215
- ev.on('connection.update', closeListener);
216
- listener = (update) => {
217
- if (check(update)) {
218
- resolve();
219
- }
220
- };
221
- ev.on(event, listener);
222
- })
223
- .finally(() => {
224
- ev.off(event, listener);
225
- ev.off('connection.update', closeListener);
226
- }));
227
- };
228
- }
229
- exports.bindWaitForEvent = bindWaitForEvent;
230
- const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
231
- exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
232
- const printQRIfNecessaryListener = (ev, logger) => {
233
- ev.on('connection.update', async ({ qr }) => {
234
- if (qr) {
235
- const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).then(m => m.default || m)
236
- .catch(() => {
237
- logger.error('QR code terminal not added as dependency');
238
- });
239
- QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
240
- }
241
- });
242
- };
243
- exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
244
- /**
245
- * utility that fetches latest baileys version from the master branch.
246
- * Use to ensure your WA connection is always on the latest version
247
- */
248
- const fetchLatestBaileysVersion = async (options = {}) => {
249
- const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json';
250
- try {
251
- const result = await axios_1.default.get(URL, {
252
- ...options,
253
- responseType: 'json'
254
- });
255
- return {
256
- version: result.data.version,
257
- isLatest: true
258
- };
259
- }
260
- catch (error) {
261
- return {
262
- version: baileys_version_json_1.version,
263
- isLatest: false,
264
- error
265
- };
266
- }
267
- };
268
- exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
269
- /**
270
- * A utility that fetches the latest web version of whatsapp.
271
- * Use to ensure your WA connection is always on the latest version
272
- */
273
- const fetchLatestWaWebVersion = async (options) => {
274
- try {
275
- const result = await axios_1.default.get('https://web.whatsapp.com/check-update?version=1&platform=web', {
276
- ...options,
277
- responseType: 'json'
278
- });
279
- const version = result.data.currentVersion.split('.');
280
- return {
281
- version: [+version[0], +version[1], +version[2]],
282
- isLatest: true
283
- };
284
- }
285
- catch (error) {
286
- return {
287
- version: baileys_version_json_1.version,
288
- isLatest: false,
289
- error
290
- };
291
- }
292
- };
293
- exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
294
- /** unique message tag prefix for MD clients */
295
- const generateMdTagPrefix = () => {
296
- const bytes = (0, crypto_1.randomBytes)(4);
297
- return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
298
- };
299
- exports.generateMdTagPrefix = generateMdTagPrefix;
300
- const STATUS_MAP = {
301
- 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
302
- 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
303
- 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
304
- };
305
- /**
306
- * Given a type of receipt, returns what the new status of the message should be
307
- * @param type type from receipt
308
- */
309
- const getStatusFromReceiptType = (type) => {
310
- const status = STATUS_MAP[type];
311
- if (typeof type === 'undefined') {
312
- return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
313
- }
314
- return status;
315
- };
316
- exports.getStatusFromReceiptType = getStatusFromReceiptType;
317
- const CODE_MAP = {
318
- conflict: Types_1.DisconnectReason.connectionReplaced
319
- };
320
- /**
321
- * Stream errors generally provide a reason, map that to a baileys DisconnectReason
322
- * @param reason the string reason given, eg. "conflict"
323
- */
324
- const getErrorCodeFromStreamError = (node) => {
325
- const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
326
- let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
327
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
328
- if (statusCode === Types_1.DisconnectReason.restartRequired) {
329
- reason = 'restart required';
330
- }
331
- return {
332
- reason,
333
- statusCode
334
- };
335
- };
336
- exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
337
- const getCallStatusFromNode = ({ tag, attrs }) => {
338
- let status;
339
- switch (tag) {
340
- case 'offer':
341
- case 'offer_notice':
342
- status = 'offer';
343
- break;
344
- case 'terminate':
345
- if (attrs.reason === 'timeout') {
346
- status = 'timeout';
347
- }
348
- else {
349
- //fired when accepted/rejected/timeout/caller hangs up
350
- status = 'terminate';
351
- }
352
- break;
353
- case 'reject':
354
- status = 'reject';
355
- break;
356
- case 'accept':
357
- status = 'accept';
358
- break;
359
- default:
360
- status = 'ringing';
361
- break;
362
- }
363
- return status;
364
- };
365
- exports.getCallStatusFromNode = getCallStatusFromNode;
366
- const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
367
- const getCodeFromWSError = (error) => {
368
- var _a, _b, _c;
369
- let statusCode = 500;
370
- if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
371
- const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
372
- if (!Number.isNaN(code) && code >= 400) {
373
- statusCode = code;
374
- }
375
- }
376
- else if (
377
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
378
- ((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
379
- || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
380
- statusCode = 408;
381
- }
382
- return statusCode;
383
- };
384
- exports.getCodeFromWSError = getCodeFromWSError;
385
- /**
386
- * Is the given platform WA business
387
- * @param platform AuthenticationCreds.platform
388
- */
389
- const isWABusinessPlatform = (platform) => {
390
- return platform === 'smbi' || platform === 'smba';
391
- };
392
- exports.isWABusinessPlatform = isWABusinessPlatform;
393
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
394
- function trimUndefined(obj) {
395
- for (const key in obj) {
396
- if (typeof obj[key] === 'undefined') {
397
- delete obj[key];
398
- }
399
- }
400
- return obj;
401
- }
402
- exports.trimUndefined = trimUndefined;
403
- const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
404
- function bytesToCrockford(buffer) {
405
- let value = 0;
406
- let bitCount = 0;
407
- const crockford = [];
408
- for (const element of buffer) {
409
- value = (value << 8) | (element & 0xff);
410
- bitCount += 8;
411
- while (bitCount >= 5) {
412
- crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
413
- bitCount -= 5;
414
- }
415
- }
416
- if (bitCount > 0) {
417
- crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
418
- }
419
- return crockford.join('');
420
- }
421
- exports.bytesToCrockford = bytesToCrockford;
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.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.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
+ const boom_1 = require("@hapi/boom");
12
+ const axios_1 = __importDefault(require("axios"));
13
+ const crypto_1 = require("crypto");
14
+ const os_1 = require("os");
15
+ const WAProto_1 = require("../../WAProto");
16
+ const baileys_version_json_1 = require("../Defaults/baileys-version.json");
17
+ const Types_1 = require("../Types");
18
+ const WABinary_1 = require("../WABinary");
19
+ const PLATFORM_MAP = {
20
+ 'aix': 'AIX',
21
+ 'darwin': 'Mac OS',
22
+ 'win32': 'Windows',
23
+ 'android': 'Android',
24
+ 'freebsd': 'FreeBSD',
25
+ 'openbsd': 'OpenBSD',
26
+ 'sunos': 'Solaris'
27
+ };
28
+ exports.Browsers = {
29
+ ubuntu: (browser) => ['Ubuntu', browser, '22.04.4'],
30
+ macOS: (browser) => ['Mac OS', browser, '14.4.1'],
31
+ baileys: (browser) => ['Baileys', browser, '6.5.0'],
32
+ windows: (browser) => ['Windows', browser, '10.0.22631'],
33
+ /** The appropriate browser based on your OS & release */
34
+ appropriate: (browser) => [PLATFORM_MAP[(0, os_1.platform)()] || 'Ubuntu', browser, (0, os_1.release)()]
35
+ };
36
+ const getPlatformId = (browser) => {
37
+ const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
38
+ return platformType ? platformType.toString().charCodeAt(0).toString() : '49'; //chrome
39
+ };
40
+ exports.getPlatformId = getPlatformId;
41
+ exports.BufferJSON = {
42
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
43
+ replacer: (k, value) => {
44
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
45
+ return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
46
+ }
47
+ return value;
48
+ },
49
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
50
+ reviver: (_, value) => {
51
+ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
52
+ const val = value.data || value.value;
53
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
54
+ }
55
+ return value;
56
+ }
57
+ };
58
+ 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)) || '');
59
+ exports.getKeyAuthor = getKeyAuthor;
60
+ const writeRandomPadMax16 = (msg) => {
61
+ const pad = (0, crypto_1.randomBytes)(1);
62
+ pad[0] &= 0xf;
63
+ if (!pad[0]) {
64
+ pad[0] = 0xf;
65
+ }
66
+ return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
67
+ };
68
+ exports.writeRandomPadMax16 = writeRandomPadMax16;
69
+ const unpadRandomMax16 = (e) => {
70
+ const t = new Uint8Array(e);
71
+ if (0 === t.length) {
72
+ throw new Error('unpadPkcs7 given empty bytes');
73
+ }
74
+ var r = t[t.length - 1];
75
+ if (r > t.length) {
76
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
77
+ }
78
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
79
+ };
80
+ exports.unpadRandomMax16 = unpadRandomMax16;
81
+ const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
82
+ exports.encodeWAMessage = encodeWAMessage;
83
+ const generateRegistrationId = () => {
84
+ return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
85
+ };
86
+ exports.generateRegistrationId = generateRegistrationId;
87
+ const encodeBigEndian = (e, t = 4) => {
88
+ let r = e;
89
+ const a = new Uint8Array(t);
90
+ for (let i = t - 1; i >= 0; i--) {
91
+ a[i] = 255 & r;
92
+ r >>>= 8;
93
+ }
94
+ return a;
95
+ };
96
+ exports.encodeBigEndian = encodeBigEndian;
97
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0);
98
+ exports.toNumber = toNumber;
99
+ /** unix timestamp of a date in seconds */
100
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
101
+ exports.unixTimestampSeconds = unixTimestampSeconds;
102
+ const debouncedTimeout = (intervalMs = 1000, task) => {
103
+ let timeout;
104
+ return {
105
+ start: (newIntervalMs, newTask) => {
106
+ task = newTask || task;
107
+ intervalMs = newIntervalMs || intervalMs;
108
+ timeout && clearTimeout(timeout);
109
+ timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
110
+ },
111
+ cancel: () => {
112
+ timeout && clearTimeout(timeout);
113
+ timeout = undefined;
114
+ },
115
+ setTask: (newTask) => task = newTask,
116
+ setInterval: (newInterval) => intervalMs = newInterval
117
+ };
118
+ };
119
+ exports.debouncedTimeout = debouncedTimeout;
120
+ const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
121
+ exports.delay = delay;
122
+ const delayCancellable = (ms) => {
123
+ const stack = new Error().stack;
124
+ let timeout;
125
+ let reject;
126
+ const delay = new Promise((resolve, _reject) => {
127
+ timeout = setTimeout(resolve, ms);
128
+ reject = _reject;
129
+ });
130
+ const cancel = () => {
131
+ clearTimeout(timeout);
132
+ reject(new boom_1.Boom('Cancelled', {
133
+ statusCode: 500,
134
+ data: {
135
+ stack
136
+ }
137
+ }));
138
+ };
139
+ return { delay, cancel };
140
+ };
141
+ exports.delayCancellable = delayCancellable;
142
+ async function promiseTimeout(ms, promise) {
143
+ if (!ms) {
144
+ return new Promise(promise);
145
+ }
146
+ const stack = new Error().stack;
147
+ // Create a promise that rejects in <ms> milliseconds
148
+ const { delay, cancel } = (0, exports.delayCancellable)(ms);
149
+ const p = new Promise((resolve, reject) => {
150
+ delay
151
+ .then(() => reject(new boom_1.Boom('Timed Out', {
152
+ statusCode: Types_1.DisconnectReason.timedOut,
153
+ data: {
154
+ stack
155
+ }
156
+ })))
157
+ .catch(err => reject(err));
158
+ promise(resolve, reject);
159
+ })
160
+ .finally(cancel);
161
+ return p;
162
+ }
163
+ // inspired from whatsmeow code
164
+ // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
165
+ const generateMessageIDV2 = (userId) => {
166
+ const data = Buffer.alloc(8 + 20 + 16);
167
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
168
+ if (userId) {
169
+ const id = (0, WABinary_1.jidDecode)(userId);
170
+ if (id === null || id === void 0 ? void 0 : id.user) {
171
+ data.write(id.user, 8);
172
+ data.write('@c.us', 8 + id.user.length);
173
+ }
174
+ }
175
+ const random = (0, crypto_1.randomBytes)(16);
176
+ random.copy(data, 28);
177
+ const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
178
+ return (process.env.WHATSAPP_CONN_IDMSG || 'WHPI') + hash.toString('hex').toUpperCase().substring(0, 18);
179
+ };
180
+ exports.generateMessageIDV2 = generateMessageIDV2;
181
+ // generate a random ID to attach to a message
182
+ const generateMessageID = () => (process.env.WHATSAPP_CONN_IDMSG || 'WHPI') + (0, crypto_1.randomBytes)(18).toString('hex').toUpperCase();
183
+ exports.generateMessageID = generateMessageID;
184
+ function bindWaitForEvent(ev, event) {
185
+ return async (check, timeoutMs) => {
186
+ let listener;
187
+ let closeListener;
188
+ await (promiseTimeout(timeoutMs, (resolve, reject) => {
189
+ closeListener = ({ connection, lastDisconnect }) => {
190
+ if (connection === 'close') {
191
+ reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
192
+ || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
193
+ }
194
+ };
195
+ ev.on('connection.update', closeListener);
196
+ listener = async (update) => {
197
+ if (await check(update)) {
198
+ resolve();
199
+ }
200
+ };
201
+ ev.on(event, listener);
202
+ })
203
+ .finally(() => {
204
+ ev.off(event, listener);
205
+ ev.off('connection.update', closeListener);
206
+ }));
207
+ };
208
+ }
209
+ const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
210
+ exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
211
+ /**
212
+ * utility that fetches latest baileys version from the master branch.
213
+ * Use to ensure your WA connection is always on the latest version
214
+ */
215
+ const fetchLatestBaileysVersion = async (options = {}) => {
216
+ const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/baileys-version.json';
217
+ try {
218
+ const result = await axios_1.default.get(URL, {
219
+ ...options,
220
+ responseType: 'json'
221
+ });
222
+ return {
223
+ version: result.data.version,
224
+ isLatest: true
225
+ };
226
+ }
227
+ catch (error) {
228
+ return {
229
+ version: baileys_version_json_1.version,
230
+ isLatest: false,
231
+ error
232
+ };
233
+ }
234
+ };
235
+ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
236
+ /**
237
+ * A utility that fetches the latest web version of whatsapp.
238
+ * Use to ensure your WA connection is always on the latest version
239
+ */
240
+ const fetchLatestWaWebVersion = async (options) => {
241
+ try {
242
+ const { data } = await axios_1.default.get('https://web.whatsapp.com/sw.js', {
243
+ ...options,
244
+ responseType: 'json'
245
+ });
246
+ const regex = /\\?"client_revision\\?":\s*(\d+)/;
247
+ const match = data.match(regex);
248
+ if (!(match === null || match === void 0 ? void 0 : match[1])) {
249
+ return {
250
+ version: baileys_version_json_1.version,
251
+ isLatest: false,
252
+ error: {
253
+ message: 'Could not find client revision in the fetched content'
254
+ }
255
+ };
256
+ }
257
+ const clientRevision = match[1];
258
+ return {
259
+ version: [2, 3000, +clientRevision],
260
+ isLatest: true
261
+ };
262
+ }
263
+ catch (error) {
264
+ return {
265
+ version: baileys_version_json_1.version,
266
+ isLatest: false,
267
+ error
268
+ };
269
+ }
270
+ };
271
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
272
+ /** unique message tag prefix for MD clients */
273
+ const generateMdTagPrefix = () => {
274
+ const bytes = (0, crypto_1.randomBytes)(4);
275
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
276
+ };
277
+ exports.generateMdTagPrefix = generateMdTagPrefix;
278
+ const STATUS_MAP = {
279
+ 'sender': WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK,
280
+ 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
281
+ 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
282
+ 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
283
+ };
284
+ /**
285
+ * Given a type of receipt, returns what the new status of the message should be
286
+ * @param type type from receipt
287
+ */
288
+ const getStatusFromReceiptType = (type) => {
289
+ const status = STATUS_MAP[type];
290
+ if (typeof type === 'undefined') {
291
+ return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
292
+ }
293
+ return status;
294
+ };
295
+ exports.getStatusFromReceiptType = getStatusFromReceiptType;
296
+ const CODE_MAP = {
297
+ conflict: Types_1.DisconnectReason.connectionReplaced
298
+ };
299
+ /**
300
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
301
+ * @param reason the string reason given, eg. "conflict"
302
+ */
303
+ const getErrorCodeFromStreamError = (node) => {
304
+ const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
305
+ let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
306
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
307
+ if (statusCode === Types_1.DisconnectReason.restartRequired) {
308
+ reason = 'restart required';
309
+ }
310
+ return {
311
+ reason,
312
+ statusCode
313
+ };
314
+ };
315
+ exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
316
+ const getCallStatusFromNode = ({ tag, attrs }) => {
317
+ let status;
318
+ switch (tag) {
319
+ case 'offer':
320
+ case 'offer_notice':
321
+ status = 'offer';
322
+ break;
323
+ case 'terminate':
324
+ if (attrs.reason === 'timeout') {
325
+ status = 'timeout';
326
+ }
327
+ else {
328
+ //fired when accepted/rejected/timeout/caller hangs up
329
+ status = 'terminate';
330
+ }
331
+ break;
332
+ case 'reject':
333
+ status = 'reject';
334
+ break;
335
+ case 'accept':
336
+ status = 'accept';
337
+ break;
338
+ default:
339
+ status = 'ringing';
340
+ break;
341
+ }
342
+ return status;
343
+ };
344
+ exports.getCallStatusFromNode = getCallStatusFromNode;
345
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
346
+ const getCodeFromWSError = (error) => {
347
+ var _a, _b, _c;
348
+ let statusCode = 500;
349
+ if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
350
+ const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
351
+ if (!Number.isNaN(code) && code >= 400) {
352
+ statusCode = code;
353
+ }
354
+ }
355
+ else if (
356
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
357
+ ((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
358
+ || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
359
+ statusCode = 408;
360
+ }
361
+ return statusCode;
362
+ };
363
+ exports.getCodeFromWSError = getCodeFromWSError;
364
+ /**
365
+ * Is the given platform WA business
366
+ * @param platform AuthenticationCreds.platform
367
+ */
368
+ const isWABusinessPlatform = (platform) => {
369
+ return platform === 'smbi' || platform === 'smba';
370
+ };
371
+ exports.isWABusinessPlatform = isWABusinessPlatform;
372
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
373
+ function trimUndefined(obj) {
374
+ for (const key in obj) {
375
+ if (typeof obj[key] === 'undefined') {
376
+ delete obj[key];
377
+ }
378
+ }
379
+ return obj;
380
+ }
381
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
382
+ function bytesToCrockford(buffer) {
383
+ let value = 0;
384
+ let bitCount = 0;
385
+ const crockford = [];
386
+ for (const element of buffer) {
387
+ value = (value << 8) | (element & 0xff);
388
+ bitCount += 8;
389
+ while (bitCount >= 5) {
390
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
391
+ bitCount -= 5;
392
+ }
393
+ }
394
+ if (bitCount > 0) {
395
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
396
+ }
397
+ return crockford.join('');
398
+ }