sanka-baileyss 2.2.8 → 2.3.0

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.
@@ -1,31 +1,37 @@
1
1
  "use strict"
2
+
2
3
  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)
4
+ if (k2 === undefined) k2 = k
5
+ var desc = Object.getOwnPropertyDescriptor(m, k)
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k] } }
8
+ }
9
+ Object.defineProperty(o, k2, desc)
9
10
  }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k
11
- o[k2] = m[k]
11
+ if (k2 === undefined) k2 = k
12
+ o[k2] = m[k]
12
13
  }))
14
+
13
15
  var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v })
16
+ Object.defineProperty(o, "default", { enumerable: true, value: v })
15
17
  }) : function(o, v) {
16
- o["default"] = v
18
+ o["default"] = v
17
19
  })
20
+
18
21
  var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod
20
- var result = {}
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k)
22
- __setModuleDefault(result, mod)
23
- return result
22
+ if (mod && mod.__esModule) return mod
23
+ var result = {}
24
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k)
25
+ __setModuleDefault(result, mod)
26
+ return result
24
27
  }
28
+
25
29
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod }
30
+ return (mod && mod.__esModule) ? mod : { "default": mod }
27
31
  }
32
+
28
33
  Object.defineProperty(exports, "__esModule", { value: true })
34
+
29
35
  const boom_1 = require("@hapi/boom")
30
36
  const axios_1 = __importDefault(require("axios"))
31
37
  const crypto_1 = require("crypto")
@@ -34,520 +40,526 @@ const WAProto_1 = require("../../WAProto")
34
40
  const baileys_version_json_1 = require("../Defaults/baileys-version.json")
35
41
  const Types_1 = require("../Types")
36
42
  const WABinary_1 = require("../WABinary")
