@itznomo/baileys 0.0.0-stage → 0.0.3

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 (124) hide show
  1. package/BUTTONS.md +153 -0
  2. package/Example/call-bot.mjs +38 -0
  3. package/Example/example.mjs +36 -0
  4. package/Example/full-bot-commands.mjs +319 -0
  5. package/Example/full-bot.mjs +77 -0
  6. package/LICENSE +21 -0
  7. package/README.md +543 -2
  8. package/WAProto/@dnuzi +1 -0
  9. package/WAProto/index.d.ts +15932 -0
  10. package/WAProto/index.js +113300 -0
  11. package/assets/banner.svg +17 -0
  12. package/assets/devider.svg +1 -0
  13. package/assets/features.svg +21 -0
  14. package/docs/CALLS.md +106 -0
  15. package/docs/FEATURES.md +1152 -0
  16. package/engine-requirements.js +19 -0
  17. package/index.d.ts +815 -0
  18. package/package.json +51 -4
  19. package/src/binary/wa-binary-constants.js +1300 -0
  20. package/src/binary/wa-binary.js +627 -0
  21. package/src/constants.js +147 -0
  22. package/src/defaults.js +106 -0
  23. package/src/foundation/ai-rich.js +654 -0
  24. package/src/foundation/audio-duration.js +470 -0
  25. package/src/foundation/audio-samples.js +250 -0
  26. package/src/foundation/boom.js +39 -0
  27. package/src/foundation/builders.js +851 -0
  28. package/src/foundation/cache.js +134 -0
  29. package/src/foundation/concurrency.js +69 -0
  30. package/src/foundation/curve25519.js +189 -0
  31. package/src/foundation/image-thumb.js +65 -0
  32. package/src/foundation/link-preview.js +278 -0
  33. package/src/foundation/logger.js +78 -0
  34. package/src/foundation/long.js +130 -0
  35. package/src/foundation/performance.js +385 -0
  36. package/src/foundation/protobuf-minimal.js +587 -0
  37. package/src/foundation/qrcode-terminal.js +273 -0
  38. package/src/foundation/sql-database.js +716 -0
  39. package/src/foundation/wa-crypto.js +47 -0
  40. package/src/foundation/zip.js +108 -0
  41. package/src/index.js +67 -0
  42. package/src/signal/libsignal.js +996 -0
  43. package/src/signal/signal-group.js +455 -0
  44. package/src/signal/signal-repository.js +635 -0
  45. package/src/socket/business-communities.js +811 -0
  46. package/src/socket/chats.js +702 -0
  47. package/src/socket/groups-newsletter.js +524 -0
  48. package/src/socket/messages-recv.js +1815 -0
  49. package/src/socket/messages-send.js +1526 -0
  50. package/src/socket/socket-builder.js +131 -0
  51. package/src/socket/socket-core.js +913 -0
  52. package/src/socket/usync.js +287 -0
  53. package/src/socket-client/native-websocket.js +344 -0
  54. package/src/socket-client/websocket-client.js +170 -0
  55. package/src/utils/auth-state-core.js +731 -0
  56. package/src/utils/auth-state-storage.js +594 -0
  57. package/src/utils/chat-sync.js +1046 -0
  58. package/src/utils/check-status.js +159 -0
  59. package/src/utils/cstoken.js +17 -0
  60. package/src/utils/media.js +807 -0
  61. package/src/utils/message-compose.js +1747 -0
  62. package/src/utils/message-processing.js +912 -0
  63. package/src/utils/modern-messages.js +435 -0
  64. package/src/utils/nomo-buttons.js +138 -0
  65. package/src/utils/nomo-commands.js +168 -0
  66. package/src/utils/spam-report-utils.js +136 -0
  67. package/src/utils/use-keyv-auth-state.js +307 -0
  68. package/src/utils/username.js +19 -0
  69. package/src/utils/wa-protocol-core.js +1227 -0
  70. package/src/voip/WaVoipCoordinator.js +158 -0
  71. package/src/voip/app-data/WaAppDataStream.js +193 -0
  72. package/src/voip/app-data/protocol.js +172 -0
  73. package/src/voip/auto.js +139 -0
  74. package/src/voip/bytes.js +63 -0
  75. package/src/voip/call/WaCallManager.js +442 -0
  76. package/src/voip/call/WaCallMediaSession.js +1727 -0
  77. package/src/voip/call/call-state.js +203 -0
  78. package/src/voip/crypto/encryption.js +13 -0
  79. package/src/voip/crypto/primitives.js +21 -0
  80. package/src/voip/crypto/rtcp.js +66 -0
  81. package/src/voip/crypto/srtp.js +180 -0
  82. package/src/voip/crypto/ssrc.js +15 -0
  83. package/src/voip/index.js +730 -0
  84. package/src/voip/media/WaAudioEngine.js +486 -0
  85. package/src/voip/media/WaVideoEngine.js +275 -0
  86. package/src/voip/media/audio-codec.js +0 -0
  87. package/src/voip/media/audio-reorder.js +107 -0
  88. package/src/voip/media/h264.js +246 -0
  89. package/src/voip/media/mlow-codec.js +465 -0
  90. package/src/voip/media/rtcp.js +68 -0
  91. package/src/voip/media/rtp.js +242 -0
  92. package/src/voip/protobuf.js +30 -0
  93. package/src/voip/relay/WaManualRelay.js +609 -0
  94. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  95. package/src/voip/relay/dtls/aead.js +46 -0
  96. package/src/voip/relay/dtls/cert-builder.js +102 -0
  97. package/src/voip/relay/dtls/der.js +98 -0
  98. package/src/voip/relay/dtls/ecdhe.js +37 -0
  99. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  100. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  101. package/src/voip/relay/dtls/handshake.js +582 -0
  102. package/src/voip/relay/dtls/prf.js +39 -0
  103. package/src/voip/relay/dtls/record.js +56 -0
  104. package/src/voip/relay/relay-ack.js +141 -0
  105. package/src/voip/relay/sctp/association.js +434 -0
  106. package/src/voip/relay/sctp/crc32c.js +21 -0
  107. package/src/voip/relay/sctp/wire.js +226 -0
  108. package/src/voip/relay/stun.js +463 -0
  109. package/src/voip/shim/baileys-resolve.js +7 -0
  110. package/src/voip/shim/core.js +66 -0
  111. package/src/voip/shim/crypto.js +6 -0
  112. package/src/voip/shim/proto.js +10 -0
  113. package/src/voip/shim/protocol.js +130 -0
  114. package/src/voip/shim/transport.js +82 -0
  115. package/src/voip/shim/util.js +207 -0
  116. package/src/voip/signaling/bridge.js +102 -0
  117. package/src/voip/signaling/screen-share.js +60 -0
  118. package/src/voip/signaling/signaling.js +491 -0
  119. package/src/voip/types.js +69 -0
  120. package/src/voip/voip-deps.js +243 -0
  121. package/src/voip/voipClient.js +314 -0
  122. package/src/wam/wam-constants.js +22852 -0
  123. package/src/wam/wam.js +146 -0
  124. package/voip.d.ts +144 -0
