@kevin-b2t/baileys 1.0.4

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 (199) hide show
  1. package/README.md +393 -0
  2. package/WAProto/index.js +169661 -0
  3. package/engine-requirements.js +10 -0
  4. package/lib/Defaults/baileys-version.json +3 -0
  5. package/lib/Defaults/index.d.ts +53 -0
  6. package/lib/Defaults/index.js +147 -0
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  9. package/lib/Signal/Group/ciphertext-message.js +15 -0
  10. package/lib/Signal/Group/group-session-builder.d.ts +14 -0
  11. package/lib/Signal/Group/group-session-builder.js +64 -0
  12. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  13. package/lib/Signal/Group/group_cipher.js +96 -0
  14. package/lib/Signal/Group/index.d.ts +11 -0
  15. package/lib/Signal/Group/index.js +57 -0
  16. package/lib/Signal/Group/keyhelper.d.ts +10 -0
  17. package/lib/Signal/Group/keyhelper.js +55 -0
  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 +13 -0
  21. package/lib/Signal/Group/sender-chain-key.js +34 -0
  22. package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
  23. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  24. package/lib/Signal/Group/sender-key-message.d.ts +18 -0
  25. package/lib/Signal/Group/sender-key-message.js +69 -0
  26. package/lib/Signal/Group/sender-key-name.d.ts +17 -0
  27. package/lib/Signal/Group/sender-key-name.js +51 -0
  28. package/lib/Signal/Group/sender-key-record.d.ts +30 -0
  29. package/lib/Signal/Group/sender-key-record.js +53 -0
  30. package/lib/Signal/Group/sender-key-state.d.ts +38 -0
  31. package/lib/Signal/Group/sender-key-state.js +99 -0
  32. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  33. package/lib/Signal/Group/sender-message-key.js +29 -0
  34. package/lib/Signal/libsignal.d.ts +3 -0
  35. package/lib/Signal/libsignal.js +174 -0
  36. package/lib/Socket/Client/abstract-socket-client.d.ts +17 -0
  37. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  38. package/lib/Socket/Client/index.d.ts +3 -0
  39. package/lib/Socket/Client/index.js +19 -0
  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/web-socket-client.d.ts +12 -0
  43. package/lib/Socket/Client/web-socket-client.js +62 -0
  44. package/lib/Socket/business.d.ts +171 -0
  45. package/lib/Socket/business.js +260 -0
  46. package/lib/Socket/chats.d.ts +267 -0
  47. package/lib/Socket/chats.js +983 -0
  48. package/lib/Socket/communities.js +421 -0
  49. package/lib/Socket/dugong.d.ts +258 -0
  50. package/lib/Socket/dugong.js +424 -0
  51. package/lib/Socket/groups.d.ts +115 -0
  52. package/lib/Socket/groups.js +324 -0
  53. package/lib/Socket/index.d.ts +173 -0
  54. package/lib/Socket/index.js +11 -0
  55. package/lib/Socket/messages-recv.d.ts +161 -0
  56. package/lib/Socket/messages-recv.js +1138 -0
  57. package/lib/Socket/messages-send.d.ts +149 -0
  58. package/lib/Socket/messages-send.js +909 -0
  59. package/lib/Socket/newsletter.d.ts +134 -0
  60. package/lib/Socket/newsletter.js +334 -0
  61. package/lib/Socket/registration.d.ts +267 -0
  62. package/lib/Socket/registration.js +166 -0
  63. package/lib/Socket/socket.d.ts +43 -0
  64. package/lib/Socket/socket.js +665 -0
  65. package/lib/Socket/usync.d.ts +36 -0
  66. package/lib/Socket/usync.js +70 -0
  67. package/lib/Store/index.d.ts +3 -0
  68. package/lib/Store/index.js +10 -0
  69. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  70. package/lib/Store/make-cache-manager-store.js +83 -0
  71. package/lib/Store/make-in-memory-store.d.ts +118 -0
  72. package/lib/Store/make-in-memory-store.js +427 -0
  73. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  74. package/lib/Store/make-ordered-dictionary.js +81 -0
  75. package/lib/Store/object-repository.d.ts +10 -0
  76. package/lib/Store/object-repository.js +27 -0
  77. package/lib/Types/Auth.d.ts +110 -0
  78. package/lib/Types/Auth.js +2 -0
  79. package/lib/Types/Call.d.ts +13 -0
  80. package/lib/Types/Call.js +2 -0
  81. package/lib/Types/Chat.d.ts +102 -0
  82. package/lib/Types/Chat.js +4 -0
  83. package/lib/Types/Contact.d.ts +19 -0
  84. package/lib/Types/Contact.js +2 -0
  85. package/lib/Types/Events.d.ts +157 -0
  86. package/lib/Types/Events.js +2 -0
  87. package/lib/Types/GroupMetadata.d.ts +55 -0
  88. package/lib/Types/GroupMetadata.js +2 -0
  89. package/lib/Types/Label.d.ts +35 -0
  90. package/lib/Types/Label.js +27 -0
  91. package/lib/Types/LabelAssociation.d.ts +29 -0
  92. package/lib/Types/LabelAssociation.js +9 -0
  93. package/lib/Types/Message.d.ts +273 -0
  94. package/lib/Types/Message.js +9 -0
  95. package/lib/Types/Newsletter.d.ts +103 -0
  96. package/lib/Types/Newsletter.js +38 -0
  97. package/lib/Types/Product.d.ts +78 -0
  98. package/lib/Types/Product.js +2 -0
  99. package/lib/Types/Signal.d.ts +57 -0
  100. package/lib/Types/Signal.js +2 -0
  101. package/lib/Types/Socket.d.ts +111 -0
  102. package/lib/Types/Socket.js +2 -0
  103. package/lib/Types/State.d.ts +27 -0
  104. package/lib/Types/State.js +2 -0
  105. package/lib/Types/USync.d.ts +25 -0
  106. package/lib/Types/USync.js +2 -0
  107. package/lib/Types/index.d.ts +57 -0
  108. package/lib/Types/index.js +42 -0
  109. package/lib/Utils/auth-utils.d.ts +18 -0
  110. package/lib/Utils/auth-utils.js +206 -0
  111. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  112. package/lib/Utils/baileys-event-stream.js +63 -0
  113. package/lib/Utils/business.d.ts +22 -0
  114. package/lib/Utils/business.js +234 -0
  115. package/lib/Utils/chat-utils.d.ts +71 -0
  116. package/lib/Utils/chat-utils.js +729 -0
  117. package/lib/Utils/crypto.d.ts +41 -0
  118. package/lib/Utils/crypto.js +151 -0
  119. package/lib/Utils/decode-wa-message.d.ts +19 -0
  120. package/lib/Utils/decode-wa-message.js +198 -0
  121. package/lib/Utils/event-buffer.d.ts +35 -0
  122. package/lib/Utils/event-buffer.js +514 -0
  123. package/lib/Utils/generics.d.ts +92 -0
  124. package/lib/Utils/generics.js +457 -0
  125. package/lib/Utils/history.d.ts +15 -0
  126. package/lib/Utils/history.js +96 -0
  127. package/lib/Utils/index.d.ts +17 -0
  128. package/lib/Utils/index.js +35 -0
  129. package/lib/Utils/lid-resolver.js +73 -0
  130. package/lib/Utils/link-preview.d.ts +21 -0
  131. package/lib/Utils/link-preview.js +93 -0
  132. package/lib/Utils/logger.d.ts +4 -0
  133. package/lib/Utils/logger.js +7 -0
  134. package/lib/Utils/lt-hash.d.ts +12 -0
  135. package/lib/Utils/lt-hash.js +51 -0
  136. package/lib/Utils/make-mutex.d.ts +7 -0
  137. package/lib/Utils/make-mutex.js +43 -0
  138. package/lib/Utils/mention.d.ts +7 -0
  139. package/lib/Utils/mention.js +147 -0
  140. package/lib/Utils/messages-media.d.ts +116 -0
  141. package/lib/Utils/messages-media.js +819 -0
  142. package/lib/Utils/messages.d.ts +77 -0
  143. package/lib/Utils/messages.js +784 -0
  144. package/lib/Utils/noise-handler.d.ts +21 -0
  145. package/lib/Utils/noise-handler.js +155 -0
  146. package/lib/Utils/process-message.d.ts +41 -0
  147. package/lib/Utils/process-message.js +321 -0
  148. package/lib/Utils/signal.d.ts +32 -0
  149. package/lib/Utils/signal.js +153 -0
  150. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  151. package/lib/Utils/use-multi-file-auth-state.js +119 -0
  152. package/lib/Utils/validate-connection.d.ts +11 -0
  153. package/lib/Utils/validate-connection.js +229 -0
  154. package/lib/WABinary/constants.d.ts +30 -0
  155. package/lib/WABinary/constants.js +40 -0
  156. package/lib/WABinary/decode.d.ts +7 -0
  157. package/lib/WABinary/decode.js +252 -0
  158. package/lib/WABinary/encode.d.ts +3 -0
  159. package/lib/WABinary/encode.js +265 -0
  160. package/lib/WABinary/generic-utils.d.ts +17 -0
  161. package/lib/WABinary/generic-utils.js +198 -0
  162. package/lib/WABinary/index.d.ts +5 -0
  163. package/lib/WABinary/index.js +21 -0
  164. package/lib/WABinary/jid-utils.d.ts +31 -0
  165. package/lib/WABinary/jid-utils.js +62 -0
  166. package/lib/WABinary/types.d.ts +18 -0
  167. package/lib/WABinary/types.js +2 -0
  168. package/lib/WAM/BinaryInfo.d.ts +17 -0
  169. package/lib/WAM/BinaryInfo.js +13 -0
  170. package/lib/WAM/constants.d.ts +38 -0
  171. package/lib/WAM/constants.js +15350 -0
  172. package/lib/WAM/encode.d.ts +3 -0
  173. package/lib/WAM/encode.js +155 -0
  174. package/lib/WAM/index.d.ts +3 -0
  175. package/lib/WAM/index.js +19 -0
  176. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  177. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  178. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  179. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  180. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  181. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  182. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  183. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  184. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +29 -0
  185. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
  186. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  187. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
  188. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  189. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  190. package/lib/WAUSync/Protocols/index.js +21 -0
  191. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  192. package/lib/WAUSync/USyncQuery.js +93 -0
  193. package/lib/WAUSync/USyncUser.d.ts +12 -0
  194. package/lib/WAUSync/USyncUser.js +26 -0
  195. package/lib/WAUSync/index.d.ts +3 -0
  196. package/lib/WAUSync/index.js +19 -0
  197. package/lib/index.d.ts +12 -0
  198. package/lib/index.js +43 -0
  199. package/package.json +111 -0