43
+
37
44
  const COMPANION_PLATFORM_MAP = {
38
- 'Chrome': '49',
39
- 'Edge': '50',
40
- 'Firefox': '51',
41
- 'Opera': '53',
42
- 'Safari': '54',
43
- 'Brave': '1.79.112',
44
- 'Vivaldi': '6.2.3105.58',
45
- 'Tor': '12.5.3',
46
- 'Yandex': '23.7.1',
47
- 'Falkon': '22.08.3',
48
- 'Epiphany': '44.2'
49
- }
45
+ 'Chrome': '49',
46
+ 'Edge': '50',
47
+ 'Firefox': '51',
48
+ 'Opera': '53',
49
+ 'Safari': '54',
50
+ 'Brave': '1.79.112',
51
+ 'Vivaldi': '6.2.3105.58',
52
+ 'Tor': '12.5.3',
53
+ 'Yandex': '23.7.1',
54
+ 'Falkon': '22.08.3',
55
+ 'Epiphany': '44.2'
56
+ }
57
+
50
58
  const PLATFORM_MAP = {
51
- 'aix': 'AIX',
52
- 'darwin': 'Mac OS',
53
- 'win32': 'Windows',
54
- 'android': 'Android',
55
- 'freebsd': 'FreeBSD',
56
- 'openbsd': 'OpenBSD',
57
- 'sunos': 'Solaris',
58
- 'linux': 'Linux',
59
- 'ubuntu': 'Ubuntu',
60
- 'ios': 'iOS',
61
- 'baileys': 'Baileys',
62
- 'chromeos': 'Chrome OS',
63
- 'tizen': 'Tizen',
64
- 'watchos': 'watchOS',
65
- 'wearos': 'Wear OS',
66
- 'harmonyos': 'HarmonyOS',
67
- 'kaios': 'KaiOS',
68
- 'smarttv': 'Smart TV',
69
- 'raspberrypi': 'Raspberry Pi OS',
70
- 'symbian': 'Symbian',
71
- 'blackberry': 'Blackberry OS',
72
- 'windowsphone': 'Windows Phone'
73
- }
59
+ 'aix': 'AIX',
60
+ 'darwin': 'Mac OS',
61
+ 'win32': 'Windows',
62
+ 'android': 'Android',
63
+ 'freebsd': 'FreeBSD',
64
+ 'openbsd': 'OpenBSD',
65
+ 'sunos': 'Solaris',
66
+ 'linux': 'Linux',
67
+ 'ubuntu': 'Ubuntu',
68
+ 'ios': 'iOS',
69
+ 'baileys': 'Baileys',
70
+ 'chromeos': 'Chrome OS',
71
+ 'tizen': 'Tizen',
72
+ 'watchos': 'watchOS',
73
+ 'wearos': 'Wear OS',
74
+ 'harmonyos': 'HarmonyOS',
75
+ 'kaios': 'KaiOS',
76
+ 'smarttv': 'Smart TV',
77
+ 'raspberrypi': 'Raspberry Pi OS',
78
+ 'symbian': 'Symbian',
79
+ 'blackberry': 'Blackberry OS',
80
+ 'windowsphone': 'Windows Phone'
81
+ }
82
+
74
83
  const PLATFORM_VERSIONS = {
75
- 'ubuntu': '22.04.4',
76
- 'darwin': '14.4.1',
77
- 'win32': '10.0.22631',
78
- 'android': '14.0.0',
79
- 'freebsd': '13.2',
80
- 'openbsd': '7.3',
81
- 'sunos': '11',
82
- 'linux': '6.5',
83
- 'ios': '18.2',
84
- 'baileys': '6.5.0',
85
- 'chromeos': '117.0.5938.132',
86
- 'tizen': '6.5',
87
- 'watchos': '10.1',
88
- 'wearos': '4.1',
89
- 'harmonyos': '4.0.0',
90
- 'kaios': '3.1',
91
- 'smarttv': '23.3.1',
92
- 'raspberrypi': '11 (Bullseye)',
93
- 'symbian': '3',
94
- 'blackberry': '10.3.3',
95
- 'windowsphone': '8.1'
96
- }
84
+ 'ubuntu': '22.04.4',
85
+ 'darwin': '18.5',
86
+ 'win32': '10.0.22631',
87
+ 'android': '14.0.0',
88
+ 'freebsd': '13.2',
89
+ 'openbsd': '7.3',
90
+ 'sunos': '11',
91
+ 'linux': '6.5',
92
+ 'ios': '18.2',
93
+ 'baileys': '6.5.0',
94
+ 'chromeos': '117.0.5938.132',
95
+ 'tizen': '6.5',
96
+ 'watchos': '10.1',
97
+ 'wearos': '4.1',
98
+ 'harmonyos': '4.0.0',
99
+ 'kaios': '3.1',
100
+ 'smarttv': '23.3.1',
101
+ 'raspberrypi': '11 (Bullseye)',
102
+ 'symbian': '3',
103
+ 'blackberry': '10.3.3',
104
+ 'windowsphone': '8.1'
105
+ }
106
+
97
107
  const Browsers = {
98
- ubuntu: (browser) => {
99
- return [PLATFORM_MAP['ubuntu'], browser, PLATFORM_VERSIONS['ubuntu']]
100
- },
101
- macOS: (browser) => {
102
- return [PLATFORM_MAP['darwin'], browser, PLATFORM_VERSIONS['darwin']]
103
- },
104
- windows: (browser) => {
105
- return [PLATFORM_MAP['win32'], browser, PLATFORM_VERSIONS['win32']]
106
- },
107
- linux: (browser) => {
108
- return [PLATFORM_MAP['linux'], browser, PLATFORM_VERSIONS['linux']]
109
- },
110
- solaris: (browser) => {
111
- return [PLATFORM_MAP['sunos'], browser, PLATFORM_VERSIONS['sunos']]
112
- },
113
- baileys: (browser) => {
114
- return [PLATFORM_MAP['baileys'], browser, PLATFORM_VERSIONS['baileys']]
115
- },
116
- android: (browser) => {
117
- return [PLATFORM_MAP['android'], browser, PLATFORM_VERSIONS['android']]
118
- },
119
- iOS: (browser) => {
120
- return [PLATFORM_MAP['ios'], browser, PLATFORM_VERSIONS['ios']]
121
- },
122
- kaiOS: (browser) => {
123
- return [PLATFORM_MAP['kaios'], browser, PLATFORM_VERSIONS['kaios']]
124
- },
125
- chromeOS: (browser) => {
126
- return [PLATFORM_MAP['chromeos'], browser, PLATFORM_VERSIONS['chromeos']]
127
- },
128
- appropriate: (browser) => {
129
- const platform = os_1.platform()
130
- const platformName = PLATFORM_MAP[platform] || 'Unknown OS'
131
- return [platformName, browser, PLATFORM_VERSIONS[platform] || 'latest']
132
- },
133
- custom: (platform, browser, version) => {
134
- const platformName = PLATFORM_MAP[platform.toLowerCase()] || platform
135
- return [platformName, browser, version || PLATFORM_VERSIONS[platform] || 'latest']
136
- }
137
- }
138
- const IZUMI = async () => {
139
- try {
140
- const { data } = await axios_1.default.get('https://raw.githubusercontent.com/Itsukichann/database/refs/heads/main/itsuki.json', {
141
- responseType: 'json'
142
- })
143
- if (Array.isArray(data)) {
144
- const naruyaizumi = data[Math.floor(Math.random() * data.length)]
145
- return naruyaizumi
146
- } else {
147
- throw new boom_1.Boom('Data is not in array format.')
148
- }
149
- } catch (error) {
150
- throw new boom_1.Boom(error.message)
151
- }
152
- }
108
+ ubuntu: (browser) => {
109
+ return [PLATFORM_MAP['ubuntu'], browser, PLATFORM_VERSIONS['ubuntu']]
110
+ },
111
+ macOS: (browser) => {
112
+ return [PLATFORM_MAP['darwin'], browser, PLATFORM_VERSIONS['darwin']]
113
+ },
114
+ windows: (browser) => {
115
+ return [PLATFORM_MAP['win32'], browser, PLATFORM_VERSIONS['win32']]
116
+ },
117
+ linux: (browser) => {
118
+ return [PLATFORM_MAP['linux'], browser, PLATFORM_VERSIONS['linux']]
119
+ },
120
+ solaris: (browser) => {
121
+ return [PLATFORM_MAP['sunos'], browser, PLATFORM_VERSIONS['sunos']]
122
+ },
123
+ baileys: (browser) => {
124
+ return [PLATFORM_MAP['baileys'], browser, PLATFORM_VERSIONS['baileys']]
125
+ },
126
+ android: (browser) => {
127
+ return [PLATFORM_MAP['android'], browser, PLATFORM_VERSIONS['android']]
128
+ },
129
+ iOS: (browser) => {
130
+ return [PLATFORM_MAP['ios'], browser, PLATFORM_VERSIONS['ios']]
131
+ },
132
+ kaiOS: (browser) => {
133
+ return [PLATFORM_MAP['kaios'], browser, PLATFORM_VERSIONS['kaios']]
134
+ },
135
+ chromeOS: (browser) => {
136
+ return [PLATFORM_MAP['chromeos'], browser, PLATFORM_VERSIONS['chromeos']]
137
+ },
138
+ appropriate: (browser) => {
139
+ const platform = os_1.platform()
140
+ const platformName = PLATFORM_MAP[platform] || 'Unknown OS'
141
+ return [platformName, browser, PLATFORM_VERSIONS[platform] || 'latest']
142
+ },
143
+ custom: (platform, browser, version) => {
144
+ const platformName = PLATFORM_MAP[platform.toLowerCase()] || platform
145
+ return [platformName, browser, version || PLATFORM_VERSIONS[platform] || 'latest']
146
+ }
147
+ }
148
+
149
+ const Itsuki = async () => {
150
+ try {
151
+ const { data } = await axios_1.default.get('https://raw.githubusercontent.com/Itsukichann/database/refs/heads/main/itsuki.json', {
152
+ responseType: 'json'
153
+ })
154
+ if (Array.isArray(data)) {
155
+ const itsukichann = data[Math.floor(Math.random() * data.length)]
156
+ return itsukichann
157
+ } else {
158
+ throw new boom_1.Boom('Data is not in array format.')
159
+ }
160
+ } catch (error) {
161
+ throw new boom_1.Boom(error.message)
162
+ }
163
+ }
164
+
153
165
  const BufferJSON = {
154
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
155
- replacer: (k, value) => {
156
- if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
157
- return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
158
- }
159
- return value
160
- },
161
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
162
- reviver: (_, value) => {
163
- if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
164
- const val = value.data || value.value
165
- return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || [])
166
- }
167
- return value
168
- }
169
- }
166
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
167
+ replacer: (k, value) => {
168
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
169
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
170
+ }
171
+ return value
172
+ },
173
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
174
+ reviver: (_, value) => {
175
+ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
176
+ const val = value.data || value.value
177
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || [])
178
+ }
179
+ return value
180
+ }
181
+ }
182
+
170
183
  const getPlatformId = (browser) => {
171
- const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()]
172
- return platformType ? platformType.toString() : '1'
184
+ const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()]
185
+ return platformType ? platformType.toString() : '1'
173
186
  }
