@zervonexx/baileys 5.0.5 → 5.0.7

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.
@@ -315,6 +315,13 @@ message Account {
315
315
  }
316
316
  }
317
317
 
318
+ message AccountLinkingOpaqueData {
319
+ optional string accesstoken = 1;
320
+ optional string fbid = 2;
321
+ optional string nonce = 3;
322
+ optional string encryptedPassword = 4;
323
+ }
324
+
318
325
  message ActionLink {
319
326
  optional string url = 1;
320
327
  optional string buttonTitle = 2;
@@ -618,14 +618,14 @@ export const makeMessagesSocket = (config) => {
618
618
 
619
619
  const relay = async (msg, relayOptions, fullMsgObj) => {
620
620
  await relayMessage(jid, msg, { messageId: relayOptions?.messageId, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList, additionalNodes, deliveryMode: options.deliveryMode, aiLabel: options.aiLabel ?? options.ai })
621
- if (config.emitOwnEvents && fullMsgObj) process.nextTick(() => processingMutex.mutex(() => upsertMessage(fullMsgObj, 'append')))
621
+ if (config.emitOwnEvents && fullMsgObj) process.nextTick(() => processingMutex.mutex(async () => upsertMessage(await fullMsgObj, 'append')))
622
622
  }
623
623
 
624
624
  const fullMsg = await generateWAMessage(jid, content, { logger, userJid: jidNormalizedUser(activeSender), getUrlInfo: getUrlInfoFn, getProfilePicUrl: sock.profilePictureUrl, getCallLink: sock.createCallLink, upload: waUploadToServer, mediaCache: config.mediaCache, options: config.options, messageId: generateMessageIDV2(activeSender), ...options, ephemeralExpiration: ephemeralDuration, relay })
625
625
 
626
626
  if (!associatedFlowRelayed.has(fullMsg)) {
627
627
  await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList, additionalNodes, deliveryMode: options.deliveryMode, aiLabel: options.aiLabel ?? options.ai })
628
- if (config.emitOwnEvents) process.nextTick(() => processingMutex.mutex(() => upsertMessage(fullMsg, 'append')))
628
+ if (config.emitOwnEvents) process.nextTick(() => processingMutex.mutex(async () => upsertMessage(await fullMsg, 'append')))
629
629
  }
630
630
 
631
631
  return fullMsg
@@ -1,15 +1,11 @@
1
1
  import { Boom } from '@hapi/boom'
2
- import { Sticker, StickerTypes } from 'wa-sticker-formatter'
2
+ import { Sticker, StickerTypes, Exif } from 'wa-sticker-formatter'
3
3
  import sharp from 'sharp'
4
- import { fileTypeFromBuffer } from 'file-type'
5
- import ffmpegStatic from 'ffmpeg-static'
6
4
  import { randomBytes } from 'crypto'
5
+ import { execFile } from 'child_process'
7
6
  import { promises as fs, readFileSync, mkdtempSync, writeFileSync, rmSync } from 'fs'
8
- import { gunzipSync } from 'zlib'
9
7
  import path from 'path'
10
- import { execFile } from 'child_process'
11
8
  import { zip } from 'fflate'
12
- import { createRequire } from 'module'
13
9
  import { proto } from '../../WAProto/index.js'
14
10
  import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js'
15
11
  import { WAMessageStatus } from '../Types/index.js'
@@ -20,135 +16,93 @@ import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './gener
20
16
  import { downloadContentFromMessage, encryptedStream, prepareStream, generateThumbnail, getAudioDuration, getAudioWaveform, toBuffer, normalizeToBuffer, tmpdir, extractAudioFromVideo } from './messages-media.js'
21
17
  import { shouldIncludeReportingToken } from './reporting-utils.js'
22
18
 
23
- const require = createRequire(import.meta.url)
24
- const { Exif: StickerExif } = require('wa-sticker-formatter')
25
- if (ffmpegStatic) process.env.FFMPEG_PATH = ffmpegStatic
26
-
27
-
28
19
  const MIMETYPE_DEFAULTS = { image: 'image/jpeg', video: 'video/mp4', document: 'application/pdf', audio: 'audio/ogg; codecs=opus', sticker: 'image/webp', 'product-catalog-image': 'image/jpeg' }
29
20
 
30
- // user-facing send keys that are NOT proto field names — drives pass-through detection in generateWAMessageContent
31
- const HIGH_LEVEL_KEYS = new Set([
32
- 'text', 'react', 'delete', 'forward', 'disappearingMessagesInChat', 'groupInvite',
33
- 'stickerPack', 'pin', 'buttonReply', 'ptv', 'product', 'listReply', 'event', 'poll',
34
- 'inviteAdmin', 'requestPayment', 'sharePhoneNumber', 'limitSharing', 'viewOnce', 'mentions',
35
- 'edit', 'buttons', 'templateButtons', 'sections', 'interactiveButtons', 'album', 'call',
36
- 'keep', 'shop', 'payment', 'collection', 'contacts',
37
- ...Object.entries(proto.Message.fields).filter(([, fd]) => fd.type === 'msg').flatMap(([f]) => [f, f.replace(/Message$/, '')])
38
- ])
21
+ const toCamel = s => s.toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase())
39
22
 
40
- // wrapper field = proto.Message field whose sub-message has a 'message' field pointing back to proto.Message
41
23
  const WRAPPER_KEYS = new Set(
42
24
  Object.entries(proto.Message.fields)
43
25
  .filter(([, fd]) => fd.type === 'msg' && proto.Message[fd.msgType]?.fields?.message?.msgType === 'Message')
44
26
  .map(([name]) => name)
45
27
  )
46
28
 