@@ -0,0 +1,457 @@
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, 1029030078]
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
+ // --- ported from whiskey: companion web-client type, used in the pairing QR ---
42
+ const CompanionWebClientType = {
43
+ UNKNOWN: 0, CHROME: 1, EDGE: 2, FIREFOX: 3, IE: 4, OPERA: 5, SAFARI: 6, ELECTRON: 7, UWP: 8, OTHER_WEB_CLIENT: 9
44
+ };
45
+ exports.CompanionWebClientType = CompanionWebClientType;
46
+ const BROWSER_TO_COMPANION_WEB_CLIENT = {
47
+ Chrome: CompanionWebClientType.CHROME,
48
+ Edge: CompanionWebClientType.EDGE,
49
+ Firefox: CompanionWebClientType.FIREFOX,
50
+ IE: CompanionWebClientType.IE,
51
+ Opera: CompanionWebClientType.OPERA,
52
+ Safari: CompanionWebClientType.SAFARI
53
+ };
54
+ const getCompanionWebClientType = ([os, browserName]) => {
55
+ if (browserName === 'Desktop') {
56
+ return os === 'Windows' ? CompanionWebClientType.UWP : CompanionWebClientType.ELECTRON;
57
+ }
58
+ return BROWSER_TO_COMPANION_WEB_CLIENT[browserName] || CompanionWebClientType.OTHER_WEB_CLIENT;
59
+ };
60
+ exports.getCompanionWebClientType = getCompanionWebClientType;
61
+ const getCompanionPlatformId = (browser) => getCompanionWebClientType(browser).toString();
62
+ exports.getCompanionPlatformId = getCompanionPlatformId;
63
+ const buildPairingQRData = (ref, noiseKeyB64, identityKeyB64, advB64, browser) => {
64
+ // NOTE: reverted to the long-standing 4-field WA QR format (ref, noiseKey, identityKey, advSecret).
65
+ // A 5th "companion platform id" field was experimentally added here in a previous patch, ported
66
+ // from an unverified "whiskey" source. That field is NOT part of the actual QR pairing payload that
67
+ // WhatsApp's phone scanner expects (the platform id is only sent separately, inside the
68
+ // `companion_platform_id` XML tag during the *pairing code* flow - see requestPairingCode() in
69
+ // socket.js). Sending a 5-field QR string risks the phone app failing to parse the code ("Gagal
70
+ // Pairing"). `browser` is intentionally unused now but kept in the signature so existing call sites
71
+ // don't need to change.
72
+ return [ref, noiseKeyB64, identityKeyB64, advB64].join(',');
73
+ };
74
+ exports.buildPairingQRData = buildPairingQRData;
75
+ exports.BufferJSON = {
76
+ replacer: (k, value) => {
77
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {
78
+ return { type: 'Buffer', data: Buffer.from((value === null || value === void 0 ? void 0 : value.data) || value).toString('base64') };
79
+ }
80
+ return value;
81
+ },
82
+ reviver: (_, value) => {
83
+ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
84
+ const val = value.data || value.value;
85
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || []);
86
+ }
87
+ return value;
88
+ }
89
+ };
90
+ 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)) || '');
91
+ exports.getKeyAuthor = getKeyAuthor;
92
+ const writeRandomPadMax16 = (msg) => {
93
+ const pad = (0, crypto_1.randomBytes)(1);
94
+ pad[0] &= 0xf;
95
+ if (!pad[0]) {
96
+ pad[0] = 0xf;
97
+ }
98
+ return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])]);
99
+ };
100
+ exports.writeRandomPadMax16 = writeRandomPadMax16;
101
+ const unpadRandomMax16 = (e) => {
102
+ const t = new Uint8Array(e);
103
+ if (0 === t.length) {
104
+ throw new Error('unpadPkcs7 given empty bytes');
105
+ }
106
+ var r = t[t.length - 1];
107
+ if (r > t.length) {
108
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`);
109
+ }
110
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r);
111
+ };
112
+ exports.unpadRandomMax16 = unpadRandomMax16;
113
+ const encodeWAMessage = (message) => ((0, exports.writeRandomPadMax16)(WAProto_1.proto.Message.encode(message).finish()));
114
+ exports.encodeWAMessage = encodeWAMessage;
115
+ const generateRegistrationId = () => {
116
+ return Uint16Array.from((0, crypto_1.randomBytes)(2))[0] & 16383;
117
+ };
118
+ exports.generateRegistrationId = generateRegistrationId;
119
+ const encodeBigEndian = (e, t = 4) => {
120
+ let r = e;
121
+ const a = new Uint8Array(t);
122
+ for (let i = t - 1; i >= 0; i--) {
123
+ a[i] = 255 & r;
124
+ r >>>= 8;
125
+ }
126
+ return a;
127
+ };
128
+ exports.encodeBigEndian = encodeBigEndian;
129
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
130
+ exports.toNumber = toNumber;
131
+ /** unix timestamp of a date in seconds */
132
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000);
133
+ exports.unixTimestampSeconds = unixTimestampSeconds;
134
+ const debouncedTimeout = (intervalMs = 1000, task) => {
135
+ let timeout;
136
+ return {
137
+ start: (newIntervalMs, newTask) => {
138
+ task = newTask || task;
139
+ intervalMs = newIntervalMs || intervalMs;
140
+ timeout && clearTimeout(timeout);
141
+ timeout = setTimeout(() => task === null || task === void 0 ? void 0 : task(), intervalMs);
142
+ },
143
+ cancel: () => {
144
+ timeout && clearTimeout(timeout);
145
+ timeout = undefined;
146
+ },
147
+ setTask: (newTask) => task = newTask,
148
+ setInterval: (newInterval) => intervalMs = newInterval
149
+ };
150
+ };
151
+ exports.debouncedTimeout = debouncedTimeout;
152
+ const delay = (ms) => (0, exports.delayCancellable)(ms).delay;
153
+ exports.delay = delay;
154
+ const delayCancellable = (ms) => {
155
+ const stack = new Error().stack;
156
+ let timeout;
157
+ let reject;
158
+ const delay = new Promise((resolve, _reject) => {
159
+ timeout = setTimeout(resolve, ms);
160
+ reject = _reject;
161
+ });
162
+ const cancel = () => {
163
+ clearTimeout(timeout);
164
+ reject(new boom_1.Boom('Cancelled', {
165
+ statusCode: 500,
166
+ data: {
167
+ stack
168
+ }
169
+ }));
170
+ };
171
+ return { delay, cancel };
172
+ };
173
+ exports.delayCancellable = delayCancellable;
174
+ async function promiseTimeout(ms, promise) {
175
+ if (!ms) {
176
+ return new Promise(promise);
177
+ }
178
+ const stack = new Error().stack;
179
+ // Create a promise that rejects in <ms> milliseconds
180
+ const { delay, cancel } = (0, exports.delayCancellable)(ms);
181
+ const p = new Promise((resolve, reject) => {
182
+ delay
183
+ .then(() => reject(new boom_1.Boom('Timed Out', {
184
+ statusCode: Types_1.DisconnectReason.timedOut,
185
+ data: {
186
+ stack
187
+ }
188
+ })))
189
+ .catch(err => reject(err));
190
+ promise(resolve, reject);
191
+ })
192
+ .finally(cancel);
193
+ return p;
194
+ }
195
+ exports.promiseTimeout = promiseTimeout;
196
+ const generateMessageIDV2 = (userId) => {
197
+ const data = Buffer.alloc(8 + 20 + 16);
198
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
199
+ if (userId) {
200
+ const id = (0, WABinary_1.jidDecode)(userId);
201
+ if (id === null || id === void 0 ? void 0 : id.user) {
202
+ data.write(id.user, 8);
203
+ data.write('@c.us', 8 + id.user.length);
204
+ }
205
+ }
206
+ const random = (0, crypto_1.randomBytes)(16);
207
+ random.copy(data, 28);
208
+ const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
209
+ return '3EB0' + hash.toString('hex').toUpperCase().substring(0, 18);
210
+ };
211
+ exports.generateMessageIDV2 = generateMessageIDV2;
212
+ // generate a random ID to attach to a message
213
+ const generateMessageID = () => 'ILSYM-' + (0, crypto_1.randomBytes)(6).toString('hex').toUpperCase();
214
+ exports.generateMessageID = generateMessageID;
215
+ function bindWaitForEvent(ev, event) {
216
+ return async (check, timeoutMs) => {
217
+ let listener;
218
+ let closeListener;
219
+ await (promiseTimeout(timeoutMs, (resolve, reject) => {
220
+ closeListener = ({ connection, lastDisconnect }) => {
221
+ if (connection === 'close') {
222
+ reject((lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error)
223
+ || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }));
224
+ }
225
+ };
226
+ ev.on('connection.update', closeListener);
227
+ listener = (update) => {
228
+ if (check(update)) {
229
+ resolve();
230
+ }
231
+ };
232
+ ev.on(event, listener);
233
+ })
234
+ .finally(() => {
235
+ ev.off(event, listener);
236
+ ev.off('connection.update', closeListener);
237
+ }));
238
+ };
239
+ }
240
+ exports.bindWaitForEvent = bindWaitForEvent;
241
+ const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
242
+ exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
243
+ const printQRIfNecessaryListener = (ev, logger) => {
244
+ ev.on('connection.update', async ({ qr }) => {
245
+ if (qr) {
246
+ const QR = await import('qrcode-terminal')
247
+ .then(m => m.default || m)
248
+ .catch(() => {
249
+ logger.error('QR code terminal not added as dependency');
250
+ });
251
+ QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
252
+ }
253
+ });
254
+ };
255
+ exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
256
+ /**
257
+ * utility that fetches latest baileys version from the master branch.
258
+ * Use to ensure your WA connection is always on the latest version
259
+ */
260
+ const fetchLatestWaWebVersion = async (options = {}) => {
261
+ try {
262
+ const defaultHeaders = {
263
+ 'User-Agent':
264
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
265
+ 'Accept': '*/*'
266
+ }
267
+
268
+ const headers = { ...defaultHeaders, ...options.headers }
269
+
270
+ const response = await fetch_1('https://web.whatsapp.com/sw.js', {
271
+ method: 'GET',
272
+ headers
273
+ })
274
+
275
+ if (!response.ok) {
276
+ throw new Error(`Failed to fetch sw.js: ${response.status} ${response.statusText}`)
277
+ }
278
+
279
+ const data = await response.text()
280
+ const regex = /"client_revision":\s*(\d+)/ // regex cukup begini untuk Node
281
+ const match = data.match(regex)
282
+
283
+ if (!match || !match[1]) {
284
+ return {
285
+ version: baileysVersion,
286
+ isLatest: false,
287
+ error: { message: 'Client revision not found' }
288
+ }
289
+ }
290
+
291
+ const clientRevision = match[1]
292
+ return {
293
+ version: [2, 3000, +clientRevision],
294
+ isLatest: true
295
+ }
296
+ } catch (error) {
297
+ return {
298
+ version: baileysVersion,
299
+ isLatest: false,
300
+ error
301
+ }
302
+ }
303
+ }
304
+ exports.fetchLatestWaWebVersion = fetchLatestWaWebVersion;
305
+ /**
306
+ * utility that fetches latest baileys version from the master branch.
307
+ * Use to ensure your WA connection is always on the latest version
308
+ */
309
+ const fetchLatestBaileysVersion = async (options = {}) => {
310
+ const URL = 'https://raw.githubusercontent.com/kiuur/baileys/master/src/Defaults/baileys-version.json';
311
+ try {
312
+ const result = await axios_1.default.get(URL, {
313
+ ...options,
314
+ responseType: 'json'
315
+ });
316
+ return {
317
+ version: result.data.version,
318
+ isLatest: true
319
+ };
320
+ }
321
+ catch (error) {
322
+ return {
323
+ version: baileys_version_json_1.version,
324
+ isLatest: false,
325
+ error
326
+ };
327
+ }
328
+ };
329
+ exports.fetchLatestBaileysVersion = fetchLatestBaileysVersion;
330
+ /** unique message tag prefix for MD clients */
331
+ const generateMdTagPrefix = () => {
332
+ const bytes = (0, crypto_1.randomBytes)(4);
333
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`;
334
+ };
335
+ exports.generateMdTagPrefix = generateMdTagPrefix;
336
+ const STATUS_MAP = {
337
+ 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
338
+ 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
339
+ 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
340
+ };
341
+ /**
342
+ * Given a type of receipt, returns what the new status of the message should be
343
+ * @param type type from receipt
344
+ */
345
+ const getStatusFromReceiptType = (type) => {
346
+ const status = STATUS_MAP[type];
347
+ if (typeof type === 'undefined') {
348
+ return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK;
349
+ }
350
+ return status;
351
+ };
352
+ exports.getStatusFromReceiptType = getStatusFromReceiptType;
353
+ const CODE_MAP = {
354
+ conflict: Types_1.DisconnectReason.connectionReplaced
355
+ };
356
+ /**
357
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
358
+ * @param reason the string reason given, eg. "conflict"
359
+ */
360
+ const getErrorCodeFromStreamError = (node) => {
361
+ const [reasonNode] = (0, WABinary_1.getAllBinaryNodeChildren)(node);
362
+ let reason = (reasonNode === null || reasonNode === void 0 ? void 0 : reasonNode.tag) || 'unknown';
363
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession);
364
+ if (statusCode === Types_1.DisconnectReason.restartRequired) {
365
+ reason = 'restart required';
366
+ }
367
+ return {
368
+ reason,
369
+ statusCode
370
+ };
371
+ };
372
+ exports.getErrorCodeFromStreamError = getErrorCodeFromStreamError;
373
+ const getCallStatusFromNode = ({ tag, attrs }) => {
374
+ let status;
375
+ switch (tag) {
376
+ case 'offer':
377
+ case 'offer_notice':
378
+ status = 'offer';
379
+ break;
380
+ case 'terminate':
381
+ if (attrs.reason === 'timeout') {
382
+ status = 'timeout';
383
+ }
384
+ else {
385
+ status = 'reject';
386
+ }
387
+ break;
388
+ case 'reject':
389
+ status = 'reject';
390
+ break;
391
+ case 'accept':
392
+ status = 'accept';
393
+ break;
394
+ default:
395
+ status = 'ringing';
396
+ break;
397
+ }
398
+ return status;
399
+ };
400
+ exports.getCallStatusFromNode = getCallStatusFromNode;
401
+ const UNEXPECTED_SERVER_CODE_TEXT = 'Unexpected server response: ';
402
+ const getCodeFromWSError = (error) => {
403
+ var _a, _b, _c;
404
+ let statusCode = 500;
405
+ if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes(UNEXPECTED_SERVER_CODE_TEXT)) {
406
+ const code = +(error === null || error === void 0 ? void 0 : error.message.slice(UNEXPECTED_SERVER_CODE_TEXT.length));
407
+ if (!Number.isNaN(code) && code >= 400) {
408
+ statusCode = code;
409
+ }
410
+ }
411
+ else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
412
+ || ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc
413
+ statusCode = 408;
414
+ }
415
+ return statusCode;
416
+ };
417
+ exports.getCodeFromWSError = getCodeFromWSError;
418
+ /**
419
+ * Is the given platform WA business
420
+ * @param platform AuthenticationCreds.platform
421
+ */
422
+ const isWABusinessPlatform = (platform) => {
423
+ return platform === 'smbi' || platform === 'smba';
424
+ };
425
+ exports.isWABusinessPlatform = isWABusinessPlatform;
426
+ function trimUndefined(obj) {
427
+ for (const key in obj) {
428
+ if (typeof obj[key] === 'undefined') {
429
+ delete obj[key];
430
+ }
431
+ }
432
+ return obj;
433
+ }
434
+ exports.trimUndefined = trimUndefined;
435
+ const CROCKFORD_CHARACTERS = '123456789ABCDEFGHJKLMNPQRSTVWXYZ';
436
+ function bytesToCrockford(buffer) {
437
+ let value = 0;
438
+ let bitCount = 0;
439
+ const crockford = [];
440
+ for (let i = 0; i < buffer.length; i++) {
441
+ value = (value << 8) | (buffer[i] & 0xff);
442
+ bitCount += 8;
443
+ while (bitCount >= 5) {
444
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value >>> (bitCount - 5)) & 31));
445
+ bitCount -= 5;
446
+ }
447
+ }
448
+ if (bitCount > 0) {
449
+ crockford.push(CROCKFORD_CHARACTERS.charAt((value << (5 - bitCount)) & 31));
450
+ }
451
+ return crockford.join('');
452
+ }
453
+ exports.bytesToCrockford = bytesToCrockford;
454
+ const encodeNewsletterMessage = (message) => {
455
+ return WAProto_1.proto.Message.encode(message).finish()
456
+ }
457
+ exports.encodeNewsletterMessage = encodeNewsletterMessage;
@@ -0,0 +1,15 @@
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
+ chats: Chat[];
7
+ contacts: Contact[];
8
+ messages: proto.IWebMessageInfo[];
9
+ };
10
+ export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<{
11
+ chats: Chat[];
12
+ contacts: Contact[];
13
+ messages: proto.IWebMessageInfo[];
14
+ }>;
15
+ export declare const getHistoryMsg: (message: proto.IMessage) => proto.Message.IHistorySyncNotification | null | undefined;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getHistoryMsg = exports.downloadAndProcessHistorySyncNotification = exports.processHistoryMessage = exports.downloadHistory = void 0;
4
+ const util_1 = require("util");
5
+ const zlib_1 = require("zlib");
6
+ const WAProto_1 = require("../../WAProto");
7
+ const Types_1 = require("../Types");
8
+ const WABinary_1 = require("../WABinary");
9
+ const generics_1 = require("./generics");
10
+ const messages_1 = require("./messages");
11
+ const messages_media_1 = require("./messages-media");
12
+ const inflatePromise = (0, util_1.promisify)(zlib_1.inflate);
13
+ const downloadHistory = async (msg, options) => {
14
+ const stream = await (0, messages_media_1.downloadContentFromMessage)(msg, 'md-msg-hist', { options });
15
+ const bufferArray = [];
16
+ for await (const chunk of stream) {
17
+ bufferArray.push(chunk);
18
+ }
19
+ let buffer = Buffer.concat(bufferArray);
20
+ // decompress buffer
21
+ buffer = await inflatePromise(buffer);
22
+ const syncData = WAProto_1.proto.HistorySync.decode(buffer);
23
+ return syncData;
24
+ };
25
+ exports.downloadHistory = downloadHistory;
26
+ const processHistoryMessage = (item) => {
27
+ var _a, _b, _c;
28
+ const messages = [];
29
+ const contacts = [];
30
+ const chats = [];
31
+ switch (item.syncType) {
32
+ case WAProto_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
33
+ case WAProto_1.proto.HistorySync.HistorySyncType.RECENT:
34
+ case WAProto_1.proto.HistorySync.HistorySyncType.FULL:
35
+ for (const chat of item.conversations) {
36
+ contacts.push({
37
+ id: chat.id,
38
+ name: chat.name || undefined,
39
+ lid: chat.lidJid || undefined,
40
+ jid: (0, WABinary_1.isJidUser)(chat.id) ? chat.id : undefined
41
+ });
42
+ const msgs = chat.messages || [];
43
+ delete chat.messages;
44
+ delete chat.archived;
45
+ delete chat.muteEndTime;
46
+ delete chat.pinned;
47
+ for (const item of msgs) {
48
+ const message = item.message;
49
+ messages.push(message);
50
+ if (!((_a = chat.messages) === null || _a === void 0 ? void 0 : _a.length)) {
51
+ // keep only the most recent message in the chat array
52
+ chat.messages = [{ message }];
53
+ }
54
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
55
+ chat.lastMessageRecvTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
56
+ }
57
+ if ((message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP
58
+ || message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB)
59
+ && ((_b = message.messageStubParameters) === null || _b === void 0 ? void 0 : _b[0])) {
60
+ contacts.push({
61
+ id: message.key.participant || message.key.remoteJid,
62
+ verifiedName: (_c = message.messageStubParameters) === null || _c === void 0 ? void 0 : _c[0],
63
+ });
64
+ }
65
+ }
66
+ if ((0, WABinary_1.isJidUser)(chat.id) && chat.readOnly && chat.archived) {
67
+ delete chat.readOnly;
68
+ }
69
+ chats.push({ ...chat });
70
+ }
71
+ break;
72
+ case WAProto_1.proto.HistorySync.HistorySyncType.PUSH_NAME:
73
+ for (const c of item.pushnames) {
74
+ contacts.push({ id: c.id, notify: c.pushname });
75
+ }
76
+ break;
77
+ }
78
+ return {
79
+ chats,
80
+ contacts,
81
+ messages,
82
+ };
83
+ };
84
+ exports.processHistoryMessage = processHistoryMessage;
85
+ const downloadAndProcessHistorySyncNotification = async (msg, options) => {
86
+ const historyMsg = await (0, exports.downloadHistory)(msg, options);
87
+ return (0, exports.processHistoryMessage)(historyMsg);
88
+ };
89
+ exports.downloadAndProcessHistorySyncNotification = downloadAndProcessHistorySyncNotification;
90
+ const getHistoryMsg = (message) => {
91
+ var _a;
92
+ const normalizedContent = !!message ? (0, messages_1.normalizeMessageContent)(message) : undefined;
93
+ const anyHistoryMsg = (_a = normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage) === null || _a === void 0 ? void 0 : _a.historySyncNotification;
94
+ return anyHistoryMsg;
95
+ };
96
+ exports.getHistoryMsg = getHistoryMsg;
@@ -0,0 +1,17 @@
1
+ export * from './generics';
2
+ export * from './decode-wa-message';
3
+ export * from './messages';
4
+ export * from './messages-media';
5
+ export * from './validate-connection';
6
+ export * from './crypto';
7
+ export * from './signal';
8
+ export * from './noise-handler';
9
+ export * from './history';
10
+ export * from './chat-utils';
11
+ export * from './lt-hash';
12
+ export * from './auth-utils';
13
+ export * from './baileys-event-stream';
14
+ export * from './use-multi-file-auth-state';
15
+ export * from './link-preview';
16
+ export * from './event-buffer';
17
+ export * from './process-message';
@@ -0,0 +1,35 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./generics"), exports);
18
+ __exportStar(require("./decode-wa-message"), exports);
19
+ __exportStar(require("./messages"), exports);
20
+ __exportStar(require("./messages-media"), exports);
21
+ __exportStar(require("./validate-connection"), exports);
22
+ __exportStar(require("./crypto"), exports);
23
+ __exportStar(require("./signal"), exports);
24
+ __exportStar(require("./noise-handler"), exports);
25
+ __exportStar(require("./history"), exports);
26
+ __exportStar(require("./chat-utils"), exports);
27
+ __exportStar(require("./lt-hash"), exports);
28
+ __exportStar(require("./auth-utils"), exports);
29
+ __exportStar(require("./baileys-event-stream"), exports);
30
+ __exportStar(require("./use-multi-file-auth-state"), exports);
31
+ __exportStar(require("./link-preview"), exports);
32
+ __exportStar(require("./event-buffer"), exports);
33
+ __exportStar(require("./process-message"), exports);
34
+ __exportStar(require("./mention"), exports);
35
+ __exportStar(require("./lid-resolver"), exports);