187
+
174
188
  const getKeyAuthor = (key, meId = 'me') => {
175
- return key?.fromMe ? meId : key?.participant || key?.remoteJid || ''
189
+ return key?.fromMe ? meId : key?.participant || key?.remoteJid || ''
176
190
  }
191
+
177
192
  const writeRandomPadMax16 = (msg) => {
178
- const pad = crypto_1.randomBytes(1)
179
- pad[0] &= 0xf
180
- if (!pad[0]) {
181
- pad[0] = 0xf
182
- }
183
- return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])])
184
- }
193
+ const pad = crypto_1.randomBytes(1)
194
+ pad[0] &= 0xf
195
+ if (!pad[0]) {
196
+ pad[0] = 0xf
197
+ }
198
+ return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])])
199
+ }
200
+
185
201
  const unpadRandomMax16 = (e) => {
186
- const t = new Uint8Array(e)
187
- if (0 === t.length) {
188
- throw new Error('unpadPkcs7 given empty bytes')
189
- }
190
- var r = t[t.length - 1]
191
- if (r > t.length) {
192
- throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`)
193
- }
194
- return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
195
- }
202
+ const t = new Uint8Array(e)
203
+ if (0 === t.length) {
204
+ throw new Error('unpadPkcs7 given empty bytes')
205
+ }
206
+ var r = t[t.length - 1]
207
+ if (r > t.length) {
208
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`)
209
+ }
210
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
211
+ }
212
+
196
213
  const encodeWAMessage = (message) => {
197
- return writeRandomPadMax16(WAProto_1.proto.Message.encode(message).finish())
214
+ return writeRandomPadMax16(WAProto_1.proto.Message.encode(message).finish())
198
215
  }
