@alannxd/baileys 6.0.5 → 6.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/WAProto/fix-import.js +29 -0
  2. package/WAProto/index.js +160 -201
  3. package/engine-requirements.js +1 -1
  4. package/lib/Defaults/baileys-version.json +3 -0
  5. package/lib/Defaults/index.d.ts +15 -37
  6. package/lib/Defaults/index.js +136 -119
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/Signal/Group/ciphertext-message.d.ts +0 -1
  9. package/lib/Signal/Group/ciphertext-message.js +5 -2
  10. package/lib/Signal/Group/group-session-builder.d.ts +3 -4
  11. package/lib/Signal/Group/group-session-builder.js +41 -7
  12. package/lib/Signal/Group/group_cipher.d.ts +4 -4
  13. package/lib/Signal/Group/group_cipher.js +51 -37
  14. package/lib/Signal/Group/index.d.ts +11 -12
  15. package/lib/Signal/Group/index.js +57 -12
  16. package/lib/Signal/Group/keyhelper.d.ts +1 -2
  17. package/lib/Signal/Group/keyhelper.js +44 -7
  18. package/lib/Signal/Group/queue-job.d.ts +1 -0
  19. package/lib/Signal/Group/queue-job.js +57 -0
  20. package/lib/Signal/Group/sender-chain-key.d.ts +2 -3
  21. package/lib/Signal/Group/sender-chain-key.js +15 -7
  22. package/lib/Signal/Group/sender-key-distribution-message.d.ts +1 -2
  23. package/lib/Signal/Group/sender-key-distribution-message.js +11 -8
  24. package/lib/Signal/Group/sender-key-message.d.ts +1 -2
  25. package/lib/Signal/Group/sender-key-message.js +12 -9
  26. package/lib/Signal/Group/sender-key-name.d.ts +0 -1
  27. package/lib/Signal/Group/sender-key-name.js +5 -2
  28. package/lib/Signal/Group/sender-key-record.d.ts +2 -3
  29. package/lib/Signal/Group/sender-key-record.js +21 -9
  30. package/lib/Signal/Group/sender-key-state.d.ts +6 -7
  31. package/lib/Signal/Group/sender-key-state.js +42 -27
  32. package/lib/Signal/Group/sender-message-key.d.ts +0 -1
  33. package/lib/Signal/Group/sender-message-key.js +7 -4
  34. package/lib/Signal/libsignal.d.ts +3 -5
  35. package/lib/Signal/libsignal.js +90 -347
  36. package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +5 -4
  37. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  38. package/lib/Socket/Client/index.d.ts +3 -3
  39. package/lib/Socket/Client/index.js +19 -3
  40. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  41. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  42. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +2 -3
  43. package/lib/Socket/Client/web-socket-client.js +62 -0
  44. package/lib/Socket/business.d.ts +108 -154
  45. package/lib/Socket/business.js +43 -162
  46. package/lib/Socket/chats.d.ts +239 -96
  47. package/lib/Socket/chats.js +427 -627
  48. package/lib/Socket/communities.d.ts +146 -239
  49. package/lib/Socket/communities.js +80 -90
  50. package/lib/Socket/groups.d.ts +57 -104
  51. package/lib/Socket/groups.js +161 -154
  52. package/lib/Socket/index.d.ts +115 -202
  53. package/lib/Socket/index.js +10 -11
  54. package/lib/Socket/luxu.d.ts +266 -22
  55. package/lib/Socket/luxu.js +465 -422
  56. package/lib/Socket/messages-recv.d.ts +84 -136
  57. package/lib/Socket/messages-recv.js +615 -1421
  58. package/lib/Socket/messages-send.d.ts +126 -142
  59. package/lib/Socket/messages-send.js +671 -878
  60. package/lib/Socket/newsletter.d.ts +85 -121
  61. package/lib/Socket/newsletter.js +272 -147
  62. package/lib/Socket/registration.d.ts +267 -0
  63. package/lib/Socket/registration.js +166 -0
  64. package/lib/Socket/socket.d.ts +19 -34
  65. package/lib/Socket/socket.js +313 -544
  66. package/lib/Socket/usync.d.ts +36 -0
  67. package/lib/Socket/usync.js +70 -0
  68. package/lib/Store/index.d.ts +3 -10
  69. package/lib/Store/index.js +10 -10
  70. package/lib/Store/make-cache-manager-store.d.ts +11 -17
  71. package/lib/Store/make-cache-manager-store.js +41 -43
  72. package/lib/Store/make-in-memory-store.d.ts +118 -39
  73. package/lib/Store/make-in-memory-store.js +341 -112
  74. package/lib/Store/make-ordered-dictionary.d.ts +10 -11
  75. package/lib/Store/make-ordered-dictionary.js +20 -14
  76. package/lib/Store/object-repository.d.ts +9 -10
  77. package/lib/Store/object-repository.js +6 -11
  78. package/lib/Types/Auth.d.ts +12 -19
  79. package/lib/Types/Auth.js +2 -2
  80. package/lib/Types/Call.d.ts +1 -3
  81. package/lib/Types/Call.js +2 -2
  82. package/lib/Types/Chat.d.ts +13 -35
  83. package/lib/Types/Chat.js +4 -8
  84. package/lib/Types/Contact.d.ts +1 -8
  85. package/lib/Types/Contact.js +2 -2
  86. package/lib/Types/Events.d.ts +17 -116
  87. package/lib/Types/Events.js +2 -2
  88. package/lib/Types/GroupMetadata.d.ts +5 -21
  89. package/lib/Types/GroupMetadata.js +2 -2
  90. package/lib/Types/Label.d.ts +0 -12
  91. package/lib/Types/Label.js +5 -3
  92. package/lib/Types/LabelAssociation.d.ts +0 -1
  93. package/lib/Types/LabelAssociation.js +5 -3
  94. package/lib/Types/Message.d.ts +58 -105
  95. package/lib/Types/Message.js +9 -11
  96. package/lib/Types/Newsletter.d.ts +103 -0
  97. package/lib/Types/Newsletter.js +38 -0
  98. package/lib/Types/Product.d.ts +1 -2
  99. package/lib/Types/Product.js +2 -2
  100. package/lib/Types/Signal.d.ts +2 -32
  101. package/lib/Types/Signal.js +2 -2
  102. package/lib/Types/Socket.d.ts +25 -50
  103. package/lib/Types/Socket.js +2 -3
  104. package/lib/Types/State.d.ts +2 -72
  105. package/lib/Types/State.js +2 -56
  106. package/lib/Types/USync.d.ts +2 -3
  107. package/lib/Types/USync.js +2 -2
  108. package/lib/Types/index.d.ts +14 -22
  109. package/lib/Types/index.js +31 -15
  110. package/lib/Utils/auth-utils.d.ts +6 -12
  111. package/lib/Utils/auth-utils.js +143 -239
  112. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  113. package/lib/Utils/baileys-event-stream.js +63 -0
  114. package/lib/Utils/business.d.ts +2 -3
  115. package/lib/Utils/business.js +69 -66
  116. package/lib/Utils/chat-utils.d.ts +23 -52
  117. package/lib/Utils/chat-utils.js +253 -396
  118. package/lib/Utils/crypto.d.ts +22 -18
  119. package/lib/Utils/crypto.js +90 -57
  120. package/lib/Utils/decode-wa-message.d.ts +8 -55
  121. package/lib/Utils/decode-wa-message.js +84 -203
  122. package/lib/Utils/event-buffer.d.ts +8 -9
  123. package/lib/Utils/event-buffer.js +77 -185
  124. package/lib/Utils/generics.d.ts +29 -28
  125. package/lib/Utils/generics.js +210 -180
  126. package/lib/Utils/history.d.ts +9 -18
  127. package/lib/Utils/history.js +55 -93
  128. package/lib/Utils/index.d.ts +17 -22
  129. package/lib/Utils/index.js +33 -22
  130. package/lib/Utils/link-preview.d.ts +5 -5
  131. package/lib/Utils/link-preview.js +24 -16
  132. package/lib/Utils/logger.d.ts +3 -11
  133. package/lib/Utils/logger.js +7 -3
  134. package/lib/Utils/lt-hash.d.ts +12 -8
  135. package/lib/Utils/lt-hash.js +46 -3
  136. package/lib/Utils/make-mutex.d.ts +2 -4
  137. package/lib/Utils/make-mutex.js +34 -24
  138. package/lib/Utils/messages-media.d.ts +44 -61
  139. package/lib/Utils/messages-media.js +482 -451
  140. package/lib/Utils/messages.d.ts +18 -32
  141. package/lib/Utils/messages.js +369 -458
  142. package/lib/Utils/noise-handler.d.ts +14 -13
  143. package/lib/Utils/noise-handler.js +99 -145
  144. package/lib/Utils/process-message.d.ts +12 -31
  145. package/lib/Utils/process-message.js +150 -459
  146. package/lib/Utils/signal.d.ts +5 -20
  147. package/lib/Utils/signal.js +72 -120
  148. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -2
  149. package/lib/Utils/use-multi-file-auth-state.js +27 -29
  150. package/lib/Utils/validate-connection.d.ts +7 -7
  151. package/lib/Utils/validate-connection.js +99 -73
  152. package/lib/WABinary/constants.d.ts +27 -25
  153. package/lib/WABinary/constants.js +20 -1281
  154. package/lib/WABinary/decode.d.ts +5 -5
  155. package/lib/WABinary/decode.js +42 -52
  156. package/lib/WABinary/encode.d.ts +3 -3
  157. package/lib/WABinary/encode.js +155 -110
  158. package/lib/WABinary/generic-utils.d.ts +7 -8
  159. package/lib/WABinary/generic-utils.js +49 -48
  160. package/lib/WABinary/index.d.ts +5 -6
  161. package/lib/WABinary/index.js +21 -6
  162. package/lib/WABinary/jid-utils.d.ts +8 -25
  163. package/lib/WABinary/jid-utils.js +40 -74
  164. package/lib/WABinary/types.d.ts +1 -2
  165. package/lib/WABinary/types.js +2 -2
  166. package/lib/WAM/BinaryInfo.d.ts +11 -3
  167. package/lib/WAM/BinaryInfo.js +5 -2
  168. package/lib/WAM/constants.d.ts +3 -5
  169. package/lib/WAM/constants.js +11958 -19461
  170. package/lib/WAM/encode.d.ts +3 -3
  171. package/lib/WAM/encode.js +22 -17
  172. package/lib/WAM/index.d.ts +3 -4
  173. package/lib/WAM/index.js +19 -4
  174. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +3 -4
  175. package/lib/WAUSync/Protocols/USyncContactProtocol.js +13 -33
  176. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -3
  177. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +14 -11
  178. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -3
  179. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +12 -9
  180. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -3
  181. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +13 -9
  182. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +3 -4
  183. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +22 -20
  184. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +3 -5
  185. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +8 -13
  186. package/lib/WAUSync/Protocols/index.d.ts +4 -6
  187. package/lib/WAUSync/Protocols/index.js +20 -6
  188. package/lib/WAUSync/USyncQuery.d.ts +4 -6
  189. package/lib/WAUSync/USyncQuery.js +35 -44
  190. package/lib/WAUSync/USyncUser.d.ts +5 -10
  191. package/lib/WAUSync/USyncUser.js +5 -10
  192. package/lib/WAUSync/index.js +19 -4
  193. package/lib/index.d.ts +9 -10
  194. package/lib/index.js +34 -12
  195. package/package.json +50 -83
  196. package/WAProto/GenerateStatics.sh +0 -3
  197. package/WAProto/WAProto.proto +0 -5479
  198. package/WAProto/fix-imports.js +0 -85
  199. package/WAProto/index.d.ts +0 -14017
  200. package/lib/Signal/lid-mapping.d.ts +0 -23
  201. package/lib/Signal/lid-mapping.js +0 -277
  202. package/lib/Socket/Client/types.js +0 -11
  203. package/lib/Socket/Client/websocket.js +0 -54
  204. package/lib/Socket/mex.d.ts +0 -3
  205. package/lib/Socket/mex.js +0 -42
  206. package/lib/Store/keyed-db.d.ts +0 -22
  207. package/lib/Store/keyed-db.js +0 -108
  208. package/lib/Types/Bussines.d.ts +0 -25
  209. package/lib/Types/Bussines.js +0 -2
  210. package/lib/Types/Mex.d.ts +0 -141
  211. package/lib/Types/Mex.js +0 -37
  212. package/lib/Utils/browser-utils.d.ts +0 -4
  213. package/lib/Utils/browser-utils.js +0 -28
  214. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  215. package/lib/Utils/companion-reg-client-utils.js +0 -35
  216. package/lib/Utils/identity-change-handler.d.ts +0 -44
  217. package/lib/Utils/identity-change-handler.js +0 -50
  218. package/lib/Utils/message-retry-manager.d.ts +0 -115
  219. package/lib/Utils/message-retry-manager.js +0 -265
  220. package/lib/Utils/offline-node-processor.d.ts +0 -17
  221. package/lib/Utils/offline-node-processor.js +0 -40
  222. package/lib/Utils/pre-key-manager.d.ts +0 -28
  223. package/lib/Utils/pre-key-manager.js +0 -106
  224. package/lib/Utils/reporting-utils.d.ts +0 -11
  225. package/lib/Utils/reporting-utils.js +0 -258
  226. package/lib/Utils/stanza-ack.d.ts +0 -11
  227. package/lib/Utils/stanza-ack.js +0 -38
  228. package/lib/Utils/sync-action-utils.d.ts +0 -19
  229. package/lib/Utils/sync-action-utils.js +0 -49
  230. package/lib/Utils/tc-token-utils.d.ts +0 -37
  231. package/lib/Utils/tc-token-utils.js +0 -163
  232. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  233. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  234. package/lib/WAUSync/index.d.ts +0 -4