47
- const toCamel = s => s.toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase())
48
-
49
- // AssociationType keys (mediaPoll, mediaAlbum, hdVideoDualUpload, etc.) — also high-level
50
29
  const ASSOCIATED_FLOW_KEYS = Object.fromEntries(
51
30
  Object.entries(proto.MessageAssociation?.AssociationType ?? {})
52
31
  .filter(([, v]) => typeof v === 'number' && v !== 0)
53
32
  .map(([name, value]) => [toCamel(name), value])
54
33
  )
34
+
55
35
  export const USER_MEDIA_KEYS = new Set(['image', 'video', 'ptv', 'audio', 'document', 'sticker'])
36
+
56
37
  const MEDIA_PROP_KEYS = new Set([
57
- // bare media type keys: image, video, audio, etc.
58
38
  ...USER_MEDIA_KEYS,
59
- // scalar fields on proto.Message itself (conversation, backgroundArgb, etc.)
60
39
  ...Object.keys(proto.Message.fields).filter(k => proto.Message.fields[k].type !== 'msg'),
61
- // scalar fields on each media message type (ptt, mimetype, caption, gifPlayback, etc.)
62
40
  ...[...USER_MEDIA_KEYS].flatMap(t => {
63
41
  const MsgType = proto.Message[t.charAt(0).toUpperCase() + t.slice(1) + 'Message']
64
42
  return Object.keys(MsgType?.fields ?? {}).filter(k => MsgType.fields[k].type !== 'msg')
65
43
  }),
66
44
  ])
45
+
46
+ const HIGH_LEVEL_KEYS = new Set([
47
+ 'text', 'react', 'delete', 'forward', 'disappearingMessagesInChat', 'groupInvite',
48
+ 'stickerPack', 'pin', 'buttonReply', 'ptv', 'product', 'listReply', 'event', 'poll',
49
+ 'inviteAdmin', 'requestPayment', 'sharePhoneNumber', 'limitSharing', 'viewOnce', 'mentions',
50
+ 'edit', 'buttons', 'templateButtons', 'sections', 'interactiveButtons', 'album', 'call',
51
+ 'keep', 'shop', 'payment', 'collection', 'contacts',
52
+ ...Object.entries(proto.Message.fields).filter(([, fd]) => fd.type === 'msg').flatMap(([f]) => [f, f.replace(/Message$/, '')])
53
+ ])
67
54
  Object.keys(ASSOCIATED_FLOW_KEYS).forEach(k => HIGH_LEVEL_KEYS.add(k))
68
55
 
69
56
  const REUPLOAD_REQUIRED_STATUS = [410, 404]
70
- const STICKER_MAX_BYTES = 1_000_000
71
- const CIRCLE_GEQ = `clip(256-hypot(X-W/2\\,Y-H/2)\\,0\\,1)*255`
72
- const ROUNDED_GEQ = `st(0\\,abs(X-W/2)-W/2+50);st(1\\,abs(Y-H/2)-H/2+50);st(2\\,hypot(max(ld(0)\\,0)\\,max(ld(1)\\,0))+min(max(ld(0)\\,ld(1))\\,0)-50);clip(-ld(2)\\,0\\,1)*255`
73
- const BASE_CROP_VF = 'scale=512:512:force_original_aspect_ratio=increase,crop=512:512:(iw-512)/2:(ih-512)/2,fps=8'
74
- const BASE_FULL_VF = 'scale=512:512,fps=8'
75
- const WEBP_ANIM_CODEC = ['-vcodec', 'libwebp_anim', '-lossless', '0', '-compression_level', '4', '-q:v', '35', '-loop', '0', '-preset', 'default']
76
- const WEBP_STATIC_CODEC = q => ['-vcodec', 'libwebp', '-lossless', '0', '-compression_level', '6', '-q:v', String(q), '-loop', '0', '-preset', 'picture']
77
57
 
78
58
  // ─── STICKER ──────────────────────────────────────────────────────────────────
79
59
 