216
+
199
217
  const encodeNewsletterMessage = (message) => {
200
- return WAProto_1.proto.Message.encode(message).finish()
218
+ return WAProto_1.proto.Message.encode(message).finish()
201
219
  }
220
+
202
221
  const generateRegistrationId = () => {
203
- return Uint16Array.from(crypto_1.randomBytes(2))[0] & 16383
222
+ return Uint16Array.from(crypto_1.randomBytes(2))[0] & 16383
204
223
  }
224
+
205
225
  const encodeBigEndian = (e, t = 4) => {
206
- let r = e
207
- const a = new Uint8Array(t)
208
- for (let i = t - 1; i >= 0; i--) {
209
- a[i] = 255 & r
210
- r >>>= 8
211
- }
212
- return a
213
- }
226
+ let r = e
227
+ const a = new Uint8Array(t)
228
+ for (let i = t - 1; i >= 0; i--) {
229
+ a[i] = 255 & r
230
+ r >>>= 8
231
+ }
232
+ return a
233
+ }
234
+
214
235
  const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0)
236
+
215
237
  /** unix timestamp of a date in seconds */
216
238
  const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000)
239
+
217
240
  const debouncedTimeout = (intervalMs = 1000, task) => {
218
- let timeout
219
- return {
220
- start: (newIntervalMs, newTask) => {
221
- task = newTask || task
222
- intervalMs = newIntervalMs || intervalMs
223
- timeout && clearTimeout(timeout)
224
- timeout = setTimeout(() => task?.(), intervalMs)
225
- },
226
- cancel: () => {
227
- timeout && clearTimeout(timeout)
228
- timeout = undefined
229
- },
230
- setTask: (newTask) => task = newTask,
231
- setInterval: (newInterval) => intervalMs = newInterval
232
- }
233
- }
241
+ let timeout
242
+ return {
243
+ start: (newIntervalMs, newTask) => {
244
+ task = newTask || task
245
+ intervalMs = newIntervalMs || intervalMs
246
+ timeout && clearTimeout(timeout)
247
+ timeout = setTimeout(() => task?.(), intervalMs)
248
+ },
249
+ cancel: () => {
250
+ timeout && clearTimeout(timeout)
251
+ timeout = undefined
252
+ },
253
+ setTask: (newTask) => task = newTask,
254
+ setInterval: (newInterval) => intervalMs = newInterval
255
+ }
256
+ }
257
+
234
258
  const delay = (ms) => {
235
- return delayCancellable(ms).delay
259
+ return delayCancellable(ms).delay
236
260
  }
