@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,589 +1,589 @@
1
- import crypto from 'crypto'
2
- import { proto } from '../../WAProto/index.js'
3
- import { BOT_RENDERING_CONFIG_METADATA } from '../Defaults/index.js'
4
- import { generateWAMessage, generateWAMessageFromContent, normalizeToBuffer, generateMessageIDV2, prepareStickerPackMessage, prepareWAMessageMedia, resolveNativeFlowButtons, extractImageThumb, resolveToMediaUrl } from '../Utils/index.js'
5
- import { getBizBinaryNode } from '../WABinary/index.js'
6
- import { BaseBuilder, norm, q } from './base.js'
7
-
8
- const delay = ms => new Promise(r => setTimeout(r, ms))
9
-
10
- // ─── Button ───────────────────────────────────────────────────────────────────
11
- export class Button {
12
- #client; #buttons = []; #header = {}; #body = ''; #footer = ''
13
- #title = ''; #subtitle = ''; #params = {}; #mode = 'native'
14
-
15
- constructor(client, opts = {}) {
16
- if (!client) throw new Error('Socket client is required')
17
- this.#client = client
18
- if (opts.mode) this.#mode = opts.mode
19
- }
20
-
21
- setTitle(t) { this.#title = t; return this }
22
- setSubtitle(s) { this.#subtitle = s; return this }
23
- setBody(t) { this.#body = t; return this }
24
- setFooter(t) { this.#footer = t; return this }
25
- #resolveLocation(lat, lon, name, opts = {}) {
26
- const o = (typeof lat === 'object' && lat !== null) ? lat : (typeof lat === 'string' && lon === undefined) ? { title: lat, ...opts } : { lat, lon, name, ...opts }
27
- 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 } : {}), ...(o.thumbnail != null ? { _thumbnail: o.thumbnail } : {}) } }
28
- }
29
- 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 }
30
- 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 }
31
- setImage(url, opts = {}) { this.#header = { _headerType: proto.Message.ButtonsMessage.HeaderType.IMAGE, imageMessage: { url, ...opts } }; return this }
32
- setVideo(url, opts = {}) { this.#header = { _headerType: proto.Message.ButtonsMessage.HeaderType.VIDEO, videoMessage: { url, ...opts } }; return this }
33
- setDocument(url, fileName = 'file', opts = {}) { this.#header = { _headerType: proto.Message.ButtonsMessage.HeaderType.DOCUMENT, documentMessage: { url, fileName, ...opts } }; return this }
34
- setText(text) { this.#header = { _headerType: proto.Message.ButtonsMessage.HeaderType.TEXT, text }; return this }
35
- setParams(p) { this.#params = p; return this }
36
- setLimitedTimeOffer(exp) { this.#params.limited_time_offer = { expiration_time_ms: exp }; return this }
37
- setBottomSheet(opts = {}) { this.#params.bottom_sheet = opts; return this }
38
- setTapTargetConfiguration(opts = {}) { this.#params.tap_target_configuration = opts; return this }
39
- #addNative(name, params) { this.#mode = 'native'; this.#buttons.push({ name, buttonParamsJson: JSON.stringify(params) }); return this }
40
- reply(text, id) { return this.#addNative('quick_reply', { display_text: text, id }) }
41
- url(text, url, merchantUrl) { return this.#addNative('cta_url', { display_text: text, url, merchant_url: merchantUrl ?? url }) }
42
- call(text, phone) { return this.#addNative('cta_call', { display_text: text, phone_number: phone }) }
43
- copy(text, code) { return this.#addNative('cta_copy', { display_text: text, copy_code: code }) }
44
- openWebview(text, url, opts = {}) { return this.#addNative('cta_open_webview', { display_text: text, url, ...opts }) }
45
- catalog(text, opts = {}) { return this.#addNative('catalog', { display_text: text, ...opts }) }
46
- flow(text, flowId, opts = {}) { return this.#addNative('flow', { display_text: text, flow_id: flowId, flow_token: opts.token ?? crypto.randomUUID(), ...opts }) }
47
- remind(text, opts = {}) { return this.#addNative('cta_reminder', { display_text: text, ...opts }) }
48
- cancelReminder(text, opts = {}) { return this.#addNative('cta_cancel_reminder', { display_text: text, ...opts }) }
49
- address(text, opts = {}) { return this.#addNative('address', { display_text: text, ...opts }) }
50
- sendLocation(text) { return this.#addNative('send_location', { display_text: text }) }
51
- reviewAndPay(text, opts = {}) { return this.#addNative('review_and_pay', { display_text: text, ...opts }) }
52
- reviewOrder(text, opts = {}) { return this.#addNative('review_order', { display_text: text, ...opts }) }
53
- orderDetails(text, opts = {}) { return this.#addNative('order_details', { display_text: text, ...opts }) }
54
- paymentStatus(text, opts = {}) { return this.#addNative('payment_status', { display_text: text, ...opts }) }
55
- transactionDetails(text, opts = {}) { return this.#addNative('transaction_details', { display_text: text, ...opts }) }
56
- select(title, sections) { return this.#addNative('single_select', { title, sections }) }
57
-
58
- legacyButton(text, id) { this.#mode = 'legacy'; this.#buttons.push({ buttonId: id, buttonText: { displayText: text }, type: 1 }); return this }
59
- templateReply(text, id) { this.#mode = 'template'; this.#buttons.push({ quickReplyButton: { displayText: text, id } }); return this }
60
- templateUrl(text, url) { this.#mode = 'template'; this.#buttons.push({ urlButton: { displayText: text, url } }); return this }
61
- templateCall(text, phone) { this.#mode = 'template'; this.#buttons.push({ callButton: { displayText: text, phoneNumber: phone } }); return this }
62
-
63
- buttonsMessage(opts = {}) {
64
- this.#mode = 'buttonsMessage'
65
- if (opts.location) this.setLocationHeader(opts.location)
66
- else if (opts.image) this.setImage(typeof opts.image === 'string' ? opts.image : opts.image.url, opts.image)
67
- else if (opts.video) this.setVideo(typeof opts.video === 'string' ? opts.video : opts.video.url, opts.video)
68
- else if (opts.document) this.setDocument(opts.document.url ?? opts.document, opts.document.fileName, opts.document)
69
- else if (opts.text) this.setText(opts.text)
70
- if (opts.body) this.#body = opts.body
71
- if (opts.footer) this.#footer = opts.footer
72
- if (opts.buttons?.length) {
73
- const nfm = { buttons: opts.buttons }
74
- proto.Message.InteractiveMessage.NativeFlowMessage.create({ buttons: resolveNativeFlowButtons(nfm.buttons), messageParamsJson: '' }).buttons
75
- .forEach(b => { const p = JSON.parse(b.buttonParamsJson ?? '{}'); this.#buttons.push({ buttonId: p.id ?? p.display_text ?? b.name, buttonText: { displayText: p.display_text ?? p.title ?? '' }, type: b.name === 'single_select' ? 2 : 1, ...(b.name === 'single_select' ? { nativeFlowInfo: { name: 'single_select', paramsJson: b.buttonParamsJson } } : {}) }) })
76
- }
77
- return this
78
- }
79
-
80
- setBloksWidget(components) {
81
- const flat = []
82
- const resolve = c => { if (!c.__id) c.__id = `c_${flat.length}`; flat.push(c); if (c.children) c.children = c.children.map(ch => { resolve(ch); return ch.__id }); if (c.$ref) c.$ref = c.$ref.__id }
83
- ; (Array.isArray(components) ? components : [components]).forEach(c => resolve(c))
84
- this.#buttons = [{ name: 'galaxy_message', buttonParamsJson: JSON.stringify({ wa_flow_response_params: { title: this.#title }, components: flat }) }]
85
- this.#mode = 'native'; return this
86
- }
87
-
88
- toCard() { return { header: this.#header, body: { text: this.#body }, footer: { text: this.#footer }, nativeFlowMessage: { buttons: this.#buttons } } }
89
-
90
- #resolveButtonsMessageHeader() {
91
- const { _headerType, locationMessage, imageMessage, videoMessage, documentMessage, text } = this.#header
92
- const H = proto.Message.ButtonsMessage.HeaderType
93
- if (locationMessage) return { headerType: _headerType ?? H.LOCATION, field: { locationMessage: { ...locationMessage } } }
94
- if (imageMessage) return { headerType: _headerType ?? H.IMAGE, field: { imageMessage: { ...imageMessage } } }
95
- if (videoMessage) return { headerType: _headerType ?? H.VIDEO, field: { videoMessage: { ...videoMessage } } }
96
- if (documentMessage) return { headerType: _headerType ?? H.DOCUMENT, field: { documentMessage: { ...documentMessage } } }
97
- if (text) return { headerType: _headerType ?? H.TEXT, field: { text } }
98
- return { headerType: H.EMPTY, field: { contentText: this.#body } }
99
- }
100
-
101
- async #resolveThumbnail(field) {
102
- const inner = Object.values(field)[0]
103
- if (inner?._thumbnail) { inner.jpegThumbnail = (await extractImageThumb(inner._thumbnail, 300)).buffer; delete inner._thumbnail }
104
- }
105
-
106
- async #resolveHeader() {
107
- const upload = this.#client.waUploadToServer
108
- const [key, type] = Object.entries({ imageMessage: 'image', videoMessage: 'video', documentMessage: 'document' }).find(([k]) => this.#header[k]?._raw) ?? []
109
- if (!key) return
110
- const { _raw, ...rest } = this.#header[key]
111
- const src = await normalizeToBuffer(_raw)
112
- const p = await prepareWAMessageMedia({ [type]: src, ...(type === 'document' && { mimetype: rest.mimetype ?? 'application/octet-stream', fileName: rest.fileName ?? 'file' }) }, { upload })
113
- this.#header = { _headerType: this.#header._headerType, [key]: { ...p[key], ...rest } }
114
- }
115
-
116
- async build(jid, opts = {}) {
117
- await this.#resolveHeader()
118
- const messageId = opts.messageId ?? generateMessageIDV2()
119
- const userJid = this.#client.user?.id
120
- if (this.#mode === 'legacy') {
121
- const { _headerType, ...header } = this.#header
122
- const headerType = _headerType ?? (Object.keys(header).length ? proto.Message.ButtonsMessage.HeaderType.TEXT : proto.Message.ButtonsMessage.HeaderType.EMPTY)
123
- await this.#resolveThumbnail(header)
124
- return await generateWAMessageFromContent(jid, { buttonsMessage: { ...header, contentText: this.#body, footerText: this.#footer, buttons: this.#buttons, headerType } }, { userJid, messageId, waUploadToServer: this.#client.waUploadToServer })
125
- }
126
- if (this.#mode === 'template') return await generateWAMessageFromContent(jid, { templateMessage: { hydratedTemplate: { hydratedContentText: this.#body, hydratedFooterText: this.#footer, hydratedButtons: this.#buttons } } }, { userJid, messageId, waUploadToServer: this.#client.waUploadToServer })
127
- if (this.#mode === 'buttonsMessage') {
128
- const { headerType, field } = this.#resolveButtonsMessageHeader()
129
- await this.#resolveThumbnail(field)
130
- return await generateWAMessageFromContent(jid, { buttonsMessage: { ...field, footerText: this.#footer, headerType, buttons: this.#buttons } }, { userJid, messageId, waUploadToServer: this.#client.waUploadToServer })
131
- }
132
- const isSingleSelect = this.#buttons.length === 1 && this.#buttons[0].name === 'single_select'
133
- if (isSingleSelect) { const params = JSON.parse(this.#buttons[0].buttonParamsJson); 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 }) }
134
- const { field } = this.#resolveButtonsMessageHeader()
135
- await this.#resolveThumbnail(field)
136
- const hasMedia = !!(field.imageMessage || field.videoMessage || field.documentMessage || field.productMessage)
137
- const interactiveHeader = Object.keys(this.#header).length ? { hasMediaAttachment: hasMedia, ...field } : undefined
138
- const nativeFlow = proto.Message.InteractiveMessage.NativeFlowMessage.create({ buttons: resolveNativeFlowButtons(this.#buttons), messageParamsJson: Object.keys(this.#params).length ? JSON.stringify(this.#params) : '' })
139
- return await generateWAMessageFromContent(jid, { interactiveMessage: { header: interactiveHeader, body: { text: this.#body }, footer: { text: this.#footer }, nativeFlowMessage: nativeFlow, ...(this.#title ? { title: this.#title } : {}), ...(this.#subtitle ? { subtitle: this.#subtitle } : {}) } }, { userJid, messageId, waUploadToServer: this.#client.waUploadToServer })
140
- }
141
-
142
- async send(jid, opts = {}) {
143
- const msg = await this.build(jid, opts)
144
- const bizNode = getBizBinaryNode(msg.message)
145
- await this.#client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
146
- return msg
147
- }
148
- }
149
-
150
- // ─── Interactive ──────────────────────────────────────────────────────────────
151
- export class Interactive extends BaseBuilder {
152
- static dispatchKeys = ['interactiveMessage']
153
- static shortcuts = {
154
- sendInteractiveMessage: sock => (jid, data, quoted) => new Interactive(sock).from(data).send(jid, q(quoted)),
155
- sendProductMessage: sock => (jid, data, quoted) => new Interactive(sock).from(data, { __product: true }).send(jid, q(quoted)),
156
- }
157
-
158
- async send(jid, opts = {}) {
159
- const i = this.data
160
- const userJid = this.client.user?.id
161
- const upload = this.client.waUploadToServer
162
- let media = null
163
- if (i.thumbnail) media = await prepareWAMessageMedia({ image: { url: i.thumbnail } }, { upload })
164
- else if (i.image) media = await prepareWAMessageMedia({ image: i.image }, { upload })
165
- else if (i.video) media = await prepareWAMessageMedia({ video: i.video }, { upload })
166
- else if (i.document) media = await prepareWAMessageMedia({ document: i.document }, { upload })
167
- const bodyText = i.body?.text ?? i.title ?? ''
168
- const footerText = typeof i.footer === 'string' ? i.footer : (i.footer?.text ?? '')
169
- const headerTitle = typeof i.header === 'string' ? i.header : (i.header?.title ?? '')
170
- let nativeFlow = null
171
- if (i.buttons?.length || i.nativeFlowMessage) { const nfm = i.nativeFlowMessage ?? {}; const rawButtons = i.buttons ?? nfm.buttons ?? []; nativeFlow = proto.Message.InteractiveMessage.NativeFlowMessage.create({ buttons: resolveNativeFlowButtons(rawButtons), messageParamsJson: nfm.messageParamsJson ?? '' }) }
172
- const headerMedia = {}
173
- if (media?.imageMessage) headerMedia.imageMessage = media.imageMessage
174
- if (media?.videoMessage) headerMedia.videoMessage = media.videoMessage
175
- if (media?.documentMessage) headerMedia.documentMessage = media.documentMessage
176
- const interactive = proto.Message.InteractiveMessage.create({ body: proto.Message.InteractiveMessage.Body.create({ text: bodyText }), footer: proto.Message.InteractiveMessage.Footer.create({ text: footerText }), header: proto.Message.InteractiveMessage.Header.create({ title: headerTitle, hasMediaAttachment: !!media, ...headerMedia }), ...(nativeFlow ? { nativeFlowMessage: nativeFlow } : {}) })
177
- if (i.contextInfo) interactive.contextInfo = i.contextInfo
178
- const msg = await generateWAMessageFromContent(jid, { interactiveMessage: interactive }, { userJid, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer })
179
- const bizNode = getBizBinaryNode(msg.message)
180
- await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
181
- return msg
182
- }
183
- }
184
-
185
- // ─── Carousel ─────────────────────────────────────────────────────────────────
186
- export class Carousel extends BaseBuilder {
187
- #cards = []; #caption = ''; #footer = ''; #cardType = 'HSCROLL_CARDS'
188
- static #PLACEHOLDER = 'https://placehold.co/600x400/000000/ffffff?text=No+Image'
189
-
190
- static dispatchKeys = ['carouselMessage']
191
- static shortcuts = {
192
- sendCarouselMessage: sock => (jid, data, quoted) => { const d = norm(data); const c = new Carousel(sock); if (d.caption) c.setCaption(d.caption); if (d.footer) c.setFooter(d.footer); (d.cards ?? []).forEach(card => { const resolved = card.nativeFlow ? { ...card, nativeFlow: undefined, nativeFlowMessage: { buttons: resolveNativeFlowButtons(Array.isArray(card.nativeFlow) ? card.nativeFlow : [card.nativeFlow]) } } : card; c.card(resolved) }); return c.send(jid, q(quoted)) },
193
- sendCarouselProtoMessage: sock => (jid, data, quoted) => Carousel.shortcuts.sendCarouselMessage(sock)(jid, data, quoted),
194
- }
195
-
196
- constructor(client) { super(client) }
197
-
198
- from(data, opts = {}) {
199
- const d = norm(data, opts)
200
- if (d.caption) this.setCaption(d.caption)
201
- if (d.footer) this.setFooter(d.footer)
202
- if (d.cardType) this.setCardType(d.cardType)
203
- ; (d.cards ?? []).forEach(card => { const resolved = card.nativeFlow ? { ...card, nativeFlow: undefined, nativeFlowMessage: { buttons: resolveNativeFlowButtons(Array.isArray(card.nativeFlow) ? card.nativeFlow : [card.nativeFlow]) } } : card; this.card(resolved) })
204
- return this
205
- }
206
-
207
- setCaption(t) { this.#caption = t; return this }
208
- setFooter(t) { this.#footer = t; return this }
209
- setCardType(t) { this.#cardType = t; return this }
210
- 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 }
211
-
212
- async send(jid, opts = {}) {
213
- if (this.#cards.length < 2) throw new Error('Carousel requires at least 2 cards')
214
- if (this.#cards.length > 10) throw new Error('Carousel max 10 cards')
215
- const cards = this.#cards.map(c => ({ ...c, header: (c.header?.imageMessage || c.header?.hasMediaAttachment) ? c.header : { ...c.header, hasMediaAttachment: true, imageMessage: { url: Carousel.#PLACEHOLDER } } }))
216
- const msg = await generateWAMessageFromContent(jid, { interactiveMessage: proto.Message.InteractiveMessage.create({ header: proto.Message.InteractiveMessage.Header.create({ hasMediaAttachment: false }), body: proto.Message.InteractiveMessage.Body.create({ text: this.#caption }), footer: proto.Message.InteractiveMessage.Footer.create({ text: this.#footer }), carouselMessage: proto.Message.InteractiveMessage.CarouselMessage.create({ cards: cards.map(c => ({ header: proto.Message.InteractiveMessage.Header.create({ title: c.header?.title ?? '', hasMediaAttachment: c.header?.hasMediaAttachment ?? false, ...c.header }), body: proto.Message.InteractiveMessage.Body.create({ text: c.body?.text ?? '' }), footer: proto.Message.InteractiveMessage.Footer.create({ text: c.footer?.text ?? '' }), nativeFlowMessage: proto.Message.InteractiveMessage.NativeFlowMessage.create({ buttons: resolveNativeFlowButtons(c.nativeFlowMessage?.buttons ?? []) }) })), messageVersion: 1, carouselCardType: this.#cardType === 'ALBUM_IMAGE' ? 2 : 1 }) }) }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
217
- const bizNode = getBizBinaryNode(msg.message)
218
- await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
219
- return msg
220
- }
221
- }
222
-
223
- // ─── Album ────────────────────────────────────────────────────────────────────
224
- export class Album extends BaseBuilder {
225
- #items = []; #delay = 1500
226
-
227
- static dispatchKeys = ['albumMessage']
228
- static shortcuts = {
229
- sendAlbumMessage: sock => (jid, items, quoted, opts = {}) => sock.sendMessage(jid, { albumMessage: items }, { ...q(quoted), ...opts }),
230
- }
231
-
232
- image(urlOrBuffer, caption = '') { this.#items.push({ image: typeof urlOrBuffer === 'string' ? { url: urlOrBuffer } : urlOrBuffer, caption }); return this }
233
- video(urlOrBuffer, caption = '') { this.#items.push({ video: typeof urlOrBuffer === 'string' ? { url: urlOrBuffer } : urlOrBuffer, caption }); return this }
234
- add(items) { items.forEach(item => this.#items.push(item)); return this }
235
- setDelay(ms) { this.#delay = ms; return this }
236
-
237
- async send(jid, opts = {}) {
238
- const items = this.data.albumMessage ? (Array.isArray(this.data.albumMessage) ? this.data.albumMessage : [this.data.albumMessage]) : this.#items
239
- if (items.length < 2) throw new Error('Album requires at least 2 items')
240
- const userJid = this.client.user?.id
241
- const album = await generateWAMessageFromContent(jid, { messageContextInfo: proto.MessageContextInfo.create({ messageSecret: crypto.randomBytes(32) }), albumMessage: proto.Message.AlbumMessage.create({ expectedImageCount: items.filter(a => a.image).length, expectedVideoCount: items.filter(a => a.video).length }) }, { userJid, messageId: generateMessageIDV2() })
242
- await this.client.relayMessage(jid, album.message, { messageId: album.key.id })
243
- for (const item of items) {
244
- const img = await generateWAMessage(jid, item, { upload: this.client.waUploadToServer, userJid })
245
- img.message.messageContextInfo = proto.MessageContextInfo.create({ messageSecret: crypto.randomBytes(32), messageAssociation: proto.MessageAssociation.create({ associationType: 1, parentMessageKey: album.key }) })
246
- await this.client.relayMessage(jid, img.message, { messageId: img.key.id })
247
- await delay(opts.albumDelay ?? this.#delay)
248
- }
249
- return album
250
- }
251
- }
252
-
253
- // ─── Poll ─────────────────────────────────────────────────────────────────────
254
- export class Poll extends BaseBuilder {
255
- #poll = { name: '', values: [], selectableOptionsCount: 1, toAnnouncementGroup: false, hideVoter: false }
256
-
257
- static shortcuts = {
258
- sendPoll: sock => (jid, name, values, multiSelect = false, opts = {}) => sock.sendMessage(jid, { poll: { name, values, selectableOptionsCount: multiSelect ? 0 : 1 } }, opts),
259
- }
260
-
261
- name(n) { this.#poll.name = n; return this }
262
- options(o) { this.#poll.values = o; return this }
263
- addOption(o) { this.#poll.values.push(o); return this }
264
- multiSelect(max = 0) { this.#poll.selectableOptionsCount = max; return this }
265
- quiz(ans) { this.#poll.pollType = 1; this.#poll.correctAnswer = ans; return this }
266
- setEndTime(t) { this.#poll.endTime = t; return this }
267
-
268
- async send(jid, opts = {}) {
269
- if (!this.#poll.name) throw new Error('Poll name is required')
270
- if (this.#poll.values.length < 2) throw new Error('Poll requires at least 2 options')
271
- return this.client.sendMessage(jid, { poll: this.#poll }, opts)
272
- }
273
- }
274
-
275
- // ─── Payment ──────────────────────────────────────────────────────────────────
276
- export class Payment extends BaseBuilder {
277
- static dispatchKeys = ['requestPaymentMessage']
278
- static shortcuts = {
279
- sendPaymentMessage: sock => (jid, data, quoted) => new Payment(sock).from(data).send(jid, q(quoted)),
280
- }
281
-
282
- setAmount(a) { this.data.amount = a; return this }
283
- setCurrency(c) { this.data.currency = c; return this }
284
- setExpiry(t) { this.data.expiry = t; return this }
285
- setNote(n) { this.data.note = n; return this }
286
- setFrom(j) { this.data.from = j; return this }
287
- setBackground(b) { this.data.background = b; return this }
288
-
289
- async send(jid, opts = {}) {
290
- const d = this.data
291
- const currency = d.currency ?? 'NGN'
292
- const amount = d.amount ?? 0
293
- const ctx = opts.quoted ? { stanzaId: opts.quoted.key?.id, participant: opts.quoted.key?.participant, quotedMessage: opts.quoted.message } : {}
294
- const notes = d.note ? { extendedTextMessage: { text: d.note, contextInfo: ctx } } : {}
295
- const msg = await generateWAMessageFromContent(jid, { requestPaymentMessage: proto.Message.RequestPaymentMessage.fromObject({ expiryTimestamp: d.expiry ?? 0, amount1000: amount, currencyCodeIso4217: currency, requestFrom: d.from ?? '0@s.whatsapp.net', noteMessage: notes, amount: proto.Money.create({ value: amount, offset: 1000, currencyCode: currency }), ...(d.background ? { background: proto.PaymentBackground.create({ id: d.background.id ?? 'DEFAULT', placeholderArgb: d.background.placeholderArgb ?? 0xfff0f0f0, textArgb: d.background.textArgb ?? 0, subtextArgb: d.background.subtextArgb ?? 0, type: proto.PaymentBackground.Type.DEFAULT }) } : {}) }) }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
296
- const bizNode = getBizBinaryNode(msg.message)
297
- await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
298
- return msg
299
- }
300
- }
301
-
302
- // ─── Order ────────────────────────────────────────────────────────────────────
303
- export class Order extends BaseBuilder {
304
- static dispatchKeys = ['orderMessage']
305
- static shortcuts = {
306
- sendOrderMessage: sock => (jid, data, quoted) => new Order(sock).from(data).send(jid, q(quoted)),
307
- }
308
-
309
- async send(jid, opts = {}) {
310
- const o = this.data
311
- const userJid = this.client.user?.id
312
- let thumb = null
313
- if (o.thumbnail) {
314
- thumb = await normalizeToBuffer(o.thumbnail).catch(() => undefined)
315
- }
316
- const cleanJid = id => { if (!id) return null; const [user] = id.split(':'); return user.includes('@') ? user : `${user}@s.whatsapp.net` }
317
- const seller = cleanJid(o.sellerJid) ?? cleanJid(userJid) ?? cleanJid(jid) ?? '0@s.whatsapp.net'
318
- const msg = await generateWAMessageFromContent(jid, { orderMessage: proto.Message.OrderMessage.create({ orderId: o.orderId ?? `zervonex${Date.now()}`, thumbnail: thumb, itemCount: o.itemCount ?? 0, status: o.status ?? proto.Message.OrderMessage.OrderStatus.INQUIRY, surface: o.surface ?? proto.Message.OrderMessage.OrderSurface.CATALOG, message: o.message, orderTitle: o.orderTitle, sellerJid: seller, token: o.token ?? 'zervonex_TOKEN', totalAmount1000: o.totalAmount1000 ?? 0, totalCurrencyCode: o.totalCurrencyCode ?? 'NGN', messageVersion: o.messageVersion ?? 2, ...(o.catalogType ? { catalogType: o.catalogType } : {}), ...(o.contextInfo ? { contextInfo: o.contextInfo } : {}) }) }, { userJid, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer })
319
- const bizNode = getBizBinaryNode(msg.message)
320
- await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
321
- return msg
322
- }
323
- }
324
-
325
- // ─── Event ────────────────────────────────────────────────────────────────────
326
- export class Event extends BaseBuilder {
327
- static dispatchKeys = ['eventMessage']
328
- static shortcuts = { sendEventMessage: sock => (jid, data, quoted) => new Event(sock).from(data).send(jid, q(quoted)) }
329
-
330
- setName(n) { this.data.name = n; return this }
331
- setDescription(d) { this.data.description = d; return this }
332
- setLocation(l) { this.data.location = l; return this }
333
- setJoinLink(l) { this.data.joinLink = l; return this }
334
- setStartTime(t) { this.data.startDate = t instanceof Date ? t : new Date(t); return this }
335
- setEndTime(t) { this.data.endDate = t instanceof Date ? t : new Date(t); return this }
336
- setCanceled(v = true) { this.data.isCanceled = v; return this }
337
- setReminder(sec) { this.data.hasReminder = true; this.data.reminderOffsetSec = sec; return this }
338
- setScheduledCall(v = true) { this.data.isScheduleCall = v; return this }
339
- setMessageSecret(s) { this.data.messageSecret = s; return this }
340
-
341
- async send(jid, opts = {}) {
342
- const e = this.data
343
- if (!e.name) throw new Error('Event name is required')
344
- const startDate = e.startDate instanceof Date ? e.startDate : new Date(e.startDate ?? Date.now())
345
- const endDate = e.endDate ? (e.endDate instanceof Date ? e.endDate : new Date(e.endDate)) : null
346
- const msg = await generateWAMessageFromContent(jid, { messageContextInfo: proto.MessageContextInfo.create({ messageSecret: e.messageSecret || crypto.randomBytes(32) }), eventMessage: proto.Message.EventMessage.create({ isCanceled: e.isCanceled ?? false, name: e.name, description: e.description ?? '', location: e.location ?? { degreesLatitude: 0, degreesLongitude: 0, name: 'Location' }, joinLink: e.joinLink ?? '', startTime: Math.floor(startDate.getTime() / 1000), endTime: endDate ? Math.floor(endDate.getTime() / 1000) : undefined, extraGuestsAllowed: e.extraGuestsAllowed !== false, isScheduleCall: e.isScheduleCall ?? false, hasReminder: e.hasReminder ?? false, reminderOffsetSec: e.reminderOffsetSec ?? 0 }) }, { userJid: this.client.user?.id, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer })
347
- const bizNode = getBizBinaryNode(msg.message)
348
- await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: [{ tag: 'meta', attrs: { event_type: 'creation' } }, ...(bizNode ? [bizNode] : [])] })
349
- return msg
350
- }
351
- }
352
-
353
- // ─── StickerPack ──────────────────────────────────────────────────────────────
354
- export class StickerPack extends BaseBuilder {
355
- static dispatchKeys = ['stickerPack', 'stickerPackMessage']
356
- static shortcuts = {
357
- stickerPackMessage: sock => (jid, data, opts = {}) => new StickerPack(sock).from(data, { name: opts.packName, publisher: opts.packPublisher }).send(jid, q(opts.quoted)),
358
- }
359
-
360
- setStickers(s) { this.data.stickers = s; return this }
361
-
362
- async send(jid, opts = {}) {
363
- const userJid = this.client.user?.id
364
- const { quoted, ...passOpts } = opts
365
- const result = await prepareStickerPackMessage(this.data, { upload: this.client.waUploadToServer, logger: this.client.logger, ...passOpts })
366
- if (result.isBatched) {
367
- let last
368
- for (let i = 0; i < result.stickerPackMessage.length; i++) {
369
- const msg = await generateWAMessageFromContent(jid, { stickerPackMessage: result.stickerPackMessage[i] }, { userJid, quoted, waUploadToServer: this.client.waUploadToServer })
370
- await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id })
371
- last = msg
372
- if (i < result.stickerPackMessage.length - 1) await delay(2000)
373
- }
374
- return last
375
- }
376
- const msg = await generateWAMessageFromContent(jid, { stickerPackMessage: result.stickerPackMessage }, { userJid, quoted, waUploadToServer: this.client.waUploadToServer })
377
- await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id })
378
- return msg
379
- }
380
- }
381
- // ─── VerticalAlbum ────────────────────────────────────────────────────────────
382
- export class VerticalAlbum extends BaseBuilder {
383
- static dispatchKeys = ['verticalAlbumMessage']
384
- static shortcuts = {
385
- sendVerticalAlbumMessage: sock => (jid, data, opts = {}) => new VerticalAlbum(sock).from(data, opts).send(jid, opts)
386
- }
387
-
388
- async send(jid, opts = {}) {
389
- const items = this.data.items ?? (Array.isArray(this.data.verticalAlbumMessage) ? this.data.verticalAlbumMessage : [])
390
- if (!Array.isArray(items) || items.length < 2) throw new Error('VerticalAlbum requires at least 2 items')
391
- const expiration = String(Date.now() + 30 * 24 * 60 * 60 * 1000)
392
- const primitives = items.map((item, i) => {
393
- const kind = item?.type || (item?.video ? 'video' : 'image')
394
- if (kind === 'video') {
395
- const v = item.video || item.data || item
396
- const url = typeof v === 'string' ? v : (v?.url ?? v?.videoUrl ?? '')
397
- if (!url) throw new Error(`VerticalAlbum item ${i}: video requires a URL`)
398
- return { media: { url, mime_type: v?.mimeType ?? v?.mime_type ?? 'video/mp4', file_length: v?.fileLength ?? v?.file_length ?? 0, duration: v?.duration ?? 0 }, imagine_type: 'ANIMATE', status: { status: 'READY' }, __typename: 'GenAIImaginePrimitive', ...(v?.thumbnail ? { thumbnail: { raw_media: v.thumbnail } } : {}) }
399
- }
400
- const img = item?.image || item?.data || item
401
- const url = typeof img === 'string' ? img : (img?.imageHighResUrl ?? img?.highResUrl ?? img?.fullUrl ?? img?.imagePreviewUrl ?? img?.previewUrl ?? img?.url ?? '')
402
- if (!url) throw new Error(`VerticalAlbum item ${i}: image requires a URL`)
403
- const w = Number(img?.width ?? 600), h = Number(img?.height ?? 400)
404
- const media = (u, mw, mh) => ({ url: u, url_fallback: u, mime_type: img?.mimeType ?? img?.mime_type ?? 'image/png', expiration_timestamp_ms: expiration, width: mw, height: mh })
405
- return { preview_image: media(url, w, h), full_image: media(img?.highResUrl ?? url, w, h), dark_mode_preview_image: media(img?.darkModePreviewUrl ?? url, w, h), dark_mode_full_image: media(img?.darkModeHighResUrl ?? url, w, h), asset_query_status: 'FETCHED', display_mode: 'FULL_WIDTH', full_width: true, __typename: 'GenAIImagePrimitive' }
406
- })
407
- const unified = { response_id: crypto.randomUUID(), sections: [{ view_model: { primitives, display_mode: 'FULL_WIDTH', full_width: true, __typename: 'GenAIVStackLayoutViewModel' } }] }
408
- const msg = await generateWAMessageFromContent(jid, {
409
- messageContextInfo: { botMetadata: { pluginMetadata: {}, botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA } },
410
- botForwardedMessage: { message: { richResponseMessage: proto.Message.AIRichResponseMessage?.create?.({ messageType: 1, submessages: [], unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) }, contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 } }) ?? { messageType: 1, submessages: [], unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) }, contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 } } } }
411
- }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
412
- const bizNode = getBizBinaryNode(msg.message)
413
- const relayFn = this.client.relayRichMessage ?? this.client.relayMessage
414
- await relayFn(jid, msg, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
415
- return msg
416
- }
417
- }
418
-
419
- // ─── GridImage ────────────────────────────────────────────────────────────────
420
- export class GridImage extends BaseBuilder {
421
- static dispatchKeys = ['gridImageMessage']
422
- static shortcuts = {
423
- sendGridImageMessage: sock => (jid, data, opts = {}) => new GridImage(sock).from(data, opts).send(jid, opts)
424
- }
425
-
426
- async send(jid, opts = {}) {
427
- const imageUrls = this.data.imageUrls ?? this.data.images ?? (Array.isArray(this.data.gridImageMessage) ? this.data.gridImageMessage : [])
428
- if (!Array.isArray(imageUrls) || imageUrls.length < 2) throw new Error('GridImage requires at least 2 images')
429
- const expiration = String(Date.now() + 30 * 24 * 60 * 60 * 1000)
430
- // GRID_IMAGE submessage type (6) — proper protocol path, not just unified sections
431
- const submessages = [{ messageType: 6, gridImageMetadata: { imageUrls } }]
432
- const sections = imageUrls.map(img => {
433
- const image = typeof img === 'string' ? { url: img } : img
434
- const url = image.imageHighResUrl ?? image.highResUrl ?? image.fullUrl ?? image.imagePreviewUrl ?? image.previewUrl ?? image.url ?? ''
435
- const w = Number(image.width ?? 600), h = Number(image.height ?? 400)
436
- const media = (u, mw, mh) => ({ url: u, url_fallback: u, mime_type: image.mimeType ?? image.mime_type ?? 'image/png', expiration_timestamp_ms: expiration, width: mw, height: mh })
437
- return { preview_image: media(url, w, h), full_image: media(image.highResUrl ?? url, w, h), dark_mode_preview_image: media(image.darkModePreviewUrl ?? url, w, h), dark_mode_full_image: media(image.darkModeHighResUrl ?? url, w, h), asset_query_status: 'FETCHED', __typename: 'GenAIImagePrimitive' }
438
- })
439
- const unified = { response_id: crypto.randomUUID(), sections: [{ view_model: { primitives: sections, __typename: 'GenAIGridLayoutViewModel' } }] }
440
- const msg = await generateWAMessageFromContent(jid, {
441
- messageContextInfo: { botMetadata: { pluginMetadata: {}, botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA } },
442
- botForwardedMessage: { message: { richResponseMessage: { messageType: 1, submessages, unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) }, contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 } } } }
443
- }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
444
- const bizNode = getBizBinaryNode(msg.message)
445
- const relayFn = this.client.relayRichMessage ?? this.client.relayMessage
446
- await relayFn(jid, msg, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
447
- return msg
448
- }
449
- }
450
-
451
- // ─── VideoGrid ────────────────────────────────────────────────────────────────
452
- export class VideoGrid extends BaseBuilder {
453
- static dispatchKeys = ['videoGridMessage']
454
- static shortcuts = {
455
- sendVideoGridMessage: sock => (jid, data, opts = {}) => new VideoGrid(sock).from(data, opts).send(jid, opts)
456
- }
457
-
458
- async send(jid, opts = {}) {
459
- const videos = this.data.videos ?? (Array.isArray(this.data.videoGridMessage) ? this.data.videoGridMessage : [])
460
- if (!Array.isArray(videos) || videos.length < 2) throw new Error('VideoGrid requires at least 2 videos')
461
- const primitives = videos.map((v, i) => {
462
- const url = typeof v === 'string' ? v : (v?.url ?? v?.videoUrl ?? v?.reelsUrl ?? '')
463
- if (!url) throw new Error(`VideoGrid item ${i}: requires a URL`)
464
- const item = typeof v === 'string' ? {} : v
465
- return { post_id: item.postId != null ? String(item.postId) : undefined, reels_url: url, reels_title: item.title, thumbnail_url: item.thumbnailUrl ?? item.thumbnail, creator: item.creator, avatar_url: item.avatarUrl, content_hash: item.contentHash, likes_count: item.likes, comments_count: item.comments, shares_count: item.shares, is_verified: item.isVerified, source_app: item.sourceApp, video_delivery_response: { progressive_urls: (item.progressiveUrls ?? []).map(u => ({ progressive_url: u, __typename: 'GenAIProgressiveUrlResponse' })), dash_manifests: (item.dashManifests ?? []).map(m => ({ manifest_xml: m, __typename: 'GenAIDashManifestResponse' })), __typename: 'GenAIVideoDeliveryResponse' }, __typename: 'GenAIVideoPrimitive' }
466
- })
467
- const unified = { response_id: crypto.randomUUID(), sections: [{ view_model: { primitives, __typename: 'GenAIGridLayoutViewModel' } }] }
468
- const msg = await generateWAMessageFromContent(jid, {
469
- messageContextInfo: { botMetadata: { pluginMetadata: {}, botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA } },
470
- botForwardedMessage: { message: { richResponseMessage: { messageType: 1, submessages: [], unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) }, contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 } } } }
471
- }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
472
- const bizNode = getBizBinaryNode(msg.message)
473
- const relayFn = this.client.relayRichMessage ?? this.client.relayMessage
474
- await relayFn(jid, msg, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
475
- return msg
476
- }
477
- }
478
-
479
- // ─── A2UI ─────────────────────────────────────────────────────────────────────
480
- export class A2UI extends BaseBuilder {
481
- static VERSION = 'v0.9'
482
- static get CATALOG() { return `https://a2ui.org/specification/${this.VERSION}/catalogs/basic/catalog.json` }
483
- static dispatchKeys = ['a2uiMessage']
484
- static shortcuts = {
485
- sendA2UIMessage: sock => (jid, data, opts = {}) => new A2UI(sock).from(data, opts).send(jid, opts),
486
- sendA2UICommandMenu: sock => (jid, data, opts = {}) => new A2UI(sock).from(data, { __commandMenu: true, ...opts }).send(jid, opts),
487
- sendA2UI: sock => (jid, components, opts = {}) => new A2UI(sock).addComponents(components).send(jid, opts)
488
- }
489
- static #v = { imgVariant: ['icon', 'avatar', 'smallFeature', 'mediumFeature', 'largeFeature', 'header'], imgFit: ['contain', 'cover', 'fill', 'none', 'scaleDown'], textVariant: ['h1', 'h2', 'h3', 'h4', 'h5', 'caption', 'body'], btnVariant: ['default', 'primary', 'borderless'], colJustify: ['start', 'center', 'end', 'spaceBetween', 'spaceAround', 'spaceEvenly', 'stretch'], rowJustify: ['center', 'end', 'spaceAround', 'spaceBetween', 'spaceEvenly', 'start', 'stretch'], align: ['start', 'center', 'end', 'stretch'], listDir: ['vertical', 'horizontal'], tfVariant: ['longText', 'number', 'shortText', 'obscured'], cpVariant: ['mutuallyExclusive', 'multipleSelection'], cpDisplay: ['checkbox', 'chips'], divAxis: ['horizontal', 'vertical'], icons: ['accountCircle', 'add', 'arrowBack', 'arrowForward', 'attachFile', 'calendarToday', 'call', 'camera', 'check', 'close', 'delete', 'download', 'edit', 'event', 'error', 'fastForward', 'favorite', 'favoriteOff', 'folder', 'help', 'home', 'info', 'locationOn', 'lock', 'lockOpen', 'mail', 'menu', 'moreVert', 'moreHoriz', 'notificationsOff', 'notifications', 'pause', 'payment', 'person', 'phone', 'photo', 'play', 'print', 'refresh', 'rewind', 'search', 'send', 'settings', 'share', 'shoppingCart', 'skipNext', 'skipPrevious', 'star', 'starHalf', 'starOff', 'stop', 'upload', 'visibility', 'visibilityOff', 'volumeDown', 'volumeMute', 'volumeOff', 'volumeUp', 'warning'] }
490
- static #pick(val, list, def) { return list.includes(val) ? val : def }
491
- static #id(id, name) { if (!id) throw new TypeError(`${name} requires an id`); return id }
492
- static text(id, text, { variant = 'body' } = {}) { return { id: A2UI.#id(id, 'text'), component: 'Text', text: String(text), variant: A2UI.#pick(variant, A2UI.#v.textVariant, 'body') } }
493
- static image(id, input, { variant = 'mediumFeature', fit = 'fill' } = {}) { if (!input) throw new TypeError('image requires a url, buffer, or file path'); return { id: A2UI.#id(id, 'image'), component: 'Image', url: '', _raw: input, variant: A2UI.#pick(variant, A2UI.#v.imgVariant, 'mediumFeature'), fit: A2UI.#pick(fit, A2UI.#v.imgFit, 'fill') } }
494
- static icon(id, name) { if (!name) throw new TypeError('icon requires a name'); if (typeof name === 'string' && !A2UI.#v.icons.includes(name)) throw new TypeError(`invalid icon: ${name}`); return { id: A2UI.#id(id, 'icon'), component: 'Icon', name } }
495
- static video(id, url) { if (!url) throw new TypeError('video requires a url'); return { id: A2UI.#id(id, 'video'), component: 'Video', url: String(url) } }
496
- static audio(id, url, { description = '' } = {}) { if (!url) throw new TypeError('audio requires a url'); return { id: A2UI.#id(id, 'audio'), component: 'AudioPlayer', url: String(url), ...(description ? { description: String(description) } : {}) } }
497
- static column(id, children = [], { justify = 'start', align = 'stretch' } = {}) { if (!children.length) throw new TypeError('column requires at least one child'); return { id: A2UI.#id(id, 'column'), component: 'Column', children: children.map(String), justify: A2UI.#pick(justify, A2UI.#v.colJustify, 'start'), align: A2UI.#pick(align, A2UI.#v.align, 'stretch') } }
498
- static row(id, children = [], { justify = 'start', align = 'stretch' } = {}) { if (!children.length) throw new TypeError('row requires at least one child'); return { id: A2UI.#id(id, 'row'), component: 'Row', children: children.map(String), justify: A2UI.#pick(justify, A2UI.#v.rowJustify, 'start'), align: A2UI.#pick(align, A2UI.#v.align, 'stretch') } }
499
- static list(id, children = [], { direction = 'vertical', align = 'stretch' } = {}) { if (!children.length) throw new TypeError('list requires at least one child'); return { id: A2UI.#id(id, 'list'), component: 'List', children: children.map(String), direction: A2UI.#pick(direction, A2UI.#v.listDir, 'vertical'), align: A2UI.#pick(align, A2UI.#v.align, 'stretch') } }
500
- static card(id, child) { if (!child) throw new TypeError('card requires a child id'); return { id: A2UI.#id(id, 'card'), component: 'Card', child: String(child) } }
501
- static tabs(id, tabs = []) { if (!tabs.length) throw new TypeError('tabs requires at least one tab'); return { id: A2UI.#id(id, 'tabs'), component: 'Tabs', tabs: tabs.map((t, i) => ({ title: String(t.title ?? t.label ?? `Tab ${i + 1}`), child: String(t.child) })) } }
502
- static modal(id, trigger, content) { if (!trigger) throw new TypeError('modal requires a trigger id'); if (!content) throw new TypeError('modal requires a content id'); return { id: A2UI.#id(id, 'modal'), component: 'Modal', trigger: String(trigger), content: String(content) } }
503
- static divider(id, { axis = 'horizontal' } = {}) { return { id: A2UI.#id(id, 'divider'), component: 'Divider', axis: A2UI.#pick(axis, A2UI.#v.divAxis, 'horizontal') } }
504
- static button(id, child, action, { variant = 'default' } = {}) { if (!child) throw new TypeError('button requires a child id'); if (!action) throw new TypeError('button requires an action'); return { id: A2UI.#id(id, 'button'), component: 'Button', child: String(child), action, variant: A2UI.#pick(variant, A2UI.#v.btnVariant, 'default') } }
505
- static textField(id, label, { value = '', variant = 'shortText', validationRegexp = '' } = {}) { if (!label) throw new TypeError('textField requires a label'); return { id: A2UI.#id(id, 'textField'), component: 'TextField', label: String(label), value: String(value), variant: A2UI.#pick(variant, A2UI.#v.tfVariant, 'shortText'), ...(validationRegexp ? { validationRegexp: String(validationRegexp) } : {}) } }
506
- static checkBox(id, label, value = false) { if (!label) throw new TypeError('checkBox requires a label'); return { id: A2UI.#id(id, 'checkBox'), component: 'CheckBox', label: String(label), value: Boolean(value) } }
507
- static choicePicker(id, options = [], value = [], { label = '', variant = 'mutuallyExclusive', displayStyle = 'checkbox', filterable = false } = {}) { if (!options.length) throw new TypeError('choicePicker requires at least one option'); return { id: A2UI.#id(id, 'choicePicker'), component: 'ChoicePicker', options: options.map(o => typeof o === 'string' ? { label: o, value: o } : { label: String(o.label), value: String(o.value) }), value: (Array.isArray(value) ? value : [value]).map(String), ...(label ? { label: String(label) } : {}), variant: A2UI.#pick(variant, A2UI.#v.cpVariant, 'mutuallyExclusive'), displayStyle: A2UI.#pick(displayStyle, A2UI.#v.cpDisplay, 'checkbox'), filterable: Boolean(filterable) } }
508
- static slider(id, value, max, { label = '', min = 0 } = {}) { if (max == null) throw new TypeError('slider requires a max'); return { id: A2UI.#id(id, 'slider'), component: 'Slider', value: Number(value), max: Number(max), min: Number(min), ...(label ? { label: String(label) } : {}) } }
509
- static dateTimeInput(id, value = '', { label = '', enableDate = false, enableTime = false, min = '', max = '' } = {}) { return { id: A2UI.#id(id, 'dateTimeInput'), component: 'DateTimeInput', value: String(value), enableDate: Boolean(enableDate), enableTime: Boolean(enableTime), ...(label ? { label: String(label) } : {}), ...(min ? { min: String(min) } : {}), ...(max ? { max: String(max) } : {}) } }
510
- static surface(components, { surfaceId, catalogId = A2UI.CATALOG, version = A2UI.VERSION } = {}) { const id = surfaceId ?? `zervonex-a2ui-${crypto.randomUUID()}`; return Buffer.from(JSON.stringify({ version, createSurface: { surfaceId: id, catalogId, sendDataModel: false, components } }), 'utf8') }
511
- static async #resolveImage(input) { return { url: await resolveToMediaUrl(input) } }
512
- #components = []; #buttons = []; #surfaceId = `zervonex-a2ui-${crypto.randomUUID()}`; #fallback = ''; #imageMessage = null
513
- async #resolveComponents() { return Promise.all(this.#components.map(async c => { if (c.component !== 'Image' || !c._raw) return c; const { _raw, ...rest } = c; try { return { ...rest, url: await resolveToMediaUrl(_raw) } } catch { return { ...rest, url: '' } } })) }
514
- async #buildHeader(upload) {
515
- if (!this.#imageMessage) return { header: { hasMediaAttachment: false } }
516
- const input = this.#imageMessage
517
- if (Buffer.isBuffer(input)) { const p = await prepareWAMessageMedia({ image: input }, { upload }); return { header: { ...p, hasMediaAttachment: true } } }
518
- if (input?.image) { const p = await prepareWAMessageMedia({ image: input.image }, { upload }); return { header: { ...p, hasMediaAttachment: true } } }
519
- const url = input?.url ?? (typeof input === 'string' ? input : null)
520
- if (url) return { header: { imageMessage: { url }, hasMediaAttachment: true } }
521
- return { header: { hasMediaAttachment: false } }
522
- }
523
- addComponent(obj) { if (!obj?.id) throw new TypeError('addComponent requires an object with an id'); this.#components.push(obj); return this }
524
- addComponents(arr) { if (!Array.isArray(arr)) throw new TypeError('addComponents requires an array'); for (const c of arr) this.addComponent(c); return this }
525
- addText(id, text, opts = {}) { return this.addComponent(A2UI.text(id, text, opts)) }
526
- addImage(id, input, opts = {}) { return this.addComponent(A2UI.image(id, input, opts)) }
527
- addIcon(id, name) { return this.addComponent(A2UI.icon(id, name)) }
528
- addVideo(id, url) { return this.addComponent(A2UI.video(id, url)) }
529
- addAudio(id, url, opts = {}) { return this.addComponent(A2UI.audio(id, url, opts)) }
530
- addColumn(id, children = [], opts = {}) { return this.addComponent(A2UI.column(id, children, opts)) }
531
- addRow(id, children = [], opts = {}) { return this.addComponent(A2UI.row(id, children, opts)) }
532
- addList(id, children = [], opts = {}) { return this.addComponent(A2UI.list(id, children, opts)) }
533
- addCard(id, child) { return this.addComponent(A2UI.card(id, child)) }
534
- addTabs(id, tabs = []) { return this.addComponent(A2UI.tabs(id, tabs)) }
535
- addModal(id, trigger, content) { return this.addComponent(A2UI.modal(id, trigger, content)) }
536
- addDivider(id, opts = {}) { return this.addComponent(A2UI.divider(id, opts)) }
537
- addButtonComponent(id, child, action, opts = {}) { return this.addComponent(A2UI.button(id, child, action, opts)) }
538
- addTextField(id, label, opts = {}) { return this.addComponent(A2UI.textField(id, label, opts)) }
539
- addCheckBox(id, label, value = false) { return this.addComponent(A2UI.checkBox(id, label, value)) }
540
- addChoicePicker(id, options, value, opts = {}) { return this.addComponent(A2UI.choicePicker(id, options, value, opts)) }
541
- addSlider(id, value, max, opts = {}) { return this.addComponent(A2UI.slider(id, value, max, opts)) }
542
- addDateTimeInput(id, value, opts = {}) { return this.addComponent(A2UI.dateTimeInput(id, value, opts)) }
543
- addButton(nameOrShorthand, params = {}) {
544
- if (!nameOrShorthand) throw new TypeError('addButton requires a name or shorthand object')
545
- if (typeof nameOrShorthand === 'object') { const [r] = resolveNativeFlowButtons([nameOrShorthand]); this.#buttons.push(r) }
546
- else this.#buttons.push({ name: nameOrShorthand, buttonParamsJson: typeof params === 'string' ? params : JSON.stringify(params) })
547
- return this
548
- }
549
- setFallback(text) { this.#fallback = String(text); return this }
550
- setSurfaceId(id) { this.#surfaceId = String(id); return this }
551
- setImage(input) { if (!input) throw new TypeError('setImage requires a url, buffer, or file path'); this.#imageMessage = input; return this }
552
- async send(jid, opts = {}) {
553
- const d = this.data
554
- if (d.components?.length) { this.addComponents(d.components); if (d.buttons?.length) for (const b of d.buttons) this.#buttons.push(b) }
555
- const upload = this.client.waUploadToServer
556
- if (this.#components.length) {
557
- if (!this.#components.some(c => c.id === 'root')) throw new Error('A2UI components must include one with id "root"')
558
- const [components, { header }] = await Promise.all([this.#resolveComponents(), this.#buildHeader(upload)])
559
- const buttons = [...this.#buttons, ...(opts.buttons ?? [])]
560
- const content = { interactiveMessage: { header, body: { text: d.body ?? d.text ?? '\u200b' }, bloksWidget: { uuid: this.#surfaceId, type: 'im_a2ui', data: A2UI.surface(components, { surfaceId: this.#surfaceId }), fallback: this.#fallback }, ...(buttons.length ? { nativeFlowMessage: { messageParamsJson: JSON.stringify(opts.nativeFlowParams ?? {}), buttons, messageVersion: 1 } } : {}) } }
561
- const msg = await generateWAMessageFromContent(jid, content, { userJid: this.client.user?.id, waUploadToServer: upload })
562
- const bizNode = getBizBinaryNode(msg.message)
563
- await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
564
- return msg
565
- }
566
- let content
567
- if (d.__commandMenu) {
568
- const rows = (d.rows ?? []).map((r, i) => ({ title: String(r?.[0] ?? r?.title ?? `Command ${i + 1}`), description: String(r?.[1] ?? r?.description ?? ''), id: String(r?.[2] ?? r?.id ?? r?.[0] ?? `command_${i + 1}`) }))
569
- const buttons = (d.buttons ?? []).map((b, i) => ({ id: `a2ui_button_${i + 1}`, label: String(b?.text ?? b?.label ?? `Button ${i + 1}`), url: String(b?.url ?? '') }))
570
- const components = [{ id: 'root', component: 'Column', align: 'center', children: ['title', 'divider', 'tableCard', 'footer', ...(buttons.length ? ['buttonRow'] : [])] }, { id: 'title', component: 'Text', text: String(d.title ?? 'Menu'), variant: 'h2' }, { id: 'divider', component: 'Divider' }, { id: 'tableCard', component: 'Card', child: 'tableColumn' }, { id: 'tableColumn', component: 'Column', children: ['headerRow', ...rows.flatMap((_, i) => [`divider_${i}`, `row_${i}`])] }, { id: 'headerRow', component: 'Row', children: ['headerCommand', 'headerFunction'] }, { id: 'headerCommand', component: 'Text', text: 'Command', variant: 'h5' }, { id: 'headerFunction', component: 'Text', text: 'Function', variant: 'h5' }, ...rows.flatMap((r, i) => [{ id: `divider_${i}`, component: 'Divider' }, { id: `row_${i}`, component: 'Row', children: [`command_${i}`, `description_${i}`] }, { id: `command_${i}`, component: 'Text', text: r.title }, { id: `description_${i}`, component: 'Text', text: r.description }]), { id: 'footer', component: 'Text', text: String(d.footer ?? 'Powered by zervonex'), variant: 'caption' }]
571
- if (buttons.length) { components.push({ id: 'buttonRow', component: 'Row', justify: 'spaceEvenly', children: buttons.flatMap((_, i) => [`buttonLabel_${i}`, `button_${i}`]) }); buttons.forEach((b, i) => { components.push({ id: `buttonLabel_${i}`, component: 'Text', text: b.label }); components.push({ id: `button_${i}`, component: 'Button', child: `buttonLabel_${i}`, variant: 'primary', action: { call: 'openUrl', args: { url: b.url } } }) }) }
572
- const surfaceId = `zervonex-a2ui-${crypto.randomUUID()}`
573
- let cmdHeader = { hasMediaAttachment: false }
574
- if (d.imageMessage) cmdHeader = { imageMessage: d.imageMessage, hasMediaAttachment: true }
575
- else if (d.image) { const { url } = await A2UI.#resolveImage(d.image); cmdHeader = { imageMessage: { url }, hasMediaAttachment: true } }
576
- content = { interactiveMessage: { header: cmdHeader, body: { text: d.body ?? d.text ?? '\u200b' }, bloksWidget: { uuid: surfaceId, type: 'im_a2ui', data: A2UI.surface(components, { surfaceId }), fallback: String(d.fallback ?? d.title ?? '') }, nativeFlowMessage: { messageParamsJson: JSON.stringify({ limited_time_offer: { text: String(d.title ?? ''), url: buttons[0]?.url ?? '', copy_code: String(d.title ?? ''), expiration_time: Date.now() * 1000 } }), buttons: [{ name: 'single_select', buttonParamsJson: JSON.stringify({ title: String(d.title ?? ''), sections: [{ title: 'Available Commands', rows }] }) }], messageVersion: 1 } } }
577
- } else {
578
- const { imageMessage, image, bloksWidget = {}, nativeFlowMessage, fallback = '', ...rest } = d
579
- let elseHeader = { hasMediaAttachment: false }
580
- if (imageMessage) elseHeader = { imageMessage, hasMediaAttachment: true }
581
- else if (image) { const { url } = await A2UI.#resolveImage(image); elseHeader = { imageMessage: { url }, hasMediaAttachment: true } }
582
- content = { interactiveMessage: { ...rest, header: elseHeader, body: { text: d.body ?? d.text ?? '\u200b' }, bloksWidget: { uuid: bloksWidget.uuid ?? crypto.randomUUID(), type: bloksWidget.type ?? 'im_a2ui', data: Buffer.isBuffer(bloksWidget.data) ? bloksWidget.data : Buffer.from(typeof bloksWidget.data === 'string' ? bloksWidget.data : JSON.stringify(bloksWidget.data ?? {}), 'utf8'), ...(bloksWidget.fallback || fallback ? { fallback: String(bloksWidget.fallback ?? fallback) } : {}) }, ...(nativeFlowMessage ? { nativeFlowMessage: { ...nativeFlowMessage, messageVersion: nativeFlowMessage.messageVersion ?? 1 } } : {}) } }
583
- }
584
- const msg = await generateWAMessageFromContent(jid, content, { userJid: this.client.user?.id, waUploadToServer: upload })
585
- const bizNode = getBizBinaryNode(msg.message)
586
- await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
587
- return msg
588
- }
1
+ import crypto from 'crypto'
2
+ import { proto } from '../../WAProto/index.js'
3
+ import { BOT_RENDERING_CONFIG_METADATA } from '../Defaults/index.js'
4
+ import { generateWAMessage, generateWAMessageFromContent, normalizeToBuffer, generateMessageIDV2, prepareStickerPackMessage, prepareWAMessageMedia, resolveNativeFlowButtons, extractImageThumb, resolveToMediaUrl } from '../Utils/index.js'
5
+ import { getBizBinaryNode } from '../WABinary/index.js'
6
+ import { BaseBuilder, norm, q } from './base.js'
7
+
8
+ const delay = ms => new Promise(r => setTimeout(r, ms))
9
+
10
+ // ─── Button ───────────────────────────────────────────────────────────────────
11
+ export class Button {
12
+ #client; #buttons = []; #header = {}; #body = ''; #footer = ''
13
+ #title = ''; #subtitle = ''; #params = {}; #mode = 'native'
14
+
15
+ constructor(client, opts = {}) {
16
+ if (!client) throw new Error('Socket client is required')
17
+ this.#client = client
18
+ if (opts.mode) this.#mode = opts.mode
19
+ }
20
+
21
+ setTitle(t) { this.#title = t; return this }
22
+ setSubtitle(s) { this.#subtitle = s; return this }
23
+ setBody(t) { this.#body = t; return this }
24
+ setFooter(t) { this.#footer = t; return this }
25
+ #resolveLocation(lat, lon, name, opts = {}) {
26
+ const o = (typeof lat === 'object' && lat !== null) ? lat : (typeof lat === 'string' && lon === undefined) ? { title: lat, ...opts } : { lat, lon, name, ...opts }
27
+ 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 } : {}), ...(o.thumbnail != null ? { _thumbnail: o.thumbnail } : {}) } }
28
+ }
29
+ 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 }
30
+ 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 }
31
+ setImage(url, opts = {}) { this.#header = { _headerType: proto.Message.ButtonsMessage.HeaderType.IMAGE, imageMessage: { url, ...opts } }; return this }
32
+ setVideo(url, opts = {}) { this.#header = { _headerType: proto.Message.ButtonsMessage.HeaderType.VIDEO, videoMessage: { url, ...opts } }; return this }
33
+ setDocument(url, fileName = 'file', opts = {}) { this.#header = { _headerType: proto.Message.ButtonsMessage.HeaderType.DOCUMENT, documentMessage: { url, fileName, ...opts } }; return this }
34
+ setText(text) { this.#header = { _headerType: proto.Message.ButtonsMessage.HeaderType.TEXT, text }; return this }
35
+ setParams(p) { this.#params = p; return this }
36
+ setLimitedTimeOffer(exp) { this.#params.limited_time_offer = { expiration_time_ms: exp }; return this }
37
+ setBottomSheet(opts = {}) { this.#params.bottom_sheet = opts; return this }
38
+ setTapTargetConfiguration(opts = {}) { this.#params.tap_target_configuration = opts; return this }
39
+ #addNative(name, params) { this.#mode = 'native'; this.#buttons.push({ name, buttonParamsJson: JSON.stringify(params) }); return this }
40
+ reply(text, id) { return this.#addNative('quick_reply', { display_text: text, id }) }
41
+ url(text, url, merchantUrl) { return this.#addNative('cta_url', { display_text: text, url, merchant_url: merchantUrl ?? url }) }
42
+ call(text, phone) { return this.#addNative('cta_call', { display_text: text, phone_number: phone }) }
43
+ copy(text, code) { return this.#addNative('cta_copy', { display_text: text, copy_code: code }) }
44
+ openWebview(text, url, opts = {}) { return this.#addNative('cta_open_webview', { display_text: text, url, ...opts }) }
45
+ catalog(text, opts = {}) { return this.#addNative('catalog', { display_text: text, ...opts }) }
46
+ flow(text, flowId, opts = {}) { return this.#addNative('flow', { display_text: text, flow_id: flowId, flow_token: opts.token ?? crypto.randomUUID(), ...opts }) }
47
+ remind(text, opts = {}) { return this.#addNative('cta_reminder', { display_text: text, ...opts }) }
48
+ cancelReminder(text, opts = {}) { return this.#addNative('cta_cancel_reminder', { display_text: text, ...opts }) }
49
+ address(text, opts = {}) { return this.#addNative('address', { display_text: text, ...opts }) }
50
+ sendLocation(text) { return this.#addNative('send_location', { display_text: text }) }
51
+ reviewAndPay(text, opts = {}) { return this.#addNative('review_and_pay', { display_text: text, ...opts }) }
52
+ reviewOrder(text, opts = {}) { return this.#addNative('review_order', { display_text: text, ...opts }) }
53
+ orderDetails(text, opts = {}) { return this.#addNative('order_details', { display_text: text, ...opts }) }
54
+ paymentStatus(text, opts = {}) { return this.#addNative('payment_status', { display_text: text, ...opts }) }
55
+ transactionDetails(text, opts = {}) { return this.#addNative('transaction_details', { display_text: text, ...opts }) }
56
+ select(title, sections) { return this.#addNative('single_select', { title, sections }) }
57
+
58
+ legacyButton(text, id) { this.#mode = 'legacy'; this.#buttons.push({ buttonId: id, buttonText: { displayText: text }, type: 1 }); return this }
59
+ templateReply(text, id) { this.#mode = 'template'; this.#buttons.push({ quickReplyButton: { displayText: text, id } }); return this }
60
+ templateUrl(text, url) { this.#mode = 'template'; this.#buttons.push({ urlButton: { displayText: text, url } }); return this }
61
+ templateCall(text, phone) { this.#mode = 'template'; this.#buttons.push({ callButton: { displayText: text, phoneNumber: phone } }); return this }
62
+
63
+ buttonsMessage(opts = {}) {
64
+ this.#mode = 'buttonsMessage'
65
+ if (opts.location) this.setLocationHeader(opts.location)
66
+ else if (opts.image) this.setImage(typeof opts.image === 'string' ? opts.image : opts.image.url, opts.image)
67
+ else if (opts.video) this.setVideo(typeof opts.video === 'string' ? opts.video : opts.video.url, opts.video)
68
+ else if (opts.document) this.setDocument(opts.document.url ?? opts.document, opts.document.fileName, opts.document)
69
+ else if (opts.text) this.setText(opts.text)
70
+ if (opts.body) this.#body = opts.body
71
+ if (opts.footer) this.#footer = opts.footer
72
+ if (opts.buttons?.length) {
73
+ const nfm = { buttons: opts.buttons }
74
+ proto.Message.InteractiveMessage.NativeFlowMessage.create({ buttons: resolveNativeFlowButtons(nfm.buttons), messageParamsJson: '' }).buttons
75
+ .forEach(b => { const p = JSON.parse(b.buttonParamsJson ?? '{}'); this.#buttons.push({ buttonId: p.id ?? p.display_text ?? b.name, buttonText: { displayText: p.display_text ?? p.title ?? '' }, type: b.name === 'single_select' ? 2 : 1, ...(b.name === 'single_select' ? { nativeFlowInfo: { name: 'single_select', paramsJson: b.buttonParamsJson } } : {}) }) })
76
+ }
77
+ return this
78
+ }
79
+
80
+ setBloksWidget(components) {
81
+ const flat = []
82
+ const resolve = c => { if (!c.__id) c.__id = `c_${flat.length}`; flat.push(c); if (c.children) c.children = c.children.map(ch => { resolve(ch); return ch.__id }); if (c.$ref) c.$ref = c.$ref.__id }
83
+ ; (Array.isArray(components) ? components : [components]).forEach(c => resolve(c))
84
+ this.#buttons = [{ name: 'galaxy_message', buttonParamsJson: JSON.stringify({ wa_flow_response_params: { title: this.#title }, components: flat }) }]
85
+ this.#mode = 'native'; return this
86
+ }
87
+
88
+ toCard() { return { header: this.#header, body: { text: this.#body }, footer: { text: this.#footer }, nativeFlowMessage: { buttons: this.#buttons } } }
89
+
90
+ #resolveButtonsMessageHeader() {
91
+ const { _headerType, locationMessage, imageMessage, videoMessage, documentMessage, text } = this.#header
92
+ const H = proto.Message.ButtonsMessage.HeaderType
93
+ if (locationMessage) return { headerType: _headerType ?? H.LOCATION, field: { locationMessage: { ...locationMessage } } }
94
+ if (imageMessage) return { headerType: _headerType ?? H.IMAGE, field: { imageMessage: { ...imageMessage } } }
95
+ if (videoMessage) return { headerType: _headerType ?? H.VIDEO, field: { videoMessage: { ...videoMessage } } }
96
+ if (documentMessage) return { headerType: _headerType ?? H.DOCUMENT, field: { documentMessage: { ...documentMessage } } }
97
+ if (text) return { headerType: _headerType ?? H.TEXT, field: { text } }
98
+ return { headerType: H.EMPTY, field: { contentText: this.#body } }
99
+ }
100
+
101
+ async #resolveThumbnail(field) {
102
+ const inner = Object.values(field)[0]
103
+ if (inner?._thumbnail) { inner.jpegThumbnail = (await extractImageThumb(inner._thumbnail, 300)).buffer; delete inner._thumbnail }
104
+ }
105
+
106
+ async #resolveHeader() {
107
+ const upload = this.#client.waUploadToServer
108
+ const [key, type] = Object.entries({ imageMessage: 'image', videoMessage: 'video', documentMessage: 'document' }).find(([k]) => this.#header[k]?._raw) ?? []
109
+ if (!key) return
110
+ const { _raw, ...rest } = this.#header[key]
111
+ const src = await normalizeToBuffer(_raw)
112
+ const p = await prepareWAMessageMedia({ [type]: src, ...(type === 'document' && { mimetype: rest.mimetype ?? 'application/octet-stream', fileName: rest.fileName ?? 'file' }) }, { upload })
113
+ this.#header = { _headerType: this.#header._headerType, [key]: { ...p[key], ...rest } }
114
+ }
115
+
116
+ async build(jid, opts = {}) {
117
+ await this.#resolveHeader()
118
+ const messageId = opts.messageId ?? generateMessageIDV2()
119
+ const userJid = this.#client.user?.id
120
+ if (this.#mode === 'legacy') {
121
+ const { _headerType, ...header } = this.#header
122
+ const headerType = _headerType ?? (Object.keys(header).length ? proto.Message.ButtonsMessage.HeaderType.TEXT : proto.Message.ButtonsMessage.HeaderType.EMPTY)
123
+ await this.#resolveThumbnail(header)
124
+ return await generateWAMessageFromContent(jid, { buttonsMessage: { ...header, contentText: this.#body, footerText: this.#footer, buttons: this.#buttons, headerType } }, { userJid, messageId, waUploadToServer: this.#client.waUploadToServer })
125
+ }
126
+ if (this.#mode === 'template') return await generateWAMessageFromContent(jid, { templateMessage: { hydratedTemplate: { hydratedContentText: this.#body, hydratedFooterText: this.#footer, hydratedButtons: this.#buttons } } }, { userJid, messageId, waUploadToServer: this.#client.waUploadToServer })
127
+ if (this.#mode === 'buttonsMessage') {
128
+ const { headerType, field } = this.#resolveButtonsMessageHeader()
129
+ await this.#resolveThumbnail(field)
130
+ return await generateWAMessageFromContent(jid, { buttonsMessage: { ...field, footerText: this.#footer, headerType, buttons: this.#buttons } }, { userJid, messageId, waUploadToServer: this.#client.waUploadToServer })
131
+ }
132
+ const isSingleSelect = this.#buttons.length === 1 && this.#buttons[0].name === 'single_select'
133
+ if (isSingleSelect) { const params = JSON.parse(this.#buttons[0].buttonParamsJson); 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 }) }
134
+ const { field } = this.#resolveButtonsMessageHeader()
135
+ await this.#resolveThumbnail(field)
136
+ const hasMedia = !!(field.imageMessage || field.videoMessage || field.documentMessage || field.productMessage)
137
+ const interactiveHeader = Object.keys(this.#header).length ? { hasMediaAttachment: hasMedia, ...field } : undefined
138
+ const nativeFlow = proto.Message.InteractiveMessage.NativeFlowMessage.create({ buttons: resolveNativeFlowButtons(this.#buttons), messageParamsJson: Object.keys(this.#params).length ? JSON.stringify(this.#params) : '' })
139
+ return await generateWAMessageFromContent(jid, { interactiveMessage: { header: interactiveHeader, body: { text: this.#body }, footer: { text: this.#footer }, nativeFlowMessage: nativeFlow, ...(this.#title ? { title: this.#title } : {}), ...(this.#subtitle ? { subtitle: this.#subtitle } : {}) } }, { userJid, messageId, waUploadToServer: this.#client.waUploadToServer })
140
+ }
141
+
142
+ async send(jid, opts = {}) {
143
+ const msg = await this.build(jid, opts)
144
+ const bizNode = getBizBinaryNode(msg.message)
145
+ await this.#client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
146
+ return msg
147
+ }
148
+ }
149
+
150
+ // ─── Interactive ──────────────────────────────────────────────────────────────
151
+ export class Interactive extends BaseBuilder {
152
+ static dispatchKeys = ['interactiveMessage']
153
+ static shortcuts = {
154
+ sendInteractiveMessage: sock => (jid, data, quoted) => new Interactive(sock).from(data).send(jid, q(quoted)),
155
+ sendProductMessage: sock => (jid, data, quoted) => new Interactive(sock).from(data, { __product: true }).send(jid, q(quoted)),
156
+ }
157
+
158
+ async send(jid, opts = {}) {
159
+ const i = this.data
160
+ const userJid = this.client.user?.id
161
+ const upload = this.client.waUploadToServer
162
+ let media = null
163
+ if (i.thumbnail) media = await prepareWAMessageMedia({ image: { url: i.thumbnail } }, { upload })
164
+ else if (i.image) media = await prepareWAMessageMedia({ image: i.image }, { upload })
165
+ else if (i.video) media = await prepareWAMessageMedia({ video: i.video }, { upload })
166
+ else if (i.document) media = await prepareWAMessageMedia({ document: i.document }, { upload })
167
+ const bodyText = i.body?.text ?? i.title ?? ''
168
+ const footerText = typeof i.footer === 'string' ? i.footer : (i.footer?.text ?? '')
169
+ const headerTitle = typeof i.header === 'string' ? i.header : (i.header?.title ?? '')
170
+ let nativeFlow = null
171
+ if (i.buttons?.length || i.nativeFlowMessage) { const nfm = i.nativeFlowMessage ?? {}; const rawButtons = i.buttons ?? nfm.buttons ?? []; nativeFlow = proto.Message.InteractiveMessage.NativeFlowMessage.create({ buttons: resolveNativeFlowButtons(rawButtons), messageParamsJson: nfm.messageParamsJson ?? '' }) }
172
+ const headerMedia = {}
173
+ if (media?.imageMessage) headerMedia.imageMessage = media.imageMessage
174
+ if (media?.videoMessage) headerMedia.videoMessage = media.videoMessage
175
+ if (media?.documentMessage) headerMedia.documentMessage = media.documentMessage
176
+ const interactive = proto.Message.InteractiveMessage.create({ body: proto.Message.InteractiveMessage.Body.create({ text: bodyText }), footer: proto.Message.InteractiveMessage.Footer.create({ text: footerText }), header: proto.Message.InteractiveMessage.Header.create({ title: headerTitle, hasMediaAttachment: !!media, ...headerMedia }), ...(nativeFlow ? { nativeFlowMessage: nativeFlow } : {}) })
177
+ if (i.contextInfo) interactive.contextInfo = i.contextInfo
178
+ const msg = await generateWAMessageFromContent(jid, { interactiveMessage: interactive }, { userJid, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer })
179
+ const bizNode = getBizBinaryNode(msg.message)
180
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
181
+ return msg
182
+ }
183
+ }
184
+
185
+ // ─── Carousel ─────────────────────────────────────────────────────────────────
186
+ export class Carousel extends BaseBuilder {
187
+ #cards = []; #caption = ''; #footer = ''; #cardType = 'HSCROLL_CARDS'
188
+ static #PLACEHOLDER = 'https://placehold.co/600x400/000000/ffffff?text=No+Image'
189
+
190
+ static dispatchKeys = ['carouselMessage']
191
+ static shortcuts = {
192
+ sendCarouselMessage: sock => (jid, data, quoted) => { const d = norm(data); const c = new Carousel(sock); if (d.caption) c.setCaption(d.caption); if (d.footer) c.setFooter(d.footer); (d.cards ?? []).forEach(card => { const resolved = card.nativeFlow ? { ...card, nativeFlow: undefined, nativeFlowMessage: { buttons: resolveNativeFlowButtons(Array.isArray(card.nativeFlow) ? card.nativeFlow : [card.nativeFlow]) } } : card; c.card(resolved) }); return c.send(jid, q(quoted)) },
193
+ sendCarouselProtoMessage: sock => (jid, data, quoted) => Carousel.shortcuts.sendCarouselMessage(sock)(jid, data, quoted),
194
+ }
195
+
196
+ constructor(client) { super(client) }
197
+
198
+ from(data, opts = {}) {
199
+ const d = norm(data, opts)
200
+ if (d.caption) this.setCaption(d.caption)
201
+ if (d.footer) this.setFooter(d.footer)
202
+ if (d.cardType) this.setCardType(d.cardType)
203
+ ; (d.cards ?? []).forEach(card => { const resolved = card.nativeFlow ? { ...card, nativeFlow: undefined, nativeFlowMessage: { buttons: resolveNativeFlowButtons(Array.isArray(card.nativeFlow) ? card.nativeFlow : [card.nativeFlow]) } } : card; this.card(resolved) })
204
+ return this
205
+ }
206
+
207
+ setCaption(t) { this.#caption = t; return this }
208
+ setFooter(t) { this.#footer = t; return this }
209
+ setCardType(t) { this.#cardType = t; return this }
210
+ 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 }
211
+
212
+ async send(jid, opts = {}) {
213
+ if (this.#cards.length < 2) throw new Error('Carousel requires at least 2 cards')
214
+ if (this.#cards.length > 10) throw new Error('Carousel max 10 cards')
215
+ const cards = this.#cards.map(c => ({ ...c, header: (c.header?.imageMessage || c.header?.hasMediaAttachment) ? c.header : { ...c.header, hasMediaAttachment: true, imageMessage: { url: Carousel.#PLACEHOLDER } } }))
216
+ const msg = await generateWAMessageFromContent(jid, { interactiveMessage: proto.Message.InteractiveMessage.create({ header: proto.Message.InteractiveMessage.Header.create({ hasMediaAttachment: false }), body: proto.Message.InteractiveMessage.Body.create({ text: this.#caption }), footer: proto.Message.InteractiveMessage.Footer.create({ text: this.#footer }), carouselMessage: proto.Message.InteractiveMessage.CarouselMessage.create({ cards: cards.map(c => ({ header: proto.Message.InteractiveMessage.Header.create({ title: c.header?.title ?? '', hasMediaAttachment: c.header?.hasMediaAttachment ?? false, ...c.header }), body: proto.Message.InteractiveMessage.Body.create({ text: c.body?.text ?? '' }), footer: proto.Message.InteractiveMessage.Footer.create({ text: c.footer?.text ?? '' }), nativeFlowMessage: proto.Message.InteractiveMessage.NativeFlowMessage.create({ buttons: resolveNativeFlowButtons(c.nativeFlowMessage?.buttons ?? []) }) })), messageVersion: 1, carouselCardType: this.#cardType === 'ALBUM_IMAGE' ? 2 : 1 }) }) }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
217
+ const bizNode = getBizBinaryNode(msg.message)
218
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
219
+ return msg
220
+ }
221
+ }
222
+
223
+ // ─── Album ────────────────────────────────────────────────────────────────────
224
+ export class Album extends BaseBuilder {
225
+ #items = []; #delay = 1500
226
+
227
+ static dispatchKeys = ['albumMessage']
228
+ static shortcuts = {
229
+ sendAlbumMessage: sock => (jid, items, quoted, opts = {}) => sock.sendMessage(jid, { albumMessage: items }, { ...q(quoted), ...opts }),
230
+ }
231
+
232
+ image(urlOrBuffer, caption = '') { this.#items.push({ image: typeof urlOrBuffer === 'string' ? { url: urlOrBuffer } : urlOrBuffer, caption }); return this }
233
+ video(urlOrBuffer, caption = '') { this.#items.push({ video: typeof urlOrBuffer === 'string' ? { url: urlOrBuffer } : urlOrBuffer, caption }); return this }
234
+ add(items) { items.forEach(item => this.#items.push(item)); return this }
235
+ setDelay(ms) { this.#delay = ms; return this }
236
+
237
+ async send(jid, opts = {}) {
238
+ const items = this.data.albumMessage ? (Array.isArray(this.data.albumMessage) ? this.data.albumMessage : [this.data.albumMessage]) : this.#items
239
+ if (items.length < 2) throw new Error('Album requires at least 2 items')
240
+ const userJid = this.client.user?.id
241
+ const album = await generateWAMessageFromContent(jid, { messageContextInfo: proto.MessageContextInfo.create({ messageSecret: crypto.randomBytes(32) }), albumMessage: proto.Message.AlbumMessage.create({ expectedImageCount: items.filter(a => a.image).length, expectedVideoCount: items.filter(a => a.video).length }) }, { userJid, messageId: generateMessageIDV2() })
242
+ await this.client.relayMessage(jid, album.message, { messageId: album.key.id })
243
+ for (const item of items) {
244
+ const img = await generateWAMessage(jid, item, { upload: this.client.waUploadToServer, userJid })
245
+ img.message.messageContextInfo = proto.MessageContextInfo.create({ messageSecret: crypto.randomBytes(32), messageAssociation: proto.MessageAssociation.create({ associationType: 1, parentMessageKey: album.key }) })
246
+ await this.client.relayMessage(jid, img.message, { messageId: img.key.id })
247
+ await delay(opts.albumDelay ?? this.#delay)
248
+ }
249
+ return album
250
+ }
251
+ }
252
+
253
+ // ─── Poll ─────────────────────────────────────────────────────────────────────
254
+ export class Poll extends BaseBuilder {
255
+ #poll = { name: '', values: [], selectableOptionsCount: 1, toAnnouncementGroup: false, hideVoter: false }
256
+
257
+ static shortcuts = {
258
+ sendPoll: sock => (jid, name, values, multiSelect = false, opts = {}) => sock.sendMessage(jid, { poll: { name, values, selectableOptionsCount: multiSelect ? 0 : 1 } }, opts),
259
+ }
260
+
261
+ name(n) { this.#poll.name = n; return this }
262
+ options(o) { this.#poll.values = o; return this }
263
+ addOption(o) { this.#poll.values.push(o); return this }
264
+ multiSelect(max = 0) { this.#poll.selectableOptionsCount = max; return this }
265
+ quiz(ans) { this.#poll.pollType = 1; this.#poll.correctAnswer = ans; return this }
266
+ setEndTime(t) { this.#poll.endTime = t; return this }
267
+
268
+ async send(jid, opts = {}) {
269
+ if (!this.#poll.name) throw new Error('Poll name is required')
270
+ if (this.#poll.values.length < 2) throw new Error('Poll requires at least 2 options')
271
+ return this.client.sendMessage(jid, { poll: this.#poll }, opts)
272
+ }
273
+ }
274
+
275
+ // ─── Payment ──────────────────────────────────────────────────────────────────
276
+ export class Payment extends BaseBuilder {
277
+ static dispatchKeys = ['requestPaymentMessage']
278
+ static shortcuts = {
279
+ sendPaymentMessage: sock => (jid, data, quoted) => new Payment(sock).from(data).send(jid, q(quoted)),
280
+ }
281
+
282
+ setAmount(a) { this.data.amount = a; return this }
283
+ setCurrency(c) { this.data.currency = c; return this }
284
+ setExpiry(t) { this.data.expiry = t; return this }
285
+ setNote(n) { this.data.note = n; return this }
286
+ setFrom(j) { this.data.from = j; return this }
287
+ setBackground(b) { this.data.background = b; return this }
288
+
289
+ async send(jid, opts = {}) {
290
+ const d = this.data
291
+ const currency = d.currency ?? 'NGN'
292
+ const amount = d.amount ?? 0
293
+ const ctx = opts.quoted ? { stanzaId: opts.quoted.key?.id, participant: opts.quoted.key?.participant, quotedMessage: opts.quoted.message } : {}
294
+ const notes = d.note ? { extendedTextMessage: { text: d.note, contextInfo: ctx } } : {}
295
+ const msg = await generateWAMessageFromContent(jid, { requestPaymentMessage: proto.Message.RequestPaymentMessage.fromObject({ expiryTimestamp: d.expiry ?? 0, amount1000: amount, currencyCodeIso4217: currency, requestFrom: d.from ?? '0@s.whatsapp.net', noteMessage: notes, amount: proto.Money.create({ value: amount, offset: 1000, currencyCode: currency }), ...(d.background ? { background: proto.PaymentBackground.create({ id: d.background.id ?? 'DEFAULT', placeholderArgb: d.background.placeholderArgb ?? 0xfff0f0f0, textArgb: d.background.textArgb ?? 0, subtextArgb: d.background.subtextArgb ?? 0, type: proto.PaymentBackground.Type.DEFAULT }) } : {}) }) }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
296
+ const bizNode = getBizBinaryNode(msg.message)
297
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
298
+ return msg
299
+ }
300
+ }
301
+
302
+ // ─── Order ────────────────────────────────────────────────────────────────────
303
+ export class Order extends BaseBuilder {
304
+ static dispatchKeys = ['orderMessage']
305
+ static shortcuts = {
306
+ sendOrderMessage: sock => (jid, data, quoted) => new Order(sock).from(data).send(jid, q(quoted)),
307
+ }
308
+
309
+ async send(jid, opts = {}) {
310
+ const o = this.data
311
+ const userJid = this.client.user?.id
312
+ let thumb = null
313
+ if (o.thumbnail) {
314
+ thumb = await normalizeToBuffer(o.thumbnail).catch(() => undefined)
315
+ }
316
+ const cleanJid = id => { if (!id) return null; const [user] = id.split(':'); return user.includes('@') ? user : `${user}@s.whatsapp.net` }
317
+ const seller = cleanJid(o.sellerJid) ?? cleanJid(userJid) ?? cleanJid(jid) ?? '0@s.whatsapp.net'
318
+ const msg = await generateWAMessageFromContent(jid, { orderMessage: proto.Message.OrderMessage.create({ orderId: o.orderId ?? `zervonex${Date.now()}`, thumbnail: thumb, itemCount: o.itemCount ?? 0, status: o.status ?? proto.Message.OrderMessage.OrderStatus.INQUIRY, surface: o.surface ?? proto.Message.OrderMessage.OrderSurface.CATALOG, message: o.message, orderTitle: o.orderTitle, sellerJid: seller, token: o.token ?? 'zervonex_TOKEN', totalAmount1000: o.totalAmount1000 ?? 0, totalCurrencyCode: o.totalCurrencyCode ?? 'NGN', messageVersion: o.messageVersion ?? 2, ...(o.catalogType ? { catalogType: o.catalogType } : {}), ...(o.contextInfo ? { contextInfo: o.contextInfo } : {}) }) }, { userJid, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer })
319
+ const bizNode = getBizBinaryNode(msg.message)
320
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
321
+ return msg
322
+ }
323
+ }
324
+
325
+ // ─── Event ────────────────────────────────────────────────────────────────────
326
+ export class Event extends BaseBuilder {
327
+ static dispatchKeys = ['eventMessage']
328
+ static shortcuts = { sendEventMessage: sock => (jid, data, quoted) => new Event(sock).from(data).send(jid, q(quoted)) }
329
+
330
+ setName(n) { this.data.name = n; return this }
331
+ setDescription(d) { this.data.description = d; return this }
332
+ setLocation(l) { this.data.location = l; return this }
333
+ setJoinLink(l) { this.data.joinLink = l; return this }
334
+ setStartTime(t) { this.data.startDate = t instanceof Date ? t : new Date(t); return this }
335
+ setEndTime(t) { this.data.endDate = t instanceof Date ? t : new Date(t); return this }
336
+ setCanceled(v = true) { this.data.isCanceled = v; return this }
337
+ setReminder(sec) { this.data.hasReminder = true; this.data.reminderOffsetSec = sec; return this }
338
+ setScheduledCall(v = true) { this.data.isScheduleCall = v; return this }
339
+ setMessageSecret(s) { this.data.messageSecret = s; return this }
340
+
341
+ async send(jid, opts = {}) {
342
+ const e = this.data
343
+ if (!e.name) throw new Error('Event name is required')
344
+ const startDate = e.startDate instanceof Date ? e.startDate : new Date(e.startDate ?? Date.now())
345
+ const endDate = e.endDate ? (e.endDate instanceof Date ? e.endDate : new Date(e.endDate)) : null
346
+ const msg = await generateWAMessageFromContent(jid, { messageContextInfo: proto.MessageContextInfo.create({ messageSecret: e.messageSecret || crypto.randomBytes(32) }), eventMessage: proto.Message.EventMessage.create({ isCanceled: e.isCanceled ?? false, name: e.name, description: e.description ?? '', location: e.location ?? { degreesLatitude: 0, degreesLongitude: 0, name: 'Location' }, joinLink: e.joinLink ?? '', startTime: Math.floor(startDate.getTime() / 1000), endTime: endDate ? Math.floor(endDate.getTime() / 1000) : undefined, extraGuestsAllowed: e.extraGuestsAllowed !== false, isScheduleCall: e.isScheduleCall ?? false, hasReminder: e.hasReminder ?? false, reminderOffsetSec: e.reminderOffsetSec ?? 0 }) }, { userJid: this.client.user?.id, quoted: opts.quoted, waUploadToServer: this.client.waUploadToServer })
347
+ const bizNode = getBizBinaryNode(msg.message)
348
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: [{ tag: 'meta', attrs: { event_type: 'creation' } }, ...(bizNode ? [bizNode] : [])] })
349
+ return msg
350
+ }
351
+ }
352
+
353
+ // ─── StickerPack ──────────────────────────────────────────────────────────────
354
+ export class StickerPack extends BaseBuilder {
355
+ static dispatchKeys = ['stickerPack', 'stickerPackMessage']
356
+ static shortcuts = {
357
+ stickerPackMessage: sock => (jid, data, opts = {}) => new StickerPack(sock).from(data, { name: opts.packName, publisher: opts.packPublisher }).send(jid, q(opts.quoted)),
358
+ }
359
+
360
+ setStickers(s) { this.data.stickers = s; return this }
361
+
362
+ async send(jid, opts = {}) {
363
+ const userJid = this.client.user?.id
364
+ const { quoted, ...passOpts } = opts
365
+ const result = await prepareStickerPackMessage(this.data, { upload: this.client.waUploadToServer, logger: this.client.logger, ...passOpts })
366
+ if (result.isBatched) {
367
+ let last
368
+ for (let i = 0; i < result.stickerPackMessage.length; i++) {
369
+ const msg = await generateWAMessageFromContent(jid, { stickerPackMessage: result.stickerPackMessage[i] }, { userJid, quoted, waUploadToServer: this.client.waUploadToServer })
370
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id })
371
+ last = msg
372
+ if (i < result.stickerPackMessage.length - 1) await delay(2000)
373
+ }
374
+ return last
375
+ }
376
+ const msg = await generateWAMessageFromContent(jid, { stickerPackMessage: result.stickerPackMessage }, { userJid, quoted, waUploadToServer: this.client.waUploadToServer })
377
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id })
378
+ return msg
379
+ }
380
+ }
381
+ // ─── VerticalAlbum ────────────────────────────────────────────────────────────
382
+ export class VerticalAlbum extends BaseBuilder {
383
+ static dispatchKeys = ['verticalAlbumMessage']
384
+ static shortcuts = {
385
+ sendVerticalAlbumMessage: sock => (jid, data, opts = {}) => new VerticalAlbum(sock).from(data, opts).send(jid, opts)
386
+ }
387
+
388
+ async send(jid, opts = {}) {
389
+ const items = this.data.items ?? (Array.isArray(this.data.verticalAlbumMessage) ? this.data.verticalAlbumMessage : [])
390
+ if (!Array.isArray(items) || items.length < 2) throw new Error('VerticalAlbum requires at least 2 items')
391
+ const expiration = String(Date.now() + 30 * 24 * 60 * 60 * 1000)
392
+ const primitives = items.map((item, i) => {
393
+ const kind = item?.type || (item?.video ? 'video' : 'image')
394
+ if (kind === 'video') {
395
+ const v = item.video || item.data || item
396
+ const url = typeof v === 'string' ? v : (v?.url ?? v?.videoUrl ?? '')
397
+ if (!url) throw new Error(`VerticalAlbum item ${i}: video requires a URL`)
398
+ return { media: { url, mime_type: v?.mimeType ?? v?.mime_type ?? 'video/mp4', file_length: v?.fileLength ?? v?.file_length ?? 0, duration: v?.duration ?? 0 }, imagine_type: 'ANIMATE', status: { status: 'READY' }, __typename: 'GenAIImaginePrimitive', ...(v?.thumbnail ? { thumbnail: { raw_media: v.thumbnail } } : {}) }
399
+ }
400
+ const img = item?.image || item?.data || item
401
+ const url = typeof img === 'string' ? img : (img?.imageHighResUrl ?? img?.highResUrl ?? img?.fullUrl ?? img?.imagePreviewUrl ?? img?.previewUrl ?? img?.url ?? '')
402
+ if (!url) throw new Error(`VerticalAlbum item ${i}: image requires a URL`)
403
+ const w = Number(img?.width ?? 600), h = Number(img?.height ?? 400)
404
+ const media = (u, mw, mh) => ({ url: u, url_fallback: u, mime_type: img?.mimeType ?? img?.mime_type ?? 'image/png', expiration_timestamp_ms: expiration, width: mw, height: mh })
405
+ return { preview_image: media(url, w, h), full_image: media(img?.highResUrl ?? url, w, h), dark_mode_preview_image: media(img?.darkModePreviewUrl ?? url, w, h), dark_mode_full_image: media(img?.darkModeHighResUrl ?? url, w, h), asset_query_status: 'FETCHED', display_mode: 'FULL_WIDTH', full_width: true, __typename: 'GenAIImagePrimitive' }
406
+ })
407
+ const unified = { response_id: crypto.randomUUID(), sections: [{ view_model: { primitives, display_mode: 'FULL_WIDTH', full_width: true, __typename: 'GenAIVStackLayoutViewModel' } }] }
408
+ const msg = await generateWAMessageFromContent(jid, {
409
+ messageContextInfo: { botMetadata: { pluginMetadata: {}, botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA } },
410
+ botForwardedMessage: { message: { richResponseMessage: proto.Message.AIRichResponseMessage?.create?.({ messageType: 1, submessages: [], unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) }, contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 } }) ?? { messageType: 1, submessages: [], unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) }, contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 } } } }
411
+ }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
412
+ const bizNode = getBizBinaryNode(msg.message)
413
+ const relayFn = this.client.relayRichMessage ?? this.client.relayMessage
414
+ await relayFn(jid, msg, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
415
+ return msg
416
+ }
417
+ }
418
+
419
+ // ─── GridImage ────────────────────────────────────────────────────────────────
420
+ export class GridImage extends BaseBuilder {
421
+ static dispatchKeys = ['gridImageMessage']
422
+ static shortcuts = {
423
+ sendGridImageMessage: sock => (jid, data, opts = {}) => new GridImage(sock).from(data, opts).send(jid, opts)
424
+ }
425
+
426
+ async send(jid, opts = {}) {
427
+ const imageUrls = this.data.imageUrls ?? this.data.images ?? (Array.isArray(this.data.gridImageMessage) ? this.data.gridImageMessage : [])
428
+ if (!Array.isArray(imageUrls) || imageUrls.length < 2) throw new Error('GridImage requires at least 2 images')
429
+ const expiration = String(Date.now() + 30 * 24 * 60 * 60 * 1000)
430
+ // GRID_IMAGE submessage type (6) — proper protocol path, not just unified sections
431
+ const submessages = [{ messageType: 6, gridImageMetadata: { imageUrls } }]
432
+ const sections = imageUrls.map(img => {
433
+ const image = typeof img === 'string' ? { url: img } : img
434
+ const url = image.imageHighResUrl ?? image.highResUrl ?? image.fullUrl ?? image.imagePreviewUrl ?? image.previewUrl ?? image.url ?? ''
435
+ const w = Number(image.width ?? 600), h = Number(image.height ?? 400)
436
+ const media = (u, mw, mh) => ({ url: u, url_fallback: u, mime_type: image.mimeType ?? image.mime_type ?? 'image/png', expiration_timestamp_ms: expiration, width: mw, height: mh })
437
+ return { preview_image: media(url, w, h), full_image: media(image.highResUrl ?? url, w, h), dark_mode_preview_image: media(image.darkModePreviewUrl ?? url, w, h), dark_mode_full_image: media(image.darkModeHighResUrl ?? url, w, h), asset_query_status: 'FETCHED', __typename: 'GenAIImagePrimitive' }
438
+ })
439
+ const unified = { response_id: crypto.randomUUID(), sections: [{ view_model: { primitives: sections, __typename: 'GenAIGridLayoutViewModel' } }] }
440
+ const msg = await generateWAMessageFromContent(jid, {
441
+ messageContextInfo: { botMetadata: { pluginMetadata: {}, botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA } },
442
+ botForwardedMessage: { message: { richResponseMessage: { messageType: 1, submessages, unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) }, contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 } } } }
443
+ }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
444
+ const bizNode = getBizBinaryNode(msg.message)
445
+ const relayFn = this.client.relayRichMessage ?? this.client.relayMessage
446
+ await relayFn(jid, msg, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
447
+ return msg
448
+ }
449
+ }
450
+
451
+ // ─── VideoGrid ────────────────────────────────────────────────────────────────
452
+ export class VideoGrid extends BaseBuilder {
453
+ static dispatchKeys = ['videoGridMessage']
454
+ static shortcuts = {
455
+ sendVideoGridMessage: sock => (jid, data, opts = {}) => new VideoGrid(sock).from(data, opts).send(jid, opts)
456
+ }
457
+
458
+ async send(jid, opts = {}) {
459
+ const videos = this.data.videos ?? (Array.isArray(this.data.videoGridMessage) ? this.data.videoGridMessage : [])
460
+ if (!Array.isArray(videos) || videos.length < 2) throw new Error('VideoGrid requires at least 2 videos')
461
+ const primitives = videos.map((v, i) => {
462
+ const url = typeof v === 'string' ? v : (v?.url ?? v?.videoUrl ?? v?.reelsUrl ?? '')
463
+ if (!url) throw new Error(`VideoGrid item ${i}: requires a URL`)
464
+ const item = typeof v === 'string' ? {} : v
465
+ return { post_id: item.postId != null ? String(item.postId) : undefined, reels_url: url, reels_title: item.title, thumbnail_url: item.thumbnailUrl ?? item.thumbnail, creator: item.creator, avatar_url: item.avatarUrl, content_hash: item.contentHash, likes_count: item.likes, comments_count: item.comments, shares_count: item.shares, is_verified: item.isVerified, source_app: item.sourceApp, video_delivery_response: { progressive_urls: (item.progressiveUrls ?? []).map(u => ({ progressive_url: u, __typename: 'GenAIProgressiveUrlResponse' })), dash_manifests: (item.dashManifests ?? []).map(m => ({ manifest_xml: m, __typename: 'GenAIDashManifestResponse' })), __typename: 'GenAIVideoDeliveryResponse' }, __typename: 'GenAIVideoPrimitive' }
466
+ })
467
+ const unified = { response_id: crypto.randomUUID(), sections: [{ view_model: { primitives, __typename: 'GenAIGridLayoutViewModel' } }] }
468
+ const msg = await generateWAMessageFromContent(jid, {
469
+ messageContextInfo: { botMetadata: { pluginMetadata: {}, botRenderingConfigMetadata: BOT_RENDERING_CONFIG_METADATA } },
470
+ botForwardedMessage: { message: { richResponseMessage: { messageType: 1, submessages: [], unifiedResponse: { data: Buffer.from(JSON.stringify(unified)) }, contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid: '867051314767696@bot' }, forwardOrigin: 4 } } } }
471
+ }, { userJid: this.client.user?.id, waUploadToServer: this.client.waUploadToServer })
472
+ const bizNode = getBizBinaryNode(msg.message)
473
+ const relayFn = this.client.relayRichMessage ?? this.client.relayMessage
474
+ await relayFn(jid, msg, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
475
+ return msg
476
+ }
477
+ }
478
+
479
+ // ─── A2UI ─────────────────────────────────────────────────────────────────────
480
+ export class A2UI extends BaseBuilder {
481
+ static VERSION = 'v0.9'
482
+ static get CATALOG() { return `https://a2ui.org/specification/${this.VERSION}/catalogs/basic/catalog.json` }
483
+ static dispatchKeys = ['a2uiMessage']
484
+ static shortcuts = {
485
+ sendA2UIMessage: sock => (jid, data, opts = {}) => new A2UI(sock).from(data, opts).send(jid, opts),
486
+ sendA2UICommandMenu: sock => (jid, data, opts = {}) => new A2UI(sock).from(data, { __commandMenu: true, ...opts }).send(jid, opts),
487
+ sendA2UI: sock => (jid, components, opts = {}) => new A2UI(sock).addComponents(components).send(jid, opts)
488
+ }
489
+ static #v = { imgVariant: ['icon', 'avatar', 'smallFeature', 'mediumFeature', 'largeFeature', 'header'], imgFit: ['contain', 'cover', 'fill', 'none', 'scaleDown'], textVariant: ['h1', 'h2', 'h3', 'h4', 'h5', 'caption', 'body'], btnVariant: ['default', 'primary', 'borderless'], colJustify: ['start', 'center', 'end', 'spaceBetween', 'spaceAround', 'spaceEvenly', 'stretch'], rowJustify: ['center', 'end', 'spaceAround', 'spaceBetween', 'spaceEvenly', 'start', 'stretch'], align: ['start', 'center', 'end', 'stretch'], listDir: ['vertical', 'horizontal'], tfVariant: ['longText', 'number', 'shortText', 'obscured'], cpVariant: ['mutuallyExclusive', 'multipleSelection'], cpDisplay: ['checkbox', 'chips'], divAxis: ['horizontal', 'vertical'], icons: ['accountCircle', 'add', 'arrowBack', 'arrowForward', 'attachFile', 'calendarToday', 'call', 'camera', 'check', 'close', 'delete', 'download', 'edit', 'event', 'error', 'fastForward', 'favorite', 'favoriteOff', 'folder', 'help', 'home', 'info', 'locationOn', 'lock', 'lockOpen', 'mail', 'menu', 'moreVert', 'moreHoriz', 'notificationsOff', 'notifications', 'pause', 'payment', 'person', 'phone', 'photo', 'play', 'print', 'refresh', 'rewind', 'search', 'send', 'settings', 'share', 'shoppingCart', 'skipNext', 'skipPrevious', 'star', 'starHalf', 'starOff', 'stop', 'upload', 'visibility', 'visibilityOff', 'volumeDown', 'volumeMute', 'volumeOff', 'volumeUp', 'warning'] }
490
+ static #pick(val, list, def) { return list.includes(val) ? val : def }
491
+ static #id(id, name) { if (!id) throw new TypeError(`${name} requires an id`); return id }
492
+ static text(id, text, { variant = 'body' } = {}) { return { id: A2UI.#id(id, 'text'), component: 'Text', text: String(text), variant: A2UI.#pick(variant, A2UI.#v.textVariant, 'body') } }
493
+ static image(id, input, { variant = 'mediumFeature', fit = 'fill' } = {}) { if (!input) throw new TypeError('image requires a url, buffer, or file path'); return { id: A2UI.#id(id, 'image'), component: 'Image', url: '', _raw: input, variant: A2UI.#pick(variant, A2UI.#v.imgVariant, 'mediumFeature'), fit: A2UI.#pick(fit, A2UI.#v.imgFit, 'fill') } }
494
+ static icon(id, name) { if (!name) throw new TypeError('icon requires a name'); if (typeof name === 'string' && !A2UI.#v.icons.includes(name)) throw new TypeError(`invalid icon: ${name}`); return { id: A2UI.#id(id, 'icon'), component: 'Icon', name } }
495
+ static video(id, url) { if (!url) throw new TypeError('video requires a url'); return { id: A2UI.#id(id, 'video'), component: 'Video', url: String(url) } }
496
+ static audio(id, url, { description = '' } = {}) { if (!url) throw new TypeError('audio requires a url'); return { id: A2UI.#id(id, 'audio'), component: 'AudioPlayer', url: String(url), ...(description ? { description: String(description) } : {}) } }
497
+ static column(id, children = [], { justify = 'start', align = 'stretch' } = {}) { if (!children.length) throw new TypeError('column requires at least one child'); return { id: A2UI.#id(id, 'column'), component: 'Column', children: children.map(String), justify: A2UI.#pick(justify, A2UI.#v.colJustify, 'start'), align: A2UI.#pick(align, A2UI.#v.align, 'stretch') } }
498
+ static row(id, children = [], { justify = 'start', align = 'stretch' } = {}) { if (!children.length) throw new TypeError('row requires at least one child'); return { id: A2UI.#id(id, 'row'), component: 'Row', children: children.map(String), justify: A2UI.#pick(justify, A2UI.#v.rowJustify, 'start'), align: A2UI.#pick(align, A2UI.#v.align, 'stretch') } }
499
+ static list(id, children = [], { direction = 'vertical', align = 'stretch' } = {}) { if (!children.length) throw new TypeError('list requires at least one child'); return { id: A2UI.#id(id, 'list'), component: 'List', children: children.map(String), direction: A2UI.#pick(direction, A2UI.#v.listDir, 'vertical'), align: A2UI.#pick(align, A2UI.#v.align, 'stretch') } }
500
+ static card(id, child) { if (!child) throw new TypeError('card requires a child id'); return { id: A2UI.#id(id, 'card'), component: 'Card', child: String(child) } }
501
+ static tabs(id, tabs = []) { if (!tabs.length) throw new TypeError('tabs requires at least one tab'); return { id: A2UI.#id(id, 'tabs'), component: 'Tabs', tabs: tabs.map((t, i) => ({ title: String(t.title ?? t.label ?? `Tab ${i + 1}`), child: String(t.child) })) } }
502
+ static modal(id, trigger, content) { if (!trigger) throw new TypeError('modal requires a trigger id'); if (!content) throw new TypeError('modal requires a content id'); return { id: A2UI.#id(id, 'modal'), component: 'Modal', trigger: String(trigger), content: String(content) } }
503
+ static divider(id, { axis = 'horizontal' } = {}) { return { id: A2UI.#id(id, 'divider'), component: 'Divider', axis: A2UI.#pick(axis, A2UI.#v.divAxis, 'horizontal') } }
504
+ static button(id, child, action, { variant = 'default' } = {}) { if (!child) throw new TypeError('button requires a child id'); if (!action) throw new TypeError('button requires an action'); return { id: A2UI.#id(id, 'button'), component: 'Button', child: String(child), action, variant: A2UI.#pick(variant, A2UI.#v.btnVariant, 'default') } }
505
+ static textField(id, label, { value = '', variant = 'shortText', validationRegexp = '' } = {}) { if (!label) throw new TypeError('textField requires a label'); return { id: A2UI.#id(id, 'textField'), component: 'TextField', label: String(label), value: String(value), variant: A2UI.#pick(variant, A2UI.#v.tfVariant, 'shortText'), ...(validationRegexp ? { validationRegexp: String(validationRegexp) } : {}) } }
506
+ static checkBox(id, label, value = false) { if (!label) throw new TypeError('checkBox requires a label'); return { id: A2UI.#id(id, 'checkBox'), component: 'CheckBox', label: String(label), value: Boolean(value) } }
507
+ static choicePicker(id, options = [], value = [], { label = '', variant = 'mutuallyExclusive', displayStyle = 'checkbox', filterable = false } = {}) { if (!options.length) throw new TypeError('choicePicker requires at least one option'); return { id: A2UI.#id(id, 'choicePicker'), component: 'ChoicePicker', options: options.map(o => typeof o === 'string' ? { label: o, value: o } : { label: String(o.label), value: String(o.value) }), value: (Array.isArray(value) ? value : [value]).map(String), ...(label ? { label: String(label) } : {}), variant: A2UI.#pick(variant, A2UI.#v.cpVariant, 'mutuallyExclusive'), displayStyle: A2UI.#pick(displayStyle, A2UI.#v.cpDisplay, 'checkbox'), filterable: Boolean(filterable) } }
508
+ static slider(id, value, max, { label = '', min = 0 } = {}) { if (max == null) throw new TypeError('slider requires a max'); return { id: A2UI.#id(id, 'slider'), component: 'Slider', value: Number(value), max: Number(max), min: Number(min), ...(label ? { label: String(label) } : {}) } }
509
+ static dateTimeInput(id, value = '', { label = '', enableDate = false, enableTime = false, min = '', max = '' } = {}) { return { id: A2UI.#id(id, 'dateTimeInput'), component: 'DateTimeInput', value: String(value), enableDate: Boolean(enableDate), enableTime: Boolean(enableTime), ...(label ? { label: String(label) } : {}), ...(min ? { min: String(min) } : {}), ...(max ? { max: String(max) } : {}) } }
510
+ static surface(components, { surfaceId, catalogId = A2UI.CATALOG, version = A2UI.VERSION } = {}) { const id = surfaceId ?? `zervonex-a2ui-${crypto.randomUUID()}`; return Buffer.from(JSON.stringify({ version, createSurface: { surfaceId: id, catalogId, sendDataModel: false, components } }), 'utf8') }
511
+ static async #resolveImage(input) { return { url: await resolveToMediaUrl(input) } }
512
+ #components = []; #buttons = []; #surfaceId = `zervonex-a2ui-${crypto.randomUUID()}`; #fallback = ''; #imageMessage = null
513
+ async #resolveComponents() { return Promise.all(this.#components.map(async c => { if (c.component !== 'Image' || !c._raw) return c; const { _raw, ...rest } = c; try { return { ...rest, url: await resolveToMediaUrl(_raw) } } catch { return { ...rest, url: '' } } })) }
514
+ async #buildHeader(upload) {
515
+ if (!this.#imageMessage) return { header: { hasMediaAttachment: false } }
516
+ const input = this.#imageMessage
517
+ if (Buffer.isBuffer(input)) { const p = await prepareWAMessageMedia({ image: input }, { upload }); return { header: { ...p, hasMediaAttachment: true } } }
518
+ if (input?.image) { const p = await prepareWAMessageMedia({ image: input.image }, { upload }); return { header: { ...p, hasMediaAttachment: true } } }
519
+ const url = input?.url ?? (typeof input === 'string' ? input : null)
520
+ if (url) return { header: { imageMessage: { url }, hasMediaAttachment: true } }
521
+ return { header: { hasMediaAttachment: false } }
522
+ }
523
+ addComponent(obj) { if (!obj?.id) throw new TypeError('addComponent requires an object with an id'); this.#components.push(obj); return this }
524
+ addComponents(arr) { if (!Array.isArray(arr)) throw new TypeError('addComponents requires an array'); for (const c of arr) this.addComponent(c); return this }
525
+ addText(id, text, opts = {}) { return this.addComponent(A2UI.text(id, text, opts)) }
526
+ addImage(id, input, opts = {}) { return this.addComponent(A2UI.image(id, input, opts)) }
527
+ addIcon(id, name) { return this.addComponent(A2UI.icon(id, name)) }
528
+ addVideo(id, url) { return this.addComponent(A2UI.video(id, url)) }
529
+ addAudio(id, url, opts = {}) { return this.addComponent(A2UI.audio(id, url, opts)) }
530
+ addColumn(id, children = [], opts = {}) { return this.addComponent(A2UI.column(id, children, opts)) }
531
+ addRow(id, children = [], opts = {}) { return this.addComponent(A2UI.row(id, children, opts)) }
532
+ addList(id, children = [], opts = {}) { return this.addComponent(A2UI.list(id, children, opts)) }
533
+ addCard(id, child) { return this.addComponent(A2UI.card(id, child)) }
534
+ addTabs(id, tabs = []) { return this.addComponent(A2UI.tabs(id, tabs)) }
535
+ addModal(id, trigger, content) { return this.addComponent(A2UI.modal(id, trigger, content)) }
536
+ addDivider(id, opts = {}) { return this.addComponent(A2UI.divider(id, opts)) }
537
+ addButtonComponent(id, child, action, opts = {}) { return this.addComponent(A2UI.button(id, child, action, opts)) }
538
+ addTextField(id, label, opts = {}) { return this.addComponent(A2UI.textField(id, label, opts)) }
539
+ addCheckBox(id, label, value = false) { return this.addComponent(A2UI.checkBox(id, label, value)) }
540
+ addChoicePicker(id, options, value, opts = {}) { return this.addComponent(A2UI.choicePicker(id, options, value, opts)) }
541
+ addSlider(id, value, max, opts = {}) { return this.addComponent(A2UI.slider(id, value, max, opts)) }
542
+ addDateTimeInput(id, value, opts = {}) { return this.addComponent(A2UI.dateTimeInput(id, value, opts)) }
543
+ addButton(nameOrShorthand, params = {}) {
544
+ if (!nameOrShorthand) throw new TypeError('addButton requires a name or shorthand object')
545
+ if (typeof nameOrShorthand === 'object') { const [r] = resolveNativeFlowButtons([nameOrShorthand]); this.#buttons.push(r) }
546
+ else this.#buttons.push({ name: nameOrShorthand, buttonParamsJson: typeof params === 'string' ? params : JSON.stringify(params) })
547
+ return this
548
+ }
549
+ setFallback(text) { this.#fallback = String(text); return this }
550
+ setSurfaceId(id) { this.#surfaceId = String(id); return this }
551
+ setImage(input) { if (!input) throw new TypeError('setImage requires a url, buffer, or file path'); this.#imageMessage = input; return this }
552
+ async send(jid, opts = {}) {
553
+ const d = this.data
554
+ if (d.components?.length) { this.addComponents(d.components); if (d.buttons?.length) for (const b of d.buttons) this.#buttons.push(b) }
555
+ const upload = this.client.waUploadToServer
556
+ if (this.#components.length) {
557
+ if (!this.#components.some(c => c.id === 'root')) throw new Error('A2UI components must include one with id "root"')
558
+ const [components, { header }] = await Promise.all([this.#resolveComponents(), this.#buildHeader(upload)])
559
+ const buttons = [...this.#buttons, ...(opts.buttons ?? [])]
560
+ const content = { interactiveMessage: { header, body: { text: d.body ?? d.text ?? '\u200b' }, bloksWidget: { uuid: this.#surfaceId, type: 'im_a2ui', data: A2UI.surface(components, { surfaceId: this.#surfaceId }), fallback: this.#fallback }, ...(buttons.length ? { nativeFlowMessage: { messageParamsJson: JSON.stringify(opts.nativeFlowParams ?? {}), buttons, messageVersion: 1 } } : {}) } }
561
+ const msg = await generateWAMessageFromContent(jid, content, { userJid: this.client.user?.id, waUploadToServer: upload })
562
+ const bizNode = getBizBinaryNode(msg.message)
563
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
564
+ return msg
565
+ }
566
+ let content
567
+ if (d.__commandMenu) {
568
+ const rows = (d.rows ?? []).map((r, i) => ({ title: String(r?.[0] ?? r?.title ?? `Command ${i + 1}`), description: String(r?.[1] ?? r?.description ?? ''), id: String(r?.[2] ?? r?.id ?? r?.[0] ?? `command_${i + 1}`) }))
569
+ const buttons = (d.buttons ?? []).map((b, i) => ({ id: `a2ui_button_${i + 1}`, label: String(b?.text ?? b?.label ?? `Button ${i + 1}`), url: String(b?.url ?? '') }))
570
+ const components = [{ id: 'root', component: 'Column', align: 'center', children: ['title', 'divider', 'tableCard', 'footer', ...(buttons.length ? ['buttonRow'] : [])] }, { id: 'title', component: 'Text', text: String(d.title ?? 'Menu'), variant: 'h2' }, { id: 'divider', component: 'Divider' }, { id: 'tableCard', component: 'Card', child: 'tableColumn' }, { id: 'tableColumn', component: 'Column', children: ['headerRow', ...rows.flatMap((_, i) => [`divider_${i}`, `row_${i}`])] }, { id: 'headerRow', component: 'Row', children: ['headerCommand', 'headerFunction'] }, { id: 'headerCommand', component: 'Text', text: 'Command', variant: 'h5' }, { id: 'headerFunction', component: 'Text', text: 'Function', variant: 'h5' }, ...rows.flatMap((r, i) => [{ id: `divider_${i}`, component: 'Divider' }, { id: `row_${i}`, component: 'Row', children: [`command_${i}`, `description_${i}`] }, { id: `command_${i}`, component: 'Text', text: r.title }, { id: `description_${i}`, component: 'Text', text: r.description }]), { id: 'footer', component: 'Text', text: String(d.footer ?? 'Powered by zervonex'), variant: 'caption' }]
571
+ if (buttons.length) { components.push({ id: 'buttonRow', component: 'Row', justify: 'spaceEvenly', children: buttons.flatMap((_, i) => [`buttonLabel_${i}`, `button_${i}`]) }); buttons.forEach((b, i) => { components.push({ id: `buttonLabel_${i}`, component: 'Text', text: b.label }); components.push({ id: `button_${i}`, component: 'Button', child: `buttonLabel_${i}`, variant: 'primary', action: { call: 'openUrl', args: { url: b.url } } }) }) }
572
+ const surfaceId = `zervonex-a2ui-${crypto.randomUUID()}`
573
+ let cmdHeader = { hasMediaAttachment: false }
574
+ if (d.imageMessage) cmdHeader = { imageMessage: d.imageMessage, hasMediaAttachment: true }
575
+ else if (d.image) { const { url } = await A2UI.#resolveImage(d.image); cmdHeader = { imageMessage: { url }, hasMediaAttachment: true } }
576
+ content = { interactiveMessage: { header: cmdHeader, body: { text: d.body ?? d.text ?? '\u200b' }, bloksWidget: { uuid: surfaceId, type: 'im_a2ui', data: A2UI.surface(components, { surfaceId }), fallback: String(d.fallback ?? d.title ?? '') }, nativeFlowMessage: { messageParamsJson: JSON.stringify({ limited_time_offer: { text: String(d.title ?? ''), url: buttons[0]?.url ?? '', copy_code: String(d.title ?? ''), expiration_time: Date.now() * 1000 } }), buttons: [{ name: 'single_select', buttonParamsJson: JSON.stringify({ title: String(d.title ?? ''), sections: [{ title: 'Available Commands', rows }] }) }], messageVersion: 1 } } }
577
+ } else {
578
+ const { imageMessage, image, bloksWidget = {}, nativeFlowMessage, fallback = '', ...rest } = d
579
+ let elseHeader = { hasMediaAttachment: false }
580
+ if (imageMessage) elseHeader = { imageMessage, hasMediaAttachment: true }
581
+ else if (image) { const { url } = await A2UI.#resolveImage(image); elseHeader = { imageMessage: { url }, hasMediaAttachment: true } }
582
+ content = { interactiveMessage: { ...rest, header: elseHeader, body: { text: d.body ?? d.text ?? '\u200b' }, bloksWidget: { uuid: bloksWidget.uuid ?? crypto.randomUUID(), type: bloksWidget.type ?? 'im_a2ui', data: Buffer.isBuffer(bloksWidget.data) ? bloksWidget.data : Buffer.from(typeof bloksWidget.data === 'string' ? bloksWidget.data : JSON.stringify(bloksWidget.data ?? {}), 'utf8'), ...(bloksWidget.fallback || fallback ? { fallback: String(bloksWidget.fallback ?? fallback) } : {}) }, ...(nativeFlowMessage ? { nativeFlowMessage: { ...nativeFlowMessage, messageVersion: nativeFlowMessage.messageVersion ?? 1 } } : {}) } }
583
+ }
584
+ const msg = await generateWAMessageFromContent(jid, content, { userJid: this.client.user?.id, waUploadToServer: upload })
585
+ const bizNode = getBizBinaryNode(msg.message)
586
+ await this.client.relayMessage(jid, msg.message, { messageId: msg.key.id, additionalNodes: bizNode ? [bizNode] : [] })
587
+ return msg
588
+ }
589
589
  }