80
- const ffmpegRun = args => new Promise((resolve, reject) => execFile(ffmpegStatic, args, { timeout: 120_000 }, err => err ? reject(err) : resolve()))
81
-
82
- const buildArgs = async (stickerType, inPath, outPath, extraIn = [], codecArgs = []) => {
83
- if (stickerType === StickerTypes.CIRCLE || stickerType === StickerTypes.ROUNDED) {
84
- const geq = stickerType === StickerTypes.CIRCLE ? CIRCLE_GEQ : ROUNDED_GEQ
85
- return ['-y', '-threads', '0', ...extraIn, '-i', inPath, '-filter_complex', `[0:v]${BASE_CROP_VF},format=rgba,geq=r='r(X\\,Y)':g='g(X\\,Y)':b='b(X\\,Y)':a='${geq}'[out]`, '-map', '[out]', ...codecArgs, '-an', outPath]
86
- }
87
- const vf = stickerType === StickerTypes.DEFAULT ? null : stickerType === StickerTypes.FULL ? BASE_FULL_VF : BASE_CROP_VF
88
- return ['-y', '-threads', '0', ...extraIn, '-i', inPath, ...(vf ? ['-vf', vf] : []), ...codecArgs, '-an', outPath]
60
+ const _runFfmpeg = async args => {
61
+ let bin
62
+ try { const { default: p } = await import('ffmpeg-static'); bin = p } catch { }
63
+ bin ||= process.env.FFMPEG_PATH || 'ffmpeg'
64
+ return new Promise((resolve, reject) => execFile(bin, args, { timeout: 120_000 }, err => err ? reject(err) : resolve()))
89
65
  }
90
66
 
91
- const shrinkToLimit = async (buf, { animated } = {}, _depth = 0) => {
92
- if (buf.length <= STICKER_MAX_BYTES) return buf
93
- if (_depth >= 2) return buf
94
- const ratio = STICKER_MAX_BYTES / buf.length
67
+ const shrinkWebp = async buf => {
68
+ if (buf.length <= 1_048_576) return buf
69
+ const ratio = 1_048_576 / buf.length
95
70
  const q = Math.max(10, Math.min(60, Math.floor(ratio * 80 * 0.85)))
96
- const out = (await compressWebp(buf, { animated, quality: q })).buffer
97
- if (out.length <= STICKER_MAX_BYTES) return out
98
- const q2 = Math.max(10, Math.floor(q * (STICKER_MAX_BYTES / out.length) * 0.85))
99
- const out2 = (await compressWebp(buf, { animated, quality: q2 })).buffer
100
- return out.length < out2.length ? out : out2
101
- }
102
-
103
- const tagExif = async (buf, packName, authorName) => new StickerExif({ pack: packName, author: authorName }).add(buf)
104
-
105
- const compressWebp = async (buf, { animated, quality = 80, stickerType = StickerTypes.ROUNDED, packName, authorName } = {}) => {
106
- const detected = await fileTypeFromBuffer(buf)
107
- const cuid = generateMessageIDV2()
108
- const videoExts = new Set(['mp4', 'webm', 'mkv', 'avi', 'mov', 'flv', 'gif'])
109
- if (detected && videoExts.has(detected.ext)) {
110
- const tmpIn = path.join(tmpdir(), `stk_in_${cuid}.${detected.ext}`)
111
- const tmpOut = path.join(tmpdir(), `stk_out_${cuid}.webp`)
112
- try {
113
- writeFileSync(tmpIn, buf)
114
- await ffmpegRun(await buildArgs(stickerType, tmpIn, tmpOut, ['-t', '10'], WEBP_ANIM_CODEC))
115
- const out = readFileSync(tmpOut)
116
- return { buffer: packName ? await tagExif(await shrinkToLimit(out, { animated: true }), packName, authorName) : out, isAnimated: true }
117
- } finally { fs.unlink(tmpIn).catch(() => { }); fs.unlink(tmpOut).catch(() => { }) }
118
- }
119
- if (detected?.mime === 'image/webp') {
120
- const meta = await sharp(buf, { animated: true }).metadata()
121
- const isAnim = animated ?? ((meta.pages || 1) > 1)
122
- const tmpOut = path.join(tmpdir(), `stk_out_${cuid}.webp`)
123
- if (isAnim) {
124
- try {
125
- await sharp(buf, { animated: true }).webp({ quality, effort: 1, loop: 0 }).toFile(tmpOut)
126
- const out = readFileSync(tmpOut)
127
- return { buffer: packName ? await tagExif(await shrinkToLimit(out, { animated: true }), packName, authorName) : out, isAnimated: true }
128
- } finally { fs.unlink(tmpOut).catch(() => { }) }
129
- }
130
- const tmpIn = path.join(tmpdir(), `stk_in_${cuid}.webp`)
131
- try {
132
- writeFileSync(tmpIn, buf)
133
- await ffmpegRun(await buildArgs(stickerType, tmpIn, tmpOut, [], WEBP_STATIC_CODEC(quality)))
134
- const out = readFileSync(tmpOut)
135
- return { buffer: packName ? await tagExif(await shrinkToLimit(out, { animated: false }), packName, authorName) : out, isAnimated: false }
136
- } finally { fs.unlink(tmpIn).catch(() => { }); fs.unlink(tmpOut).catch(() => { }) }
137
- }
138
- const converted = await new Sticker(buf, { pack: packName, author: authorName, type: stickerType, quality }).toBuffer()
139
- return { buffer: converted.length <= STICKER_MAX_BYTES ? converted : await shrinkToLimit(converted, { animated: false }), isAnimated: false }
140
- }
71
+ const out = await sharp(buf, { animated: true }).webp({ quality: q, effort: 1, loop: 0 }).toBuffer()
72
+ if (out.length <= 1_048_576) return out
73
+ const q2 = Math.max(10, Math.floor(q * (1_048_576 / out.length) * 0.85))
74
+ const out2 = await sharp(buf, { animated: true }).webp({ quality: q2, effort: 1, loop: 0 }).toBuffer()
75
+ return out2.length < buf.length ? out2 : out
76
+ }
77
+
78
+ // pick a value from message then options, with a fallback default
79
+ const _pick = (msg, opts, key, def) => msg?.[key] ?? opts?.[key] ?? def
80
+
81
+ const buildStickerOpts = (pack, author, src, opts) => ({
82
+ pack, author,
83
+ type: _pick(src, opts, 'type', StickerTypes.ROUNDED),
84
+ quality: _pick(src, opts, 'quality', 80),
85
+ maxSize: _pick(src, opts, 'maxSize', 1_048_576),
86
+ fps: _pick(src, opts, 'fps', 15),
87
+ maxDuration: _pick(src, opts, 'maxDuration', 10),
88
+ categories: src?.categories ?? opts?.categories ?? [],
89
+ ...(src?.id || opts?.stickerPackId ? { id: src?.id || opts?.stickerPackId } : {}),
90
+ ...(src?.background || opts?.background ? { background: src?.background || opts?.background } : {}),
91
+ ...(src?.androidAppStoreLink || opts?.androidAppStoreLink ? { androidAppStoreLink: src?.androidAppStoreLink || opts?.androidAppStoreLink } : {}),
92
+ ...(src?.iosAppStoreLink || opts?.iosAppStoreLink ? { iosAppStoreLink: src?.iosAppStoreLink || opts?.iosAppStoreLink } : {}),
93
+ })
141
94
 
142
95
  let _rlottieApi = null
143
96
  const getRlottieApi = async () => {
144
97
  if (_rlottieApi) return _rlottieApi
145
- const { init } = await import('rlottie')
146
- const wasmBuf = readFileSync(require.resolve('rlottie/wasm'))
147
- _rlottieApi = await init('data:application/wasm;base64,' + wasmBuf.toString('base64'))
98
+ const [{ init }, { createRequire }] = await Promise.all([import('rlottie'), import('module')])
99
+ const _require = createRequire(import.meta.url)
100
+ _rlottieApi = await init('data:application/wasm;base64,' + readFileSync(_require.resolve('rlottie/wasm')).toString('base64'))
148
101
  return _rlottieApi
149
102
  }
150
103
 
151
104
  const tgsToWebp = async (tgsBuffer, { quality = 80, fps = 30 } = {}) => {
105
+ const { gunzipSync } = await import('node:zlib')
152
106
  const lottieJson = JSON.parse(gunzipSync(tgsBuffer).toString())
153
107
  const api = await getRlottieApi()
154
108
  const W = 512, H = 512, handle = api.lottie_init()
@@ -167,15 +121,15 @@ const tgsToWebp = async (tgsBuffer, { quality = 80, fps = 30 } = {}) => {
167
121
  }
168
122
  const encode = async (outFps, q) => {
169
123
  const outPath = path.join(tgsTmpDir, `out_${outFps}_${q}.webp`)
170
- await ffmpegRun(['-y', '-framerate', String(fps), '-i', path.join(tgsTmpDir, 'f%04d.png'), '-vcodec', 'libwebp', '-vf', `scale=512:512,fps=${outFps}`, '-lossless', '0', '-compression_level', '6', '-q:v', String(q), '-loop', '0', '-preset', 'default', '-an', '-vsync', '0', outPath])
124
+ await _runFfmpeg(['-y', '-framerate', String(fps), '-i', path.join(tgsTmpDir, 'f%04d.png'), '-vcodec', 'libwebp', '-vf', `scale=512:512,fps=${outFps}`, '-lossless', '0', '-compression_level', '6', '-q:v', String(q), '-loop', '0', '-preset', 'default', '-an', '-vsync', '0', outPath])
171
125
  return readFileSync(outPath)
172
126
  }
173
127
  let out = await encode(fps, quality)
174
- if (out.length <= STICKER_MAX_BYTES) return out
175
- const targetFps = Math.max(8, Math.floor(fps * (STICKER_MAX_BYTES / out.length) * 0.9))
128
+ if (out.length <= 1_048_576) return out
129
+ const targetFps = Math.max(8, Math.floor(fps * (1_048_576 / out.length) * 0.9))
176
130
  out = await encode(targetFps, quality)
177
- if (out.length <= STICKER_MAX_BYTES) return out
178
- return encode(targetFps, Math.max(10, Math.floor(quality * (STICKER_MAX_BYTES / out.length) * 0.9)))
131
+ if (out.length <= 1_048_576) return out
132
+ return encode(targetFps, Math.max(10, Math.floor(quality * (1_048_576 / out.length) * 0.9)))
179
133
  } finally { api.lottie_destroy(handle); rmSync(tgsTmpDir, { recursive: true, force: true }) }
180
134
  }