261
+
237
262
  const delayCancellable = (ms) => {
238
- const stack = new Error().stack
239
- let timeout
240
- let reject
241
- const delay = new Promise((resolve, _reject) => {
242
- timeout = setTimeout(resolve, ms)
243
- reject = _reject
244
- })
245
- const cancel = () => {
246
- clearTimeout(timeout)
247
- reject(new boom_1.Boom('Cancelled', {
248
- statusCode: 500,
249
- data: {
250
- stack
251
- }
252
- }))
253
- }
254
- return { delay, cancel }
255
- }
263
+ const stack = new Error().stack
264
+ let timeout
265
+ let reject
266
+ const delay = new Promise((resolve, _reject) => {
267
+ timeout = setTimeout(resolve, ms)
268
+ reject = _reject
269
+ })
270
+ const cancel = () => {
271
+ clearTimeout(timeout)
272
+ reject(new boom_1.Boom('Cancelled', {
273
+ statusCode: 500,
274
+ data: {
275
+ stack
276
+ }
277
+ }))
278
+ }
279
+ return { delay, cancel }
280
+ }
281
+
256
282
  async function promiseTimeout(ms, promise) {
257
- if (!ms) {
258
- return new Promise(promise)
259
- }
260
- const stack = new Error().stack
261
- // Create a promise that rejects in <ms> milliseconds
262
- const { delay, cancel } = delayCancellable(ms)
263
- const p = new Promise((resolve, reject) => {
264
- delay.then(() => reject(new boom_1.Boom('Timed Out', {
265
- statusCode: Types_1.DisconnectReason.timedOut,
266
- data: {
267
- stack
268
- }
269
- }))).catch(err => reject(err))
270
- promise(resolve, reject)
271
- }).finally(cancel)
272
- return p
273
- }
283
+ if (!ms) {
284
+ return new Promise(promise)
285
+ }
286
+ const stack = new Error().stack
287
+ // Create a promise that rejects in <ms> milliseconds
288
+ const { delay, cancel } = delayCancellable(ms)
289
+ const p = new Promise((resolve, reject) => {
290
+ delay.then(() => reject(new boom_1.Boom('Timed Out', {
291
+ statusCode: Types_1.DisconnectReason.timedOut,
292
+ data: {
293
+ stack
294
+ }
295
+ }))).catch(err => reject(err))
296
+ promise(resolve, reject)
297
+ }).finally(cancel)
298
+ return p
299
+ }
300
+
274
301
  const generateMessageID = (userId) => {
275
- const data = Buffer.alloc(8 + 20 + 16);
276
- data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)));
277
- if (userId) {
278
- const id = (0, WABinary_1.jidDecode)(userId);
279
- if (id === null || id === void 0 ? void 0 : id.user) {
280
- data.write(id.user, 8);
281
- data.write('@c.us', 8 + id.user.length);
282
- }
283
- }
284
- const random = (0, crypto_1.randomBytes)(16);
285
- random.copy(data, 28);
286
- const sha = asciiDecode([ 83, 65, 78, 75, 65, 45 ]);
287
- const hash = (0, crypto_1.createHash)('sha256').update(data).digest();
288
- return sha + crypto_1.randomBytes(5).toString('hex').toUpperCase();
289
- };
290
- exports.generateMessageID = generateMessageID;
302
+ const data = Buffer.alloc(8 + 20 + 16)
303
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
304
+ if (userId) {
305
+ const id = WABinary_1.jidDecode(userId)
306
+ if (id?.user) {
307
+ data.write(id.user, 8)
308
+ data.write('@c.us', 8 + id.user.length)
309
+ }
310
+ }
311
+ const random = (0, crypto_1.randomBytes)(16)
312
+ random.copy(data, 28)
313
+ const sha = asciiDecode([ 83, 65, 78, 75, 65, 45 ])
314
+ const hash = crypto_1.createHash('sha256').update(data).digest()
315
+ return sha + crypto_1.randomBytes(5).toString('hex').toUpperCase();
316
+ }
317
+
291
318
  function bindWaitForEvent(ev, event) {
292
- return async (check, timeoutMs) => {
293
- let listener
294
- let closeListener
295
- await (promiseTimeout(timeoutMs, (resolve, reject) => {
296
- closeListener = ({ connection, lastDisconnect }) => {
297
- if (connection === 'close') {
298
- reject((lastDisconnect?.error)
299
- || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }))
300
- }
301
- }
302
- ev.on('connection.update', closeListener)
303
- listener = async (update) => {
304
- if (await check(update)) {
305
- resolve()
306
- }
307
- }
308
- ev.on(event, listener)
309
- }).finally(() => {
310
- ev.off(event, listener)
311
- ev.off('connection.update', closeListener)
312
- }))
313
- }
314
- }
319
+ return async (check, timeoutMs) => {
320
+ let listener
321
+ let closeListener
322
+ await (promiseTimeout(timeoutMs, (resolve, reject) => {
323
+ closeListener = ({ connection, lastDisconnect }) => {
324
+ if (connection === 'close') {
325
+ reject((lastDisconnect?.error)
326
+ || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }))
327
+ }
328
+ }
329
+ ev.on('connection.update', closeListener)
330
+ listener = async (update) => {
331
+ if (await check(update)) {
332
+ resolve()
333
+ }
334
+ }
335
+ ev.on(event, listener)
336
+ }).finally(() => {
337
+ ev.off(event, listener)
338
+ ev.off('connection.update', closeListener)
339
+ }))
340
+ }
341
+ }
342
+
315
343
  const bindWaitForConnectionUpdate = (ev) => {
316
- return bindWaitForEvent(ev, 'connection.update')
344
+ return bindWaitForEvent(ev, 'connection.update')
317
345
  }
