@alannxd/baileys 6.0.6 → 6.0.9

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