181
135
 
@@ -261,7 +215,14 @@ const normalizeExternalAdReplyThumbnail = async ext => {
261
215
  if (!thumbnail) return ext
262
216
  if (thumbnail.length <= 50_000) return { ...ext, thumbnail }
263
217
  let quality = 90
264
- while (quality >= 10) { thumbnail = await toJpeg(quality, true); if (!thumbnail) return ext; if (thumbnail.length <= 50_000) return { ...ext, thumbnail }; const next = Math.max(10, Math.floor(quality * (50_000 / thumbnail.length) * 0.85)); if (next === quality) break; quality = next }
218
+ while (quality >= 10) {
219
+ thumbnail = await toJpeg(quality, true)
220
+ if (!thumbnail) return ext
221
+ if (thumbnail.length <= 50_000) return { ...ext, thumbnail }
222
+ const next = Math.max(10, Math.floor(quality * (50_000 / thumbnail.length) * 0.85))
223
+ if (next === quality) break
224
+ quality = next
225
+ }
265
226
  return ext
266
227
  }
267
228
 
@@ -302,19 +263,21 @@ export const prepareWAMessageMedia = async (message, options) => {
302
263
  const packName = message.pack || message.packName || options?.pack || options?.packName || 'ZervonexStickers'
303
264
  const authorName = message.author || message.publisher || message.packPublisher || options?.author || options?.publisher || options?.packPublisher || 'Zervonex'
304
265
  const rawBuffer = await toBuffer(uploadData.media)
305
- const { buffer } = await compressWebp(rawBuffer, { packName, authorName, stickerType: message.stickerType || options?.stickerType || StickerTypes.ROUNDED, quality: message.quality || options?.quality || 80 })
266
+ const { sticker: buffer, isAnimated } = await new Sticker(rawBuffer, buildStickerOpts(packName, authorName, message, options)).toMessage()
306
267
  uploadData.media = buffer
268
+ uploadData.isAnimated = isAnimated
307
269
  uploadData.stickerSentTs = Date.now()
308
270
  if (message.premium != null) uploadData.premium = message.premium
309
271
  const rawAudio = message.audio ?? message.stickerAudio ?? message.audioFooter
310
272
  if (rawAudio != null) {
311
- try { uploadData.audioMessage = (await prepareWAMessageMedia({ audio: rawAudio }, options)).audioMessage; uploadData.isAnimated = true } catch (e) { options.logger?.warn({ err: e }, 'sticker audio preparation failed') }
273
+ try { uploadData.audioMessage = (await prepareWAMessageMedia({ audio: rawAudio }, options)).audioMessage } catch (e) { options.logger?.warn({ err: e }, 'sticker audio preparation failed') }
312
274
  } else if (message.audioMessage != null) {
313
275
  uploadData.audioMessage = message.audioMessage
314
- uploadData.isAnimated = true
315
276
  } else if (message.extractAudio || options?.extractAudio) {
316
- uploadData.audioMessage = (await prepareWAMessageMedia({ audio: await extractAudioFromVideo(rawBuffer) }, options)).audioMessage
317
- uploadData.isAnimated = true
277
+ try {
278
+ const audioBuffer = await extractAudioFromVideo(rawBuffer)
279
+ if (audioBuffer) uploadData.audioMessage = (await prepareWAMessageMedia({ audio: audioBuffer }, options)).audioMessage
280
+ } catch (e) { options.logger?.warn({ err: e }, 'sticker audio extraction failed') }
318
281
  }
319
282
  } catch (e) { options.logger?.warn({ err: e }, 'sticker formatting failed, sending raw') }