346
+
318
347
  const printQRIfNecessaryListener = (ev, logger) => {
319
- ev.on('connection.update', async ({ qr }) => {
320
- if (qr) {
321
- const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).then(m => m.default || m)
322
- .catch(() => {
323
- logger.error('QR code terminal not added as dependency')
324
- })
325
- QR?.generate(qr, { small: true })
326
- }
327
- })
328
- }
348
+ ev.on('connection.update', async ({ qr }) => {
349
+ if (qr) {
350
+ const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).then(m => m.default || m)
351
+ .catch(() => {
352
+ logger.error('QR code terminal not added as dependency')
353
+ })
354
+ QR?.generate(qr, { small: true })
355
+ }
356
+ })
357
+ }
358
+
329
359
  /**
330
- * utility that fetches latest baileys version from the master branch.
331
- * Use to ensure your WA connection is always on the latest version
332
- */
360
+ * utility that fetches latest baileys version from the master branch.
361
+ * Use to ensure your WA connection is always on the latest version
362
+ */
333
363
  const fetchLatestBaileysVersion = async (options = {}) => {
334
- const URL = 'https://raw.githubusercontent.com/Itsukichann/Baileys/refs/heads/master/lib/Defaults/baileys-version.json'
335
- try {
336
- const result = await axios_1.default.get(URL, {
337
- ...options,
338
- responseType: 'json'
339
- })
340
- return {
341
- version: result.data.version,
342
- isLatest: true
343
- }
344
- }
345
- catch (error) {
346
- return {
347
- version: baileys_version_json_1.version,
348
- isLatest: false,
349
- error
350
- }
351
- }
352
- }
353
- /**
354
- * A utility that fetches the latest web version of whatsapp.
355
- * Use to ensure your WA connection is always on the latest version
356
- */
357
- const fetchLatestWaWebVersion = async (options) => {
358
- try {
359
- const { data } = await axios_1.default.get('https://web.whatsapp.com/sw.js', {
360
- ...options,
361
- responseType: 'json'
362
- })
363
- const regex = /\\?"client_revision\\?":\s*(\d+)/
364
- const match = data.match(regex)
365
- if (!match?.match[1]) {
366
- return {
367
- version: baileys_version_json_1.version,
368
- isLatest: false,
369
- error: {
370
- message: 'Could not find client revision in the fetched content'
371
- }
372
- }
373
- }
374
- const clientRevision = match[1]
375
- return {
376
- version: [2, 3000, +clientRevision],
377
- isLatest: true
378
- }
379
- }
380
- catch (error) {
381
- return {
382
- version: baileys_version_json_1.version,
383
- isLatest: false,
384
- error
385
- }
386
- }
387
- }
364
+ const URL = 'https://raw.githubusercontent.com/wppconnect-team/wa-version/refs/heads/main/versions.json'
365
+ try {
366
+ const result = await axios_1.default.get(URL, {
367
+ ...options,
368
+ responseType: 'json'
369
+ })
370
+ .then((result) => result.data.currentVersion.replace('-alpha', ''))
371
+ .then((numb) => numb.split('.'))
372
+
373
+ return {
374
+ version: result,
375
+ isLatest: true
376
+ }
377
+ }
378
+ catch (error) {
379
+ return {
380
+ version: baileys_version_json_1.version,
381
+ isLatest: false,
382
+ error
383
+ }
384
+ }
385
+ }
386
+
388
387
  /** unique message tag prefix for MD clients */
389
388
  const generateMdTagPrefix = () => {
390
- const bytes = crypto_1.randomBytes(4)
391
- return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`
389
+ const bytes = crypto_1.randomBytes(4)
390
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`
392
391
  }
392
+
393
393
  const STATUS_MAP = {
394
- 'sender': WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK,
395
- 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
396
- 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
397
- 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
394
+ 'sender': WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK,
395
+ 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
396
+ 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
397
+ 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
398
398
  }
399
+
399
400
  /**
400
- * Given a type of receipt, returns what the new status of the message should be
401
- * @param type type from receipt
402
- */
401
+ * Given a type of receipt, returns what the new status of the message should be
402
+ * @param type type from receipt
403
+ */
403
404
  const getStatusFromReceiptType = (type) => {
404
- const status = STATUS_MAP[type]
405
- if (typeof type === 'undefined') {
406
- return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK
407
- }
408
- return status
405
+ const status = STATUS_MAP[type]
406
+ if (typeof type === 'undefined') {
407
+ return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK
408
+ }
409
+ return status
409
410
  }
411
+
410
412
  const CODE_MAP = {
411
- conflict: Types_1.DisconnectReason.connectionReplaced
413
+ conflict: Types_1.DisconnectReason.connectionReplaced
412
414
  }