@@ -1,45 +1,70 @@
1
- import { Boom } from '@hapi/boom';
2
- import { createHash, randomBytes } from 'crypto';
3
- import { proto } from '../../WAProto/index.js';
4
- const baileysVersion = [2, 3000, 1035194821];
5
- import { DisconnectReason } from '../Types/index.js';
6
- import { getAllBinaryNodeChildren, jidDecode } from '../WABinary/index.js';
7
- import { sha256 } from './crypto.js';
8
- export const BufferJSON = {
9
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
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.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;
7
+ const boom_1 = require("@hapi/boom");
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const crypto_1 = require("crypto");
10
+ 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");
14
+ const Types_1 = require("../Types");
15
+ const WABinary_1 = require("../WABinary");
16
+ const baileysVersion = [2, 3000, 1027934701]
17
+ 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
29
+ };
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
+ };
35
+
36
+ const getPlatformId = (browser) => {
37
+ const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()];
38
+ return platformType ? platformType.toString() : '1'; //chrome
39
+ };
40
+ exports.getPlatformId = getPlatformId;
41
+ exports.BufferJSON = {
10
42
  replacer: (k, value) => {
11
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
12
- return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') };
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') };
13
45
  }
14
46
  return value;
15
47
  },
16
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
48
  reviver: (_, value) => {
18
- if (typeof value === 'object' && value !== null && value.type === 'Buffer' && typeof value.data === 'string') {
19
- return Buffer.from(value.data, 'base64');
20
- }
21
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
22
- const keys = Object.keys(value);
23
- if (keys.length > 0 && keys.every(k => !isNaN(parseInt(k, 10)))) {
24
- const values = Object.values(value);
25
- if (values.every(v => typeof v === 'number')) {
26
- return Buffer.from(values);
27
- }
28
- }
49
+ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
50
+ const val = value.data || value.value;
51
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
29
52
  }