320
283
  }
@@ -323,11 +286,7 @@ export const prepareWAMessageMedia = async (message, options) => {
323
286
  ? `${mediaType}:${uploadData.media.url.toString()}` : null
324
287
  if (cacheableKey) {
325
288
  const cached = await options.mediaCache?.get(cacheableKey)
326
- if (cached) {
327
- const obj = proto.Message.decode(cached)
328
- Object.assign(obj[protoKey], { ...uploadData, media: undefined })
329
- return obj
330
- }
289
+ if (cached) { const obj = proto.Message.decode(cached); Object.assign(obj[protoKey], { ...uploadData, media: undefined }); return obj }
331
290
  }
332
291
 
333
292
  const isNewsletter = !!options.jid && isJidNewsletter(options.jid)
@@ -391,6 +350,7 @@ export const prepareStickerPackMessage = async (stickerPack, options) => {
391
350
  const packName = name || packNameAlias || options?.packName || options?.name || 'ZervonexStickers'
392
351
  const authorName = publisher || packPublisher || author || options?.packPublisher || options?.publisher || options?.author || 'Zervonex'
393
352
  const MAX_STICKERS_PER_PACK = 60, skippedStickers = []
353
+
394
354
  const runWithLimit = (() => {
395
355
  const limit = 6, queue = []
396
356
  let running = 0
@@ -409,23 +369,19 @@ export const prepareStickerPackMessage = async (stickerPack, options) => {
409
369
  const buf = await normalizeToBuffer(raw)
410
370
  if (!buf?.length) { skippedStickers.push({ index: i, reason: 'Empty buffer' }); return null }
411
371
  const emojis = Array.isArray(s.emojis) ? s.emojis : Object.values(s.emojis || {})
412
- let finalBuf
372
+ let finalBuf, isAnimated = false
413
373
  if (s.isLottie) {
414
- finalBuf = await tagExif(await shrinkToLimit(await tgsToWebp(buf, { quality: 80, fps: 30 }), { animated: true }), packName, authorName)
415
- } else if (s.isAnimated) {
416
- const tmpIn = path.join(tmpdir(), `stk_in_${i}_${uid}.webp`), tmpRaw = path.join(tmpdir(), `stk_raw_${i}_${uid}.webp`)
417
- writeFileSync(tmpIn, buf)
418
- try {
419
- await ffmpegRun(await buildArgs(s.type || StickerTypes.ROUNDED, tmpIn, tmpRaw, ['-vcodec', 'vp9', '-t', '10'], WEBP_ANIM_CODEC))
420
- finalBuf = await tagExif(await shrinkToLimit(readFileSync(tmpRaw), { animated: true }), packName, authorName)
421
- } finally { fs.unlink(tmpIn).catch(() => { }); fs.unlink(tmpRaw).catch(() => { }) }
374
+ finalBuf = await new Exif({ pack: packName, author: authorName }).add(await shrinkWebp(await tgsToWebp(buf, { quality: 80, fps: 30 })))
375
+ isAnimated = true
422
376
  } else {
423
- finalBuf = await shrinkToLimit(await new Sticker(buf, { pack: packName, author: authorName, type: s.type || StickerTypes.ROUNDED, quality: 80 }).toBuffer(), { animated: false })
377
+ const result = await new Sticker(buf, buildStickerOpts(packName, authorName, s, null)).toMessage()
378
+ finalBuf = result.sticker
379
+ isAnimated = result.isAnimated
424
380
  }
425
381
  const hash = sha256(finalBuf).toString('base64').replace(/\//g, '-').replace(/=/g, '')
426
382
  const fileSize = finalBuf.length
427
383
  writeFileSync(tmpOut, finalBuf); finalBuf = null
428
- return { fileName: `${hash}.webp`, filePath: tmpOut, fileSize, mimetype: 'image/webp', isAnimated: s.isAnimated || false, isLottie: s.isLottie || false, emojis, accessibilityLabel: s.accessibilityLabel || '', ...((s.premium ?? stickerPack.premium) != null && { premium: s.premium ?? stickerPack.premium }) }
384
+ return { fileName: `${hash}.webp`, filePath: tmpOut, fileSize, mimetype: 'image/webp', isAnimated, isLottie: s.isLottie || false, emojis, accessibilityLabel: s.accessibilityLabel || '', ...((s.premium ?? stickerPack.premium) != null && { premium: s.premium ?? stickerPack.premium }) }
429
385
  } catch (e) {
430
386
  options.logger?.warn({ err: e }, `failed processing sticker at index ${i}`)
431
387
  skippedStickers.push({ index: i, reason: e.message }); fs.unlink(tmpOut).catch(() => { }); return null
@@ -473,9 +429,8 @@ export const prepareStickerPackMessage = async (stickerPack, options) => {
473
429
  }
474
430
  const allProcessed = (await Promise.all(stickers.map((s, j) => runWithLimit(() => processSticker(s, j))))).filter(Boolean)
475
431
  if (!coverFilePath && allProcessed.length) coverFilePath = allProcessed[0].filePath
476
- const sizeBatches = []
477
- let curBatch = []
478
- for (const s of allProcessed) { if (curBatch.length >= MAX_STICKERS_PER_PACK) { sizeBatches.push(curBatch); curBatch = [] }; curBatch.push(s) }
432
+ const sizeBatches = [], curBatch = []
433
+ for (const s of allProcessed) { if (curBatch.length >= MAX_STICKERS_PER_PACK) { sizeBatches.push([...curBatch]); curBatch.length = 0 }; curBatch.push(s) }
479
434
  if (curBatch.length) sizeBatches.push(curBatch)
480
435
  const totalBatches = sizeBatches.length
481
436
  const allResults = await Promise.all(sizeBatches.map((batch, idx) => processBatch(batch, idx, totalBatches, coverFilePath).finally(() => { for (const s of batch) fs.unlink(s.filePath).catch(() => { }) })))
@@ -485,8 +440,6 @@ export const prepareStickerPackMessage = async (stickerPack, options) => {
485
440
  }
486
441
 
487
442
  // ─── MESSAGE HANDLERS ─────────────────────────────────────────────────────────
488
- // Each key maps to async fn(message, options) -> proto-compatible object.
489
- // Add a new type here only when it needs custom logic; everything else is auto-registered below.
490
443
 
491
444
  const MESSAGE_HANDLERS = {
492
445
  text: async (msg, opts) => {
@@ -548,14 +501,11 @@ const MESSAGE_HANDLERS = {
548
501
  if (msg.poll.selectableCount < 0 || msg.poll.selectableCount > msg.poll.values.length) throw new Boom(`poll.selectableCount should be >= 0 and <= ${msg.poll.values.length}`, { statusCode: 400 })
549
502
  const normalize = v => typeof v === 'string' ? { optionName: v } : { optionName: v.name ?? v.optionName, ...(v.image ? { _image: v.image } : {}) }
550
503
  const options = msg.poll.values.map(normalize)
551
- if (options.some(o => o._image)) {
552
- const pollMsg = { name: msg.poll.name, selectableOptionsCount: msg.poll.selectableCount, options: options.map(o => ({ optionName: o.optionName })), ...(msg.poll.endDate ? { endTime: msg.poll.endDate.getTime() } : {}), ...(msg.poll.hideVoter != null ? { hideParticipantName: msg.poll.hideVoter } : {}), ...(msg.poll.canAddOption != null ? { allowAddOption: msg.poll.canAddOption } : {}) }
553
- const key = msg.poll.toAnnouncementGroup ? 'pollCreationMessageV2' : msg.poll.selectableCount === 1 ? 'pollCreationMessageV3' : 'pollCreationMessage'
554
- return { _associatedFlow: true, associationType: ASSOCIATED_FLOW_KEYS.mediaPoll, _parent: { [key]: pollMsg, messageContextInfo: { messageSecret: msg.poll.messageSecret || randomBytes(32) } }, _children: options.filter(o => o._image).map(o => ({ pollCreationOptionImageMessage: { message: { imageMessage: o._image } } })) }
555
- }
556
- const pollMsg = { name: msg.poll.name, selectableOptionsCount: msg.poll.selectableCount, options: options.map(o => ({ optionName: o.optionName })), ...(msg.poll.endDate ? { endTime: msg.poll.endDate.getTime() } : {}), ...(msg.poll.hideVoter != null ? { hideParticipantName: msg.poll.hideVoter } : {}), ...(msg.poll.canAddOption != null ? { allowAddOption: msg.poll.canAddOption } : {}) }
504
+ const pollBase = { name: msg.poll.name, selectableOptionsCount: msg.poll.selectableCount, options: options.map(o => ({ optionName: o.optionName })), ...(msg.poll.endDate ? { endTime: msg.poll.endDate.getTime() } : {}), ...(msg.poll.hideVoter != null ? { hideParticipantName: msg.poll.hideVoter } : {}), ...(msg.poll.canAddOption != null ? { allowAddOption: msg.poll.canAddOption } : {}) }
557
505
  const key = msg.poll.toAnnouncementGroup ? 'pollCreationMessageV2' : msg.poll.selectableCount === 1 ? 'pollCreationMessageV3' : 'pollCreationMessage'
558
- return { [key]: pollMsg, messageContextInfo: { messageSecret: msg.poll.messageSecret || randomBytes(32) } }
506
+ const ctx = { messageSecret: msg.poll.messageSecret || randomBytes(32) }
507
+ if (options.some(o => o._image)) return { _associatedFlow: true, associationType: ASSOCIATED_FLOW_KEYS.mediaPoll, _parent: { [key]: pollBase, messageContextInfo: ctx }, _children: options.filter(o => o._image).map(o => ({ pollCreationOptionImageMessage: { message: { imageMessage: o._image } } })) }
508
+ return { [key]: pollBase, messageContextInfo: ctx }
559
509
  },
560
510
  react: async msg => { if (!msg.react.senderTimestampMs) msg.react.senderTimestampMs = Date.now(); return { reactionMessage: proto.Message.ReactionMessage.create(msg.react) } },
561
511
  keep: async msg => ({ keepInChatMessage: { key: msg.keep, keepType: msg.type, timestampMs: Date.now() } }),
@@ -582,27 +532,20 @@ const _buildSafeMsgTypes = () => {
582
532
  const safe = new Set(['ContextInfo', 'MessageKey', 'LocationMessage', 'SingleSelectReply', 'Option']), all = new Map(), seen = new WeakSet()
583
533
  const scan = ns => { if (!ns || typeof ns !== 'object' || seen.has(ns)) return; seen.add(ns); for (const [k, v] of Object.entries(ns)) { if (!_isSubMsg(k, v)) continue; if (!all.has(k)) all.set(k, v); scan(v) } }
584
534
  scan(proto.Message)
585
- // Include top-level message types referenced directly by proto.Message fields.
586
535
  for (const fd of Object.values(proto.Message.fields || {})) if (fd.type === 'msg' && proto[fd.msgType]) scan(proto[fd.msgType])
587
536
  const isSafe = val => !val.fields || Object.values(val.fields).every(f => SCALAR_KINDS.has(f.type) || (f.type === 'msg' && safe.has(f.msgType)))
588
537
  while ([...all.entries()].some(([k, v]) => !safe.has(k) && isSafe(v) && safe.add(k)));
589
538
  return safe
590
539
  }
591
540
  export const SAFE_MSG_TYPES = _buildSafeMsgTypes()
592
- // Auto-register handlers from proto schema — no manual maintenance needed.
593
- // Part 1: simple proto.Message fields whose sub-messages are all scalar.
594
- // Part 2: all ProtocolMessage.Type entries not already covered.
595
- ; (() => {
596
- const scalarKinds = SCALAR_KINDS
597
- const safeMsgTypes = SAFE_MSG_TYPES
598
541
 
542
+ ; (() => {
543
+ const scalarKinds = SCALAR_KINDS, safeMsgTypes = SAFE_MSG_TYPES
599
544
  for (const [fieldName, fd] of Object.entries(proto.Message.fields)) {
600
545
  if (fd.type !== 'msg') continue
601
546
  const sub = proto.Message[fd.msgType]
602
- if (!sub?.fields) continue
603
- if (sub.fields?.message?.msgType === 'Message') continue
604
- const isAutoSafe = Object.values(sub.fields).every(f => scalarKinds.has(f.type) || (f.type === 'msg' && safeMsgTypes.has(f.msgType)))
605
- if (!isAutoSafe) continue
547
+ if (!sub?.fields || sub.fields?.message?.msgType === 'Message') continue
548
+ if (!Object.values(sub.fields).every(f => scalarKinds.has(f.type) || (f.type === 'msg' && safeMsgTypes.has(f.msgType)))) continue
606
549
  const inputKey = fieldName.replace(/Message$/, '')
607
550
  const CtorKey = Object.keys(proto.Message).find(k => k.toLowerCase() === fieldName.toLowerCase())
608
551
  const Ctor = CtorKey ? proto.Message[CtorKey] : { fromObject: o => o }
@@ -612,19 +555,8 @@ export const SAFE_MSG_TYPES = _buildSafeMsgTypes()
612
555
  if (!MESSAGE_HANDLERS[inputKey + 'Message']) MESSAGE_HANDLERS[inputKey + 'Message'] = handler
613
556
  }
614
557
 
615
- const pm = proto.Message.ProtocolMessage
616
- const pmFields = pm?.fields ?? {}
617
- const findPmField = camel => {
618
- if (pmFields[camel]) return camel
619
- if (pmFields[camel + 'Message']) return camel + 'Message'
620
- return Object.entries(pmFields).find(([k]) => k.toLowerCase() === camel.toLowerCase())?.[0] ?? null
621
- }
622
- const isResolvable = (msgType, depth = 0) => {
623
- if (depth > 5) return false
624
- const sub = proto.Message[msgType]
625
- if (!sub?.fields) return true
626
- return Object.values(sub.fields).every(f => scalarKinds.has(f.type) || (f.type === 'msg' && isResolvable(f.msgType, depth + 1)))
627
- }
558
+ const pm = proto.Message.ProtocolMessage, pmFields = pm?.fields ?? {}
559
+ const findPmField = camel => pmFields[camel] ? camel : pmFields[camel + 'Message'] ? camel + 'Message' : Object.entries(pmFields).find(([k]) => k.toLowerCase() === camel.toLowerCase())?.[0] ?? null
628
560
  const reg = (keys, fn) => { for (const k of keys) { if (k && !MESSAGE_HANDLERS[k]) MESSAGE_HANDLERS[k] = fn } }
629
561
 
630
562
  for (const [typeName, typeVal] of Object.entries(pm?.Type ?? {})) {
@@ -636,12 +568,7 @@ export const SAFE_MSG_TYPES = _buildSafeMsgTypes()
636
568
  const shortKey = inputKey.replace(/(?:Setting|Config|Info|Data|Params|Options|Request|Response|Update|Notification|Event)$/, '')
637
569
  const keys = [...new Set([camel, inputKey, fieldName, shortKey, camel + 'Message', inputKey + 'Message', shortKey + 'Message'].filter(Boolean))]
638
570
  if (!fieldName) {
639
- reg(keys, async msg => {
640
- const payload = { type: typeVal }
641
- const msgKey = msg[camel]?.key ?? msg.key
642
- if (msgKey && typeof msgKey === 'object') payload.key = msgKey
643
- return { protocolMessage: payload }
644
- })
571
+ reg(keys, async msg => { const payload = { type: typeVal }; const msgKey = msg[camel]?.key ?? msg.key; if (msgKey && typeof msgKey === 'object') payload.key = msgKey; return { protocolMessage: payload } })
645
572
  } else {
646
573
  const fd = pmFields[fieldName]
647
574
  const CtorKey = fd.type === 'msg' ? Object.keys(proto.Message).find(k => k.toLowerCase() === fd.msgType.toLowerCase()) : null
@@ -650,7 +577,9 @@ export const SAFE_MSG_TYPES = _buildSafeMsgTypes()
650
577
  const data = msg[shortKey] ?? msg[inputKey] ?? msg[fieldName] ?? msg[camel]
651
578
  const encodeDeep = (msgType, obj) => {
652
579
  if (!obj || typeof obj !== 'object') return obj
653
- const Sub = proto.Message[msgType]; if (!Sub?.fields) return obj; const result = { ...obj }; for (const [fName, fDesc] of Object.entries(Sub.fields)) { if (fDesc.type === 'msg' && result[fName] != null) { const SubCtor = proto.Message[fDesc.msgType]; result[fName] = SubCtor ? SubCtor.fromObject(encodeDeep(fDesc.msgType, result[fName])) : result[fName] } }
580
+ const Sub = proto.Message[msgType]; if (!Sub?.fields) return obj
581
+ const result = { ...obj }
582
+ for (const [fName, fDesc] of Object.entries(Sub.fields)) { if (fDesc.type === 'msg' && result[fName] != null) { const SubCtor = proto.Message[fDesc.msgType]; result[fName] = SubCtor ? SubCtor.fromObject(encodeDeep(fDesc.msgType, result[fName])) : result[fName] } }
654
583
  return Sub.fromObject(result)
655
584
  }
656
585
  return { protocolMessage: { type: typeVal, [fieldName]: Ctor ? encodeDeep(fd.msgType, data ?? {}) : data } }
@@ -735,7 +664,6 @@ export const generateWAMessageContent = async (message, options = {}) => {
735
664
  if (!message || typeof message !== 'object') return proto.Message.create({})
736
665
  const msgKeys = Object.keys(message)
737
666
  const isWrapper = msgKeys.some(k => WRAPPER_KEYS.has(k))
738
- // raw proto pass-through: no high-level keys present, or is a known wrapper type
739
667
  if (isWrapper || (!msgKeys.some(k => HIGH_LEVEL_KEYS.has(k)) && msgKeys.some(k => k.endsWith('Message') || k === 'conversation'))) return proto.Message.create(message)
740
668
 
741
669
  let m = {}
@@ -757,7 +685,6 @@ export const generateWAMessageContent = async (message, options = {}) => {
757
685
 
758
686
  for (const key of overlayKeys) { if (key in message && message[key]) { m = await OVERLAY_HANDLERS[key](m, message, options); break } }
759
687
 
760
- // deep-merge contextInfo/mentions onto the primary content key
761
688
  const finalKey = Object.keys(m)[0]
762
689
  if ((message.contextInfo || message.mentions?.length) && finalKey && m[finalKey] && typeof m[finalKey] === 'object') {
763
690
  const existing = m[finalKey].contextInfo || {}, incoming = message.contextInfo || {}
@@ -767,7 +694,6 @@ export const generateWAMessageContent = async (message, options = {}) => {
767
694
 
768
695
  if ('viewOnce' in message && message.viewOnce) m = { viewOnceMessage: { message: m } }
769
696
  if ('edit' in message) m = { protocolMessage: { key: message.edit, editedMessage: m, timestampMs: Date.now(), type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT } }
770
-
771
697
  if (shouldIncludeReportingToken(m)) { m.messageContextInfo ??= {}; m.messageContextInfo.messageSecret ??= randomBytes(32) }
772
698
  return proto.Message.create(m)
773
699
  }
@@ -830,7 +756,6 @@ export const generateWAMessageFromAssociatedFlow = async (jid, parentContent, ch
830
756
  return parent
831
757
  }
832
758
 
833
- // generateWAMessage is the main entry point — handles associated flows, poll image children, and standard messages
834
759
  export const generateWAMessage = async (jid, content, options = {}) => {
835
760
  if (content?.key?.remoteJid && content?.message) return content
836
761
  const msgId = options.messageId || generateMessageIDV2()
package/lib/index.js CHANGED
@@ -29,7 +29,7 @@ const info = [
29
29
  '╭──────────────────────────────────────────────────────────────╮',
30
30
  '│ │',
31
31
  '│ ◆ Package › @zervonexx/baileys │',
32
- '│ ◆ Version › 5.0.5 │',
32
+ '│ ◆ Version › 5.0.7 │',
33
33
  '│ ◆ Status › Production Ready │',
34
34
  '│ │',
35
35
  '├──────────────────────────── ◇◆◇ ─────────────────────────────┤',
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@zervonexx/baileys",
4
4
  "type": "module",
5
- "version": "5.0.5",
5
+ "version": "5.0.7",
6
6
  "description": "Advanced WhatsApp Web API built on Baileys — interactive messages, buttons, carousels, products, events, payments, polls, albums, sticker packs and more.",
7
7
  "keywords": [
8
8
  "baileys",
@@ -123,16 +123,13 @@
123
123
  "unfurl.js": "^6.4.0",
124
124
  "url-regex-safe": "^4.0.0",
125
125
  "uuid": "^14.0.3",
126
- "wa-sticker-formatter": "^4.4.4",
126
+ "wa-sticker-formatter": "^5.0.0",
127
127
  "whatsapp-rust-bridge": "^0.5.5",
128
128
  "ws": "^8.22.0"
129
129
  },
130
130
  "overrides": {
131
131
  "wa-sticker-formatter": {
132
- "sharp": "^0.35.5",
133
- "axios": "^1.20.0",
134
- "file-type": "^22.2.0",
135
- "image-size": "^2.0.4"
132
+ "sharp": "^0.35.5"
136
133
  },
137
134
  "jest": "^29.0.0",
138
135
  "tar": "^7.5.22",
@@ -161,9 +158,6 @@
161
158
  },
162
159
  "resolutions": {
163
160
  "wa-sticker-formatter/sharp": "^0.35.5",
164
- "wa-sticker-formatter/axios": "^1.20.0",
165
- "wa-sticker-formatter/file-type": "^22.2.0",
166
- "wa-sticker-formatter/image-size": "^2.0.4",
167
161
  "tar": "^7.5.22",
168
162
  "@tootallnate/once": "^3.0.1",
169
163
  "image-size": "^2.0.4",