@@ -0,0 +1,851 @@
1
+ /**
2
+ * src/foundation/builders.js
3
+ * Fluent message builders for nomo-baileys
4
+ * — CJS-compatible, zero top-level await
5
+ */
6
+
7
+ import crypto from 'crypto'
8
+ import { proto } from '../../WAProto/index.js'
9
+ import { generateWAMessage, generateWAMessageFromContent, prepareStickerPackMessage, prepareWAMessageMedia } from '../utils/message-compose.js'
10
+ import { generateMessageIDV2 } from '../utils/wa-protocol-core.js'
11
+ import { extractImageThumb } from '../utils/media.js'
12
+ import { getBizBinaryNode } from '../binary/wa-binary.js'
13
+
14
+ // BOT_RENDERING_CONFIG_METADATA (from upstream lib/Defaults/index.js)
15
+ export const BOT_RENDERING_CONFIG_METADATA = {
16
+ bloksVersioningId: '6e955f4ffe31e9c45cd7702090f9b02107f6ef04bbbae6062a2d9c9b99e03f05',
17
+ pixelDensity: 2.75
18
+ }
19
+
20
+ const delay = ms => new Promise(r => setTimeout(r, ms))
21
+
22
+ // ─── resolveNativeFlowButtons (from upstream lib/Utils/native-flow.js) ─────────
23
+ export const resolveNativeFlowButtons = (rawButtons) => {
24
+ const buttons = Array.isArray(rawButtons) ? rawButtons : [rawButtons]
25
+ return buttons.filter(Boolean).map(b => {
26
+ if (b.name && b.buttonParamsJson !== undefined) return b // already formatted
27
+ const text = b.text ?? b.display_text ?? ''
28
+ if (b.sections) return { name: 'single_select', buttonParamsJson: JSON.stringify({ title: text, sections: b.sections }) }
29
+ if (b.url && b.useWebview) return { name: 'cta_open_webview', buttonParamsJson: JSON.stringify({ display_text: text, url: b.url }) }
30
+ if (b.url) return { name: 'cta_url', buttonParamsJson: JSON.stringify({ display_text: text, url: b.url, merchant_url: b.merchantUrl ?? b.url }) }
31
+ if (b.call) return { name: 'cta_call', buttonParamsJson: JSON.stringify({ display_text: text, phone_number: b.call }) }
32
+ if (b.copy) return { name: 'cta_copy', buttonParamsJson: JSON.stringify({ display_text: text, copy_code: b.copy }) }
33
+ if (b.flow_id ?? b.flowId) return { name: 'flow', buttonParamsJson: JSON.stringify({ display_text: text, flow_id: b.flow_id ?? b.flowId, flow_token: b.flow_token ?? b.flowToken ?? crypto.randomUUID() }) }
34
+ if (b.remind) return { name: 'cta_reminder', buttonParamsJson: JSON.stringify({ display_text: text, ...b.remind }) }
35
+ if (b.cancelReminder) return { name: 'cta_cancel_reminder', buttonParamsJson: JSON.stringify({ display_text: text }) }
36
+ if (b.location) return { name: 'send_location', buttonParamsJson: JSON.stringify({ display_text: text }) }
37
+ if (b.address) return { name: 'address_message', buttonParamsJson: JSON.stringify({ display_text: text }) }
38
+ if (b.catalog) return { name: 'catalog_message', buttonParamsJson: JSON.stringify({ display_text: text, ...b.catalog }) }
39
+ if (b.reviewAndPay) return { name: 'review_and_pay', buttonParamsJson: JSON.stringify({ display_text: text, ...b.reviewAndPay }) }
40
+ if (b.reviewOrder) return { name: 'review_order', buttonParamsJson: JSON.stringify({ display_text: text, ...b.reviewOrder }) }
41
+ if (b.orderDetails) return { name: 'order_details', buttonParamsJson: JSON.stringify({ display_text: text, ...b.orderDetails }) }
42
+ if (b.paymentStatus) return { name: 'payment_status', buttonParamsJson: JSON.stringify({ display_text: text, ...b.paymentStatus }) }
43
+ if (b.transactionDetails) return { name: 'transaction_details', buttonParamsJson: JSON.stringify({ display_text: text, ...b.transactionDetails }) }
44
+ // default: quick_reply
45
+ return { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: text, id: b.id ?? text }) }
46
+ })
47
+ }
48
+
49
+ export const makeWhatsAppFlowButton = flow => ({
50
+ name: flow?.nativeFlowName || 'galaxy_message',
51
+ buttonParamsJson: JSON.stringify({
52
+ name: flow?.nativeFlowName || 'galaxy_message',
53
+ flow_message_version: String(flow?.flowMessageVersion ?? '3'),
54
+ flow_token: String(flow?.flowToken ?? crypto.randomUUID()),
55
+ flow_id: String(flow?.flowId ?? ''),
56
+ flow_cta: String(flow?.cta ?? 'Open'),
57
+ flow_action: flow?.action ?? 'navigate',
58
+ ...(flow?.actionPayload ? { flow_action_payload: flow.actionPayload } : {}),
59
+ ...(flow?.metadata ? { flow_metadata: flow.metadata } : {})
60
+ })
61
+ })
62
+
63
+ // ─── norm & helpers ───────────────────────────────────────────────────────────
64
+ export const getRandomHex = () => '#' + Array.from(crypto.getRandomValues(new Uint8Array(3)), b => b.toString(16).padStart(2, '0')).join('')
65
+
66
+ export const norm = (data, opts = {}) => {
67
+ if (!data) return { ...opts }
68
+ if (Array.isArray(data)) return { stickers: data, ...opts }
69
+ if (typeof data !== 'object') return { ...opts }
70
+ const keys = Object.keys(data)
71
+ const base = keys.length && keys.every(k => !isNaN(k)) ? { stickers: Object.values(data) } : { ...data }
72
+ return { ...base, ...Object.fromEntries(Object.entries(opts).filter(([, v]) => v != null)) }
73
+ }
74
+
75
+ export const q = quoted => quoted ? { quoted } : {}
76
+
77
+ // ─── BaseBuilder ──────────────────────────────────────────────────────────────
78
+ export class BaseBuilder {
79
+ #client; #data = {}
80
+ constructor(client) {
81
+ if (!client) throw new Error('Socket client is required')
82
+ this.#client = client
83
+ }
84
+ from(data, opts = {}) { this.#data = norm(data, opts); return this }
85
+ get data() { return this.#data }
86
+ get client() { return this.#client }
87
+ }
88
+
89
+ // ─── buildDispatch & buildPlugins ─────────────────────────────────────────────
90
+ export const buildDispatch = (builders, handlers = {}) => ({
91
+ ...Object.fromEntries(builders.flatMap(B => (B.dispatchKeys ?? []).map(key => [key, (sock, jid, content, opts) => {
92
+ const { relay, upload, waUploadToServer, logger, ...safeOpts } = opts ?? {}
93
+ const b = new B(sock)
94
+ return (typeof b.from === 'function' ? b.from(content[key], safeOpts) : b).send(jid, opts)
95
+ }]))),
96
+ ...handlers
97
+ })
98
+
99
+ const toFactoryName = key => key.replace(/(?:Message|Pack|Packet)$/i, '').toLowerCase()
100
+ const toSendName = key => key.toLowerCase().startsWith('send') ? key : 'send' + key.charAt(0).toUpperCase() + key.slice(1)
101
+
102
+ export const buildPlugins = (builders, extra = {}) => {
103
+ const seen = new Set()
104
+ const entries = []
105
+ for (const B of builders) {
106
+ for (const [name, factory] of Object.entries(B.shortcuts ?? {})) {
107
+ if (!seen.has(name)) { seen.add(name); entries.push([name, factory]) }
108
+ }
109
+ for (const key of B.dispatchKeys ?? []) {
110
+ const factoryName = toFactoryName(key)
111
+ const sendName = toSendName(key)
112
+ if (!seen.has(factoryName)) { seen.add(factoryName); entries.push([factoryName, sock => opts => new B(sock, opts)]) }
113
+ if (!seen.has(sendName)) { seen.add(sendName); entries.push([sendName, sock => (jid, data, opts = {}) => new B(sock).from(data, opts).send(jid, opts)]) }
114
+ }
115
+ const className = B.name?.toLowerCase()
116
+ if (className && !seen.has(className)) { seen.add(className); entries.push([className, sock => opts => new B(sock, opts)]) }
117
+ }
118
+ for (const [name, factory] of Object.entries(extra)) {
119
+ const idx = entries.findIndex(([n]) => n === name)
120
+ if (idx === -1) { seen.add(name); entries.push([name, factory]) }
121
+ else entries[idx] = [name, factory]
122
+ }
123
+ return Object.fromEntries(entries)
124
+ }
125
+
126
+ // ─── Handlers ─────────────────────────────────────────────────────────────────
127
+ export async function handleGroupStatus(sock, jid, content, config) {
128
+ const needsBackground = !content.image && !content.video
129
+ const msg = await generateWAMessage(jid, content, {
130
+ logger: sock.logger, userJid: sock.user?.id, upload: sock.waUploadToServer,
131
+ getUrlInfo: text => Promise.resolve(null),
132
+ ...(needsBackground && {
133
+ font: content.font ?? Math.floor(Math.random() * 9),
134
+ textColor: content.textColor || getRandomHex(),
135
+ backgroundColor: content.backgroundColor || getRandomHex()
136
+ })
137
+ })
138
+ return sock.relayMessage(jid, msg.message, {
139
+ messageId: msg.key.id,
140
+ additionalNodes: [{ tag: 'meta', attrs: { is_group_status: 'true' }, content: undefined }]
141
+ })
142
+ }
143
+
144
+ export async function handleStatusMention(sock, jid, d, config) {
145
+ const userJid = sock.user?.id
146
+ const mediaType = d.image ? 'image' : 'video'
147
+ const media = await prepareWAMessageMedia({ [mediaType]: d.image ?? d.video }, { upload: sock.waUploadToServer })
148
+ const statusMsg = await sock.relayMessage('status@broadcast', { ...media }, {
149
+ statusJidList: [d.mentions, userJid].filter(Boolean),
150
+ additionalNodes: [{ tag: 'meta', attrs: {}, content: [{ tag: 'mentioned_users', attrs: {}, content: [{ tag: 'to', attrs: { jid: d.mentions }, content: undefined }] }] }]
151
+ })
152
+ const mentionMsg = await generateWAMessageFromContent(jid, {
153
+ statusMentionMessage: proto.Message.StatusMentionMessage.create({
154
+ message: { protocolMessage: proto.Message.ProtocolMessage.create({ messageId: statusMsg?.key?.id ?? d.mentions, type: proto.Message.ProtocolMessage.Type.STATUS_MENTION_MESSAGE }) }
155
+ })
156
+ }, { userJid })
157
+ return sock.relayMessage(jid, mentionMsg.message, {
158
+ messageId: mentionMsg.key.id,
159
+ additionalNodes: [{ tag: 'meta', attrs: { is_status_mention: 'true' }, content: undefined }]
160
+ })
161
+ }
162
+
163
+ export async function handlePollResult(sock, jid, p) {
164
+ const msg = await generateWAMessageFromContent(jid, {
165
+ pollResultSnapshotMessage: proto.Message.PollResultSnapshotMessage.create({
166
+ name: p.name,
167
+ pollVotes: (p.pollVotes ?? []).map(v => proto.Message.PollResultSnapshotMessage.PollVote.create({
168
+ optionName: v.optionName,
169
+ optionVoteCount: String(v.optionVoteCount ?? 0)
170
+ })),
171
+ contextInfo: proto.ContextInfo.create({ isForwarded: true, forwardingScore: 1 })
172
+ })
173
+ }, { userJid: sock.user?.id })
174
+ await sock.relayMessage(jid, msg.message, { messageId: msg.key.id })
175
+ return msg
176
+ }
177
+
178
+ export async function handleNativeFlow(sock, jid, content, opts = {}) {
179
+ const rawButtons = content.nativeFlow
180
+ const resolved = resolveNativeFlowButtons(rawButtons)
181
+ const offerParams = content.offerText
182
+ ? { limited_time_offer: { text: content.offerText, url: content.offerUrl || '', copy_code: content.offerCode || '', expiration_time: content.offerExpiration ? Math.floor(content.offerExpiration / 1000) : 0 } }
183
+ : {}
184
+ const messageParams = { ...offerParams }
185
+ if (content.optionText) messageParams.bottom_sheet = { in_thread_buttons_limit: 1, divider_indices: Array.from({ length: resolved.length }, (_, i) => i), list_title: content.optionTitle || content.optionText, button_title: content.optionText }
186
+ if (content.interactiveAsTemplate) {
187
+ return sock.sendMessage(jid, {
188
+ ...content, nativeFlow: undefined, interactiveButtons: undefined,
189
+ templateButtons: resolved.map(b => {
190
+ const p = JSON.parse(b.buttonParamsJson ?? '{}')
191
+ return b.name === 'cta_url' ? { text: p.display_text, url: p.url }
192
+ : b.name === 'cta_call' ? { text: p.display_text, call: p.phone_number }
193
+ : { text: p.display_text, id: p.id }
194
+ })
195
+ }, opts)
196
+ }
197
+ return sock.sendMessage(jid, {
198
+ ...content, nativeFlow: undefined,
199
+ interactiveButtons: resolved,
200
+ ...(Object.keys(messageParams).length ? { messageParamsJson: JSON.stringify(messageParams) } : {})
201
+ }, opts)
202
+ }
203
+
204
+ // ─── Primitive & handler shortcuts ────────────────────────────────────────────
205
+ export const PRIMITIVE_SHORTCUTS = {
206
+ sendText: sock => (jid, text, opts = {}) => sock.sendMessage(jid, { text }, opts),
207
+ sendImage: sock => (jid, image, caption = '', opts = {}) => sock.sendMessage(jid, { image, caption }, opts),
208
+ sendVideo: sock => (jid, video, caption = '', opts = {}) => sock.sendMessage(jid, { video, caption }, opts),
209
+ sendDocument: sock => (jid, document, caption = '', opts = {}) => sock.sendMessage(jid, { document, caption }, opts),
210
+ sendAudio: sock => (jid, audio, opts = {}) => sock.sendMessage(jid, { audio, ptt: opts.ptt ?? false, ...opts }),
211
+ sendSticker: sock => (jid, sticker, opts = {}) => sock.sendMessage(jid, { sticker }, opts),
212
+ sendLocation: sock => (jid, location, opts = {}) => sock.sendMessage(jid, { location }, opts),
213
+ sendContact: sock => (jid, contact, opts = {}) => sock.sendMessage(jid, { contacts: { displayName: contact.name ?? '', contacts: [contact] } }, opts),
214
+ sendReaction: sock => (jid, key, emoji, opts = {}) => sock.sendMessage(jid, { react: { text: emoji, key } }, opts),
215
+ sendForward: sock => (jid, message, opts = {}) => sock.sendMessage(jid, { forward: message, force: opts.force }, opts)
216
+ }
217
+
218
+ export const HANDLER_SHORTCUTS = {
219
+ sendStatusMentionMessage: (sock, config) => (jid, data) => handleStatusMention(sock, jid, norm(data), config),
220
+ sendStatusMentions: (sock, config) => (jid, data) => handleStatusMention(sock, jid, norm(data), config),
221
+ sendPollResultMessage: sock => (jid, data) => handlePollResult(sock, jid, norm(data)),
222
+ sendGroupStatusMessage: (sock, config) => (jid, content, opts = {}) => handleGroupStatus(sock, jid, norm(content), config),
223
+ sendNativeFlow: sock => (jid, content, opts = {}) => handleNativeFlow(sock, jid, norm(content), opts)
224
+ }
225
+
226
+ // ─── Button ───────────────────────────────────────────────────────────────────
227
+ export class Button {
228
+ #client; #buttons = []; #header = {}; #body = ''; #footer = ''
229
+ #title = ''; #subtitle = ''; #params = {}; #mode = 'native'
230
+
231
+ constructor(client, opts = {}) {
232
+ if (!client) throw new Error('Socket client is required')
233
+ this.#client = client
234
+ if (opts.mode) this.#mode = opts.mode
235
+ }
236
+
237
+ setTitle(t) { this.#title = t; return this }
238
+ setSubtitle(s) { this.#subtitle = s; return this }
239
+ setBody(t) { this.#body = t; return this }
240
+ setFooter(t) { this.#footer = t; return this }
241
+ #resolveLocation(lat, lon, name, opts = {}) {
242
+ const o = (typeof lat === 'object' && lat !== null) ? lat : (typeof lat === 'string' && lon === undefined) ? { title: lat, ...opts } : { lat, lon, name, ...opts }
243
+ return { locationMessage: { degreesLatitude: o.lat ?? o.latitude ?? 0, degreesLongitude: o.lon ?? o.longitude ?? 0, ...(o.name ?? o.title ? { name: o.name ?? o.title } : {}), ...(o.address != null ? { address: o.address } : {}) } }
244
+ }
245
+ setLocation(lat, lon, name, opts = {}) { if (typeof lon === 'object' && lon !== null) { opts = lon; lon = undefined } this.#header = this.#resolveLocation(lat, lon, name, opts); return this }
246
+ setLocationHeader(lat, lon, name, opts = {}) { if (typeof lon === 'object' && lon !== null) { opts = lon; lon = undefined } this.#header = { _headerType: proto.Message.ButtonsMessage?.HeaderType?.LOCATION, ...this.#resolveLocation(lat, lon, name, opts) }; return this }
247
+ setImage(url, opts = {}) { this.#header = { _headerType: proto.Message.ButtonsMessage?.HeaderType?.IMAGE, imageMessage: { url, ...opts } }; return this }
248
+ setVideo(url, opts = {}) { this.#header = { _headerType: proto.Message.ButtonsMessage?.HeaderType?.VIDEO, videoMessage: { url, ...opts } }; return this }
249
+ setDocument(url, fileName = 'file', opts = {}) { this.#header = { _headerType: proto.Message.ButtonsMessage?.HeaderType?.DOCUMENT, documentMessage: { url, fileName, ...opts } }; return this }
250
+ setText(text) { this.#header = { _headerType: proto.Message.ButtonsMessage?.HeaderType?.TEXT, text }; return this }
251
+ setParams(p) { this.#params = p; return this }
252
+ setLimitedTimeOffer(exp) { this.#params.limited_time_offer = { expiration_time_ms: exp }; return this }
253
+ setBottomSheet(opts = {}) { this.#params.bottom_sheet = opts; return this }
254
+ #addNative(name, params) { this.#mode = 'native'; this.#buttons.push({ name, buttonParamsJson: JSON.stringify(params) }); return this }
255
+ reply(text, id) { return this.#addNative('quick_reply', { display_text: text, id }) }
256
+ url(text, url, merchantUrl) { return this.#addNative('cta_url', { display_text: text, url, merchant_url: merchantUrl ?? url }) }
257
+ call(text, phone) { return this.#addNative('cta_call', { display_text: text, phone_number: phone }) }
258
+ copy(text, code) { return this.#addNative('cta_copy', { display_text: text, copy_code: code }) }
259
+ openWebview(text, url, opts = {}) { return this.#addNative('cta_open_webview', { display_text: text, url, ...opts }) }
260
+ catalog(text, opts = {}) { return this.#addNative('catalog', { display_text: text, ...opts }) }
261
+ flow(text, flowId, opts = {}) { return this.#addNative('flow', { display_text: text, flow_id: flowId, flow_token: opts.token ?? crypto.randomUUID(), ...opts }) }
262
+ remind(text, opts = {}) { return this.#addNative('cta_reminder', { display_text: text, ...opts }) }
263
+ cancelReminder(text, opts = {}) { return this.#addNative('cta_cancel_reminder', { display_text: text, ...opts }) }
264
+ address(text, opts = {}) { return this.#addNative('address', { display_text: text, ...opts }) }
265
+ sendLocation(text) { return this.#addNative('send_location', { display_text: text }) }
266
+ reviewAndPay(text, opts = {}) { return this.#addNative('review_and_pay', { display_text: text, ...opts }) }
267
+ reviewOrder(text, opts = {}) { return this.#addNative('review_order', { display_text: text, ...opts }) }
268
+ orderDetails(text, opts = {}) { return this.#addNative('order_details', { display_text: text, ...opts }) }
269
+ paymentStatus(text, opts = {}) { return this.#addNative('payment_status', { display_text: text, ...opts }) }
270
+ transactionDetails(text, opts = {}) { return this.#addNative('transaction_details', { display_text: text, ...opts }) }
271
+ select(title, sections) { return this.#addNative('single_select', { title, sections }) }
272
+
273
+ legacyButton(text, id) { this.#mode = 'legacy'; this.#buttons.push({ buttonId: id, buttonText: { displayText: text }, type: 1 }); return this }
274
+ templateReply(text, id) { this.#mode = 'template'; this.#buttons.push({ quickReplyButton: { displayText: text, id } }); return this }
275
+ templateUrl(text, url) { this.#mode = 'template'; this.#buttons.push({ urlButton: { displayText: text, url } }); return this }
276
+ templateCall(text, phone) { this.#mode = 'template'; this.#buttons.push({ callButton: { displayText: text, phoneNumber: phone } }); return this }
277
+
278
+ toCard() { return { header: this.#header, body: { text: this.#body }, footer: { text: this.#footer }, nativeFlowMessage: { buttons: this.#buttons } } }
279
+
280
+ async build(jid, opts = {}) {
281
+ const messageId = opts.messageId ?? generateMessageIDV2()
282
+ const userJid = this.#client.user?.id
283
+ if (this.#mode === 'legacy') {
284
+ const { _headerType, ...header } = this.#header
285
+ const headerType = _headerType ?? (Object.keys(header).length ? 1 : 0)
286
+ return await generateWAMessageFromContent(jid, { buttonsMessage: { ...header, contentText: this.#body, footerText: this.#footer, buttons: this.#buttons, headerType } }, { userJid, messageId, waUploadToServer: this.#client.waUploadToServer })
287
+ }
288
+ if (this.#mode === 'template') {
289
+ return await generateWAMessageFromContent(jid, { templateMessage: { hydratedTemplate: { hydratedContentText: this.#body, hydratedFooterText: this.#footer, hydratedButtons: this.#buttons } } }, { userJid, messageId, waUploadToServer: this.#client.waUploadToServer })
290
+ }
291
+ const isSingleSelect = this.#buttons.length === 1 && this.#buttons[0].name === 'single_select'
292
+ if (isSingleSelect) {
293
+ const params = JSON.parse(this.#buttons[0].buttonParamsJson)
294
+ return await generateWAMessageFromContent(jid, { listMessage: { title: this.#title, description: this.#body, footerText: this.#footer, buttonText: params.title ?? 'Select', listType: 1, sections: params.sections ?? [] } }, { userJid, messageId, waUploadToServer: this.#client.waUploadToServer })
295
+ }
296
+ const hasMedia = !!(this.#header.imageMessage || this.#header.videoMessage || this.#header.documentMessage)
297
+ const { _headerType, ...headerFields } = this.#header
298
+ const interactiveHeader = Object.keys(this.#header).length ? { hasMediaAttachment: hasMedia, ...headerFields } : undefined
299
+ const nativeFlow = proto.Message.InteractiveMessage?.NativeFlowMessage?.create({ buttons: resolveNativeFlowButtons(this.#buttons), messageParamsJson: Object.keys(this.#params).length ? JSON.stringify(this.#params) : '' })
300
+ ?? { buttons: resolveNativeFlowButtons(this.#buttons), messageParamsJson: '' }
301
+ return await generateWAMessageFromContent(jid, {
302
+ interactiveMessage: {
303
+ header: interactiveHeader,
304
+ body: { text: this.#body },
305
+ footer: { text: this.#footer },
306
+ nativeFlowMessage: nativeFlow,
307
+ ...(this.#title ? { title: this.#title } : {}),
308
+ ...(this.#subtitle ? { subtitle: this.#subtitle } : {})
309
+ }
310
+ }, { userJid, messageId, waUploadToServer: this.#client.waUploadToServer })
311
+ }
312
+
313
+ async send(jid, opts = {}) {
314
+ const msg = await this.build(jid, opts)
315
+ const bizNode = getBizBinaryNode(msg.message)
316
+ await this.#client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
317
+ return msg
318
+ }
319
+ }
320
+
321
+ // ─── Interactive ──────────────────────────────────────────────────────────────
322
+ export class Interactive extends BaseBuilder {
323
+ static dispatchKeys = ['interactiveMessage']
324
+ static shortcuts = {
325
+ sendInteractiveMessage: sock => (jid, data, quoted) => new Interactive(sock).from(data).send(jid, q(quoted)),
326
+ sendProductMessage: sock => (jid, data, quoted) => new Interactive(sock).from(data, { __product: true }).send(jid, q(quoted)),
327
+ }
328
+
329
+ async send(jid, opts = {}) {
330
+ const i = this.data
331
+ const userJid = this.client.user?.id
332
+ const upload = this.client.waUploadToServer
333
+ let media = null
334
+ if (i.thumbnail) media = await prepareWAMessageMedia({ image: { url: i.thumbnail } }, { upload })
335
+ else if (i.image) media = await prepareWAMessageMedia({ image: i.image }, { upload })
336
+ else if (i.video) media = await prepareWAMessageMedia({ video: i.video }, { upload })
337
+ else if (i.document) media = await prepareWAMessageMedia({ document: i.document }, { upload })
338
+ const bodyText = i.body?.text ?? i.title ?? ''
339
+ const footerText = typeof i.footer === 'string' ? i.footer : (i.footer?.text ?? '')
340
+ const headerTitle = typeof i.header === 'string' ? i.header : (i.header?.title ?? '')
341
+ let nativeFlow = null
342
+ if (i.buttons?.length || i.nativeFlowMessage) {
343
+ const nfm = i.nativeFlowMessage ?? {}
344
+ const rawButtons = i.buttons ?? nfm.buttons ?? []
345
+ nativeFlow = { buttons: resolveNativeFlowButtons(rawButtons), messageParamsJson: nfm.messageParamsJson ?? '' }
346
+ }
347
+ const headerMedia = {}
348
+ if (media?.imageMessage) headerMedia.imageMessage = media.imageMessage
349
+ if (media?.videoMessage) headerMedia.videoMessage = media.videoMessage
350
+ if (media?.documentMessage) headerMedia.documentMessage = media.documentMessage
351
+ const interactive = { body: { text: bodyText }, footer: { text: footerText }, header: { title: headerTitle, hasMediaAttachment: !!media, ...headerMedia }, ...(nativeFlow ? { nativeFlowMessage: nativeFlow } : {}) }
352
+ if (i.contextInfo) interactive.contextInfo = i.contextInfo
353
+ const msg = await generateWAMessageFromContent(jid, { interactiveMessage: interactive }, { userJid, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer })
354
+ const bizNode = getBizBinaryNode(msg.message)
355
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
356
+ return msg
357
+ }
358
+ }
359
+
360
+ // ─── Carousel ─────────────────────────────────────────────────────────────────
361
+ export class Carousel extends BaseBuilder {
362
+ #cards = []; #caption = ''; #footer = ''; #cardType = 'HSCROLL_CARDS'
363
+ static #PLACEHOLDER = 'https://placehold.co/600x400/000000/ffffff?text=No+Image'
364
+
365
+ static dispatchKeys = ['carouselMessage']
366
+ static shortcuts = {
367
+ sendCarouselMessage: sock => (jid, data, quoted) => {
368
+ const d = norm(data)
369
+ const c = new Carousel(sock)
370
+ if (d.caption) c.setCaption(d.caption)
371
+ if (d.footer) c.setFooter(d.footer)
372
+ ; (d.cards ?? []).forEach(card => {
373
+ const resolved = card.nativeFlow
374
+ ? { ...card, nativeFlow: undefined, nativeFlowMessage: { buttons: resolveNativeFlowButtons(Array.isArray(card.nativeFlow) ? card.nativeFlow : [card.nativeFlow]) } }
375
+ : card
376
+ c.card(resolved)
377
+ })
378
+ return c.send(jid, q(quoted))
379
+ }
380
+ }
381
+
382
+ constructor(client) { super(client) }
383
+
384
+ from(data, opts = {}) {
385
+ const d = norm(data, opts)
386
+ if (d.caption) this.setCaption(d.caption)
387
+ if (d.footer) this.setFooter(d.footer)
388
+ if (d.cardType) this.setCardType(d.cardType)
389
+ ; (d.cards ?? []).forEach(card => {
390
+ const resolved = card.nativeFlow
391
+ ? { ...card, nativeFlow: undefined, nativeFlowMessage: { buttons: resolveNativeFlowButtons(Array.isArray(card.nativeFlow) ? card.nativeFlow : [card.nativeFlow]) } }
392
+ : card
393
+ this.card(resolved)
394
+ })
395
+ return this
396
+ }
397
+
398
+ setCaption(t) { this.#caption = t; return this }
399
+ setFooter(t) { this.#footer = t; return this }
400
+ setCardType(t) { this.#cardType = t; return this }
401
+ card(b) { this.#cards.push(b instanceof Button ? b.toCard() : (b.text || b.url || b.id ? new Button(this.client).reply(b.text ?? '', b.id ?? '').toCard() : b)); return this }
402
+
403
+ async send(jid, opts = {}) {
404
+ if (this.#cards.length < 2) throw new Error('Carousel requires at least 2 cards')
405
+ if (this.#cards.length > 10) throw new Error('Carousel max 10 cards')
406
+ const cards = this.#cards.map(c => ({
407
+ ...c,
408
+ header: (c.header?.imageMessage || c.header?.hasMediaAttachment)
409
+ ? c.header
410
+ : { ...c.header, hasMediaAttachment: true, imageMessage: { url: Carousel.#PLACEHOLDER } }
411
+ }))
412
+ const msg = await generateWAMessageFromContent(jid, {
413
+ interactiveMessage: {
414
+ header: { hasMediaAttachment: false },
415
+ body: { text: this.#caption },
416
+ footer: { text: this.#footer },
417
+ carouselMessage: {
418
+ cards: cards.map(c => ({
419
+ header: { title: c.header?.title ?? '', hasMediaAttachment: c.header?.hasMediaAttachment ?? false, ...c.header },
420
+ body: { text: c.body?.text ?? '' },
421
+ footer: { text: c.footer?.text ?? '' },
422
+ nativeFlowMessage: { buttons: resolveNativeFlowButtons(c.nativeFlowMessage?.buttons ?? []) }
423
+ })),
424
+ messageVersion: 1,
425
+ carouselCardType: this.#cardType === 'ALBUM_IMAGE' ? 2 : 1
426
+ }
427
+ }
428
+ }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
429
+ const bizNode = getBizBinaryNode(msg.message)
430
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
431
+ return msg
432
+ }
433
+ }
434
+
435
+ // ─── Album ────────────────────────────────────────────────────────────────────
436
+ export class Album extends BaseBuilder {
437
+ #items = []; #delay = 1500
438
+
439
+ static dispatchKeys = ['albumMessage']
440
+ static shortcuts = {
441
+ sendAlbumMessage: sock => (jid, items, quoted, opts = {}) => sock.sendMessage(jid, { albumMessage: items }, { ...q(quoted), ...opts }),
442
+ }
443
+
444
+ image(urlOrBuffer, caption = '') { this.#items.push({ image: typeof urlOrBuffer === 'string' ? { url: urlOrBuffer } : urlOrBuffer, caption }); return this }
445
+ video(urlOrBuffer, caption = '') { this.#items.push({ video: typeof urlOrBuffer === 'string' ? { url: urlOrBuffer } : urlOrBuffer, caption }); return this }
446
+ add(items) { items.forEach(item => this.#items.push(item)); return this }
447
+ setDelay(ms) { this.#delay = ms; return this }
448
+
449
+ async send(jid, opts = {}) {
450
+ const items = this.data.albumMessage ? (Array.isArray(this.data.albumMessage) ? this.data.albumMessage : [this.data.albumMessage]) : this.#items
451
+ if (items.length < 2) throw new Error('Album requires at least 2 items')
452
+ const userJid = this.client.user?.id
453
+ const album = await generateWAMessageFromContent(jid, {
454
+ messageContextInfo: { messageSecret: crypto.randomBytes(32) },
455
+ albumMessage: {
456
+ expectedImageCount: items.filter(a => a.image).length,
457
+ expectedVideoCount: items.filter(a => a.video).length
458
+ }
459
+ }, { userJid, messageId: generateMessageIDV2() })
460
+ await this.client.relayMessage(jid, album.message, { messageId: album.key.id })
461
+ for (const item of items) {
462
+ const img = await generateWAMessage(jid, item, { upload: this.client.waUploadToServer, userJid })
463
+ img.message.messageContextInfo = {
464
+ messageSecret: crypto.randomBytes(32),
465
+ messageAssociation: { associationType: 1, parentMessageKey: album.key }
466
+ }
467
+ await this.client.relayMessage(jid, img.message, { messageId: img.key.id })
468
+ await delay(opts.albumDelay ?? this.#delay)
469
+ }
470
+ return album
471
+ }
472
+ }
473
+
474
+ // ─── Poll ─────────────────────────────────────────────────────────────────────
475
+ export class Poll extends BaseBuilder {
476
+ #poll = { name: '', values: [], selectableOptionsCount: 1, toAnnouncementGroup: false, hideVoter: false }
477
+
478
+ static shortcuts = {
479
+ sendPoll: sock => (jid, name, values, multiSelect = false, opts = {}) =>
480
+ sock.sendMessage(jid, { poll: { name, values, selectableOptionsCount: multiSelect ? 0 : 1 } }, opts),
481
+ }
482
+
483
+ name(n) { this.#poll.name = n; return this }
484
+ options(o) { this.#poll.values = o; return this }
485
+ addOption(o) { this.#poll.values.push(o); return this }
486
+ multiSelect(max = 0) { this.#poll.selectableOptionsCount = max; return this }
487
+ quiz(ans) { this.#poll.pollType = 1; this.#poll.correctAnswer = ans; return this }
488
+ setEndTime(t) { this.#poll.endTime = t; return this }
489
+
490
+ async send(jid, opts = {}) {
491
+ if (!this.#poll.name) throw new Error('Poll name is required')
492
+ if (this.#poll.values.length < 2) throw new Error('Poll requires at least 2 options')
493
+ return this.client.sendMessage(jid, { poll: this.#poll }, opts)
494
+ }
495
+ }
496
+
497
+ // ─── Payment ──────────────────────────────────────────────────────────────────
498
+ export class Payment extends BaseBuilder {
499
+ static dispatchKeys = ['requestPaymentMessage']
500
+ static shortcuts = {
501
+ sendPaymentMessage: sock => (jid, data, quoted) => new Payment(sock).from(data).send(jid, q(quoted)),
502
+ }
503
+
504
+ async send(jid, opts = {}) {
505
+ const d = this.data
506
+ const currency = d.currency ?? 'USD'
507
+ const amount = d.amount ?? 0
508
+ const ctx = opts.quoted ? { stanzaId: opts.quoted.key?.id, participant: opts.quoted.key?.participant, quotedMessage: opts.quoted.message } : {}
509
+ const notes = d.note ? { extendedTextMessage: { text: d.note, contextInfo: ctx } } : {}
510
+ const msg = await generateWAMessageFromContent(jid, {
511
+ requestPaymentMessage: {
512
+ expiryTimestamp: d.expiry ?? 0,
513
+ amount1000: amount,
514
+ currencyCodeIso4217: currency,
515
+ requestFrom: d.from ?? '0@s.whatsapp.net',
516
+ noteMessage: notes,
517
+ amount: { value: amount, offset: 1000, currencyCode: currency }
518
+ }
519
+ }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
520
+ const bizNode = getBizBinaryNode(msg.message)
521
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
522
+ return msg
523
+ }
524
+ }
525
+
526
+ // ─── Order ────────────────────────────────────────────────────────────────────
527
+ export class Order extends BaseBuilder {
528
+ static dispatchKeys = ['orderMessage']
529
+ static shortcuts = {
530
+ sendOrderMessage: sock => (jid, data, quoted) => new Order(sock).from(data).send(jid, q(quoted)),
531
+ }
532
+
533
+ async send(jid, opts = {}) {
534
+ const o = this.data
535
+ const userJid = this.client.user?.id
536
+ const cleanJid = id => { if (!id) return null; const [user] = id.split(':'); return user.includes('@') ? user : `${user}@s.whatsapp.net` }
537
+ const seller = cleanJid(o.sellerJid) ?? cleanJid(userJid) ?? cleanJid(jid) ?? '0@s.whatsapp.net'
538
+ const msg = await generateWAMessageFromContent(jid, {
539
+ orderMessage: {
540
+ orderId: o.orderId ?? `dnuzi${Date.now()}`,
541
+ itemCount: o.itemCount ?? 0,
542
+ status: o.status ?? 1,
543
+ surface: o.surface ?? 1,
544
+ message: o.message,
545
+ orderTitle: o.orderTitle,
546
+ sellerJid: seller,
547
+ token: o.token ?? 'DNUZI_TOKEN',
548
+ totalAmount1000: o.totalAmount1000 ?? 0,
549
+ totalCurrencyCode: o.totalCurrencyCode ?? 'USD',
550
+ messageVersion: o.messageVersion ?? 2,
551
+ ...(o.contextInfo ? { contextInfo: o.contextInfo } : {})
552
+ }
553
+ }, { userJid, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer })
554
+ const bizNode = getBizBinaryNode(msg.message)
555
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
556
+ return msg
557
+ }
558
+ }
559
+
560
+ // ─── Event ────────────────────────────────────────────────────────────────────
561
+ export class Event extends BaseBuilder {
562
+ static dispatchKeys = ['eventMessage']
563
+ static shortcuts = { sendEventMessage: sock => (jid, data, quoted) => new Event(sock).from(data).send(jid, q(quoted)) }
564
+
565
+ setName(n) { this.data.name = n; return this }
566
+ setDescription(d) { this.data.description = d; return this }
567
+ setLocation(l) { this.data.location = l; return this }
568
+ setJoinLink(l) { this.data.joinLink = l; return this }
569
+ setStartTime(t) { this.data.startDate = t instanceof Date ? t : new Date(t); return this }
570
+ setEndTime(t) { this.data.endDate = t instanceof Date ? t : new Date(t); return this }
571
+ setCanceled(v = true) { this.data.isCanceled = v; return this }
572
+ setReminder(sec) { this.data.hasReminder = true; this.data.reminderOffsetSec = sec; return this }
573
+
574
+ async send(jid, opts = {}) {
575
+ const e = this.data
576
+ if (!e.name) throw new Error('Event name is required')
577
+ const startDate = e.startDate instanceof Date ? e.startDate : new Date(e.startDate ?? Date.now())
578
+ const endDate = e.endDate ? (e.endDate instanceof Date ? e.endDate : new Date(e.endDate)) : null
579
+ const msg = await generateWAMessageFromContent(jid, {
580
+ messageContextInfo: { messageSecret: e.messageSecret || crypto.randomBytes(32) },
581
+ eventMessage: {
582
+ isCanceled: e.isCanceled ?? false,
583
+ name: e.name,
584
+ description: e.description ?? '',
585
+ location: e.location ?? { degreesLatitude: 0, degreesLongitude: 0, name: 'Location' },
586
+ joinLink: e.joinLink ?? '',
587
+ startTime: Math.floor(startDate.getTime() / 1000),
588
+ endTime: endDate ? Math.floor(endDate.getTime() / 1000) : undefined,
589
+ extraGuestsAllowed: e.extraGuestsAllowed !== false,
590
+ isScheduleCall: e.isScheduleCall ?? false,
591
+ hasReminder: e.hasReminder ?? false,
592
+ reminderOffsetSec: e.reminderOffsetSec ?? 0
593
+ }
594
+ }, { userJid: this.client.user?.id, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer })
595
+ const bizNode = getBizBinaryNode(msg.message)
596
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: [{ tag: 'meta', attrs: { event_type: 'creation' } }, ...(bizNode ? [bizNode] : [])] })
597
+ return msg
598
+ }
599
+ }
600
+
601
+ // ─── StickerPack ──────────────────────────────────────────────────────────────
602
+ export class StickerPack extends BaseBuilder {
603
+ static dispatchKeys = ['stickerPack', 'stickerPackMessage']
604
+ static shortcuts = {
605
+ stickerPackMessage: sock => (jid, data, opts = {}) => new StickerPack(sock).from(data, { name: opts.packName, publisher: opts.packPublisher }).send(jid, q(opts.quoted)),
606
+ }
607
+
608
+ setStickers(s) { this.data.stickers = s; return this }
609
+
610
+ async send(jid, opts = {}) {
611
+ const userJid = this.client.user?.id
612
+ const { quoted, ...passOpts } = opts
613
+ const result = await prepareStickerPackMessage(this.data, { upload: this.client.waUploadToServer, logger: this.client.logger, ...passOpts })
614
+ if (result?.isBatched) {
615
+ let last
616
+ for (let i = 0; i < result.stickerPackMessage.length; i++) {
617
+ const msg = await generateWAMessageFromContent(jid, { stickerPackMessage: result.stickerPackMessage[i] }, { userJid, quoted, waUploadToServer: this.client.waUploadToServer })
618
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id })
619
+ last = msg
620
+ if (i < result.stickerPackMessage.length - 1) await delay(2000)
621
+ }
622
+ return last
623
+ }
624
+ const msg = await generateWAMessageFromContent(jid, { stickerPackMessage: result?.stickerPackMessage ?? result }, { userJid, quoted, waUploadToServer: this.client.waUploadToServer })
625
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id })
626
+ return msg
627
+ }
628
+ }
629
+
630
+ // ─── VerticalAlbum ────────────────────────────────────────────────────────────
631
+ export class VerticalAlbum extends BaseBuilder {
632
+ static dispatchKeys = ['verticalAlbumMessage']
633
+ static shortcuts = {
634
+ sendVerticalAlbumMessage: sock => (jid, data, opts = {}) => new VerticalAlbum(sock).from(data, opts).send(jid, opts)
635
+ }
636
+
637
+ async send(jid, opts = {}) {
638
+ const items = this.data.items ?? (Array.isArray(this.data.verticalAlbumMessage) ? this.data.verticalAlbumMessage : [])
639
+ if (!Array.isArray(items) || items.length < 2) throw new Error('VerticalAlbum requires at least 2 items')
640
+ const expiration = String(Date.now() + 30 * 24 * 60 * 60 * 1000)
641
+ const primitives = items.map((item, i) => {
642
+ const kind = item?.type || (item?.video ? 'video' : 'image')
643
+ if (kind === 'video') {
644
+ const v = item.video || item.data || item
645
+ const url = typeof v === 'string' ? v : (v?.url ?? v?.videoUrl ?? '')
646
+ if (!url) throw new Error(`VerticalAlbum item ${i}: video requires a URL`)
647
+ return { media: { url, mime_type: v?.mimeType ?? 'video/mp4', file_length: v?.fileLength ?? 0, duration: v?.duration ?? 0 }, imagine_type: 'ANIMATE', status: { status: 'READY' }, __typename: 'GenAIImaginePrimitive' }
648
+ }
649
+ const img = item?.image || item?.data || item
650
+ const url = typeof img === 'string' ? img : (img?.url ?? img?.highResUrl ?? img?.imageHighResUrl ?? '')
651
+ if (!url) throw new Error(`VerticalAlbum item ${i}: image requires a URL`)
652
+ const w = Number(img?.width ?? 600), h = Number(img?.height ?? 400)
653
+ const media = (u, mw, mh) => ({ url: u, url_fallback: u, mime_type: 'image/png', expiration_timestamp_ms: expiration, width: mw, height: mh })
654
+ return { preview_image: media(url, w, h), full_image: media(url, w, h), dark_mode_preview_image: media(url, w, h), dark_mode_full_image: media(url, w, h), asset_query_status: 'FETCHED', display_mode: 'FULL_WIDTH', full_width: true, __typename: 'GenAIImagePrimitive' }
655
+ })
656
+ const unified = { response_id: crypto.randomUUID(), sections: [{ view_model: { primitives, display_mode: 'FULL_WIDTH', full_width: true, __typename: 'GenAIVStackLayoutViewModel' } }] }
657
+ const msg = await generateWAMessageFromContent(jid, {
658
+ messageContextInfo: { botMetadata: { pluginMetadata: {}, botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA } },
659
+ botForwardedMessage: { message: { richResponseMessage: { messageType: 1, submessages: [], unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) }, contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 } } } }
660
+ }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
661
+ const bizNode = getBizBinaryNode(msg.message)
662
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
663
+ return msg
664
+ }
665
+ }
666
+
667
+ // ─── GridImage ────────────────────────────────────────────────────────────────
668
+ export class GridImage extends BaseBuilder {
669
+ static dispatchKeys = ['gridImageMessage']
670
+ static shortcuts = {
671
+ sendGridImageMessage: sock => (jid, data, opts = {}) => new GridImage(sock).from(data, opts).send(jid, opts)
672
+ }
673
+
674
+ async send(jid, opts = {}) {
675
+ const imageUrls = this.data.imageUrls ?? this.data.images ?? (Array.isArray(this.data.gridImageMessage) ? this.data.gridImageMessage : [])
676
+ if (!Array.isArray(imageUrls) || imageUrls.length < 2) throw new Error('GridImage requires at least 2 images')
677
+ const expiration = String(Date.now() + 30 * 24 * 60 * 60 * 1000)
678
+ const submessages = [{ messageType: 6, gridImageMetadata: { imageUrls } }]
679
+ const sections = imageUrls.map(img => {
680
+ const image = typeof img === 'string' ? { url: img } : img
681
+ const url = image.url ?? image.imageHighResUrl ?? image.highResUrl ?? ''
682
+ const w = Number(image.width ?? 600), h = Number(image.height ?? 400)
683
+ const media = (u, mw, mh) => ({ url: u, url_fallback: u, mime_type: 'image/png', expiration_timestamp_ms: expiration, width: mw, height: mh })
684
+ return { preview_image: media(url, w, h), full_image: media(url, w, h), dark_mode_preview_image: media(url, w, h), dark_mode_full_image: media(url, w, h), asset_query_status: 'FETCHED', __typename: 'GenAIImagePrimitive' }
685
+ })
686
+ const unified = { response_id: crypto.randomUUID(), sections: [{ view_model: { primitives: sections, __typename: 'GenAIGridLayoutViewModel' } }] }
687
+ const msg = await generateWAMessageFromContent(jid, {
688
+ messageContextInfo: { botMetadata: { pluginMetadata: {}, botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA } },
689
+ botForwardedMessage: { message: { richResponseMessage: { messageType: 1, submessages, unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) }, contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 } } } }
690
+ }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
691
+ const bizNode = getBizBinaryNode(msg.message)
692
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
693
+ return msg
694
+ }
695
+ }
696
+
697
+ // ─── VideoGrid ────────────────────────────────────────────────────────────────
698
+ export class VideoGrid extends BaseBuilder {
699
+ static dispatchKeys = ['videoGridMessage']
700
+ static shortcuts = {
701
+ sendVideoGridMessage: sock => (jid, data, opts = {}) => new VideoGrid(sock).from(data, opts).send(jid, opts)
702
+ }
703
+
704
+ async send(jid, opts = {}) {
705
+ const videos = this.data.videos ?? (Array.isArray(this.data.videoGridMessage) ? this.data.videoGridMessage : [])
706
+ if (!Array.isArray(videos) || videos.length < 2) throw new Error('VideoGrid requires at least 2 videos')
707
+ const primitives = videos.map((v, i) => {
708
+ const url = typeof v === 'string' ? v : (v?.url ?? v?.videoUrl ?? v?.reelsUrl ?? '')
709
+ if (!url) throw new Error(`VideoGrid item ${i}: requires a URL`)
710
+ const item = typeof v === 'string' ? {} : v
711
+ return { reels_url: url, reels_title: item.title, thumbnail_url: item.thumbnailUrl ?? item.thumbnail, source_app: item.sourceApp, __typename: 'GenAIVideoPrimitive' }
712
+ })
713
+ const unified = { response_id: crypto.randomUUID(), sections: [{ view_model: { primitives, __typename: 'GenAIGridLayoutViewModel' } }] }
714
+ const msg = await generateWAMessageFromContent(jid, {
715
+ messageContextInfo: { botMetadata: { pluginMetadata: {}, botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA } },
716
+ botForwardedMessage: { message: { richResponseMessage: { messageType: 1, submessages: [], unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) }, contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 } } } }
717
+ }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
718
+ const bizNode = getBizBinaryNode(msg.message)
719
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
720
+ return msg
721
+ }
722
+ }
723
+
724
+ // ─── A2UI ─────────────────────────────────────────────────────────────────────
725
+ export class A2UI extends BaseBuilder {
726
+ static VERSION = 'v0.9'
727
+ static get CATALOG() { return `https://a2ui.org/specification/${this.VERSION}/catalogs/basic/catalog.json` }
728
+ static dispatchKeys = ['a2uiMessage']
729
+ static shortcuts = {
730
+ sendA2UIMessage: sock => (jid, data, opts = {}) => new A2UI(sock).from(data, opts).send(jid, opts),
731
+ sendA2UI: sock => (jid, components, opts = {}) => new A2UI(sock).addComponents(components).send(jid, opts)
732
+ }
733
+
734
+ static text(id, text, { variant = 'body' } = {}) { return { id, component: 'Text', text: String(text), variant } }
735
+ static image(id, input, { variant = 'mediumFeature', fit = 'fill' } = {}) { return { id, component: 'Image', url: '', _raw: input, variant, fit } }
736
+ static button(id, child, action, { variant = 'default' } = {}) { return { id, component: 'Button', child: String(child), action, variant } }
737
+ static column(id, children = [], { justify = 'start', align = 'stretch' } = {}) { return { id, component: 'Column', children: children.map(String), justify, align } }
738
+ static row(id, children = [], { justify = 'start', align = 'stretch' } = {}) { return { id, component: 'Row', children: children.map(String), justify, align } }
739
+ static list(id, children = [], { direction = 'vertical', align = 'stretch' } = {}) { return { id, component: 'List', children: children.map(String), direction, align } }
740
+ static card(id, child) { return { id, component: 'Card', child: String(child) } }
741
+ static divider(id, { axis = 'horizontal' } = {}) { return { id, component: 'Divider', axis } }
742
+ static tabs(id, tabs = []) { return { id, component: 'Tabs', tabs: tabs.map((t, i) => ({ title: String(t.title ?? t.label ?? `Tab ${i + 1}`), child: String(t.child) })) } }
743
+
744
+ static surface(components, { surfaceId, catalogId = A2UI.CATALOG, version = A2UI.VERSION } = {}) {
745
+ const id = surfaceId ?? `dnuzi-a2ui-${crypto.randomUUID()}`
746
+ return Buffer.from(JSON.stringify({ version, createSurface: { surfaceId: id, catalogId, sendDataModel: false, components } }), 'utf8')
747
+ }
748
+
749
+ static async #resolveImage(input, upload) {
750
+ if (Buffer.isBuffer(input)) { const p = await prepareWAMessageMedia({ image: input }, { upload }); return { url: p.imageMessage?.url ?? '' } }
751
+ if (typeof input === 'string' && input.startsWith('http')) return { url: input }
752
+ if (input?.url) return { url: input.url }
753
+ return { url: '' }
754
+ }
755
+
756
+ #components = []; #buttons = []; #surfaceId = `dnuzi-a2ui-${crypto.randomUUID()}`; #fallback = ''
757
+
758
+ addComponent(obj) { if (!obj?.id) throw new TypeError('addComponent requires an object with an id'); this.#components.push(obj); return this }
759
+ addComponents(arr) { if (!Array.isArray(arr)) throw new TypeError('addComponents requires an array'); for (const c of arr) this.addComponent(c); return this }
760
+ addText(id, text, opts = {}) { return this.addComponent(A2UI.text(id, text, opts)) }
761
+ addImage(id, input, opts = {}) { return this.addComponent(A2UI.image(id, input, opts)) }
762
+ addColumn(id, children = [], opts = {}) { return this.addComponent(A2UI.column(id, children, opts)) }
763
+ addRow(id, children = [], opts = {}) { return this.addComponent(A2UI.row(id, children, opts)) }
764
+ addList(id, children = [], opts = {}) { return this.addComponent(A2UI.list(id, children, opts)) }
765
+ addCard(id, child) { return this.addComponent(A2UI.card(id, child)) }
766
+ addTabs(id, tabs = []) { return this.addComponent(A2UI.tabs(id, tabs)) }
767
+ addDivider(id, opts = {}) { return this.addComponent(A2UI.divider(id, opts)) }
768
+ addButtonComponent(id, child, action, opts = {}) { return this.addComponent(A2UI.button(id, child, action, opts)) }
769
+ addButton(nameOrShorthand, params = {}) {
770
+ if (!nameOrShorthand) throw new TypeError('addButton requires a name or shorthand object')
771
+ if (typeof nameOrShorthand === 'object') { const [r] = resolveNativeFlowButtons([nameOrShorthand]); this.#buttons.push(r) }
772
+ else this.#buttons.push({ name: nameOrShorthand, buttonParamsJson: typeof params === 'string' ? params : JSON.stringify(params) })
773
+ return this
774
+ }
775
+ setFallback(text) { this.#fallback = String(text); return this }
776
+ setSurfaceId(id) { this.#surfaceId = String(id); return this }
777
+
778
+ async send(jid, opts = {}) {
779
+ const d = this.data
780
+ if (d.components?.length) { this.addComponents(d.components); if (d.buttons?.length) for (const b of d.buttons) this.#buttons.push(b) }
781
+ const upload = this.client.waUploadToServer
782
+ const components = this.#components
783
+ if (!components.length) throw new Error('A2UI requires at least one component')
784
+ if (!components.some(c => c.id === 'root')) throw new Error('A2UI components must include one with id "root"')
785
+
786
+ // Resolve image components
787
+ const resolved = await Promise.all(components.map(async c => {
788
+ if (c.component !== 'Image' || !c._raw) return c
789
+ const { _raw, ...rest } = c
790
+ const { url } = await A2UI.#resolveImage(_raw, upload)
791
+ return { ...rest, url }
792
+ }))
793
+
794
+ const buttons = [...this.#buttons, ...(opts.buttons ?? [])]
795
+ const content = {
796
+ interactiveMessage: {
797
+ header: { hasMediaAttachment: false },
798
+ body: { text: d.body ?? d.text ?? '\u200b' },
799
+ bloksWidget: { uuid: this.#surfaceId, type: 'im_a2ui', data: A2UI.surface(resolved, { surfaceId: this.#surfaceId }), fallback: this.#fallback },
800
+ ...(buttons.length ? { nativeFlowMessage: { messageParamsJson: JSON.stringify(opts.nativeFlowParams ?? {}), buttons, messageVersion: 1 } } : {})
801
+ }
802
+ }
803
+ const msg = await generateWAMessageFromContent(jid, content, { userJid: this.client.user?.id, waUploadToServer: upload })
804
+ const bizNode = getBizBinaryNode(msg.message)
805
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
806
+ return msg
807
+ }
808
+ }
809
+
810
+ // ─── Auto builders ────────────────────────────────────────────────────────────
811
+ // Auto-derive minimal builders for scalar proto message types not covered above
812
+ export const buildAutoBuilders = handBuiltKeys => {
813
+ const result = []
814
+ try {
815
+ const fields = proto.Message?.fields ?? {}
816
+ for (const [fieldName, fd] of Object.entries(fields)) {
817
+ if (fd.type !== 'msg') continue
818
+ const sub = proto.Message[fd.msgType]
819
+ if (!sub?.fields) continue
820
+ if (sub.fields?.message?.msgType === 'Message') continue
821
+ const inputKey = fieldName.replace(/Message$/, '')
822
+ if (handBuiltKeys.has(inputKey) || handBuiltKeys.has(fieldName)) continue
823
+ const className = inputKey.charAt(0).toUpperCase() + inputKey.slice(1)
824
+ const BuilderClass = class extends BaseBuilder {
825
+ static dispatchKeys = [fieldName, ...(fieldName !== inputKey ? [inputKey] : [])]
826
+ async send(jidArg, optsArg = {}) {
827
+ const msg = await generateWAMessageFromContent(jidArg, { [fieldName]: this.data }, { userJid: this.client.user?.id, quoted: optsArg.quoted, waUploadToServer: this.client.waUploadToServer })
828
+ const bizNode = getBizBinaryNode(msg.message)
829
+ await this.client.relayMessage(jidArg, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
830
+ return msg
831
+ }
832
+ }
833
+ Object.defineProperty(BuilderClass, 'name', { value: className })
834
+ result.push(BuilderClass)
835
+ }
836
+ } catch (_) { /* proto reflection not available */ }
837
+ return result
838
+ }
839
+
840
+ let _autoBuilders = null
841
+ export const getAutoBuilders = (handBuilt, messageHandlerKeys = []) => {
842
+ if (_autoBuilders) return _autoBuilders
843
+ const handBuiltKeys = new Set([
844
+ ...messageHandlerKeys,
845
+ ...handBuilt.flatMap(B =>
846
+ B?.dispatchKeys?.length ? B.dispatchKeys : B?.name ? [B.name.replace(/Builder$/, '').toLowerCase()] : []
847
+ )
848
+ ])
849
+ _autoBuilders = buildAutoBuilders(handBuiltKeys)
850
+ return _autoBuilders
851
+ }