30
53
  return value;
31
54
  }
32
55
  };
33
- export const getKeyAuthor = (key, meId = 'me') => (key?.fromMe ? meId : key?.participantAlt || key?.remoteJidAlt || key?.participant || key?.remoteJid) || '';
34
- export const isStringNullOrEmpty = (value) =>
35
- // eslint-disable-next-line eqeqeq
36
- value == null || value === '';
37
- export const writeRandomPadMax16 = (msg) => {
38
- const pad = randomBytes(1);
39
- const padLength = (pad[0] & 0x0f) + 1;
40
- return Buffer.concat([msg, Buffer.alloc(padLength, padLength)]);
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)) || '');
57
+ exports.getKeyAuthor = getKeyAuthor;
58
+ const writeRandomPadMax16 = (msg) => {
59
+ 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])]);
41
65
  };
42
- export const unpadRandomMax16 = (e) => {
66
+ exports.writeRandomPadMax16 = writeRandomPadMax16;
67
+ const unpadRandomMax16 = (e) => {
43
68
  const t = new Uint8Array(e);
44
69
  if (0 === t.length) {
45
70
  throw new Error('unpadPkcs7 given empty bytes');
@@ -50,17 +75,14 @@ export const unpadRandomMax16 = (e) => {
50
75
  }
51
76
  return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
52
77
  };
53
- // code is inspired by whatsmeow
54
- export const generateParticipantHashV2 = (participants) => {
55
- participants.sort();
56
- const sha256Hash = sha256(Buffer.from(participants.join(''))).toString('base64');
57
- return '2:' + sha256Hash.slice(0, 6);
78
+ exports.unpadRandomMax16 = unpadRandomMax16;
79
+ const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
80
+ exports.encodeWAMessage = encodeWAMessage;
81
+ const generateRegistrationId = () => {
82
+ return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
58
83
  };
59
- export const encodeWAMessage = (message) => writeRandomPadMax16(proto.Message.encode(message).finish());
60
- export const generateRegistrationId = () => {
61
- return Uint16Array.from(randomBytes(2))[0] & 16383;
62
- };
63
- export const encodeBigEndian = (e, t = 4) => {
84
+ exports.generateRegistrationId = generateRegistrationId;
85
+ const encodeBigEndian = (e, t = 4) => {
64
86
  let r = e;
65
87
  const a = new Uint8Array(t);
66
88
  for (let i = t - 1; i >= 0; i--) {
@@ -69,28 +91,33 @@ export const encodeBigEndian = (e, t = 4) => {
69
91
  }
70
92
  return a;
71
93
  };
72
- export const toNumber = (t) => typeof t === 'object' && t ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0;
94
+ exports.encodeBigEndian = encodeBigEndian;
95
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
96
+ exports.toNumber = toNumber;
73
97
  /** unix timestamp of a date in seconds */
74
- export const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
75
- export const debouncedTimeout = (intervalMs = 1000, task) => {
98
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
99
+ exports.unixTimestampSeconds = unixTimestampSeconds;
100
+ const debouncedTimeout = (intervalMs = 1000, task) => {
76
101
  let timeout;
77
102
  return {
78
103
  start: (newIntervalMs, newTask) => {
79
104
  task = newTask || task;
80
105
  intervalMs = newIntervalMs || intervalMs;
81
106
  timeout && clearTimeout(timeout);
82
- timeout = setTimeout(() => task?.(), intervalMs);
107
+ timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
83
108
  },
84
109
  cancel: () => {
85
110
  timeout && clearTimeout(timeout);
86
111
  timeout = undefined;
87
112
  },
88
- setTask: (newTask) => (task = newTask),
89
- setInterval: (newInterval) => (intervalMs = newInterval)
113
+ setTask: (newTask) => task = newTask,
114
+ setInterval: (newInterval) => intervalMs = newInterval
90
115
  };
91
116
  };
92
- export const delay = (ms) => delayCancellable(ms).delay;
93
- export const delayCancellable = (ms) => {
117
+ exports.debouncedTimeout = debouncedTimeout;
118
+ const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
119
+ exports.delay = delay;
120
+ const delayCancellable = (ms) => {
94
121
  const stack = new Error().stack;
95
122
  let timeout;
96
123
  let reject;
@@ -100,7 +127,7 @@ export const delayCancellable = (ms) => {
100
127
  });
101
128
  const cancel = () => {
102
129
  clearTimeout(timeout);
103
- reject(new Boom('Cancelled', {
130
+ reject(new boom_1.Boom('Cancelled', {
104
131
  statusCode: 500,
105
132
  data: {
106
133
  stack
@@ -109,188 +136,198 @@ export const delayCancellable = (ms) => {
109
136
  };
110
137
  return { delay, cancel };
111
138
  };
112
- export async function promiseTimeout(ms, promise) {
139
+ exports.delayCancellable = delayCancellable;
140
+ async function promiseTimeout(ms, promise) {
113
141
  if (!ms) {
114
142
  return new Promise(promise);
115
143
  }
116
144
  const stack = new Error().stack;
117
145
  // Create a promise that rejects in <ms> milliseconds
118
- const { delay, cancel } = delayCancellable(ms);
146
+ const { delay, cancel } = (0, exports.delayCancellable)(ms);
119
147
  const p = new Promise((resolve, reject) => {
120
148
  delay
121
- .then(() => reject(new Boom('Timed Out', {
122
- statusCode: DisconnectReason.timedOut,
149
+ .then(() => reject(new boom_1.Boom('Timed Out', {
150
+ statusCode: Types_1.DisconnectReason.timedOut,
123
151
  data: {
124
152
  stack
125
153
  }
126
154
  })))
127
155
  .catch(err => reject(err));
128
156
  promise(resolve, reject);
129
- }).finally(cancel);
157
+ })
158
+ .finally(cancel);
130
159
  return p;
131
160
  }
132
- // inspired from whatsmeow code
133
- // https://github.com/tulir/whatsmeow/blob/64bc969fbe78d31ae0dd443b8d4c80a5d026d07a/send.go#L42
134
- export const generateMessageIDV2 = (userId) => {
161
+ exports.promiseTimeout = promiseTimeout;
162
+ const generateMessageIDV2 = (userId) => {
135
163
  const data = Buffer.alloc(8 + 20 + 16);
136
164
  data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
137
165
  if (userId) {
138
- const id = jidDecode(userId);
139
- if (id?.user) {
166
+ const id = (0, WABinary_1.jidDecode)(userId);
167
+ if (id === null || id === void 0 ? void 0 : id.user) {
140
168
  data.write(id.user, 8);
141
169
  data.write('@c.us', 8 + id.user.length);
142
170
  }
143
171
  }
144
- const random = randomBytes(16);
172
+ const random = (0, crypto_1.randomBytes)(16);
145
173
  random.copy(data, 28);
146
- const hash = createHash('sha256').update(data).digest();
147
- return 'XZCYYX-' + hash.toString('hex').toUpperCase().substring(0, 18);
174
+ const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
175
+ return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
148
176
  };
177
+ exports.generateMessageIDV2 = generateMessageIDV2;
149
178
  // generate a random ID to attach to a message
150
- export const generateMessageID = () => 'XZCYYX-' + randomBytes(18).toString('hex').toUpperCase();
151
- export function bindWaitForEvent(ev, event) {
179
+ const generateMessageID = () => '7EPP3LI-' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
180
+ exports.generateMessageID = generateMessageID;
181
+ function bindWaitForEvent(ev, event) {
152
182
  return async (check, timeoutMs) => {
153
183
  let listener;
154
184
  let closeListener;
155
- await promiseTimeout(timeoutMs, (resolve, reject) => {
185
+ await (promiseTimeout(timeoutMs, (resolve, reject) => {
156
186
  closeListener = ({ connection, lastDisconnect }) => {
157
187
  if (connection === 'close') {
158
- reject(lastDisconnect?.error || new Boom('Connection Closed', { statusCode: DisconnectReason.connectionClosed }));
188
+ reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
189
+ || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
159
190
  }
160
191
  };
161
192
  ev.on('connection.update', closeListener);
162
- listener = async (update) => {
163
- if (await check(update)) {
193
+ listener = (update) => {
194
+ if (check(update)) {
164
195
  resolve();
165
196
  }
166
197
  };
167
198
  ev.on(event, listener);
168
- }).finally(() => {
199
+ })
200
+ .finally(() => {
169
201
  ev.off(event, listener);
170
202
  ev.off('connection.update', closeListener);
171
- });
203
+ }));
172
204
  };
173
205
  }
174
- export const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
206
+ exports.bindWaitForEvent = bindWaitForEvent;
207
+ const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
208
+ 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;
175
222
  /**
176
223
  * utility that fetches latest baileys version from the master branch.
177
224
  * Use to ensure your WA connection is always on the latest version
178
225
  */
179
- export const fetchLatestBaileysVersion = async (options = {}) => {
180
- const URL = 'https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts';
181
- try {
182
- const response = await fetch(URL, {
183
- dispatcher: options.dispatcher,
184
- method: 'GET',
185
- headers: options.headers
186
- });
187
- if (!response.ok) {
188
- throw new Boom(`Failed to fetch latest Baileys version: ${response.statusText}`, { statusCode: response.status });
189
- }
190
- const text = await response.text();
191
- // Extract version from line 7 (const version = [...])
192
- const lines = text.split('\n');
193
- const versionLine = lines[6]; // Line 7 (0-indexed)
194
- const versionMatch = versionLine.match(/const version = \[(\d+),\s*(\d+),\s*(\d+)\]/);
195
- if (versionMatch) {
196
- const version = [parseInt(versionMatch[1]), parseInt(versionMatch[2]), parseInt(versionMatch[3])];
197
- return {
198
- version,
199
- isLatest: true
200
- };
201
- }
202
- else {
203
- throw new Error('Could not parse version from Defaults/index.ts');
204
- }
205
- }
206
- catch (error) {
207
- return {
208
- version: baileysVersion,
209
- isLatest: false,
210
- error
211
- };
212
- }
213
- };
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;
214
271
  /**
215
- * A utility that fetches the latest web version of whatsapp.
272
+ * utility that fetches latest baileys version from the master branch.
216
273
  * Use to ensure your WA connection is always on the latest version
217
274
  */
218
- export const fetchLatestWaWebVersion = async (options = {}) => {
275
+ const fetchLatestBaileysVersion = async (options = {}) => {
276
+ const URL = 'https://raw.githubusercontent.com/kiuur/bails/master/src/Defaults/baileys-version.json';
219
277
  try {
220
- // Absolute minimal headers required to bypass anti-bot detection
221
- const defaultHeaders = {
222
- 'sec-fetch-site': 'none',
223
- 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
224
- };
225
- const headers = { ...defaultHeaders, ...options.headers };
226
- const response = await fetch('https://web.whatsapp.com/sw.js', {
278
+ const result = await axios_1.default.get(URL, {
227
279
  ...options,
228
- method: 'GET',
229
- headers
280
+ responseType: 'json'
230
281
  });
231
- if (!response.ok) {
232
- throw new Boom(`Failed to fetch sw.js: ${response.statusText}`, { statusCode: response.status });
233
- }
234
- const data = await response.text();
235
- const regex = /\\?"client_revision\\?":\s*(\d+)/;
236
- const match = data.match(regex);
237
- if (!match?.[1]) {
238
- return {
239
- version: baileysVersion,
240
- isLatest: false,
241
- error: {
242
- message: 'Could not find client revision in the fetched content'
243
- }
244
- };
245
- }
246
- const clientRevision = match[1];
247
282
  return {
248
- version: [2, 3000, +clientRevision],
283
+ version: result.data.version,
249
284
  isLatest: true
250
285
  };
251
286
  }
252
287
  catch (error) {
253
288
  return {
254
- version: baileysVersion,
289
+ version: baileys_version_json_1.version,
255
290
  isLatest: false,
256
291
  error
257
292
  };
258
293
  }
259
294
  };
295
+ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
260
296
  /** unique message tag prefix for MD clients */
261
- export const generateMdTagPrefix = () => {
262
- const bytes = randomBytes(4);
297
+ const generateMdTagPrefix = () => {
298
+ const bytes = (0, crypto_1.randomBytes)(4);
263
299
  return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
264
300
  };
301
+ exports.generateMdTagPrefix = generateMdTagPrefix;
265
302
  const STATUS_MAP = {
266
- sender: proto.WebMessageInfo.Status.SERVER_ACK,
267
- played: proto.WebMessageInfo.Status.PLAYED,
268
- read: proto.WebMessageInfo.Status.READ,
269
- 'read-self': proto.WebMessageInfo.Status.READ
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
270
306
  };
271
307
  /**
272
308
  * Given a type of receipt, returns what the new status of the message should be
273
309
  * @param type type from receipt
274
310
  */
275
- export const getStatusFromReceiptType = (type) => {
311
+ const getStatusFromReceiptType = (type) => {
276
312
  const status = STATUS_MAP[type];
277
313
  if (typeof type === 'undefined') {
278
- return proto.WebMessageInfo.Status.DELIVERY_ACK;
314
+ return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
279
315
  }
280
316
  return status;
281
317
  };
318
+ exports.getStatusFromReceiptType = getStatusFromReceiptType;
282
319
  const CODE_MAP = {
283
- conflict: DisconnectReason.connectionReplaced
320
+ conflict: Types_1.DisconnectReason.connectionReplaced
284
321
  };
285
322
  /**
286
323
  * Stream errors generally provide a reason, map that to a baileys DisconnectReason
287
324
  * @param reason the string reason given, eg. "conflict"
288
325
  */
289
- export const getErrorCodeFromStreamError = (node) => {
290
- const [reasonNode] = getAllBinaryNodeChildren(node);
291
- let reason = reasonNode?.tag || 'unknown';
292
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || DisconnectReason.badSession);
293
- if (statusCode === DisconnectReason.restartRequired) {
326
+ const getErrorCodeFromStreamError = (node) => {
327
+ const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
328
+ let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
329
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
330
+ if (statusCode === Types_1.DisconnectReason.restartRequired) {
294
331
  reason = 'restart required';
295
332
  }
296
333
  return {
@@ -298,7 +335,8 @@ export const getErrorCodeFromStreamError = (node) => {
298
335
  statusCode
299
336
  };
300
337
  };
301
- export const getCallStatusFromNode = ({ tag, attrs }) => {
338
+ exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
339
+ const getCallStatusFromNode = ({ tag, attrs }) => {
302
340
  let status;
303
341
  switch (tag) {
304
342
  case 'offer':
@@ -310,19 +348,9 @@ export const getCallStatusFromNode = ({ tag, attrs }) => {
310
348
  status = 'timeout';
311
349
  }
312
350
  else {
313
- //fired when accepted/rejected/timeout/caller hangs up
314
- status = 'terminate';
351
+ status = 'reject';
315
352
  }
316
353
  break;
317
- case 'preaccept':
318
- status = 'preaccept';
319
- break;
320
- case 'transport':
321
- status = 'transport';
322
- break;
323
- case 'relaylatency':
324
- status = 'relaylatency';
325
- break;
326
354
  case 'reject':
327
355
  status = 'reject';
328
356
  break;
@@ -335,33 +363,33 @@ export const getCallStatusFromNode = ({ tag, attrs }) => {
335
363
  }
336
364
  return status;
337
365
  };
366
+ exports.getCallStatusFromNode = getCallStatusFromNode;
338
367
  const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
339
- export const getCodeFromWSError = (error) => {
368
+ const getCodeFromWSError = (error) => {
369
+ var _a, _b, _c;
340
370
  let statusCode = 500;
341
- if (error?.message?.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
342
- const code = +error?.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length);
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));
343
373
  if (!Number.isNaN(code) && code >= 400) {
344
374
  statusCode = code;
345
375
  }
346
376
  }
347
- else if (
348
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
349
- error?.code?.startsWith('E') ||
350
- error?.message?.includes('timed out')) {
351
- // handle ETIMEOUT, ENOTFOUND etc
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
352
379
  statusCode = 408;
353
380
  }
354
381
  return statusCode;
355
382
  };
383
+ exports.getCodeFromWSError = getCodeFromWSError;
356
384
  /**
357
385
  * Is the given platform WA business
358
386
  * @param platform AuthenticationCreds.platform
359
387
  */
360
- export const isWABusinessPlatform = (platform) => {
388
+ const isWABusinessPlatform = (platform) => {
361
389
  return platform === 'smbi' || platform === 'smba';
362
390
  };
363
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
364
- export function trimUndefined(obj) {
391
+ exports.isWABusinessPlatform = isWABusinessPlatform;
392
+ function trimUndefined(obj) {
365
393
  for (const key in obj) {
366
394
  if (typeof obj[key] === 'undefined') {
367
395
  delete obj[key];
@@ -369,13 +397,14 @@ export function trimUndefined(obj) {
369
397
  }
370
398
  return obj;
371
399
  }
400
+ exports.trimUndefined = trimUndefined;
372
401
  const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
373
- export function bytesToCrockford(buffer) {
402
+ function bytesToCrockford(buffer) {
374
403
  let value = 0;
375
404
  let bitCount = 0;
376
405
  const crockford = [];
377
- for (const element of buffer) {
378
- value = (value << 8) | (element & 0xff);
406
+ for (let i = 0; i < buffer.length; i++) {
407
+ value = (value << 8) | (buffer[i] & 0xff);
379
408
  bitCount += 8;
380
409
  while (bitCount >= 5) {
381
410
  crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
@@ -387,7 +416,8 @@ export function bytesToCrockford(buffer) {
387
416
  }
388
417
  return crockford.join('');
389
418
  }
390
- export function encodeNewsletterMessage(message) {
391
- return proto.Message.encode(message).finish();
419
+ exports.bytesToCrockford = bytesToCrockford;
420
+ const encodeNewsletterMessage = (message) => {
421
+ return WAProto_1.proto.Message.encode(message).finish()
392
422
  }
393
- //# sourceMappingURL=generics.js.map
423
+ exports.encodeNewsletterMessage = encodeNewsletterMessage;
@@ -1,24 +1,15 @@
1
- import { proto } from '../../WAProto/index.js';
2
- import type { Chat, Contact, LIDMapping, WAMessage } from '../Types/index.js';
3
- import type { ILogger } from './logger.js';
4
- export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: RequestInit) => Promise<proto.HistorySync>;
5
- export declare const processHistoryMessage: (item: proto.IHistorySync, logger?: ILogger) => {
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>;
5
+ export declare const processHistoryMessage: (item: proto.IHistorySync) => {
6
6
  chats: Chat[];
7
7
  contacts: Contact[];
8
- messages: WAMessage[];
9
- lidPnMappings: LIDMapping[];
10
- pastParticipants: proto.IPastParticipants[] | null | undefined;
11
- syncType: proto.HistorySync.HistorySyncType | null | undefined;
12
- progress: number | null | undefined;
8
+ messages: proto.IWebMessageInfo[];
13
9
  };
14
- export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: RequestInit, logger?: ILogger) => Promise<{
10
+ export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<{
15
11
  chats: Chat[];
16
12
  contacts: Contact[];
17
- messages: WAMessage[];
18
- lidPnMappings: LIDMapping[];
19
- pastParticipants: proto.IPastParticipants[] | null | undefined;
20
- syncType: proto.HistorySync.HistorySyncType | null | undefined;
21
- progress: number | null | undefined;
13
+ messages: proto.IWebMessageInfo[];
22
14
  }>;
23
- export declare const getHistoryMsg: (message: proto.IMessage) => proto.Message.IHistorySyncNotification;
24
- //# sourceMappingURL=history.d.ts.map
15
+ export declare const getHistoryMsg: (message: proto.IMessage) => proto.Message.IHistorySyncNotification | null | undefined;