415
+
413
416
  /**
414
- * Stream errors generally provide a reason, map that to a baileys DisconnectReason
415
- * @param reason the string reason given, eg. "conflict"
416
- */
417
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
418
+ * @param reason the string reason given, eg. "conflict"
419
+ */
417
420
  const getErrorCodeFromStreamError = (node) => {
418
- const [reasonNode] = WABinary_1.getAllBinaryNodeChildren(node)
419
- let reason = reasonNode?.tag || 'unknown'
420
- const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession)
421
- if (statusCode === Types_1.DisconnectReason.restartRequired) {
422
- reason = 'restart required'
423
- }
424
- return {
425
- reason,
426
- statusCode
427
- }
428
- }
421
+ const [reasonNode] = WABinary_1.getAllBinaryNodeChildren(node)
422
+ let reason = reasonNode?.tag || 'unknown'
423
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession)
424
+ if (statusCode === Types_1.DisconnectReason.restartRequired) {
425
+ reason = 'restart required'
426
+ }
427
+ return {
428
+ reason,
429
+ statusCode
430
+ }
431
+ }
432
+
429
433
  const getCallStatusFromNode = ({ tag, attrs }) => {
430
- let status
431
- switch (tag) {
432
- case 'offer':
433
- case 'offer_notice':
434
- status = 'offer'
435
- break
436
- case 'terminate':
437
- if (attrs.reason === 'timeout') {
438
- status = 'timeout'
439
- }
440
- else {
441
- //fired when accepted/rejected/timeout/caller hangs up
442
- status = 'terminate'
443
- }
444
- break
445
- case 'reject':
446
- status = 'reject'
447
- break
448
- case 'accept':
449
- status = 'accept'
450
- break
451
- default:
452
- status = 'ringing'
453
- break
454
- }
455
- return status
456
- }
434
+ let status
435
+ switch (tag) {
436
+ case 'offer':
437
+ case 'offer_notice':
438
+ status = 'offer'
439
+ break
440
+ case 'terminate':
441
+ if (attrs.reason === 'timeout') {
442
+ status = 'timeout'
443
+ }
444
+ else {
445
+ //fired when accepted/rejected/timeout/caller hangs up
446
+ status = 'terminate'
447
+ }
448
+ break
449
+ case 'reject':
450
+ status = 'reject'
451
+ break
452
+ case 'accept':
453
+ status = 'accept'
454
+ break
455
+ default:
456
+ status = 'ringing'
457
+ break
458
+ }
459
+ return status
460
+ }
461
+
457
462
  const getCodeFromWSError = (error) => {
458
- let statusCode = 500
459
- if (error?.message?.includes('Unexpected server response: ')) {
460
- const code = +(error?.message.slice('Unexpected server response: '.length))
461
- if (!Number.isNaN(code) && code >= 400) {
462
- statusCode = code
463
- }
464
- }
465
- else if (error?.code?.startsWith('E') || error?.message?.includes('time out')) {
466
- statusCode = 408
467
- }
468
- return statusCode
469
- }
463
+ let statusCode = 500
464
+ if (error?.message?.includes('Unexpected server response: ')) {
465
+ const code = +(error?.message.slice('Unexpected server response: '.length))
466
+ if (!Number.isNaN(code) && code >= 400) {
467
+ statusCode = code
468
+ }
469
+ }
470
+ else if (error?.code?.startsWith('E') || error?.message?.includes('time out')) {
471
+ statusCode = 408
472
+ }
473
+ return statusCode
474
+ }
475
+
470
476
  /**
471
- * Is the given platform WA business
472
- * @param platform AuthenticationCreds.platform
473
- */
477
+ * Is the given platform WA business
478
+ * @param platform AuthenticationCreds.platform
479
+ */
474
480
  const isWABusinessPlatform = (platform) => {
475
- return platform === 'smbi' || platform === 'smba'
481
+ return platform === 'smbi' || platform === 'smba'
476
482
  }
