@zervonexx/baileys 5.0.0 → 5.0.2

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 (127) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +4124 -4112
  3. package/WAProto/WAProto.json +1 -0
  4. package/WAProto/WAProto.proto +7160 -0
  5. package/WAProto/WAProtoCompile.js +264 -322
  6. package/WAProto/index.js +55 -95
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +249 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +17 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +195 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +3 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +944 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. package/package.json +187 -192
  126. package/WAProto/fetcher.js +0 -68
  127. package/WAProto/parser.js +0 -334
@@ -1,943 +1,945 @@
1
- import { Boom } from '@hapi/boom'
2
- import { Sticker, StickerTypes } from 'wa-sticker-formatter'
3
- import sharp from 'sharp'
4
- import { fileTypeFromBuffer } from 'file-type'
5
- import ffmpegStatic from 'ffmpeg-static'
6
- import { randomBytes } from 'crypto'
7
- import { promises as fs, readFileSync, mkdtempSync, writeFileSync, rmSync } from 'fs'
8
- import { gunzipSync } from 'zlib'
9
- import path from 'path'
10
- import { execFile } from 'child_process'
11
- import { zip } from 'fflate'
12
- import { createRequire } from 'module'
13
- import { proto } from '../../WAProto/index.js'
14
- import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js'
15
- import { WAMessageStatus } from '../Types/index.js'
16
- import { isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js'
17
- import { sha256 } from './crypto.js'
18
- import { resolveNativeFlowButtons } from './native-flow.js'
19
- import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js'
20
- import { downloadContentFromMessage, encryptedStream, prepareStream, generateThumbnail, getAudioDuration, getAudioWaveform, toBuffer, normalizeToBuffer, tmpdir } from './messages-media.js'
21
- import { shouldIncludeReportingToken } from './reporting-utils.js'
22
-
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
- 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
-
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
- ])
39
-
40
- // wrapper field = proto.Message field whose sub-message has a 'message' field pointing back to proto.Message
41
- const WRAPPER_KEYS = new Set(
42
- Object.entries(proto.Message.fields)
43
- .filter(([, fd]) => fd.type === 'msg' && proto.Message[fd.msgType]?.fields?.message?.msgType === 'Message')
44
- .map(([name]) => name)
45
- )
46
-
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
- const ASSOCIATED_FLOW_KEYS = Object.fromEntries(
51
- Object.entries(proto.MessageAssociation?.AssociationType ?? {})
52
- .filter(([, v]) => typeof v === 'number' && v !== 0)
53
- .map(([name, value]) => [toCamel(name), value])
54
- )
55
- export const USER_MEDIA_KEYS = new Set(['image', 'video', 'ptv', 'audio', 'document', 'sticker'])
56
- const MEDIA_PROP_KEYS = new Set([
57
- // bare media type keys: image, video, audio, etc.
58
- ...USER_MEDIA_KEYS,
59
- // scalar fields on proto.Message itself (conversation, backgroundArgb, etc.)
60
- ...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
- ...[...USER_MEDIA_KEYS].flatMap(t => {
63
- const MsgType = proto.Message[t.charAt(0).toUpperCase() + t.slice(1) + 'Message']
64
- return Object.keys(MsgType?.fields ?? {}).filter(k => MsgType.fields[k].type !== 'msg')
65
- }),
66
- ])
67
- Object.keys(ASSOCIATED_FLOW_KEYS).forEach(k => HIGH_LEVEL_KEYS.add(k))
68
-
69
- 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
-
78
- // ─── STICKER ──────────────────────────────────────────────────────────────────
79
-
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]
89
- }
90
-
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
95
- 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
- }
141
-
142
- let _rlottieApi = null
143
- const getRlottieApi = async () => {
144
- 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'))
148
- return _rlottieApi
149
- }
150
-
151
- const tgsToWebp = async (tgsBuffer, { quality = 80, fps = 30 } = {}) => {
152
- const lottieJson = JSON.parse(gunzipSync(tgsBuffer).toString())
153
- const api = await getRlottieApi()
154
- const W = 512, H = 512, handle = api.lottie_init()
155
- const jsonBuf = Buffer.from(JSON.stringify(lottieJson) + '\0')
156
- const ptr = api._malloc(jsonBuf.length)
157
- api.HEAPU8.set(jsonBuf, ptr)
158
- const totalFrames = api.lottie_load_from_data(handle, ptr)
159
- api.lottie_resize(handle, W, H)
160
- const bufPtr = api.lottie_buffer(handle)
161
- const tgsTmpDir = mkdtempSync(path.join(tmpdir(), 'tgs_'))
162
- try {
163
- for (let i = 0; i < totalFrames; i++) {
164
- api.lottie_render(handle, i)
165
- const rgba = Buffer.from(api.HEAPU8.buffer, bufPtr, W * H * 4)
166
- await sharp(Buffer.from(rgba), { raw: { width: W, height: H, channels: 4 } }).png().toFile(path.join(tgsTmpDir, `f${String(i).padStart(4, '0')}.png`))
167
- }
168
- const encode = async (outFps, q) => {
169
- 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])
171
- return readFileSync(outPath)
172
- }
173
- 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))
176
- 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)))
179
- } finally { api.lottie_destroy(handle); rmSync(tgsTmpDir, { recursive: true, force: true }) }
180
- }
181
-
182
- // ─── URL / LINK PREVIEW ───────────────────────────────────────────────────────
183
-
184
- export const extractUrlFromText = text => text.match(URL_REGEX)?.[0]
185
-
186
- export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
187
- const url = extractUrlFromText(text)
188
- if (!getUrlInfo || !url) return
189
- try { return await getUrlInfo(url) } catch (e) { logger?.warn({ trace: e.stack }, 'url generation failed') }
190
- }
191
-
192
- // ─── MEDIA RESOLUTION ─────────────────────────────────────────────────────────
193
-
194
- const RESOLVABLE_MEDIA = [
195
- ...['Image', 'Video', 'Audio', 'Document', 'Sticker'].map(t => ({ key: `${t.toLowerCase()}Message`, type: t.toLowerCase() })),
196
- { key: 'image', type: 'image' },
197
- { key: 'video', type: 'video' },
198
- ]
199
-
200
- const resolveMedia = async (obj, upload) => {
201
- if (!obj || typeof obj !== 'object' || typeof upload !== 'function') return
202
- for (const { key, type } of RESOLVABLE_MEDIA) {
203
- if (!obj[key]) continue
204
- const isRaw = key === 'image' || key === 'video'
205
- if (!isRaw && obj[key].directPath) continue
206
- const src = isRaw ? obj[key] : (obj[key].url ?? obj[key])
207
- const result = await prepareWAMessageMedia({ [type]: typeof src === 'string' ? { url: src } : src }, { upload })
208
- if (isRaw) { obj[`${type}Message`] = result[`${type}Message`]; delete obj[key] }
209
- else obj[key] = result[`${type}Message`]
210
- if ('hasMediaAttachment' in obj) obj.hasMediaAttachment = true
211
- }
212
- for (const val of Object.values(obj)) {
213
- if (Array.isArray(val)) for (const item of val) await resolveMedia(item, upload)
214
- else if (val && typeof val === 'object') await resolveMedia(val, upload)
215
- }
216
- }
217
-
218
- // ─── MESSAGE HELPERS ──────────────────────────────────────────────────────────
219
-
220
- export const getContentType = content => {
221
- if (!content) return
222
- return Object.keys(content).find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage')
223
- }
224
-
225
- export const normalizeMessageContent = (content, logger) => {
226
- if (!content) return
227
- for (let i = 0; i < 5; i++) {
228
- let inner = null
229
- for (const k of WRAPPER_KEYS) { if (content?.[k]) { inner = content[k]; break } }
230
- if (!inner) break
231
- if (!inner.message) { logger?.warn({ i, keys: Object.keys(inner) }, 'normalizeMessageContent: inner wrapper has no message field'); break }
232
- content = inner.message
233
- }
234
- return content
235
- }
236
-
237
- export const extractMessageContent = content => {
238
- content = normalizeMessageContent(content)
239
- for (const t of ['image', 'video', 'audio', 'document']) { if (content?.[`${t}Message`]?.viewOnce) return { [`${t}Message`]: content[`${t}Message`] } }
240
- const fromButtons = msg => {
241
- for (const t of ['image', 'document', 'video', 'location', 'product']) { if (msg[`${t}Message`]) return { [`${t}Message`]: msg[`${t}Message`] } }
242
- return { conversation: msg.contentText || msg.hydratedContentText || msg.body?.text || '' }
243
- }
244
- if (content?.buttonsMessage) return fromButtons(content.buttonsMessage)
245
- if (content?.interactiveMessage) return fromButtons(content.interactiveMessage)
246
- for (const v of ['interactiveMessageTemplate', 'hydratedFourRowTemplate', 'hydratedTemplate', 'fourRowTemplate']) {
247
- if (content?.templateMessage?.[v]) return fromButtons(content.templateMessage[v])
248
- }
249
- return content
250
- }
251
-
252
- const normalizeExternalAdReplyThumbnail = async ext => {
253
- if (!ext?.thumbnail) return ext
254
- const thumb = await normalizeToBuffer(ext.thumbnail)
255
- if (!thumb || thumb.length <= 50_000) return { ...ext, thumbnail: thumb }
256
- let quality = 90
257
- while (quality >= 10) {
258
- const thumbnail = await sharp(ext.thumbnail, { sequentialRead: true }).resize(200, 200, { fit: 'inside' }).jpeg({ quality }).toBuffer().catch(() => null)
259
- if (!thumbnail) return ext
260
- if (thumbnail.length <= 50_000) return { ...ext, thumbnail }
261
- quality = Math.max(10, Math.floor(quality * (50_000 / thumbnail.length) * 0.85))
262
- }
263
- return ext
264
- }
265
-
266
- export const generateForwardMessageContent = (message, forceForward) => {
267
- let content = normalizeMessageContent(message.message)
268
- if (!content) throw new Boom('no content in message', { statusCode: 400 })
269
- content = proto.Message.decode(proto.Message.encode(content).finish())
270
- let key = Object.keys(content)[0]
271
- const score = (content?.[key]?.contextInfo?.forwardingScore || 0) + (message.key.fromMe && !forceForward ? 0 : 1)
272
- if (key === 'conversation') { content.extendedTextMessage = { text: content[key] }; delete content.conversation; key = 'extendedTextMessage' }
273
- content[key].contextInfo = score > 0 ? { forwardingScore: score, isForwarded: true } : {}
274
- return content
275
- }
276
-
277
- export const prepareDisappearingMessageSettingContent = ephemeralExpiration => proto.Message.fromObject({
278
- ephemeralMessage: { message: { protocolMessage: { type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING, ephemeralExpiration: ephemeralExpiration || 0 } } }
279
- })
280
-
281
- const assertColor = color => {
282
- if (typeof color === 'number') return color > 0 ? color : 0xffffffff + Number(color) + 1
283
- const hex = color.trim().replace('#', '')
284
- return parseInt(hex.length <= 6 ? 'FF' + hex.padStart(6, '0') : hex, 16)
285
- }
286
-
287
- // ─── MEDIA ────────────────────────────────────────────────────────────────────
288
-
289
- export const prepareWAMessageMedia = async (message, options) => {
290
- const mediaType = MEDIA_KEYS.find(k => k in message)
291
- if (!mediaType) throw new Boom('Invalid media type', { statusCode: 400 })
292
- const protoKey = `${mediaType}Message`
293
- const uploadData = { ...message, media: message[mediaType] }
294
- delete uploadData[mediaType]
295
- if (mediaType === 'document' && !uploadData.fileName) uploadData.fileName = 'file'
296
- if (!uploadData.mimetype) uploadData.mimetype = MIMETYPE_DEFAULTS[mediaType] || 'application/octet-stream'
297
-
298
- if (mediaType === 'sticker') {
299
- try {
300
- const rawBuf = await toBuffer(uploadData.media)
301
- const packName = message.pack || message.packName || options?.pack || options?.packName || 'ZervonexStickers'
302
- const authorName = message.author || message.publisher || message.packPublisher || options?.author || options?.publisher || options?.packPublisher || 'Zervonex'
303
- const { buffer } = await compressWebp(rawBuf, { packName, authorName, stickerType: message.stickerType || options?.stickerType || StickerTypes.ROUNDED, quality: message.quality || options?.quality || 80 })
304
- uploadData.media = buffer
305
- uploadData.stickerSentTs = Date.now()
306
- if (message.premium != null) uploadData.premium = message.premium
307
- } catch (e) { options.logger?.warn({ err: e }, 'sticker formatting failed, sending raw') }
308
- }
309
-
310
- const cacheableKey = typeof uploadData.media === 'object' && 'url' in uploadData.media && uploadData.media.url && options.mediaCache
311
- ? `${mediaType}:${uploadData.media.url.toString()}` : null
312
- if (cacheableKey) {
313
- const cached = await options.mediaCache?.get(cacheableKey)
314
- if (cached) {
315
- const obj = proto.Message.decode(cached)
316
- Object.assign(obj[protoKey], { ...uploadData, media: undefined })
317
- return obj
318
- }
319
- }
320
-
321
- const isNewsletter = !!options.jid && isJidNewsletter(options.jid)
322
- const requiresDuration = mediaType === 'audio' && typeof uploadData.seconds === 'undefined'
323
- const requiresThumbnail = (mediaType === 'image' || mediaType === 'video') && typeof uploadData.jpegThumbnail === 'undefined'
324
- if (uploadData.jpegThumbnail) uploadData.jpegThumbnail = await normalizeToBuffer(uploadData.jpegThumbnail)
325
- const requiresWaveform = mediaType === 'audio' && (uploadData.ptt === true || !!options.backgroundColor)
326
-
327
- const enc = await (isNewsletter ? prepareStream : encryptedStream)(uploadData.media, options.mediaTypeOverride || mediaType, {
328
- logger: options.logger, saveOriginalFileIfRequired: requiresDuration || requiresThumbnail || requiresWaveform,
329
- opts: options.options, isPtt: uploadData.ptt, forceOpus: mediaType === 'audio' && uploadData.mimetype?.includes('opus'), convertVideo: mediaType === 'video',
330
- })
331
- const { mediaKey, encWriteStream, bodyPath, fileEncSha256, fileSha256, fileLength, opusConverted, encFilePath, encBuffer, cleanup } = enc
332
- if (mediaType === 'audio' && opusConverted) uploadData.mimetype = 'audio/ogg; codecs=opus'
333
- const fileEncSha256B64 = (isNewsletter ? fileSha256 : (fileEncSha256 ?? fileSha256)).toString('base64')
334
-
335
- const [{ mediaUrl, directPath, handle }] = await Promise.all([
336
- (options.upload ?? options.waUploadToServer)(encFilePath || encBuffer || encWriteStream, { fileEncSha256B64, mediaType, timeoutMs: options.mediaUploadTimeoutMs }),
337
- (async () => {
338
- try {
339
- if (requiresThumbnail) {
340
- const { thumbnail, originalImageDimensions } = await generateThumbnail(bodyPath, mediaType, options)
341
- uploadData.jpegThumbnail = thumbnail
342
- if (!uploadData.width && originalImageDimensions) { uploadData.width = originalImageDimensions.width; uploadData.height = originalImageDimensions.height }
343
- }
344
- if (requiresDuration) uploadData.seconds = await getAudioDuration(bodyPath)
345
- if (requiresWaveform) {
346
- try { uploadData.waveform = await getAudioWaveform(bodyPath, options.logger) } catch {
347
- uploadData.waveform = new Uint8Array([0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99])
348
- }
349
- }
350
- if (options.backgroundColor && mediaType === 'audio') uploadData.backgroundArgb = assertColor(options.backgroundColor)
351
- } catch (e) { options.logger?.warn({ trace: e.stack }, 'failed to obtain extra info') }
352
- })()
353
- ]).finally(async () => {
354
- if (encWriteStream && !Buffer.isBuffer(encWriteStream)) encWriteStream.destroy?.()
355
- if (cleanup) await cleanup()
356
- })
357
-
358
- const CtorName = mediaType.charAt(0).toUpperCase() + mediaType.slice(1) + 'Message'
359
- const Ctor = proto.Message[CtorName] || { fromObject: o => o }
360
- const obj = proto.Message.fromObject({
361
- [protoKey]: Ctor.fromObject({ url: handle ? undefined : mediaUrl, directPath, mediaKey, fileEncSha256, fileSha256, fileLength, mediaKeyTimestamp: handle ? undefined : unixTimestampSeconds(), ...uploadData, media: undefined })
362
- })
363
- if (uploadData.ptv) { obj.ptvMessage = obj.videoMessage; delete obj.videoMessage }
364
- if (cacheableKey) await options.mediaCache?.set(cacheableKey, proto.Message.encode(obj).finish())
365
- return obj
366
- }
367
-
368
- // ─── STICKER PACK ─────────────────────────────────────────────────────────────
369
-
370
- export const prepareStickerPackMessage = async (stickerPack, options) => {
371
- if (Array.isArray(stickerPack)) stickerPack = { stickers: stickerPack }
372
- else if (stickerPack && typeof stickerPack === 'object' && !stickerPack.stickers) {
373
- const keys = Object.keys(stickerPack)
374
- if (keys.length && keys.every(k => !isNaN(k))) stickerPack = { stickers: Object.values(stickerPack) }
375
- }
376
- const { stickers, cover, name, publisher, packId, packName: packNameAlias, packPublisher, author } = stickerPack
377
- if (!stickers?.length) throw new Boom('Sticker pack must contain at least one sticker', { statusCode: 400 })
378
- const stickerPackIdValue = packId || generateMessageIDV2()
379
- const packName = name || packNameAlias || options?.packName || options?.name || 'ZervonexStickers'
380
- const authorName = publisher || packPublisher || author || options?.packPublisher || options?.publisher || options?.author || 'Zervonex'
381
- const MAX_STICKERS_PER_PACK = 60, skippedStickers = []
382
- const runWithLimit = (() => {
383
- const limit = 6, queue = []
384
- let running = 0
385
- return fn => new Promise((resolve, reject) => {
386
- const run = () => { running++; fn().then(resolve, reject).finally(() => { running--; queue.shift()?.() }) }
387
- running < limit ? run() : queue.push(run)
388
- })
389
- })()
390
-
391
- const processSticker = async (s, i) => {
392
- const uid = generateMessageIDV2()
393
- const tmpOut = path.join(tmpdir(), `stk_out_${i}_${uid}.webp`)
394
- try {
395
- const raw = s.data || s.sticker || s.buffer || s.image || s.webp || s.file || s.path || s.url
396
- if (!raw) { skippedStickers.push({ index: i, reason: 'No sticker data found' }); return null }
397
- const buf = await normalizeToBuffer(raw)
398
- if (!buf?.length) { skippedStickers.push({ index: i, reason: 'Empty buffer' }); return null }
399
- const emojis = Array.isArray(s.emojis) ? s.emojis : Object.values(s.emojis || {})
400
- let finalBuf
401
- if (s.isLottie) {
402
- finalBuf = await tagExif(await shrinkToLimit(await tgsToWebp(buf, { quality: 80, fps: 30 }), { animated: true }), packName, authorName)
403
- } else if (s.isAnimated) {
404
- const tmpIn = path.join(tmpdir(), `stk_in_${i}_${uid}.webp`), tmpRaw = path.join(tmpdir(), `stk_raw_${i}_${uid}.webp`)
405
- writeFileSync(tmpIn, buf)
406
- try {
407
- await ffmpegRun(await buildArgs(s.type || StickerTypes.ROUNDED, tmpIn, tmpRaw, ['-vcodec', 'vp9', '-t', '10'], WEBP_ANIM_CODEC))
408
- finalBuf = await tagExif(await shrinkToLimit(readFileSync(tmpRaw), { animated: true }), packName, authorName)
409
- } finally { fs.unlink(tmpIn).catch(() => { }); fs.unlink(tmpRaw).catch(() => { }) }
410
- } else {
411
- finalBuf = await shrinkToLimit(await new Sticker(buf, { pack: packName, author: authorName, type: s.type || StickerTypes.ROUNDED, quality: 80 }).toBuffer(), { animated: false })
412
- }
413
- const hash = sha256(finalBuf).toString('base64').replace(/\//g, '-').replace(/=/g, '')
414
- const fileSize = finalBuf.length
415
- writeFileSync(tmpOut, finalBuf); finalBuf = null
416
- 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 }) }
417
- } catch (e) {
418
- options.logger?.warn({ err: e }, `failed processing sticker at index ${i}`)
419
- skippedStickers.push({ index: i, reason: e.message }); fs.unlink(tmpOut).catch(() => { }); return null
420
- }
421
- }
422
-
423
- const processBatch = async (batch, batchIdx, totalBatches, coverFilePath) => {
424
- const batchData = {}
425
- for (const s of batch) batchData[s.fileName] = [new Uint8Array(readFileSync(s.filePath)), { level: 0 }]
426
- const trayFile = totalBatches > 1 ? `${stickerPackIdValue}_batch${batchIdx}.webp` : `${stickerPackIdValue}.webp`
427
- batchData[trayFile] = [new Uint8Array(readFileSync(coverFilePath)), { level: 0 }]
428
- const zipBuf = await new Promise((resolve, reject) => zip(batchData, (err, data) => err ? reject(err) : resolve(Buffer.from(data))))
429
- const upload = await encryptedStream(zipBuf, 'sticker-pack', { logger: options.logger, opts: options.options })
430
- const uploadRes = await options.upload(upload.encFilePath || upload.encBuffer, { fileEncSha256B64: upload.fileEncSha256.toString('base64'), mediaType: 'sticker-pack', timeoutMs: options.mediaUploadTimeoutMs })
431
- if (upload.encFilePath) fs.unlink(upload.encFilePath).catch(() => { })
432
- let thumbRes = null
433
- try {
434
- const thumbTmpPath = path.join(tmpdir(), `stk_thumb_${generateMessageIDV2()}.jpg`)
435
- await sharp(coverFilePath).resize(252, 252).jpeg().toFile(thumbTmpPath)
436
- const thumbBuf = readFileSync(thumbTmpPath); fs.unlink(thumbTmpPath).catch(() => { })
437
- const thumbUpload = await encryptedStream(thumbBuf, 'thumbnail-sticker-pack', { logger: options.logger, opts: options.options, mediaKey: upload.mediaKey })
438
- thumbRes = await options.upload(thumbUpload.encFilePath || thumbUpload.encBuffer, { fileEncSha256B64: thumbUpload.fileEncSha256.toString('base64'), mediaType: 'thumbnail-sticker-pack', timeoutMs: options.mediaUploadTimeoutMs })
439
- if (thumbUpload.encFilePath) fs.unlink(thumbUpload.encFilePath).catch(() => { })
440
- thumbRes._enc = thumbUpload; thumbRes._thumbBuf = thumbBuf
441
- } catch (e) { options.logger?.warn({ err: e }, 'failed generating sticker pack thumbnail') }
442
- return {
443
- name: totalBatches > 1 ? `${packName} (${batchIdx + 1}/${totalBatches})` : packName, publisher: authorName,
444
- stickerPackId: totalBatches > 1 ? `${stickerPackIdValue}_${batchIdx}` : stickerPackIdValue,
445
- stickerPackOrigin: proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED, stickerPackSize: zipBuf.length,
446
- stickers: batch.map(s => ({ fileName: s.fileName, mimetype: s.mimetype, isAnimated: s.isAnimated, isLottie: s.isLottie, emojis: s.emojis, accessibilityLabel: s.accessibilityLabel, ...(s.premium != null && { premium: s.premium }) })),
447
- fileSha256: upload.fileSha256, fileEncSha256: upload.fileEncSha256, mediaKey: upload.mediaKey,
448
- directPath: uploadRes.directPath, fileLength: upload.fileLength, mediaKeyTimestamp: unixTimestampSeconds(), trayIconFileName: trayFile,
449
- ...(thumbRes && { thumbnailDirectPath: thumbRes.directPath, thumbnailHeight: 252, thumbnailWidth: 252, thumbnailSha256: thumbRes._enc?.fileSha256, thumbnailEncSha256: thumbRes._enc?.fileEncSha256, imageDataHash: thumbRes._thumbBuf ? sha256(thumbRes._thumbBuf).toString('base64') : undefined }),
450
- }
451
- }
452
-
453
- const coverTmpPath = path.join(tmpdir(), `stk_cover_${generateMessageIDV2()}.webp`)
454
- let coverFilePath
455
- try {
456
- if (cover) {
457
- const coverBuf = await normalizeToBuffer(cover)
458
- const isWebp = coverBuf[0] === 0x52 && coverBuf[1] === 0x49 && coverBuf[8] === 0x57 && coverBuf[9] === 0x45
459
- writeFileSync(coverTmpPath, isWebp ? coverBuf : await new Sticker(coverBuf, { pack: packName, author: authorName, type: StickerTypes.ROUNDED, quality: 95 }).toBuffer())
460
- coverFilePath = coverTmpPath
461
- }
462
- const allProcessed = (await Promise.all(stickers.map((s, j) => runWithLimit(() => processSticker(s, j))))).filter(Boolean)
463
- if (!coverFilePath && allProcessed.length) coverFilePath = allProcessed[0].filePath
464
- const sizeBatches = []
465
- let curBatch = []
466
- for (const s of allProcessed) { if (curBatch.length >= MAX_STICKERS_PER_PACK) { sizeBatches.push(curBatch); curBatch = [] }; curBatch.push(s) }
467
- if (curBatch.length) sizeBatches.push(curBatch)
468
- const totalBatches = sizeBatches.length
469
- 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(() => { }) })))
470
- if (!allResults.length) throw new Boom('No valid stickers could be processed', { statusCode: 400 })
471
- return allResults.length > 1 ? { stickerPackMessage: allResults, isBatched: true, batchCount: allResults.length } : { stickerPackMessage: allResults[0], isBatched: false }
472
- } finally { fs.unlink(coverTmpPath).catch(() => { }) }
473
- }
474
-
475
- // ─── MESSAGE HANDLERS ─────────────────────────────────────────────────────────
476
- // Each key maps to async fn(message, options) -> proto-compatible object.
477
- // Add a new type here only when it needs custom logic; everything else is auto-registered below.
478
-
479
- const MESSAGE_HANDLERS = {
480
- text: async (msg, opts) => {
481
- const ext = { text: msg.text }
482
- const urlInfo = msg.linkPreview ?? await generateLinkPreviewIfRequired(msg.text, opts.getUrlInfo, opts.logger)
483
- if (urlInfo) {
484
- Object.assign(ext, { matchedText: urlInfo['matched-text'], jpegThumbnail: urlInfo.jpegThumbnail, description: urlInfo.description, title: urlInfo.title, previewType: urlInfo.previewType ?? 0 })
485
- const img = urlInfo.highQualityThumbnail
486
- if (img) Object.assign(ext, { thumbnailDirectPath: img.directPath, mediaKey: img.mediaKey, mediaKeyTimestamp: img.mediaKeyTimestamp, thumbnailWidth: img.width, thumbnailHeight: img.height, thumbnailSha256: img.fileSha256, thumbnailEncSha256: img.fileEncSha256 })
487
- }
488
- if (opts.backgroundColor) ext.backgroundArgb = assertColor(opts.backgroundColor)
489
- if (opts.font) ext.font = opts.font
490
- return { extendedTextMessage: ext }
491
- },
492
- contacts: async msg => {
493
- const { contacts } = msg.contacts
494
- if (!contacts.length) throw new Boom('require atleast 1 contact', { statusCode: 400 })
495
- return contacts.length === 1
496
- ? { contactMessage: proto.Message.ContactMessage.create(contacts[0]) }
497
- : { contactsArrayMessage: proto.Message.ContactsArrayMessage.create(msg.contacts) }
498
- },
499
- delete: async msg => ({ protocolMessage: { key: msg.delete, type: proto.Message.ProtocolMessage.Type.REVOKE } }),
500
- forward: async msg => generateForwardMessageContent(msg.forward, msg.force),
501
- disappearingMessagesInChat: async msg => prepareDisappearingMessageSettingContent(
502
- typeof msg.disappearingMessagesInChat === 'boolean' ? (msg.disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0) : msg.disappearingMessagesInChat
503
- ),
504
- stickerPack: async (msg, opts) => {
505
- const result = await prepareStickerPackMessage(msg.stickerPack, opts)
506
- if (result.isBatched) return { _batched: true, stickerPackMessage: result.stickerPackMessage, batchCount: result.batchCount }
507
- return { _finalize: true, stickerPackMessage: result.stickerPackMessage }
508
- },
509
- pin: async (msg, opts) => {
510
- const messageKey = typeof msg.pin === 'boolean'
511
- ? (opts.quoted?.key || (() => { throw new Boom('No quoted message key found for pin operation') })())
512
- : typeof msg.pin === 'object'
513
- ? (msg.pin.key || (msg.pin.id ? { remoteJid: opts.jid, fromMe: msg.pin.fromMe || false, id: msg.pin.id, participant: msg.pin.participant } : null))
514
- : msg.pin
515
- if (!messageKey?.id) throw new Boom('Invalid message key for pin operation')
516
- const shouldPin = typeof msg.pin === 'boolean' ? msg.pin : (msg.pin?.unpin !== true)
517
- return { pinInChatMessage: { key: messageKey, type: shouldPin ? 1 : 2, senderTimestampMs: Date.now().toString() }, messageContextInfo: { messageAddOnDurationInSecs: shouldPin ? (msg.pin?.time || msg.time || 86400) : 0 } }
518
- },
519
- buttonReply: async msg => ({
520
- list: { listResponseMessage: { title: msg.buttonReply.title, description: msg.buttonReply.description, singleSelectReply: { selectedRowId: msg.buttonReply.rowId }, listType: proto.Message.ListResponseMessage.ListType.SINGLE_SELECT } },
521
- template: { templateButtonReplyMessage: { selectedDisplayText: msg.buttonReply.displayText, selectedId: msg.buttonReply.id, selectedIndex: msg.buttonReply.index } },
522
- interactive: { interactiveResponseMessage: { body: { text: msg.buttonReply.displayText, format: proto.Message.InteractiveResponseMessage.Body.Format.EXTENSIONS_1 }, nativeFlowResponseMessage: { name: msg.buttonReply.nativeFlows?.name, paramsJson: msg.buttonReply.nativeFlows?.paramsJson, version: msg.buttonReply.nativeFlows?.version } } },
523
- }[msg.type] || { buttonsResponseMessage: { selectedButtonId: msg.buttonReply.id, selectedDisplayText: msg.buttonReply.displayText, type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT } }),
524
- ptv: async (msg, opts) => { const { videoMessage } = await prepareWAMessageMedia({ video: msg.video }, opts); return { ptvMessage: videoMessage } },
525
- product: async (msg, opts) => { const { imageMessage } = await prepareWAMessageMedia({ image: msg.product.productImage }, opts); return { productMessage: proto.Message.ProductMessage.create({ ...msg, product: { ...msg.product, productImage: imageMessage } }) } },
526
- sections: async msg => ({ listMessage: { title: msg.title, buttonText: msg.buttonText, footerText: msg.footer, description: msg.text, sections: msg.sections, listType: proto.Message.ListMessage.ListType.SINGLE_SELECT, contextInfo: { ...(msg.contextInfo || {}), ...(msg.mentions ? { mentionedJid: msg.mentions } : {}) } } }),
527
- event: async (msg, opts) => {
528
- const startTime = Math.floor(msg.event.startDate.getTime() / 1000)
529
- const eventMessage = { name: msg.event.name, description: msg.event.description, startTime, isCanceled: msg.event.isCancelled ?? false, extraGuestsAllowed: msg.event.extraGuestsAllowed, isScheduleCall: msg.event.isScheduleCall ?? false, location: msg.event.location, ...(msg.event.endDate ? { endTime: Math.floor(msg.event.endDate.getTime() / 1000) } : {}), ...(msg.event.hasReminder != null ? { hasReminder: msg.event.hasReminder } : {}), ...(msg.event.reminderOffsetSec != null ? { reminderOffsetSec: msg.event.reminderOffsetSec } : {}) }
530
- if (msg.event.call && opts.getCallLink) eventMessage.joinLink = (msg.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + await opts.getCallLink(msg.event.call, { startTime })
531
- return { eventMessage, messageContextInfo: { messageSecret: msg.event.messageSecret || randomBytes(32) } }
532
- },
533
- poll: async msg => {
534
- msg.poll.selectableCount ||= 0; msg.poll.toAnnouncementGroup ||= false
535
- if (!Array.isArray(msg.poll.values)) throw new Boom('Invalid poll values', { statusCode: 400 })
536
- 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 })
537
- const normalize = v => typeof v === 'string' ? { optionName: v } : { optionName: v.name ?? v.optionName, ...(v.image ? { _image: v.image } : {}) }
538
- const options = msg.poll.values.map(normalize)
539
- if (options.some(o => o._image)) {
540
- 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 } : {}) }
541
- const key = msg.poll.toAnnouncementGroup ? 'pollCreationMessageV2' : msg.poll.selectableCount === 1 ? 'pollCreationMessageV3' : 'pollCreationMessage'
542
- 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 } } })) }
543
- }
544
- 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 } : {}) }
545
- const key = msg.poll.toAnnouncementGroup ? 'pollCreationMessageV2' : msg.poll.selectableCount === 1 ? 'pollCreationMessageV3' : 'pollCreationMessage'
546
- return { [key]: pollMsg, messageContextInfo: { messageSecret: msg.poll.messageSecret || randomBytes(32) } }
547
- },
548
- react: async msg => { if (!msg.react.senderTimestampMs) msg.react.senderTimestampMs = Date.now(); return { reactionMessage: proto.Message.ReactionMessage.create(msg.react) } },
549
- keep: async msg => ({ keepInChatMessage: { key: msg.keep, keepType: msg.type, timestampMs: Date.now() } }),
550
- listReply: async msg => ({ listResponseMessage: { ...msg.listReply } }),
551
- inviteAdmin: async msg => ({ newsletterAdminInviteMessage: proto.Message.NewsletterAdminInviteMessage.fromObject({ inviteCode: msg.inviteAdmin.inviteCode, inviteExpiration: msg.inviteAdmin.inviteExpiration, caption: msg.inviteAdmin.text, newsletterJid: msg.inviteAdmin.jid, newsletterName: msg.inviteAdmin.subject, jpegThumbnail: await normalizeToBuffer(msg.inviteAdmin.thumbnail) }) }),
552
- requestPayment: async (msg, opts) => {
553
- const data = msg.requestPayment || msg.payment
554
- const sticker = data.sticker ? await prepareWAMessageMedia({ sticker: data.sticker }, opts) : null
555
- const noteMessage = sticker ? { stickerMessage: { ...sticker.stickerMessage, contextInfo: data.contextInfo } } : { extendedTextMessage: { text: data.note || 'Notes', ...(data.contextInfo ? { contextInfo: data.contextInfo } : {}) } }
556
- const m = { requestPaymentMessage: proto.Message.RequestPaymentMessage.fromObject({ expiryTimestamp: data.expiryTimestamp || data.expiry || 0, amount1000: data.amount1000 || data.amount || 0, currencyCodeIso4217: data.currencyCodeIso4217 || data.currency || 'IDR', requestFrom: data.requestFrom || data.from || '0@s.whatsapp.net', noteMessage, background: data.background ?? { id: 'DEFAULT', placeholderArgb: 0xfff0f0f0 } }) }
557
- if ((data.currencyCodeIso4217 === 'BRL' || data.currency === 'BRL') && data.pixKey) { m.requestPaymentMessage.noteMessage.extendedTextMessage ??= { text: '' }; m.requestPaymentMessage.noteMessage.extendedTextMessage.text += `\nPix Key: ${data.pixKey}` }
558
- return m
559
- },
560
- album: async msg => ({ albumMessage: { expectedImageCount: msg.album.filter(i => 'image' in i).length, expectedVideoCount: msg.album.filter(i => 'video' in i).length } }),
561
- sharePhoneNumber: async () => ({ protocolMessage: { type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER } }),
562
- limitSharing: async msg => ({ protocolMessage: { type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING, limitSharing: { sharingLimited: msg.limitSharing === true, trigger: 1, limitSharingSettingTimestamp: Date.now(), initiatedByMe: true } } }),
563
- payment: async (msg, opts) => MESSAGE_HANDLERS.requestPayment(msg, opts),
564
- }
565
-
566
- export const MESSAGE_HANDLER_KEYS = Object.keys(MESSAGE_HANDLERS)
567
- export const SCALAR_KINDS = new Set(['string', 'int', 'long', 'bool', 'bytes', 'enum', 'float', 'double'])
568
- const _isSubMsg = (k, v) => k !== 'fields' && v && typeof v === 'object' && !Array.isArray(v) && !Object.keys(v).some(k2 => !isNaN(k2))
569
- const _buildSafeMsgTypes = () => {
570
- const safe = new Set(['ContextInfo', 'MessageKey', 'LocationMessage', 'SingleSelectReply', 'Option']), all = new Map(), seen = new WeakSet()
571
- 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) } }
572
- scan(proto.Message)
573
- // Include top-level message types referenced directly by proto.Message fields.
574
- for (const fd of Object.values(proto.Message.fields || {})) if (fd.type === 'msg' && proto[fd.msgType]) scan(proto[fd.msgType])
575
- const isSafe = val => !val.fields || Object.values(val.fields).every(f => SCALAR_KINDS.has(f.type) || (f.type === 'msg' && safe.has(f.msgType)))
576
- while ([...all.entries()].some(([k, v]) => !safe.has(k) && isSafe(v) && safe.add(k)));
577
- return safe
578
- }
579
- export const SAFE_MSG_TYPES = _buildSafeMsgTypes()
580
- // Auto-register handlers from proto schema — no manual maintenance needed.
581
- // Part 1: simple proto.Message fields whose sub-messages are all scalar.
582
- // Part 2: all ProtocolMessage.Type entries not already covered.
583
- ; (() => {
584
- const scalarKinds = SCALAR_KINDS
585
- const safeMsgTypes = SAFE_MSG_TYPES
586
-
587
- for (const [fieldName, fd] of Object.entries(proto.Message.fields)) {
588
- if (fd.type !== 'msg') continue
589
- const sub = proto.Message[fd.msgType]
590
- if (!sub?.fields) continue
591
- if (sub.fields?.message?.msgType === 'Message') continue
592
- const isAutoSafe = Object.values(sub.fields).every(f => scalarKinds.has(f.type) || (f.type === 'msg' && safeMsgTypes.has(f.msgType)))
593
- if (!isAutoSafe) continue
594
- const inputKey = fieldName.replace(/Message$/, '')
595
- const CtorKey = Object.keys(proto.Message).find(k => k.toLowerCase() === fieldName.toLowerCase())
596
- const Ctor = CtorKey ? proto.Message[CtorKey] : { fromObject: o => o }
597
- const handler = async msg => ({ [fieldName]: Ctor.fromObject(msg[inputKey] ?? msg[fieldName] ?? msg) })
598
- if (!MESSAGE_HANDLERS[inputKey]) MESSAGE_HANDLERS[inputKey] = handler
599
- if (!MESSAGE_HANDLERS[fieldName]) MESSAGE_HANDLERS[fieldName] = handler
600
- if (!MESSAGE_HANDLERS[inputKey + 'Message']) MESSAGE_HANDLERS[inputKey + 'Message'] = handler
601
- }
602
-
603
- const pm = proto.Message.ProtocolMessage
604
- const pmFields = pm?.fields ?? {}
605
- const findPmField = camel => {
606
- if (pmFields[camel]) return camel
607
- if (pmFields[camel + 'Message']) return camel + 'Message'
608
- return Object.entries(pmFields).find(([k]) => k.toLowerCase() === camel.toLowerCase())?.[0] ?? null
609
- }
610
- const isResolvable = (msgType, depth = 0) => {
611
- if (depth > 5) return false
612
- const sub = proto.Message[msgType]
613
- if (!sub?.fields) return true
614
- return Object.values(sub.fields).every(f => scalarKinds.has(f.type) || (f.type === 'msg' && isResolvable(f.msgType, depth + 1)))
615
- }
616
- const reg = (keys, fn) => { for (const k of keys) { if (k && !MESSAGE_HANDLERS[k]) MESSAGE_HANDLERS[k] = fn } }
617
-
618
- for (const [typeName, typeVal] of Object.entries(pm?.Type ?? {})) {
619
- if (typeof typeVal !== 'number') continue
620
- const camel = toCamel(typeName)
621
- if (MESSAGE_HANDLERS[camel]) continue
622
- const fieldName = findPmField(camel)
623
- const inputKey = fieldName ? fieldName.replace(/Message$/, '') : camel
624
- const shortKey = inputKey.replace(/(?:Setting|Config|Info|Data|Params|Options|Request|Response|Update|Notification|Event)$/, '')
625
- const keys = [...new Set([camel, inputKey, fieldName, shortKey, camel + 'Message', inputKey + 'Message', shortKey + 'Message'].filter(Boolean))]
626
- if (!fieldName) {
627
- reg(keys, async msg => {
628
- const payload = { type: typeVal }
629
- const msgKey = msg[camel]?.key ?? msg.key
630
- if (msgKey && typeof msgKey === 'object') payload.key = msgKey
631
- return { protocolMessage: payload }
632
- })
633
- } else {
634
- const fd = pmFields[fieldName]
635
- const CtorKey = fd.type === 'msg' ? Object.keys(proto.Message).find(k => k.toLowerCase() === fd.msgType.toLowerCase()) : null
636
- const Ctor = CtorKey ? proto.Message[CtorKey] : null
637
- reg(keys, async msg => {
638
- const data = msg[shortKey] ?? msg[inputKey] ?? msg[fieldName] ?? msg[camel]
639
- const encodeDeep = (msgType, obj) => {
640
- if (!obj || typeof obj !== 'object') return obj
641
- 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] } }
642
- return Sub.fromObject(result)
643
- }
644
- return { protocolMessage: { type: typeVal, [fieldName]: Ctor ? encodeDeep(fd.msgType, data ?? {}) : data } }
645
- })
646
- }
647
- }
648
- })()
649
-
650
- // ─── OVERLAY HANDLERS ─────────────────────────────────────────────────────────
651
-
652
- const applyContextInfoAndMentions = async (interactive, msg) => {
653
- if (msg.contextInfo) { const ctx = { ...(interactive.contextInfo || {}), ...msg.contextInfo }; if (ctx.externalAdReply) ctx.externalAdReply = await normalizeExternalAdReplyThumbnail(ctx.externalAdReply); interactive.contextInfo = ctx }
654
- if (msg.mentions?.length) interactive.contextInfo = { ...(interactive.contextInfo || {}), mentionedJid: msg.mentions }
655
- }
656
-
657
- const OVERLAY_HANDLERS = {
658
- buttons: async (m, msg) => {
659
- const hasNativeFlow = msg.buttons.some(b => b.nativeFlowInfo || b.name || b.buttonParamsJson || b.url || b.call || b.sections)
660
- if (hasNativeFlow) {
661
- const interactive = { body: { text: msg.text || msg.caption || msg.contentText || '' }, footer: { text: msg.footer || msg.footerText || '' }, nativeFlowMessage: { buttons: resolveNativeFlowButtons(msg.buttons) } }
662
- if (msg.title) interactive.header = { title: msg.title, subtitle: msg.subtitle || '', hasMediaAttachment: msg.hasMediaAttachment || false }
663
- if (Object.keys(m).length) { interactive.header ??= { title: msg.title || '', hasMediaAttachment: true }; Object.assign(interactive.header, m) }
664
- await applyContextInfoAndMentions(interactive, msg)
665
- return { interactiveMessage: interactive }
666
- }
667
- const bm = { buttons: msg.buttons.map(b => ({ ...b, type: proto.Message.ButtonsMessage.Button.Type.RESPONSE })) }
668
- if ('text' in msg) { bm.contentText = msg.text; bm.headerType = proto.Message.ButtonsMessage.HeaderType.EMPTY }
669
- else {
670
- if ('caption' in msg) bm.contentText = msg.caption
671
- const type = Object.keys(m)[0]?.replace('Message', '').toUpperCase()
672
- bm.headerType = proto.Message.ButtonsMessage.HeaderType[type] || proto.Message.ButtonsMessage.HeaderType.EMPTY
673
- Object.assign(bm, m)
674
- }
675
- if (msg.title) { bm.text = msg.title; bm.headerType = proto.Message.ButtonsMessage.HeaderType.TEXT }
676
- if (msg.footer) bm.footerText = msg.footer
677
- if (msg.contextInfo) bm.contextInfo = { ...(bm.contextInfo || {}), ...msg.contextInfo }
678
- if (msg.mentions?.length) bm.contextInfo = { ...(bm.contextInfo || {}), mentionedJid: msg.mentions }
679
- return { buttonsMessage: bm }
680
- },
681
- templateButtons: (m, msg) => {
682
- const ht = { hydratedButtons: msg.templateButtons, ...('text' in msg ? { hydratedContentText: msg.text } : { ...('caption' in msg ? { hydratedContentText: msg.caption } : {}), ...m }) }
683
- if (msg.footer) ht.hydratedFooterText = msg.footer
684
- if (msg.contextInfo) ht.contextInfo = { ...(ht.contextInfo || {}), ...msg.contextInfo }
685
- if (msg.mentions?.length) ht.contextInfo = { ...(ht.contextInfo || {}), mentionedJid: msg.mentions }
686
- return { templateMessage: { fourRowTemplate: ht, hydratedTemplate: ht } }
687
- },
688
- audioFooter: async (m, msg, opts) => {
689
- const audio = await prepareWAMessageMedia({ audio: msg.audioFooter }, { upload: opts.upload ?? opts.waUploadToServer })
690
- const buttons = resolveNativeFlowButtons(Array.isArray(msg.nativeFlow) ? msg.nativeFlow : [msg.nativeFlow])
691
- return { interactiveMessage: { body: { text: msg.text || '' }, footer: { text: msg.footer || '' }, header: { hasMediaAttachment: false }, nativeFlowMessage: { buttons }, footerColumns: [{ audioMessage: audio.audioMessage }] } }
692
- },
693
- interactiveButtons: async (m, msg) => {
694
- const interactive = { nativeFlowMessage: proto.Message.InteractiveMessage.NativeFlowMessage.fromObject({ buttons: msg.interactiveButtons }) }
695
- if ('text' in msg) { interactive.body = { text: msg.text }; interactive.header = { title: msg.title || '', subtitle: msg.subtitle || '', hasMediaAttachment: false } }
696
- else if ('caption' in msg) { interactive.body = { text: msg.caption }; interactive.header = { title: msg.title || '', subtitle: msg.subtitle || '', hasMediaAttachment: msg.hasMediaAttachment ?? !!Object.keys(m).length }; if (Object.keys(m).length) Object.assign(interactive.header, m) }
697
- if (msg.footer) interactive.footer = { text: msg.footer }
698
- await applyContextInfoAndMentions(interactive, msg)
699
- return { interactiveMessage: interactive, messageContextInfo: { messageSecret: randomBytes(32) } }
700
- },
701
- shop: async (m, msg) => {
702
- const interactive = { shopStorefrontMessage: proto.Message.InteractiveMessage.ShopMessage.fromObject({ surface: msg.shop.surface || 1, id: msg.shop.id || msg.id }) }
703
- if ('text' in msg) interactive.body = { text: msg.text }
704
- else if ('caption' in msg) interactive.body = { text: msg.caption }
705
- if (msg.title || Object.keys(m).length) { interactive.header = { title: msg.title || '', subtitle: msg.subtitle || '', hasMediaAttachment: msg.hasMediaAttachment ?? !!Object.keys(m).length }; if (Object.keys(m).length) Object.assign(interactive.header, m) }
706
- if (msg.footer) interactive.footer = { text: msg.footer }
707
- await applyContextInfoAndMentions(interactive, msg)
708
- return { interactiveMessage: interactive }
709
- },
710
- collection: async (m, msg) => {
711
- const interactive = { collectionMessage: { bizJid: msg.collection.bizJid, id: msg.collection.id, messageVersion: msg.collection.version } }
712
- if ('text' in msg) { interactive.body = { text: msg.text }; interactive.header = { title: msg.title || '', hasMediaAttachment: false } }
713
- else if ('caption' in msg) { interactive.body = { text: msg.caption }; interactive.header = { title: msg.title || '', hasMediaAttachment: msg.hasMediaAttachment ?? false }; if (Object.keys(m).length) Object.assign(interactive.header, m) }
714
- if (msg.footer) interactive.footer = { text: msg.footer }
715
- await applyContextInfoAndMentions(interactive, msg)
716
- return { interactiveMessage: interactive }
717
- },
718
- }
719
-
720
- // ─── MESSAGE CONTENT GENERATION ───────────────────────────────────────────────
721
-
722
- export const generateWAMessageContent = async (message, options = {}) => {
723
- if (!message || typeof message !== 'object') return proto.Message.create({})
724
- const msgKeys = Object.keys(message)
725
- const isWrapper = msgKeys.some(k => WRAPPER_KEYS.has(k))
726
- // raw proto pass-through: no high-level keys present, or is a known wrapper type
727
- if (isWrapper || (!msgKeys.some(k => HIGH_LEVEL_KEYS.has(k)) && msgKeys.some(k => k.endsWith('Message') || k === 'conversation'))) return proto.Message.create(message)
728
-
729
- let m = {}
730
- const overlayKeys = Object.keys(OVERLAY_HANDLERS)
731
- if ('text' in message && !overlayKeys.some(k => k in message)) {
732
- m = await MESSAGE_HANDLERS.text(message, options)
733
- } else {
734
- const handlerKey = msgKeys.find(k => k !== 'text' && !MEDIA_PROP_KEYS.has(k) && MESSAGE_HANDLERS[k])
735
- if (handlerKey) {
736
- const result = await MESSAGE_HANDLERS[handlerKey](message, options)
737
- if (result?._batched) return { stickerPackMessage: result.stickerPackMessage, isBatched: true, batchCount: result.batchCount }
738
- if (result?._finalize) return proto.Message.create({ stickerPackMessage: result.stickerPackMessage })
739
- if (result?._associatedFlow) return result
740
- m = result
741
- } else if ([...USER_MEDIA_KEYS].some(k => k in message) || MEDIA_KEYS.some(k => k in message)) {
742
- m = await prepareWAMessageMedia(message, options)
743
- }
744
- }
745
-
746
- for (const key of overlayKeys) { if (key in message && message[key]) { m = await OVERLAY_HANDLERS[key](m, message, options); break } }
747
-
748
- // deep-merge contextInfo/mentions onto the primary content key
749
- const finalKey = Object.keys(m)[0]
750
- if ((message.contextInfo || message.mentions?.length) && finalKey && m[finalKey] && typeof m[finalKey] === 'object') {
751
- const existing = m[finalKey].contextInfo || {}, incoming = message.contextInfo || {}
752
- const mergedExt = (existing.externalAdReply || incoming.externalAdReply) ? await normalizeExternalAdReplyThumbnail({ ...(existing.externalAdReply || {}), ...(incoming.externalAdReply || {}) }) : undefined
753
- m[finalKey].contextInfo = { ...existing, ...incoming, ...(mergedExt ? { externalAdReply: mergedExt } : {}), ...(message.mentions?.length ? { mentionedJid: message.mentions } : {}) }
754
- }
755
-
756
- if ('viewOnce' in message && message.viewOnce) m = { viewOnceMessage: { message: m } }
757
- if ('edit' in message) m = { protocolMessage: { key: message.edit, editedMessage: m, timestampMs: Date.now(), type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT } }
758
-
759
- if (shouldIncludeReportingToken(m)) { m.messageContextInfo ??= {}; m.messageContextInfo.messageSecret ??= randomBytes(32) }
760
- return proto.Message.create(m)
761
- }
762
-
763
- // ─── ASSEMBLE FULL WA MESSAGE ─────────────────────────────────────────────────
764
-
765
- export const generateWAMessageFromContent = (jid, message, options) => {
766
- const upload = options.upload ?? options.waUploadToServer
767
- const assemble = () => {
768
- if (!options.timestamp) options.timestamp = new Date()
769
- const innerMessage = normalizeMessageContent(message)
770
- const key = getContentType(innerMessage)
771
- const { quoted, userJid } = options
772
- if (quoted && !isJidNewsletter(jid)) {
773
- const participant = quoted.key.fromMe ? userJid : (quoted.participant || quoted.key.participant || quoted.key.remoteJid)
774
- const normalizedQuoted = normalizeMessageContent(quoted.message)
775
- if (normalizedQuoted) {
776
- const quotedType = getContentType(normalizedQuoted)
777
- const quotedMsg = proto.Message.fromObject({ [quotedType]: normalizedQuoted[quotedType] })
778
- const quotedContent = quotedMsg[quotedType]
779
- if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) delete quotedContent.contextInfo
780
- const contextInfo = innerMessage[key]?.contextInfo || {}
781
- contextInfo.participant = jidNormalizedUser(participant)
782
- contextInfo.stanzaId = quoted.key.id
783
- contextInfo.quotedMessage = quotedMsg
784
- if (jid !== quoted.key.remoteJid) contextInfo.remoteJid = quoted.key.remoteJid
785
- if (innerMessage[key]) innerMessage[key].contextInfo = contextInfo
786
- }
787
- }
788
- if (options?.ephemeralExpiration && key !== 'protocolMessage' && key !== 'ephemeralMessage' && !isJidNewsletter(jid)) {
789
- innerMessage[key].contextInfo = { ...(innerMessage[key].contextInfo || {}), expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL }
790
- }
791
- return proto.WebMessageInfo.fromObject({
792
- key: { remoteJid: jid, fromMe: true, id: options?.messageId || generateMessageIDV2() },
793
- message: proto.Message.create(message),
794
- messageTimestamp: unixTimestampSeconds(options.timestamp),
795
- messageStubParameters: [],
796
- participant: (isJidGroup(jid) || isJidStatusBroadcast(jid)) ? userJid : undefined,
797
- status: WAMessageStatus.PENDING,
798
- })
799
- }
800
- const result = assemble()
801
- if (!upload) return result
802
- return Object.assign(result, { then(resolve, reject) { resolveMedia(message, upload).then(() => resolve(assemble())).catch(reject) } })
803
- }
804
-
805
- export const associatedFlowRelayed = new WeakSet()
806
- export const generateWAMessageFromAssociatedFlow = async (jid, parentContent, children, associationType, relay, options = {}) => {
807
- const parent = await generateWAMessage(jid, parentContent, options)
808
- const childMessages = await Promise.all(children.map(async (child, i) => {
809
- const msg = proto.Message.create({
810
- ...await generateWAMessageContent(child, { ...options, jid }),
811
- messageContextInfo: { messageAssociation: { associationType, parentMessageKey: parent.key, messageIndex: i } },
812
- })
813
- return generateWAMessageFromContent(jid, msg, { ...options, messageId: undefined })
814
- }))
815
- await relay(parent.message, { messageId: parent.key.id }, parent)
816
- for (const child of childMessages) await relay(child.message, { messageId: child.key.id }, child)
817
- associatedFlowRelayed.add(parent)
818
- return parent
819
- }
820
-
821
- // generateWAMessage is the main entry point — handles associated flows, poll image children, and standard messages
822
- export const generateWAMessage = async (jid, content, options = {}) => {
823
- if (content?.key?.remoteJid && content?.message) return content
824
- const msgId = options.messageId || generateMessageIDV2()
825
- options.logger = options?.logger?.child({ msgId })
826
- const flowKey = content && typeof content === 'object' ? Object.keys(content).find(k => k in ASSOCIATED_FLOW_KEYS) : null
827
- if (flowKey) {
828
- if (typeof options.relay !== 'function') return generateWAMessageFromContent(jid, await generateWAMessageContent(content, { ...options, jid, messageId: msgId }), { ...options, messageId: msgId })
829
- const msg = content[flowKey]
830
- const items = Array.isArray(msg) ? msg : Array.isArray(msg?.items) ? msg.items : null
831
- if (items) {
832
- const [first, ...rest] = items
833
- return generateWAMessageFromAssociatedFlow(jid, first, rest, ASSOCIATED_FLOW_KEYS[flowKey], options.relay, { ...options, messageId: msgId })
834
- }
835
- const allMediaKeys = new Set([...MEDIA_KEYS, 'image', 'video', 'audio', 'sticker', 'document'])
836
- const sharedProps = Object.fromEntries(Object.entries(msg).filter(([k]) => !allMediaKeys.has(k)))
837
- const [[pk, pv], ...childEntries] = Object.entries(msg).filter(([k]) => allMediaKeys.has(k))
838
- return generateWAMessageFromAssociatedFlow(jid, { [pk]: pv, ...sharedProps }, childEntries.map(([k, v]) => ({ [k]: v })), ASSOCIATED_FLOW_KEYS[flowKey], options.relay, { ...options, messageId: msgId })
839
- }
840
- const resolved = await generateWAMessageContent(content, { ...options, jid, messageId: msgId })
841
- if (resolved?._associatedFlow) {
842
- if (typeof options.relay !== 'function') throw new Boom('this message type requires a relay option', { statusCode: 400 })
843
- return generateWAMessageFromAssociatedFlow(jid, resolved._parent, resolved._children, resolved.associationType, options.relay, { ...options, messageId: msgId })
844
- }
845
- return generateWAMessageFromContent(jid, resolved, { ...options, messageId: msgId })
846
- }
847
-
848
- // ─── UPDATE UTILITIES ─────────────────────────────────────────────────────────
849
-
850
- export const updateMessageWithReceipt = (msg, receipt) => {
851
- msg.userReceipt ||= []
852
- const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid)
853
- if (recp) Object.assign(recp, receipt)
854
- else msg.userReceipt.push(receipt)
855
- }
856
-
857
- export const updateMessageWithReaction = (msg, reaction) => {
858
- const authorID = getKeyAuthor(reaction.key)
859
- msg.reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID)
860
- reaction.text ||= ''
861
- msg.reactions.push(reaction)
862
- }
863
-
864
- export const updateMessageWithPollUpdate = (msg, update) => {
865
- const authorID = getKeyAuthor(update.pollUpdateMessageKey)
866
- msg.pollUpdates = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID)
867
- if (update.vote?.selectedOptions?.length) msg.pollUpdates.push(update)
868
- }
869
-
870
- export const updateMessageWithEventResponse = (msg, update) => {
871
- const authorID = getKeyAuthor(update.eventResponseMessageKey)
872
- msg.eventResponses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID)
873
- msg.eventResponses.push(update)
874
- }
875
-
876
- export const getAggregateVotesInPollMessage = ({ message, pollUpdates }, meId) => {
877
- const opts = message?.pollCreationMessage?.options || message?.pollCreationMessageV2?.options || message?.pollCreationMessageV3?.options || []
878
- const voteHashMap = opts.reduce((acc, opt) => { acc[sha256(Buffer.from(opt.optionName || '')).toString()] = { name: opt.optionName || '', voters: [] }; return acc }, {})
879
- for (const update of pollUpdates || []) {
880
- if (!update.vote) continue
881
- for (const option of update.vote.selectedOptions || []) {
882
- const hash = option.toString()
883
- voteHashMap[hash] ||= { name: 'Unknown', voters: [] }
884
- voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId))
885
- }
886
- }
887
- return Object.values(voteHashMap)
888
- }
889
-
890
- export const getAggregateResponsesInEventMessage = ({ eventResponses }, meId) => {
891
- const responseMap = { GOING: { response: 'GOING', responders: [] }, NOT_GOING: { response: 'NOT_GOING', responders: [] }, MAYBE: { response: 'MAYBE', responders: [] } }
892
- for (const update of eventResponses || []) { const type = update.eventResponse || 'UNKNOWN'; if (responseMap[type]) responseMap[type].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId)) }
893
- return Object.values(responseMap)
894
- }
895
-
896
- export const aggregateMessageKeysNotFromMe = keys => {
897
- const keyMap = {}
898
- for (const { remoteJid, id, participant, fromMe } of keys) {
899
- if (!fromMe) { const uqKey = `${remoteJid}:${participant || ''}`; keyMap[uqKey] ||= { jid: remoteJid, participant, messageIds: [] }; keyMap[uqKey].messageIds.push(id) }
900
- }
901
- return Object.values(keyMap)
902
- }
903
-
904
- export const downloadMediaMessage = async (message, type, options, ctx) => {
905
- const downloadMsg = async () => {
906
- let normalized = message
907
- if (!message.message && message.key) normalized = { key: message.key, message: message.quoted?.message || message, messageTimestamp: message.messageTimestamp }
908
- const mContent = extractMessageContent(normalized.message)
909
- if (!mContent) throw new Boom('No message present', { statusCode: 400, data: message })
910
- const contentType = getContentType(mContent)
911
- let mediaType = contentType?.replace('Message', '')
912
- const media = mContent[contentType]
913
- if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) throw new Boom(`"${contentType}" message is not a media message`)
914
- const download = ('thumbnailDirectPath' in media && !('url' in media)) ? { directPath: media.thumbnailDirectPath, mediaKey: media.mediaKey } : media
915
- if ('thumbnailDirectPath' in media && !('url' in media)) mediaType = 'thumbnail-link'
916
- const stream = await downloadContentFromMessage(download, mediaType, options)
917
- if (type === 'buffer') return toBuffer(stream)
918
- return stream
919
- }
920
- return downloadMsg().catch(async error => {
921
- if (ctx && typeof error?.status === 'number' && REUPLOAD_REQUIRED_STATUS.includes(error.status)) { ctx.logger.info({ key: message.key }, 'sending reupload media request...'); message = await ctx.reuploadRequest(message); return downloadMsg() }
922
- throw error
923
- })
924
- }
925
-
926
- export const assertMediaContent = content => {
927
- content = extractMessageContent(content)
928
- const mediaContent = content?.documentMessage || content?.imageMessage || content?.videoMessage || content?.audioMessage || content?.stickerMessage || content?.stickerPackMessage
929
- if (!mediaContent) throw new Boom('given message is not a media message', { statusCode: 400, data: content })
930
- return mediaContent
931
- }
932
-
933
- export const getDevice = id => /^3A.{18}$/.test(id) ? 'ios' : /^3E.{20}$/.test(id) ? 'web' : /^(.{21}|.{32})$/.test(id) ? 'android' : /^(3F|.{18}$)/.test(id) ? 'desktop' : 'unknown'
934
-
935
- export const patchMessageForMdIfRequired = message => {
936
- if (message?.buttonsMessage || message?.templateMessage || message?.listMessage || message?.interactiveMessage?.nativeFlowMessage) {
937
- message = { viewOnceMessageV2Extension: { message: { messageContextInfo: { deviceListMetadataVersion: 2, deviceListMetadata: {} }, ...message } } }
938
- }
939
- return message
940
- }
941
-
942
- export const hasNonNullishProperty = (message, key) => typeof message === 'object' && message !== null && key in message && message[key] !== null && message[key] !== undefined
1
+ import { Boom } from '@hapi/boom'
2
+ import { Sticker, StickerTypes } from 'wa-sticker-formatter'
3
+ import sharp from 'sharp'
4
+ import { fileTypeFromBuffer } from 'file-type'
5
+ import ffmpegStatic from 'ffmpeg-static'
6
+ import { randomBytes } from 'crypto'
7
+ import { promises as fs, readFileSync, mkdtempSync, writeFileSync, rmSync } from 'fs'
8
+ import { gunzipSync } from 'zlib'
9
+ import path from 'path'
10
+ import { execFile } from 'child_process'
11
+ import { zip } from 'fflate'
12
+ import { createRequire } from 'module'
13
+ import { proto } from '../../WAProto/index.js'
14
+ import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js'
15
+ import { WAMessageStatus } from '../Types/index.js'
16
+ import { isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js'
17
+ import { sha256 } from './crypto.js'
18
+ import { resolveNativeFlowButtons } from './native-flow.js'
19
+ import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js'
20
+ import { downloadContentFromMessage, encryptedStream, prepareStream, generateThumbnail, getAudioDuration, getAudioWaveform, toBuffer, normalizeToBuffer, tmpdir } from './messages-media.js'
21
+ import { shouldIncludeReportingToken } from './reporting-utils.js'
22
+
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
+ 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
+
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
+ ])
39
+
40
+ // wrapper field = proto.Message field whose sub-message has a 'message' field pointing back to proto.Message
41
+ const WRAPPER_KEYS = new Set(
42
+ Object.entries(proto.Message.fields)
43
+ .filter(([, fd]) => fd.type === 'msg' && proto.Message[fd.msgType]?.fields?.message?.msgType === 'Message')
44
+ .map(([name]) => name)
45
+ )
46
+
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
+ const ASSOCIATED_FLOW_KEYS = Object.fromEntries(
51
+ Object.entries(proto.MessageAssociation?.AssociationType ?? {})
52
+ .filter(([, v]) => typeof v === 'number' && v !== 0)
53
+ .map(([name, value]) => [toCamel(name), value])
54
+ )
55
+ export const USER_MEDIA_KEYS = new Set(['image', 'video', 'ptv', 'audio', 'document', 'sticker'])
56
+ const MEDIA_PROP_KEYS = new Set([
57
+ // bare media type keys: image, video, audio, etc.
58
+ ...USER_MEDIA_KEYS,
59
+ // scalar fields on proto.Message itself (conversation, backgroundArgb, etc.)
60
+ ...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
+ ...[...USER_MEDIA_KEYS].flatMap(t => {
63
+ const MsgType = proto.Message[t.charAt(0).toUpperCase() + t.slice(1) + 'Message']
64
+ return Object.keys(MsgType?.fields ?? {}).filter(k => MsgType.fields[k].type !== 'msg')
65
+ }),
66
+ ])
67
+ Object.keys(ASSOCIATED_FLOW_KEYS).forEach(k => HIGH_LEVEL_KEYS.add(k))
68
+
69
+ 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
+
78
+ // ─── STICKER ──────────────────────────────────────────────────────────────────
79
+
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]
89
+ }
90
+
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
95
+ 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
+ }
141
+
142
+ let _rlottieApi = null
143
+ const getRlottieApi = async () => {
144
+ 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'))
148
+ return _rlottieApi
149
+ }
150
+
151
+ const tgsToWebp = async (tgsBuffer, { quality = 80, fps = 30 } = {}) => {
152
+ const lottieJson = JSON.parse(gunzipSync(tgsBuffer).toString())
153
+ const api = await getRlottieApi()
154
+ const W = 512, H = 512, handle = api.lottie_init()
155
+ const jsonBuf = Buffer.from(JSON.stringify(lottieJson) + '\0')
156
+ const ptr = api._malloc(jsonBuf.length)
157
+ api.HEAPU8.set(jsonBuf, ptr)
158
+ const totalFrames = api.lottie_load_from_data(handle, ptr)
159
+ api.lottie_resize(handle, W, H)
160
+ const bufPtr = api.lottie_buffer(handle)
161
+ const tgsTmpDir = mkdtempSync(path.join(tmpdir(), 'tgs_'))
162
+ try {
163
+ for (let i = 0; i < totalFrames; i++) {
164
+ api.lottie_render(handle, i)
165
+ const rgba = Buffer.from(api.HEAPU8.buffer, bufPtr, W * H * 4)
166
+ await sharp(Buffer.from(rgba), { raw: { width: W, height: H, channels: 4 } }).png().toFile(path.join(tgsTmpDir, `f${String(i).padStart(4, '0')}.png`))
167
+ }
168
+ const encode = async (outFps, q) => {
169
+ 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])
171
+ return readFileSync(outPath)
172
+ }
173
+ 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))
176
+ 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)))
179
+ } finally { api.lottie_destroy(handle); rmSync(tgsTmpDir, { recursive: true, force: true }) }
180
+ }
181
+
182
+ // ─── URL / LINK PREVIEW ───────────────────────────────────────────────────────
183
+
184
+ export const extractUrlFromText = text => text.match(URL_REGEX)?.[0]
185
+
186
+ export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
187
+ const url = extractUrlFromText(text)
188
+ if (!getUrlInfo || !url) return
189
+ try { return await getUrlInfo(url) } catch (e) { logger?.warn({ trace: e.stack }, 'url generation failed') }
190
+ }
191
+
192
+ // ─── MEDIA RESOLUTION ─────────────────────────────────────────────────────────
193
+
194
+ const RESOLVABLE_MEDIA = [
195
+ ...['Image', 'Video', 'Audio', 'Document', 'Sticker'].map(t => ({ key: `${t.toLowerCase()}Message`, type: t.toLowerCase() })),
196
+ { key: 'image', type: 'image' },
197
+ { key: 'video', type: 'video' },
198
+ ]
199
+
200
+ const resolveMedia = async (obj, upload) => {
201
+ if (!obj || typeof obj !== 'object' || typeof upload !== 'function') return
202
+ for (const { key, type } of RESOLVABLE_MEDIA) {
203
+ if (!obj[key]) continue
204
+ const isRaw = key === 'image' || key === 'video'
205
+ if (!isRaw && obj[key].directPath) continue
206
+ const src = isRaw ? obj[key] : (obj[key].url ?? obj[key])
207
+ const result = await prepareWAMessageMedia({ [type]: typeof src === 'string' ? { url: src } : src }, { upload })
208
+ if (isRaw) { obj[`${type}Message`] = result[`${type}Message`]; delete obj[key] }
209
+ else obj[key] = result[`${type}Message`]
210
+ if ('hasMediaAttachment' in obj) obj.hasMediaAttachment = true
211
+ }
212
+ for (const val of Object.values(obj)) {
213
+ if (Array.isArray(val)) for (const item of val) await resolveMedia(item, upload)
214
+ else if (val && typeof val === 'object') await resolveMedia(val, upload)
215
+ }
216
+ }
217
+
218
+ // ─── MESSAGE HELPERS ──────────────────────────────────────────────────────────
219
+
220
+ export const getContentType = content => {
221
+ if (!content) return
222
+ return Object.keys(content).find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage')
223
+ }
224
+
225
+ export const normalizeMessageContent = (content, logger) => {
226
+ if (!content) return
227
+ for (let i = 0; i < 5; i++) {
228
+ let inner = null
229
+ for (const k of WRAPPER_KEYS) { if (content?.[k]) { inner = content[k]; break } }
230
+ if (!inner) break
231
+ if (!inner.message) { logger?.warn({ i, keys: Object.keys(inner) }, 'normalizeMessageContent: inner wrapper has no message field'); break }
232
+ content = inner.message
233
+ }
234
+ return content
235
+ }
236
+
237
+ export const extractMessageContent = content => {
238
+ content = normalizeMessageContent(content)
239
+ for (const t of ['image', 'video', 'audio', 'document']) { if (content?.[`${t}Message`]?.viewOnce) return { [`${t}Message`]: content[`${t}Message`] } }
240
+ const fromButtons = msg => {
241
+ for (const t of ['image', 'document', 'video', 'location', 'product']) { if (msg[`${t}Message`]) return { [`${t}Message`]: msg[`${t}Message`] } }
242
+ return { conversation: msg.contentText || msg.hydratedContentText || msg.body?.text || '' }
243
+ }
244
+ if (content?.buttonsMessage) return fromButtons(content.buttonsMessage)
245
+ if (content?.interactiveMessage) return fromButtons(content.interactiveMessage)
246
+ for (const v of ['interactiveMessageTemplate', 'hydratedFourRowTemplate', 'hydratedTemplate', 'fourRowTemplate']) {
247
+ if (content?.templateMessage?.[v]) return fromButtons(content.templateMessage[v])
248
+ }
249
+ return content
250
+ }
251
+
252
+ const normalizeExternalAdReplyThumbnail = async ext => {
253
+ if (!ext?.thumbnail) return ext
254
+ const thumb = await normalizeToBuffer(ext.thumbnail)
255
+ if (!thumb || thumb.length <= 50_000) return { ...ext, thumbnail: thumb }
256
+ let quality = 90
257
+ while (quality >= 10) {
258
+ const thumbnail = await sharp(ext.thumbnail, { sequentialRead: true }).resize(200, 200, { fit: 'inside' }).jpeg({ quality }).toBuffer().catch(() => null)
259
+ if (!thumbnail) return ext
260
+ if (thumbnail.length <= 50_000) return { ...ext, thumbnail }
261
+ quality = Math.max(10, Math.floor(quality * (50_000 / thumbnail.length) * 0.85))
262
+ }
263
+ return ext
264
+ }
265
+
266
+ export const generateForwardMessageContent = (message, forceForward) => {
267
+ let content = normalizeMessageContent(message.message)
268
+ if (!content) throw new Boom('no content in message', { statusCode: 400 })
269
+ content = proto.Message.decode(proto.Message.encode(content).finish())
270
+ let key = Object.keys(content)[0]
271
+ const score = (content?.[key]?.contextInfo?.forwardingScore || 0) + (message.key.fromMe && !forceForward ? 0 : 1)
272
+ if (key === 'conversation') { content.extendedTextMessage = { text: content[key] }; delete content.conversation; key = 'extendedTextMessage' }
273
+ content[key].contextInfo = score > 0 ? { forwardingScore: score, isForwarded: true } : {}
274
+ return content
275
+ }
276
+
277
+ export const prepareDisappearingMessageSettingContent = ephemeralExpiration => proto.Message.fromObject({
278
+ ephemeralMessage: { message: { protocolMessage: { type: proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING, ephemeralExpiration: ephemeralExpiration || 0 } } }
279
+ })
280
+
281
+ const assertColor = color => {
282
+ if (typeof color === 'number') return color > 0 ? color : 0xffffffff + Number(color) + 1
283
+ const hex = color.trim().replace('#', '')
284
+ return parseInt(hex.length <= 6 ? 'FF' + hex.padStart(6, '0') : hex, 16)
285
+ }
286
+
287
+ // ─── MEDIA ────────────────────────────────────────────────────────────────────
288
+
289
+ export const prepareWAMessageMedia = async (message, options) => {
290
+ const mediaType = MEDIA_KEYS.find(k => k in message)
291
+ if (!mediaType) throw new Boom('Invalid media type', { statusCode: 400 })
292
+ const protoKey = `${mediaType}Message`
293
+ const uploadData = { ...message, media: message[mediaType] }
294
+ delete uploadData[mediaType]
295
+ if (mediaType === 'document' && !uploadData.fileName) uploadData.fileName = 'file'
296
+ if (!uploadData.mimetype) uploadData.mimetype = MIMETYPE_DEFAULTS[mediaType] || 'application/octet-stream'
297
+
298
+ if (mediaType === 'sticker') {
299
+ try {
300
+ const packName = message.pack || message.packName || options?.pack || options?.packName || 'ZervonexStickers'
301
+ const authorName = message.author || message.publisher || message.packPublisher || options?.author || options?.publisher || options?.packPublisher || 'Zervonex'
302
+ const { buffer } = await compressWebp(await toBuffer(uploadData.media), { packName, authorName, stickerType: message.stickerType || options?.stickerType || StickerTypes.ROUNDED, quality: message.quality || options?.quality || 80 })
303
+ uploadData.media = buffer
304
+ uploadData.stickerSentTs = Date.now()
305
+ if (message.premium != null) uploadData.premium = message.premium
306
+ const rawAudio = message.audio ?? message.stickerAudio ?? message.audioFooter
307
+ if (rawAudio != null) try { uploadData.audioMessage = (await prepareWAMessageMedia({ audio: rawAudio }, options)).audioMessage } catch (e) { options.logger?.warn({ err: e }, 'sticker audio preparation failed') }
308
+ else if (message.audioMessage != null) uploadData.audioMessage = message.audioMessage
309
+ } catch (e) { options.logger?.warn({ err: e }, 'sticker formatting failed, sending raw') }
310
+ }
311
+
312
+ const cacheableKey = typeof uploadData.media === 'object' && 'url' in uploadData.media && uploadData.media.url && options.mediaCache
313
+ ? `${mediaType}:${uploadData.media.url.toString()}` : null
314
+ if (cacheableKey) {
315
+ const cached = await options.mediaCache?.get(cacheableKey)
316
+ if (cached) {
317
+ const obj = proto.Message.decode(cached)
318
+ Object.assign(obj[protoKey], { ...uploadData, media: undefined })
319
+ return obj
320
+ }
321
+ }
322
+
323
+ const isNewsletter = !!options.jid && isJidNewsletter(options.jid)
324
+ const requiresDuration = mediaType === 'audio' && typeof uploadData.seconds === 'undefined'
325
+ const requiresThumbnail = (mediaType === 'image' || mediaType === 'video') && typeof uploadData.jpegThumbnail === 'undefined'
326
+ if (uploadData.jpegThumbnail) uploadData.jpegThumbnail = await normalizeToBuffer(uploadData.jpegThumbnail)
327
+ const requiresWaveform = mediaType === 'audio' && (uploadData.ptt === true || !!options.backgroundColor)
328
+
329
+ const enc = await (isNewsletter ? prepareStream : encryptedStream)(uploadData.media, options.mediaTypeOverride || mediaType, {
330
+ logger: options.logger, saveOriginalFileIfRequired: requiresDuration || requiresThumbnail || requiresWaveform,
331
+ opts: options.options, isPtt: uploadData.ptt, forceOpus: mediaType === 'audio' && uploadData.mimetype?.includes('opus'), convertVideo: mediaType === 'video',
332
+ })
333
+ const { mediaKey, encWriteStream, bodyPath, fileEncSha256, fileSha256, fileLength, opusConverted, encFilePath, encBuffer, cleanup } = enc
334
+ if (mediaType === 'audio' && opusConverted) uploadData.mimetype = 'audio/ogg; codecs=opus'
335
+ const fileEncSha256B64 = (isNewsletter ? fileSha256 : (fileEncSha256 ?? fileSha256)).toString('base64')
336
+
337
+ const [{ mediaUrl, directPath, handle }] = await Promise.all([
338
+ (options.upload ?? options.waUploadToServer)(encFilePath || encBuffer || encWriteStream, { fileEncSha256B64, mediaType, timeoutMs: options.mediaUploadTimeoutMs }),
339
+ (async () => {
340
+ try {
341
+ if (requiresThumbnail) {
342
+ const { thumbnail, originalImageDimensions } = await generateThumbnail(bodyPath, mediaType, options)
343
+ uploadData.jpegThumbnail = thumbnail
344
+ if (!uploadData.width && originalImageDimensions) { uploadData.width = originalImageDimensions.width; uploadData.height = originalImageDimensions.height }
345
+ }
346
+ if (requiresDuration) uploadData.seconds = await getAudioDuration(bodyPath)
347
+ if (requiresWaveform) {
348
+ try { uploadData.waveform = await getAudioWaveform(bodyPath, options.logger) } catch {
349
+ uploadData.waveform = new Uint8Array([0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99, 0, 99, 0, 99, 0, 99, 0, 99, 88, 99, 0, 99, 0, 55, 0, 99])
350
+ }
351
+ }
352
+ if (options.backgroundColor && mediaType === 'audio') uploadData.backgroundArgb = assertColor(options.backgroundColor)
353
+ } catch (e) { options.logger?.warn({ trace: e.stack }, 'failed to obtain extra info') }
354
+ })()
355
+ ]).finally(async () => {
356
+ if (encWriteStream && !Buffer.isBuffer(encWriteStream)) encWriteStream.destroy?.()
357
+ if (cleanup) await cleanup()
358
+ })
359
+
360
+ const CtorName = mediaType.charAt(0).toUpperCase() + mediaType.slice(1) + 'Message'
361
+ const Ctor = proto.Message[CtorName] || { fromObject: o => o }
362
+ const obj = proto.Message.fromObject({
363
+ [protoKey]: Ctor.fromObject({ url: handle ? undefined : mediaUrl, directPath, mediaKey, fileEncSha256, fileSha256, fileLength, mediaKeyTimestamp: handle ? undefined : unixTimestampSeconds(), ...uploadData, media: undefined })
364
+ })
365
+ if (uploadData.ptv) { obj.ptvMessage = obj.videoMessage; delete obj.videoMessage }
366
+ if (cacheableKey) await options.mediaCache?.set(cacheableKey, proto.Message.encode(obj).finish())
367
+ return obj
368
+ }
369
+
370
+ // ─── STICKER PACK ─────────────────────────────────────────────────────────────
371
+
372
+ export const prepareStickerPackMessage = async (stickerPack, options) => {
373
+ if (Array.isArray(stickerPack)) stickerPack = { stickers: stickerPack }
374
+ else if (stickerPack && typeof stickerPack === 'object' && !stickerPack.stickers) {
375
+ const keys = Object.keys(stickerPack)
376
+ if (keys.length && keys.every(k => !isNaN(k))) stickerPack = { stickers: Object.values(stickerPack) }
377
+ }
378
+ const { stickers, cover, name, publisher, packId, packName: packNameAlias, packPublisher, author } = stickerPack
379
+ if (!stickers?.length) throw new Boom('Sticker pack must contain at least one sticker', { statusCode: 400 })
380
+ const stickerPackIdValue = packId || generateMessageIDV2()
381
+ const packName = name || packNameAlias || options?.packName || options?.name || 'ZervonexStickers'
382
+ const authorName = publisher || packPublisher || author || options?.packPublisher || options?.publisher || options?.author || 'Zervonex'
383
+ const MAX_STICKERS_PER_PACK = 60, skippedStickers = []
384
+ const runWithLimit = (() => {
385
+ const limit = 6, queue = []
386
+ let running = 0
387
+ return fn => new Promise((resolve, reject) => {
388
+ const run = () => { running++; fn().then(resolve, reject).finally(() => { running--; queue.shift()?.() }) }
389
+ running < limit ? run() : queue.push(run)
390
+ })
391
+ })()
392
+
393
+ const processSticker = async (s, i) => {
394
+ const uid = generateMessageIDV2()
395
+ const tmpOut = path.join(tmpdir(), `stk_out_${i}_${uid}.webp`)
396
+ try {
397
+ const raw = s.data || s.sticker || s.buffer || s.image || s.webp || s.file || s.path || s.url
398
+ if (!raw) { skippedStickers.push({ index: i, reason: 'No sticker data found' }); return null }
399
+ const buf = await normalizeToBuffer(raw)
400
+ if (!buf?.length) { skippedStickers.push({ index: i, reason: 'Empty buffer' }); return null }
401
+ const emojis = Array.isArray(s.emojis) ? s.emojis : Object.values(s.emojis || {})
402
+ let finalBuf
403
+ if (s.isLottie) {
404
+ finalBuf = await tagExif(await shrinkToLimit(await tgsToWebp(buf, { quality: 80, fps: 30 }), { animated: true }), packName, authorName)
405
+ } else if (s.isAnimated) {
406
+ const tmpIn = path.join(tmpdir(), `stk_in_${i}_${uid}.webp`), tmpRaw = path.join(tmpdir(), `stk_raw_${i}_${uid}.webp`)
407
+ writeFileSync(tmpIn, buf)
408
+ try {
409
+ await ffmpegRun(await buildArgs(s.type || StickerTypes.ROUNDED, tmpIn, tmpRaw, ['-vcodec', 'vp9', '-t', '10'], WEBP_ANIM_CODEC))
410
+ finalBuf = await tagExif(await shrinkToLimit(readFileSync(tmpRaw), { animated: true }), packName, authorName)
411
+ } finally { fs.unlink(tmpIn).catch(() => { }); fs.unlink(tmpRaw).catch(() => { }) }
412
+ } else {
413
+ finalBuf = await shrinkToLimit(await new Sticker(buf, { pack: packName, author: authorName, type: s.type || StickerTypes.ROUNDED, quality: 80 }).toBuffer(), { animated: false })
414
+ }
415
+ const hash = sha256(finalBuf).toString('base64').replace(/\//g, '-').replace(/=/g, '')
416
+ const fileSize = finalBuf.length
417
+ writeFileSync(tmpOut, finalBuf); finalBuf = null
418
+ 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 }) }
419
+ } catch (e) {
420
+ options.logger?.warn({ err: e }, `failed processing sticker at index ${i}`)
421
+ skippedStickers.push({ index: i, reason: e.message }); fs.unlink(tmpOut).catch(() => { }); return null
422
+ }
423
+ }
424
+
425
+ const processBatch = async (batch, batchIdx, totalBatches, coverFilePath) => {
426
+ const batchData = {}
427
+ for (const s of batch) batchData[s.fileName] = [new Uint8Array(readFileSync(s.filePath)), { level: 0 }]
428
+ const trayFile = totalBatches > 1 ? `${stickerPackIdValue}_batch${batchIdx}.webp` : `${stickerPackIdValue}.webp`
429
+ batchData[trayFile] = [new Uint8Array(readFileSync(coverFilePath)), { level: 0 }]
430
+ const zipBuf = await new Promise((resolve, reject) => zip(batchData, (err, data) => err ? reject(err) : resolve(Buffer.from(data))))
431
+ const upload = await encryptedStream(zipBuf, 'sticker-pack', { logger: options.logger, opts: options.options })
432
+ const uploadRes = await options.upload(upload.encFilePath || upload.encBuffer, { fileEncSha256B64: upload.fileEncSha256.toString('base64'), mediaType: 'sticker-pack', timeoutMs: options.mediaUploadTimeoutMs })
433
+ if (upload.encFilePath) fs.unlink(upload.encFilePath).catch(() => { })
434
+ let thumbRes = null
435
+ try {
436
+ const thumbTmpPath = path.join(tmpdir(), `stk_thumb_${generateMessageIDV2()}.jpg`)
437
+ await sharp(coverFilePath).resize(252, 252).jpeg().toFile(thumbTmpPath)
438
+ const thumbBuf = readFileSync(thumbTmpPath); fs.unlink(thumbTmpPath).catch(() => { })
439
+ const thumbUpload = await encryptedStream(thumbBuf, 'thumbnail-sticker-pack', { logger: options.logger, opts: options.options, mediaKey: upload.mediaKey })
440
+ thumbRes = await options.upload(thumbUpload.encFilePath || thumbUpload.encBuffer, { fileEncSha256B64: thumbUpload.fileEncSha256.toString('base64'), mediaType: 'thumbnail-sticker-pack', timeoutMs: options.mediaUploadTimeoutMs })
441
+ if (thumbUpload.encFilePath) fs.unlink(thumbUpload.encFilePath).catch(() => { })
442
+ thumbRes._enc = thumbUpload; thumbRes._thumbBuf = thumbBuf
443
+ } catch (e) { options.logger?.warn({ err: e }, 'failed generating sticker pack thumbnail') }
444
+ return {
445
+ name: totalBatches > 1 ? `${packName} (${batchIdx + 1}/${totalBatches})` : packName, publisher: authorName,
446
+ stickerPackId: totalBatches > 1 ? `${stickerPackIdValue}_${batchIdx}` : stickerPackIdValue,
447
+ stickerPackOrigin: proto.Message.StickerPackMessage.StickerPackOrigin.USER_CREATED, stickerPackSize: zipBuf.length,
448
+ stickers: batch.map(s => ({ fileName: s.fileName, mimetype: s.mimetype, isAnimated: s.isAnimated, isLottie: s.isLottie, emojis: s.emojis, accessibilityLabel: s.accessibilityLabel, ...(s.premium != null && { premium: s.premium }) })),
449
+ fileSha256: upload.fileSha256, fileEncSha256: upload.fileEncSha256, mediaKey: upload.mediaKey,
450
+ directPath: uploadRes.directPath, fileLength: upload.fileLength, mediaKeyTimestamp: unixTimestampSeconds(), trayIconFileName: trayFile,
451
+ ...(thumbRes && { thumbnailDirectPath: thumbRes.directPath, thumbnailHeight: 252, thumbnailWidth: 252, thumbnailSha256: thumbRes._enc?.fileSha256, thumbnailEncSha256: thumbRes._enc?.fileEncSha256, imageDataHash: thumbRes._thumbBuf ? sha256(thumbRes._thumbBuf).toString('base64') : undefined }),
452
+ }
453
+ }
454
+
455
+ const coverTmpPath = path.join(tmpdir(), `stk_cover_${generateMessageIDV2()}.webp`)
456
+ let coverFilePath
457
+ try {
458
+ if (cover) {
459
+ const coverBuf = await normalizeToBuffer(cover)
460
+ const isWebp = coverBuf[0] === 0x52 && coverBuf[1] === 0x49 && coverBuf[8] === 0x57 && coverBuf[9] === 0x45
461
+ writeFileSync(coverTmpPath, isWebp ? coverBuf : await new Sticker(coverBuf, { pack: packName, author: authorName, type: StickerTypes.ROUNDED, quality: 95 }).toBuffer())
462
+ coverFilePath = coverTmpPath
463
+ }
464
+ const allProcessed = (await Promise.all(stickers.map((s, j) => runWithLimit(() => processSticker(s, j))))).filter(Boolean)
465
+ if (!coverFilePath && allProcessed.length) coverFilePath = allProcessed[0].filePath
466
+ const sizeBatches = []
467
+ let curBatch = []
468
+ for (const s of allProcessed) { if (curBatch.length >= MAX_STICKERS_PER_PACK) { sizeBatches.push(curBatch); curBatch = [] }; curBatch.push(s) }
469
+ if (curBatch.length) sizeBatches.push(curBatch)
470
+ const totalBatches = sizeBatches.length
471
+ 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(() => { }) })))
472
+ if (!allResults.length) throw new Boom('No valid stickers could be processed', { statusCode: 400 })
473
+ return allResults.length > 1 ? { stickerPackMessage: allResults, isBatched: true, batchCount: allResults.length } : { stickerPackMessage: allResults[0], isBatched: false }
474
+ } finally { fs.unlink(coverTmpPath).catch(() => { }) }
475
+ }
476
+
477
+ // ─── MESSAGE HANDLERS ─────────────────────────────────────────────────────────
478
+ // Each key maps to async fn(message, options) -> proto-compatible object.
479
+ // Add a new type here only when it needs custom logic; everything else is auto-registered below.
480
+
481
+ const MESSAGE_HANDLERS = {
482
+ text: async (msg, opts) => {
483
+ const ext = { text: msg.text }
484
+ const urlInfo = msg.linkPreview ?? await generateLinkPreviewIfRequired(msg.text, opts.getUrlInfo, opts.logger)
485
+ if (urlInfo) {
486
+ Object.assign(ext, { matchedText: urlInfo['matched-text'], jpegThumbnail: urlInfo.jpegThumbnail, description: urlInfo.description, title: urlInfo.title, previewType: urlInfo.previewType ?? 0 })
487
+ const img = urlInfo.highQualityThumbnail
488
+ if (img) Object.assign(ext, { thumbnailDirectPath: img.directPath, mediaKey: img.mediaKey, mediaKeyTimestamp: img.mediaKeyTimestamp, thumbnailWidth: img.width, thumbnailHeight: img.height, thumbnailSha256: img.fileSha256, thumbnailEncSha256: img.fileEncSha256 })
489
+ }
490
+ if (opts.backgroundColor) ext.backgroundArgb = assertColor(opts.backgroundColor)
491
+ if (opts.font) ext.font = opts.font
492
+ return { extendedTextMessage: ext }
493
+ },
494
+ contacts: async msg => {
495
+ const { contacts } = msg.contacts
496
+ if (!contacts.length) throw new Boom('require atleast 1 contact', { statusCode: 400 })
497
+ return contacts.length === 1
498
+ ? { contactMessage: proto.Message.ContactMessage.create(contacts[0]) }
499
+ : { contactsArrayMessage: proto.Message.ContactsArrayMessage.create(msg.contacts) }
500
+ },
501
+ delete: async msg => ({ protocolMessage: { key: msg.delete, type: proto.Message.ProtocolMessage.Type.REVOKE } }),
502
+ forward: async msg => generateForwardMessageContent(msg.forward, msg.force),
503
+ disappearingMessagesInChat: async msg => prepareDisappearingMessageSettingContent(
504
+ typeof msg.disappearingMessagesInChat === 'boolean' ? (msg.disappearingMessagesInChat ? WA_DEFAULT_EPHEMERAL : 0) : msg.disappearingMessagesInChat
505
+ ),
506
+ stickerPack: async (msg, opts) => {
507
+ const result = await prepareStickerPackMessage(msg.stickerPack, opts)
508
+ if (result.isBatched) return { _batched: true, stickerPackMessage: result.stickerPackMessage, batchCount: result.batchCount }
509
+ return { _finalize: true, stickerPackMessage: result.stickerPackMessage }
510
+ },
511
+ pin: async (msg, opts) => {
512
+ const messageKey = typeof msg.pin === 'boolean'
513
+ ? (opts.quoted?.key || (() => { throw new Boom('No quoted message key found for pin operation') })())
514
+ : typeof msg.pin === 'object'
515
+ ? (msg.pin.key || (msg.pin.id ? { remoteJid: opts.jid, fromMe: msg.pin.fromMe || false, id: msg.pin.id, participant: msg.pin.participant } : null))
516
+ : msg.pin
517
+ if (!messageKey?.id) throw new Boom('Invalid message key for pin operation')
518
+ const shouldPin = typeof msg.pin === 'boolean' ? msg.pin : (msg.pin?.unpin !== true)
519
+ return { pinInChatMessage: { key: messageKey, type: shouldPin ? 1 : 2, senderTimestampMs: Date.now().toString() }, messageContextInfo: { messageAddOnDurationInSecs: shouldPin ? (msg.pin?.time || msg.time || 86400) : 0 } }
520
+ },
521
+ buttonReply: async msg => ({
522
+ list: { listResponseMessage: { title: msg.buttonReply.title, description: msg.buttonReply.description, singleSelectReply: { selectedRowId: msg.buttonReply.rowId }, listType: proto.Message.ListResponseMessage.ListType.SINGLE_SELECT } },
523
+ template: { templateButtonReplyMessage: { selectedDisplayText: msg.buttonReply.displayText, selectedId: msg.buttonReply.id, selectedIndex: msg.buttonReply.index } },
524
+ interactive: { interactiveResponseMessage: { body: { text: msg.buttonReply.displayText, format: proto.Message.InteractiveResponseMessage.Body.Format.EXTENSIONS_1 }, nativeFlowResponseMessage: { name: msg.buttonReply.nativeFlows?.name, paramsJson: msg.buttonReply.nativeFlows?.paramsJson, version: msg.buttonReply.nativeFlows?.version } } },
525
+ }[msg.type] || { buttonsResponseMessage: { selectedButtonId: msg.buttonReply.id, selectedDisplayText: msg.buttonReply.displayText, type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT } }),
526
+ ptv: async (msg, opts) => { const { videoMessage } = await prepareWAMessageMedia({ video: msg.video }, opts); return { ptvMessage: videoMessage } },
527
+ product: async (msg, opts) => { const { imageMessage } = await prepareWAMessageMedia({ image: msg.product.productImage }, opts); return { productMessage: proto.Message.ProductMessage.create({ ...msg, product: { ...msg.product, productImage: imageMessage } }) } },
528
+ sections: async msg => ({ listMessage: { title: msg.title, buttonText: msg.buttonText, footerText: msg.footer, description: msg.text, sections: msg.sections, listType: proto.Message.ListMessage.ListType.SINGLE_SELECT, contextInfo: { ...(msg.contextInfo || {}), ...(msg.mentions ? { mentionedJid: msg.mentions } : {}) } } }),
529
+ event: async (msg, opts) => {
530
+ const startTime = Math.floor(msg.event.startDate.getTime() / 1000)
531
+ const eventMessage = { name: msg.event.name, description: msg.event.description, startTime, isCanceled: msg.event.isCancelled ?? false, extraGuestsAllowed: msg.event.extraGuestsAllowed, isScheduleCall: msg.event.isScheduleCall ?? false, location: msg.event.location, ...(msg.event.endDate ? { endTime: Math.floor(msg.event.endDate.getTime() / 1000) } : {}), ...(msg.event.hasReminder != null ? { hasReminder: msg.event.hasReminder } : {}), ...(msg.event.reminderOffsetSec != null ? { reminderOffsetSec: msg.event.reminderOffsetSec } : {}) }
532
+ if (msg.event.call && opts.getCallLink) eventMessage.joinLink = (msg.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + await opts.getCallLink(msg.event.call, { startTime })
533
+ return { eventMessage, messageContextInfo: { messageSecret: msg.event.messageSecret || randomBytes(32) } }
534
+ },
535
+ poll: async msg => {
536
+ msg.poll.selectableCount ||= 0; msg.poll.toAnnouncementGroup ||= false
537
+ if (!Array.isArray(msg.poll.values)) throw new Boom('Invalid poll values', { statusCode: 400 })
538
+ 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 })
539
+ const normalize = v => typeof v === 'string' ? { optionName: v } : { optionName: v.name ?? v.optionName, ...(v.image ? { _image: v.image } : {}) }
540
+ const options = msg.poll.values.map(normalize)
541
+ if (options.some(o => o._image)) {
542
+ 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 } : {}) }
543
+ const key = msg.poll.toAnnouncementGroup ? 'pollCreationMessageV2' : msg.poll.selectableCount === 1 ? 'pollCreationMessageV3' : 'pollCreationMessage'
544
+ 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 } } })) }
545
+ }
546
+ 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 } : {}) }
547
+ const key = msg.poll.toAnnouncementGroup ? 'pollCreationMessageV2' : msg.poll.selectableCount === 1 ? 'pollCreationMessageV3' : 'pollCreationMessage'
548
+ return { [key]: pollMsg, messageContextInfo: { messageSecret: msg.poll.messageSecret || randomBytes(32) } }
549
+ },
550
+ react: async msg => { if (!msg.react.senderTimestampMs) msg.react.senderTimestampMs = Date.now(); return { reactionMessage: proto.Message.ReactionMessage.create(msg.react) } },
551
+ keep: async msg => ({ keepInChatMessage: { key: msg.keep, keepType: msg.type, timestampMs: Date.now() } }),
552
+ listReply: async msg => ({ listResponseMessage: { ...msg.listReply } }),
553
+ inviteAdmin: async msg => ({ newsletterAdminInviteMessage: proto.Message.NewsletterAdminInviteMessage.fromObject({ inviteCode: msg.inviteAdmin.inviteCode, inviteExpiration: msg.inviteAdmin.inviteExpiration, caption: msg.inviteAdmin.text, newsletterJid: msg.inviteAdmin.jid, newsletterName: msg.inviteAdmin.subject, jpegThumbnail: await normalizeToBuffer(msg.inviteAdmin.thumbnail) }) }),
554
+ requestPayment: async (msg, opts) => {
555
+ const data = msg.requestPayment || msg.payment
556
+ const sticker = data.sticker ? await prepareWAMessageMedia({ sticker: data.sticker }, opts) : null
557
+ const noteMessage = sticker ? { stickerMessage: { ...sticker.stickerMessage, contextInfo: data.contextInfo } } : { extendedTextMessage: { text: data.note || 'Notes', ...(data.contextInfo ? { contextInfo: data.contextInfo } : {}) } }
558
+ const m = { requestPaymentMessage: proto.Message.RequestPaymentMessage.fromObject({ expiryTimestamp: data.expiryTimestamp || data.expiry || 0, amount1000: data.amount1000 || data.amount || 0, currencyCodeIso4217: data.currencyCodeIso4217 || data.currency || 'IDR', requestFrom: data.requestFrom || data.from || '0@s.whatsapp.net', noteMessage, background: data.background ?? { id: 'DEFAULT', placeholderArgb: 0xfff0f0f0 } }) }
559
+ if ((data.currencyCodeIso4217 === 'BRL' || data.currency === 'BRL') && data.pixKey) { m.requestPaymentMessage.noteMessage.extendedTextMessage ??= { text: '' }; m.requestPaymentMessage.noteMessage.extendedTextMessage.text += `\nPix Key: ${data.pixKey}` }
560
+ return m
561
+ },
562
+ album: async msg => ({ albumMessage: { expectedImageCount: msg.album.filter(i => 'image' in i).length, expectedVideoCount: msg.album.filter(i => 'video' in i).length } }),
563
+ sharePhoneNumber: async () => ({ protocolMessage: { type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER } }),
564
+ limitSharing: async msg => ({ protocolMessage: { type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING, limitSharing: { sharingLimited: msg.limitSharing === true, trigger: 1, limitSharingSettingTimestamp: Date.now(), initiatedByMe: true } } }),
565
+ payment: async (msg, opts) => MESSAGE_HANDLERS.requestPayment(msg, opts),
566
+ }
567
+
568
+ export const MESSAGE_HANDLER_KEYS = Object.keys(MESSAGE_HANDLERS)
569
+ export const SCALAR_KINDS = new Set(['string', 'int', 'long', 'bool', 'bytes', 'enum', 'float', 'double'])
570
+ const _isSubMsg = (k, v) => k !== 'fields' && v && typeof v === 'object' && !Array.isArray(v) && !Object.keys(v).some(k2 => !isNaN(k2))
571
+ const _buildSafeMsgTypes = () => {
572
+ const safe = new Set(['ContextInfo', 'MessageKey', 'LocationMessage', 'SingleSelectReply', 'Option']), all = new Map(), seen = new WeakSet()
573
+ 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) } }
574
+ scan(proto.Message)
575
+ // Include top-level message types referenced directly by proto.Message fields.
576
+ for (const fd of Object.values(proto.Message.fields || {})) if (fd.type === 'msg' && proto[fd.msgType]) scan(proto[fd.msgType])
577
+ const isSafe = val => !val.fields || Object.values(val.fields).every(f => SCALAR_KINDS.has(f.type) || (f.type === 'msg' && safe.has(f.msgType)))
578
+ while ([...all.entries()].some(([k, v]) => !safe.has(k) && isSafe(v) && safe.add(k)));
579
+ return safe
580
+ }
581
+ export const SAFE_MSG_TYPES = _buildSafeMsgTypes()
582
+ // Auto-register handlers from proto schema — no manual maintenance needed.
583
+ // Part 1: simple proto.Message fields whose sub-messages are all scalar.
584
+ // Part 2: all ProtocolMessage.Type entries not already covered.
585
+ ; (() => {
586
+ const scalarKinds = SCALAR_KINDS
587
+ const safeMsgTypes = SAFE_MSG_TYPES
588
+
589
+ for (const [fieldName, fd] of Object.entries(proto.Message.fields)) {
590
+ if (fd.type !== 'msg') continue
591
+ const sub = proto.Message[fd.msgType]
592
+ if (!sub?.fields) continue
593
+ if (sub.fields?.message?.msgType === 'Message') continue
594
+ const isAutoSafe = Object.values(sub.fields).every(f => scalarKinds.has(f.type) || (f.type === 'msg' && safeMsgTypes.has(f.msgType)))
595
+ if (!isAutoSafe) continue
596
+ const inputKey = fieldName.replace(/Message$/, '')
597
+ const CtorKey = Object.keys(proto.Message).find(k => k.toLowerCase() === fieldName.toLowerCase())
598
+ const Ctor = CtorKey ? proto.Message[CtorKey] : { fromObject: o => o }
599
+ const handler = async msg => ({ [fieldName]: Ctor.fromObject(msg[inputKey] ?? msg[fieldName] ?? msg) })
600
+ if (!MESSAGE_HANDLERS[inputKey]) MESSAGE_HANDLERS[inputKey] = handler
601
+ if (!MESSAGE_HANDLERS[fieldName]) MESSAGE_HANDLERS[fieldName] = handler
602
+ if (!MESSAGE_HANDLERS[inputKey + 'Message']) MESSAGE_HANDLERS[inputKey + 'Message'] = handler
603
+ }
604
+
605
+ const pm = proto.Message.ProtocolMessage
606
+ const pmFields = pm?.fields ?? {}
607
+ const findPmField = camel => {
608
+ if (pmFields[camel]) return camel
609
+ if (pmFields[camel + 'Message']) return camel + 'Message'
610
+ return Object.entries(pmFields).find(([k]) => k.toLowerCase() === camel.toLowerCase())?.[0] ?? null
611
+ }
612
+ const isResolvable = (msgType, depth = 0) => {
613
+ if (depth > 5) return false
614
+ const sub = proto.Message[msgType]
615
+ if (!sub?.fields) return true
616
+ return Object.values(sub.fields).every(f => scalarKinds.has(f.type) || (f.type === 'msg' && isResolvable(f.msgType, depth + 1)))
617
+ }
618
+ const reg = (keys, fn) => { for (const k of keys) { if (k && !MESSAGE_HANDLERS[k]) MESSAGE_HANDLERS[k] = fn } }
619
+
620
+ for (const [typeName, typeVal] of Object.entries(pm?.Type ?? {})) {
621
+ if (typeof typeVal !== 'number') continue
622
+ const camel = toCamel(typeName)
623
+ if (MESSAGE_HANDLERS[camel]) continue
624
+ const fieldName = findPmField(camel)
625
+ const inputKey = fieldName ? fieldName.replace(/Message$/, '') : camel
626
+ const shortKey = inputKey.replace(/(?:Setting|Config|Info|Data|Params|Options|Request|Response|Update|Notification|Event)$/, '')
627
+ const keys = [...new Set([camel, inputKey, fieldName, shortKey, camel + 'Message', inputKey + 'Message', shortKey + 'Message'].filter(Boolean))]
628
+ if (!fieldName) {
629
+ reg(keys, async msg => {
630
+ const payload = { type: typeVal }
631
+ const msgKey = msg[camel]?.key ?? msg.key
632
+ if (msgKey && typeof msgKey === 'object') payload.key = msgKey
633
+ return { protocolMessage: payload }
634
+ })
635
+ } else {
636
+ const fd = pmFields[fieldName]
637
+ const CtorKey = fd.type === 'msg' ? Object.keys(proto.Message).find(k => k.toLowerCase() === fd.msgType.toLowerCase()) : null
638
+ const Ctor = CtorKey ? proto.Message[CtorKey] : null
639
+ reg(keys, async msg => {
640
+ const data = msg[shortKey] ?? msg[inputKey] ?? msg[fieldName] ?? msg[camel]
641
+ const encodeDeep = (msgType, obj) => {
642
+ if (!obj || typeof obj !== 'object') return obj
643
+ 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] } }
644
+ return Sub.fromObject(result)
645
+ }
646
+ return { protocolMessage: { type: typeVal, [fieldName]: Ctor ? encodeDeep(fd.msgType, data ?? {}) : data } }
647
+ })
648
+ }
649
+ }
650
+ })()
651
+
652
+ // ─── OVERLAY HANDLERS ─────────────────────────────────────────────────────────
653
+
654
+ const applyContextInfoAndMentions = async (interactive, msg) => {
655
+ if (msg.contextInfo) { const ctx = { ...(interactive.contextInfo || {}), ...msg.contextInfo }; if (ctx.externalAdReply) ctx.externalAdReply = await normalizeExternalAdReplyThumbnail(ctx.externalAdReply); interactive.contextInfo = ctx }
656
+ if (msg.mentions?.length) interactive.contextInfo = { ...(interactive.contextInfo || {}), mentionedJid: msg.mentions }
657
+ }
658
+
659
+ const OVERLAY_HANDLERS = {
660
+ buttons: async (m, msg) => {
661
+ const hasNativeFlow = msg.buttons.some(b => b.nativeFlowInfo || b.name || b.buttonParamsJson || b.url || b.call || b.sections)
662
+ if (hasNativeFlow) {
663
+ const interactive = { body: { text: msg.text || msg.caption || msg.contentText || '' }, footer: { text: msg.footer || msg.footerText || '' }, nativeFlowMessage: { buttons: resolveNativeFlowButtons(msg.buttons) } }
664
+ if (msg.title) interactive.header = { title: msg.title, subtitle: msg.subtitle || '', hasMediaAttachment: msg.hasMediaAttachment || false }
665
+ if (Object.keys(m).length) { interactive.header ??= { title: msg.title || '', hasMediaAttachment: true }; Object.assign(interactive.header, m) }
666
+ await applyContextInfoAndMentions(interactive, msg)
667
+ return { interactiveMessage: interactive }
668
+ }
669
+ const bm = { buttons: msg.buttons.map(b => ({ ...b, type: proto.Message.ButtonsMessage.Button.Type.RESPONSE })) }
670
+ if ('text' in msg) { bm.contentText = msg.text; bm.headerType = proto.Message.ButtonsMessage.HeaderType.EMPTY }
671
+ else {
672
+ if ('caption' in msg) bm.contentText = msg.caption
673
+ const type = Object.keys(m)[0]?.replace('Message', '').toUpperCase()
674
+ bm.headerType = proto.Message.ButtonsMessage.HeaderType[type] || proto.Message.ButtonsMessage.HeaderType.EMPTY
675
+ Object.assign(bm, m)
676
+ }
677
+ if (msg.title) { bm.text = msg.title; bm.headerType = proto.Message.ButtonsMessage.HeaderType.TEXT }
678
+ if (msg.footer) bm.footerText = msg.footer
679
+ if (msg.contextInfo) bm.contextInfo = { ...(bm.contextInfo || {}), ...msg.contextInfo }
680
+ if (msg.mentions?.length) bm.contextInfo = { ...(bm.contextInfo || {}), mentionedJid: msg.mentions }
681
+ return { buttonsMessage: bm }
682
+ },
683
+ templateButtons: (m, msg) => {
684
+ const ht = { hydratedButtons: msg.templateButtons, ...('text' in msg ? { hydratedContentText: msg.text } : { ...('caption' in msg ? { hydratedContentText: msg.caption } : {}), ...m }) }
685
+ if (msg.footer) ht.hydratedFooterText = msg.footer
686
+ if (msg.contextInfo) ht.contextInfo = { ...(ht.contextInfo || {}), ...msg.contextInfo }
687
+ if (msg.mentions?.length) ht.contextInfo = { ...(ht.contextInfo || {}), mentionedJid: msg.mentions }
688
+ return { templateMessage: { fourRowTemplate: ht, hydratedTemplate: ht } }
689
+ },
690
+ audioFooter: async (m, msg, opts) => {
691
+ const audio = await prepareWAMessageMedia({ audio: msg.audioFooter }, { upload: opts.upload ?? opts.waUploadToServer })
692
+ const buttons = resolveNativeFlowButtons(Array.isArray(msg.nativeFlow) ? msg.nativeFlow : [msg.nativeFlow])
693
+ return { interactiveMessage: { body: { text: msg.text || '' }, footer: { text: msg.footer || '' }, header: { hasMediaAttachment: false }, nativeFlowMessage: { buttons }, footerColumns: [{ audioMessage: audio.audioMessage }] } }
694
+ },
695
+ interactiveButtons: async (m, msg) => {
696
+ const interactive = { nativeFlowMessage: proto.Message.InteractiveMessage.NativeFlowMessage.fromObject({ buttons: msg.interactiveButtons }) }
697
+ if ('text' in msg) { interactive.body = { text: msg.text }; interactive.header = { title: msg.title || '', subtitle: msg.subtitle || '', hasMediaAttachment: false } }
698
+ else if ('caption' in msg) { interactive.body = { text: msg.caption }; interactive.header = { title: msg.title || '', subtitle: msg.subtitle || '', hasMediaAttachment: msg.hasMediaAttachment ?? !!Object.keys(m).length }; if (Object.keys(m).length) Object.assign(interactive.header, m) }
699
+ if (msg.footer) interactive.footer = { text: msg.footer }
700
+ await applyContextInfoAndMentions(interactive, msg)
701
+ return { interactiveMessage: interactive, messageContextInfo: { messageSecret: randomBytes(32) } }
702
+ },
703
+ shop: async (m, msg) => {
704
+ const interactive = { shopStorefrontMessage: proto.Message.InteractiveMessage.ShopMessage.fromObject({ surface: msg.shop.surface || 1, id: msg.shop.id || msg.id }) }
705
+ if ('text' in msg) interactive.body = { text: msg.text }
706
+ else if ('caption' in msg) interactive.body = { text: msg.caption }
707
+ if (msg.title || Object.keys(m).length) { interactive.header = { title: msg.title || '', subtitle: msg.subtitle || '', hasMediaAttachment: msg.hasMediaAttachment ?? !!Object.keys(m).length }; if (Object.keys(m).length) Object.assign(interactive.header, m) }
708
+ if (msg.footer) interactive.footer = { text: msg.footer }
709
+ await applyContextInfoAndMentions(interactive, msg)
710
+ return { interactiveMessage: interactive }
711
+ },
712
+ collection: async (m, msg) => {
713
+ const interactive = { collectionMessage: { bizJid: msg.collection.bizJid, id: msg.collection.id, messageVersion: msg.collection.version } }
714
+ if ('text' in msg) { interactive.body = { text: msg.text }; interactive.header = { title: msg.title || '', hasMediaAttachment: false } }
715
+ else if ('caption' in msg) { interactive.body = { text: msg.caption }; interactive.header = { title: msg.title || '', hasMediaAttachment: msg.hasMediaAttachment ?? false }; if (Object.keys(m).length) Object.assign(interactive.header, m) }
716
+ if (msg.footer) interactive.footer = { text: msg.footer }
717
+ await applyContextInfoAndMentions(interactive, msg)
718
+ return { interactiveMessage: interactive }
719
+ },
720
+ }
721
+
722
+ // ─── MESSAGE CONTENT GENERATION ───────────────────────────────────────────────
723
+
724
+ export const generateWAMessageContent = async (message, options = {}) => {
725
+ if (!message || typeof message !== 'object') return proto.Message.create({})
726
+ const msgKeys = Object.keys(message)
727
+ const isWrapper = msgKeys.some(k => WRAPPER_KEYS.has(k))
728
+ // raw proto pass-through: no high-level keys present, or is a known wrapper type
729
+ if (isWrapper || (!msgKeys.some(k => HIGH_LEVEL_KEYS.has(k)) && msgKeys.some(k => k.endsWith('Message') || k === 'conversation'))) return proto.Message.create(message)
730
+
731
+ let m = {}
732
+ const overlayKeys = Object.keys(OVERLAY_HANDLERS)
733
+ if ('text' in message && !overlayKeys.some(k => k in message)) {
734
+ m = await MESSAGE_HANDLERS.text(message, options)
735
+ } else {
736
+ const handlerKey = msgKeys.find(k => k !== 'text' && !MEDIA_PROP_KEYS.has(k) && MESSAGE_HANDLERS[k])
737
+ if (handlerKey) {
738
+ const result = await MESSAGE_HANDLERS[handlerKey](message, options)
739
+ if (result?._batched) return { stickerPackMessage: result.stickerPackMessage, isBatched: true, batchCount: result.batchCount }
740
+ if (result?._finalize) return proto.Message.create({ stickerPackMessage: result.stickerPackMessage })
741
+ if (result?._associatedFlow) return result
742
+ m = result
743
+ } else if ([...USER_MEDIA_KEYS].some(k => k in message) || MEDIA_KEYS.some(k => k in message)) {
744
+ m = await prepareWAMessageMedia(message, options)
745
+ }
746
+ }
747
+
748
+ for (const key of overlayKeys) { if (key in message && message[key]) { m = await OVERLAY_HANDLERS[key](m, message, options); break } }
749
+
750
+ // deep-merge contextInfo/mentions onto the primary content key
751
+ const finalKey = Object.keys(m)[0]
752
+ if ((message.contextInfo || message.mentions?.length) && finalKey && m[finalKey] && typeof m[finalKey] === 'object') {
753
+ const existing = m[finalKey].contextInfo || {}, incoming = message.contextInfo || {}
754
+ const mergedExt = (existing.externalAdReply || incoming.externalAdReply) ? await normalizeExternalAdReplyThumbnail({ ...(existing.externalAdReply || {}), ...(incoming.externalAdReply || {}) }) : undefined
755
+ m[finalKey].contextInfo = { ...existing, ...incoming, ...(mergedExt ? { externalAdReply: mergedExt } : {}), ...(message.mentions?.length ? { mentionedJid: message.mentions } : {}) }
756
+ }
757
+
758
+ if ('viewOnce' in message && message.viewOnce) m = { viewOnceMessage: { message: m } }
759
+ if ('edit' in message) m = { protocolMessage: { key: message.edit, editedMessage: m, timestampMs: Date.now(), type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT } }
760
+
761
+ if (shouldIncludeReportingToken(m)) { m.messageContextInfo ??= {}; m.messageContextInfo.messageSecret ??= randomBytes(32) }
762
+ return proto.Message.create(m)
763
+ }
764
+
765
+ // ─── ASSEMBLE FULL WA MESSAGE ─────────────────────────────────────────────────
766
+
767
+ export const generateWAMessageFromContent = (jid, message, options) => {
768
+ const upload = options.upload ?? options.waUploadToServer
769
+ const assemble = () => {
770
+ if (!options.timestamp) options.timestamp = new Date()
771
+ const innerMessage = normalizeMessageContent(message)
772
+ const key = getContentType(innerMessage)
773
+ const { quoted, userJid } = options
774
+ if (quoted && !isJidNewsletter(jid)) {
775
+ const participant = quoted.key.fromMe ? userJid : (quoted.participant || quoted.key.participant || quoted.key.remoteJid)
776
+ const normalizedQuoted = normalizeMessageContent(quoted.message)
777
+ if (normalizedQuoted) {
778
+ const quotedType = getContentType(normalizedQuoted)
779
+ const quotedMsg = proto.Message.fromObject({ [quotedType]: normalizedQuoted[quotedType] })
780
+ const quotedContent = quotedMsg[quotedType]
781
+ if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) delete quotedContent.contextInfo
782
+ const contextInfo = innerMessage[key]?.contextInfo || {}
783
+ contextInfo.participant = jidNormalizedUser(participant)
784
+ contextInfo.stanzaId = quoted.key.id
785
+ contextInfo.quotedMessage = quotedMsg
786
+ if (jid !== quoted.key.remoteJid) contextInfo.remoteJid = quoted.key.remoteJid
787
+ if (innerMessage[key]) innerMessage[key].contextInfo = contextInfo
788
+ }
789
+ }
790
+ if (options?.ephemeralExpiration && key !== 'protocolMessage' && key !== 'ephemeralMessage' && !isJidNewsletter(jid)) {
791
+ innerMessage[key].contextInfo = { ...(innerMessage[key].contextInfo || {}), expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL }
792
+ }
793
+ return proto.WebMessageInfo.fromObject({
794
+ key: { remoteJid: jid, fromMe: true, id: options?.messageId || generateMessageIDV2() },
795
+ message: proto.Message.create(message),
796
+ messageTimestamp: unixTimestampSeconds(options.timestamp),
797
+ messageStubParameters: [],
798
+ participant: (isJidGroup(jid) || isJidStatusBroadcast(jid)) ? userJid : undefined,
799
+ status: WAMessageStatus.PENDING,
800
+ })
801
+ }
802
+ const result = assemble()
803
+ if (!upload) return result
804
+ return Object.assign(result, { then(resolve, reject) { resolveMedia(message, upload).then(() => resolve(assemble())).catch(reject) } })
805
+ }
806
+
807
+ export const associatedFlowRelayed = new WeakSet()
808
+ export const generateWAMessageFromAssociatedFlow = async (jid, parentContent, children, associationType, relay, options = {}) => {
809
+ const parent = await generateWAMessage(jid, parentContent, options)
810
+ const childMessages = await Promise.all(children.map(async (child, i) => {
811
+ const msg = proto.Message.create({
812
+ ...await generateWAMessageContent(child, { ...options, jid }),
813
+ messageContextInfo: { messageAssociation: { associationType, parentMessageKey: parent.key, messageIndex: i } },
814
+ })
815
+ return generateWAMessageFromContent(jid, msg, { ...options, messageId: undefined })
816
+ }))
817
+ await relay(parent.message, { messageId: parent.key.id }, parent)
818
+ for (const child of childMessages) await relay(child.message, { messageId: child.key.id }, child)
819
+ associatedFlowRelayed.add(parent)
820
+ return parent
821
+ }
822
+
823
+ // generateWAMessage is the main entry point — handles associated flows, poll image children, and standard messages
824
+ export const generateWAMessage = async (jid, content, options = {}) => {
825
+ if (content?.key?.remoteJid && content?.message) return content
826
+ const msgId = options.messageId || generateMessageIDV2()
827
+ options.logger = options?.logger?.child({ msgId })
828
+ const flowKey = content && typeof content === 'object' ? Object.keys(content).find(k => k in ASSOCIATED_FLOW_KEYS) : null
829
+ if (flowKey) {
830
+ if (typeof options.relay !== 'function') return generateWAMessageFromContent(jid, await generateWAMessageContent(content, { ...options, jid, messageId: msgId }), { ...options, messageId: msgId })
831
+ const msg = content[flowKey]
832
+ const items = Array.isArray(msg) ? msg : Array.isArray(msg?.items) ? msg.items : null
833
+ if (items) {
834
+ const [first, ...rest] = items
835
+ return generateWAMessageFromAssociatedFlow(jid, first, rest, ASSOCIATED_FLOW_KEYS[flowKey], options.relay, { ...options, messageId: msgId })
836
+ }
837
+ const allMediaKeys = new Set([...MEDIA_KEYS, 'image', 'video', 'audio', 'sticker', 'document'])
838
+ const sharedProps = Object.fromEntries(Object.entries(msg).filter(([k]) => !allMediaKeys.has(k)))
839
+ const [[pk, pv], ...childEntries] = Object.entries(msg).filter(([k]) => allMediaKeys.has(k))
840
+ return generateWAMessageFromAssociatedFlow(jid, { [pk]: pv, ...sharedProps }, childEntries.map(([k, v]) => ({ [k]: v })), ASSOCIATED_FLOW_KEYS[flowKey], options.relay, { ...options, messageId: msgId })
841
+ }
842
+ const resolved = await generateWAMessageContent(content, { ...options, jid, messageId: msgId })
843
+ if (resolved?._associatedFlow) {
844
+ if (typeof options.relay !== 'function') throw new Boom('this message type requires a relay option', { statusCode: 400 })
845
+ return generateWAMessageFromAssociatedFlow(jid, resolved._parent, resolved._children, resolved.associationType, options.relay, { ...options, messageId: msgId })
846
+ }
847
+ return generateWAMessageFromContent(jid, resolved, { ...options, messageId: msgId })
848
+ }
849
+
850
+ // ─── UPDATE UTILITIES ─────────────────────────────────────────────────────────
851
+
852
+ export const updateMessageWithReceipt = (msg, receipt) => {
853
+ msg.userReceipt ||= []
854
+ const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid)
855
+ if (recp) Object.assign(recp, receipt)
856
+ else msg.userReceipt.push(receipt)
857
+ }
858
+
859
+ export const updateMessageWithReaction = (msg, reaction) => {
860
+ const authorID = getKeyAuthor(reaction.key)
861
+ msg.reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID)
862
+ reaction.text ||= ''
863
+ msg.reactions.push(reaction)
864
+ }
865
+
866
+ export const updateMessageWithPollUpdate = (msg, update) => {
867
+ const authorID = getKeyAuthor(update.pollUpdateMessageKey)
868
+ msg.pollUpdates = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID)
869
+ if (update.vote?.selectedOptions?.length) msg.pollUpdates.push(update)
870
+ }
871
+
872
+ export const updateMessageWithEventResponse = (msg, update) => {
873
+ const authorID = getKeyAuthor(update.eventResponseMessageKey)
874
+ msg.eventResponses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID)
875
+ msg.eventResponses.push(update)
876
+ }
877
+
878
+ export const getAggregateVotesInPollMessage = ({ message, pollUpdates }, meId) => {
879
+ const opts = message?.pollCreationMessage?.options || message?.pollCreationMessageV2?.options || message?.pollCreationMessageV3?.options || []
880
+ const voteHashMap = opts.reduce((acc, opt) => { acc[sha256(Buffer.from(opt.optionName || '')).toString()] = { name: opt.optionName || '', voters: [] }; return acc }, {})
881
+ for (const update of pollUpdates || []) {
882
+ if (!update.vote) continue
883
+ for (const option of update.vote.selectedOptions || []) {
884
+ const hash = option.toString()
885
+ voteHashMap[hash] ||= { name: 'Unknown', voters: [] }
886
+ voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId))
887
+ }
888
+ }
889
+ return Object.values(voteHashMap)
890
+ }
891
+
892
+ export const getAggregateResponsesInEventMessage = ({ eventResponses }, meId) => {
893
+ const responseMap = { GOING: { response: 'GOING', responders: [] }, NOT_GOING: { response: 'NOT_GOING', responders: [] }, MAYBE: { response: 'MAYBE', responders: [] } }
894
+ for (const update of eventResponses || []) { const type = update.eventResponse || 'UNKNOWN'; if (responseMap[type]) responseMap[type].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId)) }
895
+ return Object.values(responseMap)
896
+ }
897
+
898
+ export const aggregateMessageKeysNotFromMe = keys => {
899
+ const keyMap = {}
900
+ for (const { remoteJid, id, participant, fromMe } of keys) {
901
+ if (!fromMe) { const uqKey = `${remoteJid}:${participant || ''}`; keyMap[uqKey] ||= { jid: remoteJid, participant, messageIds: [] }; keyMap[uqKey].messageIds.push(id) }
902
+ }
903
+ return Object.values(keyMap)
904
+ }
905
+
906
+ export const downloadMediaMessage = async (message, type, options, ctx) => {
907
+ const downloadMsg = async () => {
908
+ let normalized = message
909
+ if (!message.message && message.key) normalized = { key: message.key, message: message.quoted?.message || message, messageTimestamp: message.messageTimestamp }
910
+ const mContent = extractMessageContent(normalized.message)
911
+ if (!mContent) throw new Boom('No message present', { statusCode: 400, data: message })
912
+ const contentType = getContentType(mContent)
913
+ let mediaType = contentType?.replace('Message', '')
914
+ const media = mContent[contentType]
915
+ if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) throw new Boom(`"${contentType}" message is not a media message`)
916
+ const download = ('thumbnailDirectPath' in media && !('url' in media)) ? { directPath: media.thumbnailDirectPath, mediaKey: media.mediaKey } : media
917
+ if ('thumbnailDirectPath' in media && !('url' in media)) mediaType = 'thumbnail-link'
918
+ const stream = await downloadContentFromMessage(download, mediaType, options)
919
+ if (type === 'buffer') return toBuffer(stream)
920
+ return stream
921
+ }
922
+ return downloadMsg().catch(async error => {
923
+ if (ctx && typeof error?.status === 'number' && REUPLOAD_REQUIRED_STATUS.includes(error.status)) { ctx.logger.info({ key: message.key }, 'sending reupload media request...'); message = await ctx.reuploadRequest(message); return downloadMsg() }
924
+ throw error
925
+ })
926
+ }
927
+
928
+ export const assertMediaContent = content => {
929
+ content = extractMessageContent(content)
930
+ const mediaContent = content?.documentMessage || content?.imageMessage || content?.videoMessage || content?.audioMessage || content?.stickerMessage || content?.stickerPackMessage
931
+ if (!mediaContent) throw new Boom('given message is not a media message', { statusCode: 400, data: content })
932
+ return mediaContent
933
+ }
934
+
935
+ export const getDevice = id => /^3A.{18}$/.test(id) ? 'ios' : /^3E.{20}$/.test(id) ? 'web' : /^(.{21}|.{32})$/.test(id) ? 'android' : /^(3F|.{18}$)/.test(id) ? 'desktop' : 'unknown'
936
+
937
+ export const patchMessageForMdIfRequired = message => {
938
+ if (message?.buttonsMessage || message?.templateMessage || message?.listMessage || message?.interactiveMessage?.nativeFlowMessage) {
939
+ message = { viewOnceMessageV2Extension: { message: { messageContextInfo: { deviceListMetadataVersion: 2, deviceListMetadata: {} }, ...message } } }
940
+ }
941
+ return message
942
+ }
943
+
944
+ export const hasNonNullishProperty = (message, key) => typeof message === 'object' && message !== null && key in message && message[key] !== null && message[key] !== undefined
943
945
  export const hasOptionalProperty = (obj, key) => typeof obj === 'object' && obj !== null && key in obj && obj[key] !== null && obj[key] !== undefined