483
+
477
484
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
478
485
  function trimUndefined(obj) {
479
- for (const key in obj) {
480
- if (typeof obj[key] === 'undefined') {
481
- delete obj[key]
482
- }
483
- }
484
- return obj
485
- }
486
+ for (const key in obj) {
487
+ if (typeof obj[key] === 'undefined') {
488
+ delete obj[key]
489
+ }
490
+ }
491
+ return obj
492
+ }
493
+
486
494
  function bytesToCrockford(buffer) {
487
- let value = 0
488
- let bitCount = 0
489
- const crockford = []
490
- for (const element of buffer) {
491
- value = (value << 8) | (element & 0xff)
492
- bitCount += 8
493
- while (bitCount >= 5) {
494
- crockford.push('123456789ABCDEFGHJKLMNPQRSTVWXYZ'.charAt((value >>> (bitCount - 5)) & 31))
495
- bitCount -= 5
496
- }
497
- }
498
- if (bitCount > 0) {
499
- crockford.push('123456789ABCDEFGHJKLMNPQRSTVWXYZ'.charAt((value << (5 - bitCount)) & 31))
500
- }
501
- return crockford.join('')
502
- }
495
+ let value = 0
496
+ let bitCount = 0
497
+ const crockford = []
498
+ for (const element of buffer) {
499
+ value = (value << 8) | (element & 0xff)
500
+ bitCount += 8
501
+ while (bitCount >= 5) {
502
+ crockford.push('123456789ABCDEFGHJKLMNPQRSTVWXYZ'.charAt((value >>> (bitCount - 5)) & 31))
503
+ bitCount -= 5
504
+ }
505
+ }
506
+ if (bitCount > 0) {
507
+ crockford.push('123456789ABCDEFGHJKLMNPQRSTVWXYZ'.charAt((value << (5 - bitCount)) & 31))
508
+ }
509
+ return crockford.join('')
510
+ }
511
+
503
512
  const toUnicodeEscape = (text) => {
504
- return text.split("").map(char => "\\u" + char.charCodeAt(0).toString(16).padStart(4, "0")).join("")
513
+ return text.split("").map(char => "\\u" + char.charCodeAt(0).toString(16).padStart(4, "0")).join("")
505
514
  }
515
+
506
516
  const fromUnicodeEscape = (escapedText) => {
507
- return escapedText.replace(/\\u[\dA-Fa-f]{4}/g, match => String.fromCharCode(parseInt(match.slice(2), 16)))
517
+ return escapedText.replace(/\\u[\dA-Fa-f]{4}/g, match => String.fromCharCode(parseInt(match.slice(2), 16)))
508
518
  }
519
+
509
520
  const asciiEncode = (text) => {
510
- var encoded = text.split("").map(c => c.charCodeAt(0))
511
- return encoded
521
+ var encoded = text.split("").map(c => c.charCodeAt(0))
522
+ return encoded
512
523
  }
524
+
513
525
  const asciiDecode = (...codes) => {
514
- var codeArray = Array.isArray(codes[0]) ? codes[0] : codes
515
- return codeArray.map(c => String.fromCharCode(c)).join("")
526
+ var codeArray = Array.isArray(codes[0]) ? codes[0] : codes
527
+ return codeArray.map(c => String.fromCharCode(c)).join("")
516
528
  }
529
+
517
530
  module.exports = {
518
- Browsers,
519
- IZUMI,
520
- BufferJSON,
521
- getPlatformId,
522
- getKeyAuthor,
523
- writeRandomPadMax16,
524
- unpadRandomMax16,
525
- encodeWAMessage,
526
- encodeNewsletterMessage,
527
- generateRegistrationId,
528
- encodeBigEndian,
529
- toNumber,
530
- unixTimestampSeconds,
531
- debouncedTimeout,
532
- delay,
533
- delayCancellable,
534
- promiseTimeout,
535
- generateMessageID,
536
- bindWaitForEvent,
537
- bindWaitForConnectionUpdate,
538
- printQRIfNecessaryListener,
539
- fetchLatestBaileysVersion,
540
- fetchLatestWaWebVersion,
541
- generateMdTagPrefix,
542
- getStatusFromReceiptType,
543
- getErrorCodeFromStreamError,
544
- getCallStatusFromNode,
545
- getCodeFromWSError,
546
- isWABusinessPlatform,
547
- trimUndefined,
548
- bytesToCrockford,
549
- toUnicodeEscape,
550
- fromUnicodeEscape,
551
- asciiEncode,
552
- asciiDecode
531
+ Browsers,
532
+ Itsuki,
533
+ BufferJSON,
534
+ getPlatformId,
535
+ getKeyAuthor,
536
+ writeRandomPadMax16,
537
+ unpadRandomMax16,
538
+ encodeWAMessage,
539
+ encodeNewsletterMessage,
540
+ generateRegistrationId,
541
+ encodeBigEndian,
542
+ toNumber,
543
+ unixTimestampSeconds,
544
+ debouncedTimeout,
545
+ delay,
546
+ delayCancellable,
547
+ promiseTimeout,
548
+ generateMessageID,
549
+ bindWaitForEvent,
550
+ bindWaitForConnectionUpdate,
551
+ printQRIfNecessaryListener,
552
+ fetchLatestBaileysVersion,
553
+ generateMdTagPrefix,
554
+ getStatusFromReceiptType,
555
+ getErrorCodeFromStreamError,
556
+ getCallStatusFromNode,
557
+ getCodeFromWSError,
558
+ isWABusinessPlatform,
559
+ trimUndefined,
560
+ bytesToCrockford,
561
+ toUnicodeEscape,
562
+ fromUnicodeEscape,
563
+ asciiEncode,
564
+ asciiDecode
553
565
  }