@fvckerss/baileys 1.0.14 → 1.0.15

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.
@@ -0,0 +1,948 @@
1
+ /* AI Rich extras (htmlSection, sendHtmlApp, primitives catalog).
2
+ * Ported from @rexxhayanasi/elaina-baileys (MessageBuilder 4.7, MIT) —
3
+ * original credits to rexxhayanasi / Nixel are preserved. */
4
+
5
+ import { randomUUID } from 'crypto'
6
+ import { AIRich } from './index.js'
7
+ import { extractMessageContent, generateWAMessageFromContent, prepareWAMessageMedia } from '../Utils/messages.js'
8
+ import { checkHtmlApp } from '../Utils/html-app.js'
9
+
10
+ export const AI_RICH_LAYOUTS = Object.freeze([
11
+ 'Single',
12
+ 'HScroll',
13
+ 'ActionRow',
14
+ 'VStack',
15
+ 'Grid',
16
+ 'FlexibleCountGrid',
17
+ 'RichListItem',
18
+ 'AddonAction'
19
+ ])
20
+
21
+ export const AI_RICH_PRIMITIVES = Object.freeze([
22
+ 'GenAIMarkdownTextUXPrimitive',
23
+ 'GenAICodeUXPrimitive',
24
+ 'GenATableUXPrimitive',
25
+ 'GenAIMetadataTextPrimitive',
26
+ 'GenAISearchResultPrimitive',
27
+ 'GenAIReelPrimitive',
28
+ 'GenAIPostPrimitive',
29
+ 'GenAIProductItemCardPrimitive',
30
+ 'GenAIImaginePrimitive',
31
+ 'GenAIFollowUpSuggestionPillPrimitive',
32
+ 'FOATextPrimitive',
33
+ 'FOABloksPrimitive',
34
+ 'GenAIImagePrimitive',
35
+ 'GenAIDividerPrimitive',
36
+ 'GenAISpacerPrimitive',
37
+ 'GenAITaskPrimitive',
38
+ 'GenAILatexUXPrimitive',
39
+ 'GenAIBotThinkingStatusPrimitive',
40
+ 'GenAIBotProgressStatusPrimitive',
41
+ 'GenAIMetaSubsQuotaUpsellPrimitive'
42
+ ])
43
+
44
+ export const AI_RICH_HTML_PRIMITIVE = 'GenAIaeacdsnwHtmlPrimitive'
45
+ export const AI_RICH_HTML_PRIMITIVE_ANDROID_CLASS = 'FOAHtmlPrimitive'
46
+
47
+ export const AI_RICH_PRIMITIVES_ANDROID_ONLY = Object.freeze([
48
+ AI_RICH_HTML_PRIMITIVE
49
+ ])
50
+
51
+ export const DividerType = Object.freeze({ DOT: 'DOT', HORIZONTAL_LINE: 'HORIZONTAL_LINE' })
52
+ export const ImagineType = Object.freeze({ IMAGINE: 'IMAGINE', ANIMATE: 'ANIMATE', MEMU: 'MEMU' })
53
+ export const ImagineStatus = Object.freeze({ GENERATING: 'GENERATING', READY: 'READY', FAILED: 'FAILED' })
54
+ export const ThinkingIcon = Object.freeze({ THINKING: 'THINKING', WEB_SEARCH: 'WEB_SEARCH', META_SEARCH: 'META_SEARCH' })
55
+ export const TaskStatus = Object.freeze({ PENDING: 'PENDING', RUNNING: 'RUNNING', DONE: 'DONE' })
56
+ export const FooterActionType = Object.freeze({
57
+ OPEN_FULL_VIEW: 'OPEN_FULL_VIEW',
58
+ DOWNLOAD_MEDIA: 'DOWNLOAD_MEDIA',
59
+ GENERATE_IMAGE: 'GENERATE_IMAGE',
60
+ CANCEL_REASONING: 'CANCEL_REASONING',
61
+ UPGRADE_TO_SUBS: 'UPGRADE_TO_SUBS'
62
+ })
63
+ export const AddonActionType = Object.freeze({
64
+ COPY_TO_CLIPBOARD: 'COPY_TO_CLIPBOARD',
65
+ SEND_TO_CHAT: 'SEND_TO_CHAT',
66
+ FOLLOW_UP_PROMPT: 'FOLLOW_UP_PROMPT'
67
+ })
68
+
69
+ const trimEmpty = (object) => {
70
+ for (const key of Object.keys(object)) {
71
+ if (object[key] === undefined) {
72
+ delete object[key]
73
+ }
74
+ }
75
+ return object
76
+ }
77
+
78
+ export const dividerSection = ({ dividerType = DividerType.HORIZONTAL_LINE } = {}) =>
79
+ AIRich.newLayout('Single', {
80
+ divider_type: dividerType,
81
+ __typename: 'GenAIDividerPrimitive'
82
+ })
83
+
84
+ export const spacerSection = ({ spacing = 1 } = {}) =>
85
+ AIRich.newLayout('Single', {
86
+ spacing,
87
+ __typename: 'GenAISpacerPrimitive'
88
+ })
89
+
90
+ export const imageSection = (url, { fallbackUrl, previewUrl, previewFallbackUrl } = {}) =>
91
+ AIRich.newLayout('Single', {
92
+ full_image: { url, url_fallback: fallbackUrl ?? '' },
93
+ preview_image: { url: previewUrl ?? url, url_fallback: previewFallbackUrl ?? fallbackUrl ?? '' },
94
+ __typename: 'GenAIImagePrimitive'
95
+ })
96
+
97
+ export const taskSection = ({ taskId, title = '', subtitle = '', status = TaskStatus.PENDING }) => {
98
+ if (!taskId) {
99
+ throw new TypeError('taskSection requires taskId, an empty id makes WhatsApp drop the item')
100
+ }
101
+ return AIRich.newLayout('Single', {
102
+ task_id: String(taskId),
103
+ title,
104
+ subtitle,
105
+ status,
106
+ __typename: 'GenAITaskPrimitive'
107
+ })
108
+ }
109
+
110
+ export const latexSection = (expression, { image, width = 100, height = 100, fontHeight = 83.333333333333, padding = 15 } = {}) =>
111
+ AIRich.newLayout('Single', {
112
+ latex_expression: expression,
113
+ ...(image
114
+ ? {
115
+ latex_image: { url: image, width, height },
116
+ font_height: fontHeight,
117
+ padding
118
+ }
119
+ : {}),
120
+ __typename: 'GenAILatexUXPrimitive'
121
+ })
122
+
123
+ const statusSection = (typename) => (title, { icon = ThinkingIcon.THINKING, inProgress = true, metaSearchApps = [], thoughtDurationSec } = {}) =>
124
+ AIRich.newLayout('Single', trimEmpty({
125
+ title,
126
+ icon,
127
+ is_in_progress: inProgress,
128
+ meta_search_apps: metaSearchApps,
129
+ thought_duration_sec: thoughtDurationSec === undefined ? undefined : Number(thoughtDurationSec),
130
+ __typename: typename
131
+ }))
132
+
133
+ export const thinkingSection = statusSection('GenAIBotThinkingStatusPrimitive')
134
+ export const progressSection = statusSection('GenAIBotProgressStatusPrimitive')
135
+
136
+ export const lockHeight = (height) => {
137
+ const px = Number(height)
138
+ if (!Number.isFinite(px) || px <= 0) {
139
+ throw new TypeError('height must be a positive number of pixels')
140
+ }
141
+ return '<style>html,body{margin:0;padding:0;height:' + px + 'px;max-height:' + px + 'px;overflow:hidden}'
142
+ + '#__wrap{height:' + px + 'px;overflow-y:auto;-webkit-overflow-scrolling:touch;touch-action:pan-y}</style>'
143
+ + '<script>document.addEventListener("DOMContentLoaded",function(){'
144
+ + 'var w=document.createElement("div");w.id="__wrap";'
145
+ + 'while(document.body.firstChild)w.appendChild(document.body.firstChild);'
146
+ + 'document.body.appendChild(w)});<' + '/script>'
147
+ }
148
+
149
+ export const HTML_APP_BRIDGE = 'AndroidBridge'
150
+
151
+ export const dataUri = (bytes, mimetype) => {
152
+ if (typeof mimetype !== 'string' || !mimetype.includes('/')) {
153
+ throw new TypeError('dataUri needs a mimetype like video/mp4')
154
+ }
155
+ const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes)
156
+ if (!buffer.length) {
157
+ throw new TypeError('dataUri needs a non-empty buffer')
158
+ }
159
+ return 'data:' + mimetype + ';base64,' + buffer.toString('base64')
160
+ }
161
+
162
+ const MEDIA_TAGS = new Set(['video', 'audio', 'img'])
163
+
164
+ export const htmlMedia = (bytes, { mimetype, tag = 'video', label = 'Tap untuk memuat media', poster, id = 'm' + randomUUID().slice(0, 8), attributes = '' } = {}) => {
165
+ if (!MEDIA_TAGS.has(tag)) {
166
+ throw new TypeError('htmlMedia tag must be one of ' + [...MEDIA_TAGS].join(', '))
167
+ }
168
+ if (typeof id !== 'string' || !/^[A-Za-z][A-Za-z0-9_-]*$/.test(id)) {
169
+ throw new TypeError('htmlMedia id must start with a letter and stay alphanumeric')
170
+ }
171
+
172
+ const uri = dataUri(bytes, mimetype)
173
+ const controls = tag === 'img' ? '' : ' controls preload="none" playsinline'
174
+ const cover = poster && tag === 'video' ? ' poster="' + String(poster).replace(/"/g, '&quot;') + '"' : ''
175
+ const json = JSON.stringify(uri).replace(/</g, '\\u003c').replace(/>/g, '\\u003e')
176
+
177
+ return '<' + tag + ' id="' + id + '"' + controls + cover + (attributes ? ' ' + attributes : '') + '></' + tag + '>'
178
+ + '<button id="' + id + '_go" type="button">' + String(label).replace(/[<>&]/g, c => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;' })[c]) + '</button>'
179
+ + '<script>(function(){'
180
+ + 'var src=' + json + ',el=document.getElementById(' + JSON.stringify(id) + '),go=document.getElementById(' + JSON.stringify(id + '_go') + ');'
181
+ + 'go.addEventListener("click",function(){'
182
+ + 'if(el.src)return;el.src=src;go.disabled=true;go.textContent="\\u2713";'
183
+ + 'if(el.play)el.play().catch(function(){})});'
184
+ + '})();<' + '/script>'
185
+ }
186
+
187
+ export const scrollControls = ({ target = '#__wrap', step = 140, holdMs = 70, size = 36, side = 'right', inset = 6 } = {}) => {
188
+ const px = Number(step)
189
+ const hold = Number(holdMs)
190
+ const box = Number(size)
191
+ const edge = Number(inset)
192
+ if (typeof target !== 'string' || target.trim() === '') {
193
+ throw new TypeError('scrollControls target must be a CSS selector')
194
+ }
195
+ if (!Number.isFinite(px) || px <= 0) {
196
+ throw new TypeError('scrollControls step must be a positive number of pixels')
197
+ }
198
+ if (!Number.isFinite(hold) || hold < 16) {
199
+ throw new TypeError('scrollControls holdMs must be at least 16')
200
+ }
201
+ if (!Number.isFinite(box) || box < 24) {
202
+ throw new TypeError('scrollControls size must be at least 24 pixels')
203
+ }
204
+ if (side !== 'right' && side !== 'left') {
205
+ throw new TypeError('scrollControls side must be "right" or "left"')
206
+ }
207
+ if (!Number.isFinite(edge) || edge < 0) {
208
+ throw new TypeError('scrollControls inset must not be negative')
209
+ }
210
+ return '<style>'
211
+ + '#__sc{position:fixed;' + side + ':' + edge + 'px;bottom:' + edge + 'px;z-index:2147483647;'
212
+ + 'display:none;flex-direction:column;gap:' + Math.round(box / 6) + 'px}'
213
+ + '#__sc button{width:' + box + 'px;height:' + box + 'px;padding:0;border:0;'
214
+ + 'border-radius:' + Math.round(box / 4) + 'px;background:rgba(0,0,0,.6);color:#fff;'
215
+ + 'font:' + Math.round(box / 2) + 'px/1 system-ui;touch-action:none;cursor:pointer;'
216
+ + '-webkit-tap-highlight-color:transparent}'
217
+ + '#__sc button:disabled{opacity:.3}'
218
+ + '</style>'
219
+ + '<script>(function(){'
220
+ + 'var STEP=' + px + ',HOLD=' + hold + ',SEL=' + JSON.stringify(target) + ';'
221
+ + 'var box,up,down,timer=null;'
222
+ + 'function pane(){return document.querySelector(SEL)||document.scrollingElement||document.body}'
223
+ + 'function room(){var p=pane();return p?p.scrollHeight-p.clientHeight:0}'
224
+ + 'function sync(){if(!box)return;var p=pane(),r=room();'
225
+ + 'box.style.display=r>4?"flex":"none";if(r<=4)return;'
226
+ + 'up.disabled=p.scrollTop<=0;down.disabled=p.scrollTop>=r-1}'
227
+ + 'function move(by){var p=pane();if(!p)return;p.scrollTop+=by;sync()}'
228
+ + 'function stop(){if(timer!==null){clearInterval(timer);timer=null}}'
229
+ + 'function press(e,by){e.preventDefault();e.stopPropagation();stop();move(by);'
230
+ + 'timer=setInterval(function(){move(by)},HOLD)}'
231
+ + 'function make(label,by){var b=document.createElement("button");b.type="button";'
232
+ + 'b.textContent=label;b.setAttribute("aria-label",by<0?"scroll up":"scroll down");'
233
+ + 'b.addEventListener("touchstart",function(e){press(e,by)},{passive:false});'
234
+ + 'b.addEventListener("touchend",function(e){e.preventDefault();stop()},{passive:false});'
235
+ + 'b.addEventListener("touchcancel",stop);'
236
+ + 'b.addEventListener("mousedown",function(e){press(e,by)});'
237
+ + 'b.addEventListener("mouseup",stop);b.addEventListener("mouseleave",stop);'
238
+ + 'b.addEventListener("click",function(e){e.preventDefault();e.stopPropagation()});'
239
+ + 'return b}'
240
+ + 'function start(){if(box)return;'
241
+ + 'box=document.createElement("div");box.id="__sc";'
242
+ + 'up=make("\\u25b2",-STEP);down=make("\\u25bc",STEP);'
243
+ + 'box.appendChild(up);box.appendChild(down);document.body.appendChild(box);'
244
+ + 'var p=pane();if(p&&p.addEventListener)p.addEventListener("scroll",sync,{passive:true});'
245
+ + 'if(typeof ResizeObserver==="function"){try{new ResizeObserver(sync).observe(document.body)}catch(e){}}'
246
+ + 'addEventListener("load",sync);sync()}'
247
+ + 'if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start();'
248
+ + 'window.__scrollControls={by:move,sync:sync};'
249
+ + '})();<' + '/script>'
250
+ }
251
+
252
+ export const autoHeight = ({ min = 60, max = 900, settleMs = 120, maxReports = 24 } = {}) => {
253
+ const low = Number(min)
254
+ const high = Number(max)
255
+ const wait = Number(settleMs)
256
+ const cap = Number(maxReports)
257
+ if (!Number.isFinite(low) || low <= 0) {
258
+ throw new TypeError('autoHeight min must be a positive number of pixels')
259
+ }
260
+ if (!Number.isFinite(high) || high <= low) {
261
+ throw new TypeError('autoHeight max must be greater than min')
262
+ }
263
+ if (!Number.isFinite(wait) || wait < 0) {
264
+ throw new TypeError('autoHeight settleMs must not be negative')
265
+ }
266
+ if (!Number.isFinite(cap) || cap < 1) {
267
+ throw new TypeError('autoHeight maxReports must be at least 1')
268
+ }
269
+ return '<style>html,body{margin:0;padding:0}</style>'
270
+ + '<script>(function(){'
271
+ + 'var LOW=' + low + ',HIGH=' + high + ',WAIT=' + wait + ',CAP=' + cap + ';'
272
+ + 'var sent=[],timer=null,stopped=false;'
273
+ + 'function measure(){var d=document.documentElement,b=document.body;'
274
+ + 'var h=Math.max(d?d.scrollHeight:0,b?b.scrollHeight:0,b?b.offsetHeight:0);'
275
+ + 'return Math.min(HIGH,Math.max(LOW,Math.ceil(h)))}'
276
+ + 'function report(){if(stopped)return;var h=measure();'
277
+ + 'if(sent.length&&sent[sent.length-1]===h)return;'
278
+ + 'if(sent.length>=2&&sent[sent.length-2]===h){stopped=true;return}'
279
+ + 'sent.push(h);if(sent.length>=CAP)stopped=true;'
280
+ + 'try{window.AndroidBridge.updateSize(h)}catch(e){stopped=true}}'
281
+ + 'function schedule(){if(stopped)return;'
282
+ + 'if(timer!==null)clearTimeout(timer);timer=setTimeout(function(){timer=null;report()},WAIT)}'
283
+ + 'function start(){report();'
284
+ + 'if(typeof ResizeObserver==="function"&&document.body){'
285
+ + 'try{new ResizeObserver(schedule).observe(document.body)}catch(e){}}'
286
+ + 'addEventListener("load",schedule)}'
287
+ + 'if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start();'
288
+ + '})();<' + '/script>'
289
+ }
290
+
291
+ export const htmlSection = (html, { trustedSources = [], height, typename = AI_RICH_HTML_PRIMITIVE, url, sectionTypename = 'GenAIUnifiedResponseSection' } = {}) => {
292
+ if (typeof html !== 'string' || html.trim() === '') {
293
+ throw new TypeError('htmlSection requires a non-empty HTML string')
294
+ }
295
+ if (!Array.isArray(trustedSources)) {
296
+ throw new TypeError('htmlSection trustedSources must be an array of strings')
297
+ }
298
+ if (typeof typename !== 'string' || typename.trim() === '') {
299
+ throw new TypeError('htmlSection typename must be a non-empty string')
300
+ }
301
+ if (url !== undefined && (typeof url !== 'string' || url.trim() === '')) {
302
+ throw new TypeError('htmlSection url must be a non-empty string (WebView base origin, e.g. https://example.com)')
303
+ }
304
+ return {
305
+ // proven wire shape uses the GenAIUnifiedResponseSection wrapper;
306
+ // pass sectionTypename: null for the bare layout form
307
+ ...(sectionTypename ? { __typename: sectionTypename } : {}),
308
+ ...AIRich.newLayout('Single', {
309
+ payload: height === undefined ? html : lockHeight(height) + html,
310
+ ...(url ? { url: String(url) } : {}),
311
+ trusted_sources: trustedSources.map(String),
312
+ __typename: typename
313
+ })
314
+ }
315
+ }
316
+
317
+ export const sendHtmlApp = async (sock, jid, html, { title = '', label, trustedSources, height, autoHeight: auto, scrollButtons, typename, id, url, embedded = false, screenTitle, tabHeader, bypassDownload = false, guard = 'warn', ...options } = {}) => {
318
+ if (!sock) {
319
+ throw new TypeError('sendHtmlApp requires a socket as the first argument')
320
+ }
321
+ if (!jid) {
322
+ throw new TypeError('sendHtmlApp requires a target jid')
323
+ }
324
+ if (auto && height !== undefined) {
325
+ throw new TypeError('sendHtmlApp takes either height or autoHeight, not both')
326
+ }
327
+ if (url !== undefined && (typeof url !== 'string' || url.trim() === '')) {
328
+ throw new TypeError('sendHtmlApp url must be a non-empty string (WebView base origin, e.g. https://example.com)')
329
+ }
330
+
331
+ if (auto) {
332
+ html = autoHeight(auto === true ? undefined : auto) + html
333
+ }
334
+
335
+ if (scrollButtons) {
336
+ html += scrollControls(scrollButtons === true ? undefined : scrollButtons)
337
+ }
338
+
339
+ if (guard !== false) {
340
+ const report = checkHtmlApp(html, { height })
341
+ if (!report.ok && guard === true) {
342
+ throw new TypeError('this html app will not behave in the WebView:\n ' + report.problems.join('\n '))
343
+ }
344
+ if (guard === 'warn') {
345
+ for (const problem of report.problems) {
346
+ sock.logger?.warn({ jid }, 'html app: ' + problem)
347
+ }
348
+ for (const warning of report.warnings) {
349
+ sock.logger?.warn({ jid }, 'html app: ' + warning)
350
+ }
351
+ }
352
+ }
353
+
354
+ const rich = new AIRich(sock)
355
+
356
+ if (title) {
357
+ rich.setTitle(title)
358
+ }
359
+
360
+ if (embedded) {
361
+ // Reproduces the proven wire shape of a hand-relayed payload:
362
+ // body text section + the HTML primitive inside embedded_screens
363
+ // (FOAIDNixelButtonSheets tabs). With `url` set the WebView gets a
364
+ // real https base origin instead of an opaque/null one, so
365
+ // WebSocket/fetch connections are allowed.
366
+ const sheetTitle = screenTitle ?? 'Preview'
367
+
368
+ rich.addText(label ?? sheetTitle)
369
+ rich.addEmbeddedScreen({
370
+ title: sheetTitle,
371
+ content: [
372
+ {
373
+ __typename: 'FOAIDNixelButtonSheets',
374
+ tabs: [
375
+ {
376
+ id: 'tab_0',
377
+ tab_header: tabHeader ?? sheetTitle,
378
+ sections: [
379
+ htmlSection(html, { trustedSources, height, url, ...(typename ? { typename } : {}) })
380
+ ],
381
+ step_entries: []
382
+ }
383
+ ],
384
+ step_entries: []
385
+ }
386
+ ]
387
+ })
388
+
389
+ return rich.send(jid, { bypassDownload, ...options })
390
+ }
391
+
392
+ rich._addContent(
393
+ htmlSection(html, { trustedSources, height, url, ...(typename ? { typename } : {}) }),
394
+ label ? { messageType: 2, messageText: String(label) } : undefined,
395
+ id ? { id } : {}
396
+ )
397
+
398
+ return rich.send(jid, { bypassDownload, ...options })
399
+ }
400
+
401
+ export const HTML_MIME_TYPE = 'text/html'
402
+
403
+ export const sendHtmlDocument = async (sock, jid, html, { fileName = 'app.html', caption, ...options } = {}) => {
404
+ if (!sock) {
405
+ throw new TypeError('sendHtmlDocument requires a socket as the first argument')
406
+ }
407
+ if (!jid) {
408
+ throw new TypeError('sendHtmlDocument requires a target jid')
409
+ }
410
+ if (typeof html !== 'string' || html.trim() === '') {
411
+ throw new TypeError('sendHtmlDocument requires a non-empty HTML string')
412
+ }
413
+ const name = String(fileName)
414
+ if (!/\.html?$/i.test(name)) {
415
+ throw new TypeError('sendHtmlDocument fileName must end with .html or .htm')
416
+ }
417
+ return sock.sendMessage(jid, {
418
+ document: Buffer.from(html, 'utf-8'),
419
+ mimetype: HTML_MIME_TYPE,
420
+ fileName: name,
421
+ ...(caption ? { caption: String(caption) } : {}),
422
+ ...options
423
+ })
424
+ }
425
+
426
+ const fileArtifact = (typename) => (url, { title = '', fileExtension = 'html', fileLength = 0, pageCount, previewImage } = {}) => {
427
+ if (typeof url !== 'string' || url.trim() === '') {
428
+ throw new TypeError('a file section requires a non-empty url')
429
+ }
430
+ return AIRich.newLayout('Single', trimEmpty({
431
+ title: String(title),
432
+ url,
433
+ file_extension: String(fileExtension).replace(/^\./, ''),
434
+ file_length: Number(fileLength) || 0,
435
+ page_count: pageCount === undefined ? undefined : Number(pageCount) || 0,
436
+ preview_image: previewImage,
437
+ __typename: typename
438
+ }))
439
+ }
440
+
441
+ export const fileSection = fileArtifact('GenAIFilePrimitive')
442
+ export const fileLinkSection = fileArtifact('GenAIFileLinkPrimitive')
443
+
444
+ const b64 = (value) => (value === undefined || value === null ? undefined : Buffer.isBuffer(value) || value instanceof Uint8Array ? Buffer.from(value).toString('base64') : String(value))
445
+
446
+ export const botMediaMetadata = (documentMessage) => {
447
+ if (!documentMessage) {
448
+ throw new TypeError('botMediaMetadata requires a prepared document message')
449
+ }
450
+ return trimEmpty({
451
+ fileSha256: b64(documentMessage.fileSha256),
452
+ mediaKey: b64(documentMessage.mediaKey),
453
+ fileEncSha256: b64(documentMessage.fileEncSha256),
454
+ directPath: documentMessage.directPath,
455
+ mediaKeyTimestamp: documentMessage.mediaKeyTimestamp ? Number(documentMessage.mediaKeyTimestamp) : undefined,
456
+ mimetype: documentMessage.mimetype
457
+ })
458
+ }
459
+
460
+ export const prepareFileArtifact = async (sock, content, { mimetype = HTML_MIME_TYPE, fileName = 'app.html', title, id } = {}) => {
461
+ if (!sock) {
462
+ throw new TypeError('prepareFileArtifact requires a socket as the first argument')
463
+ }
464
+ const body = typeof content === 'string' ? Buffer.from(content, 'utf-8') : content
465
+ if (!Buffer.isBuffer(body) && !(body instanceof Uint8Array)) {
466
+ throw new TypeError('prepareFileArtifact content must be a string or a buffer')
467
+ }
468
+
469
+ const prepared = await prepareWAMessageMedia(
470
+ { document: Buffer.from(body), mimetype, fileName },
471
+ { upload: sock.waUploadToServer }
472
+ )
473
+ const documentMessage = prepared.documentMessage
474
+ const media = botMediaMetadata(documentMessage)
475
+ const mediaId = id ?? randomUUID()
476
+
477
+ return {
478
+ mediaId,
479
+ media,
480
+ documentMessage,
481
+ section: AIRich.newLayout('Single', {
482
+ title: String(title || fileName),
483
+ url: documentMessage.url ?? '',
484
+ file_extension: fileName.includes('.') ? fileName.split('.').pop() : '',
485
+ file_length: Number(documentMessage.fileLength) || 0,
486
+ preview_image: {
487
+ media_id: mediaId,
488
+ mime_type: mimetype,
489
+ url: documentMessage.url ?? '',
490
+ url_fallback: ''
491
+ },
492
+ __typename: 'GenAIFilePrimitive'
493
+ }),
494
+ mediaDetails: { id: mediaId, previewMedia: media, highResMedia: media }
495
+ }
496
+ }
497
+
498
+ export const sendHtmlArtifact = async (sock, jid, html, { fileName = 'app.html', title, label, id, bypassDownload = false, ...options } = {}) => {
499
+ if (!jid) {
500
+ throw new TypeError('sendHtmlArtifact requires a target jid')
501
+ }
502
+
503
+ const artifact = await prepareFileArtifact(sock, html, { mimetype: HTML_MIME_TYPE, fileName, title, id })
504
+ const rich = new AIRich(sock)
505
+
506
+ if (title) {
507
+ rich.setTitle(title)
508
+ }
509
+ rich.setBotMetadata({ unifiedResponseMutation: { mediaDetailsMetadataList: [artifact.mediaDetails] } })
510
+ rich._addContent(
511
+ artifact.section,
512
+ label ? { messageType: 2, messageText: String(label) } : undefined,
513
+ {}
514
+ )
515
+
516
+ const message = await rich.send(jid, { bypassDownload, ...options })
517
+ return { message, mediaId: artifact.mediaId }
518
+ }
519
+
520
+ export const SourceProvider = Object.freeze({ UNKNOWN: 0, BING: 1, GOOGLE: 2, SUPPORT: 3, OTHER: 4 })
521
+
522
+ export const botSourcesMetadata = (sources) => {
523
+ if (!Array.isArray(sources) || sources.length === 0) {
524
+ throw new TypeError('botSourcesMetadata requires a non-empty array of sources')
525
+ }
526
+ return {
527
+ sources: sources.map((source, index) => {
528
+ if (!source || typeof source !== 'object' || Array.isArray(source)) {
529
+ throw new TypeError('each source must be a plain object')
530
+ }
531
+ if (!source.url) {
532
+ throw new TypeError('each source requires a url')
533
+ }
534
+ return trimEmpty({
535
+ provider: source.provider ?? SourceProvider.OTHER,
536
+ sourceProviderUrl: String(source.url),
537
+ sourceTitle: source.title === undefined ? undefined : String(source.title),
538
+ sourceQuery: source.query === undefined ? undefined : String(source.query),
539
+ faviconCdnUrl: source.favicon === undefined ? undefined : String(source.favicon),
540
+ thumbnailCdnUrl: source.thumbnail === undefined ? undefined : String(source.thumbnail),
541
+ citationNumber: source.citation === undefined ? index + 1 : Number(source.citation)
542
+ })
543
+ })
544
+ }
545
+ }
546
+
547
+ export const EMBEDDED_SCREEN_PRESENTATION = Object.freeze({
548
+ HALF_HEIGHT: 'HALF_HEIGHT',
549
+ FULL_HEIGHT: 'FULL_HEIGHT'
550
+ })
551
+
552
+ export const embeddedTab = ({ id, header, tabHeader, sections = [] } = {}) => {
553
+ if (!Array.isArray(sections)) {
554
+ throw new TypeError('embeddedTab sections must be an array of sections')
555
+ }
556
+ return trimEmpty({ id: id ?? randomUUID(), header, tab_header: tabHeader, sections })
557
+ }
558
+
559
+ export const AI_RICH_RESPONSE_KEYS = Object.freeze([
560
+ 'chunk_id', 'surface', 'product', 'thread_type', 'is_forwarded', 'is_optimistic', 'nested_responses'
561
+ ])
562
+
563
+ export const embeddedScreen = ({ id, title, content, tabs, header, body, artifacts, steps, stepEntries, sources, pollId } = {}) => {
564
+ if (content !== undefined && !Array.isArray(content)) {
565
+ throw new TypeError('embeddedScreen content must be an array of sections')
566
+ }
567
+ if (tabs !== undefined && !Array.isArray(tabs)) {
568
+ throw new TypeError('embeddedScreen tabs must be an array of tabs')
569
+ }
570
+ for (const [name, value] of [['artifacts', artifacts], ['steps', steps], ['stepEntries', stepEntries], ['sources', sources]]) {
571
+ if (value !== undefined && !Array.isArray(value)) {
572
+ throw new TypeError('embeddedScreen ' + name + ' must be an array')
573
+ }
574
+ }
575
+ return trimEmpty({
576
+ id: id ?? randomUUID(),
577
+ title: title === undefined ? undefined : String(title),
578
+ content,
579
+ tabs,
580
+ header,
581
+ body,
582
+ artifacts,
583
+ steps,
584
+ step_entries: stepEntries,
585
+ sources,
586
+ poll_id: pollId
587
+ })
588
+ }
589
+
590
+ export const footerActionSection = (actionType, { buttonText = '', actionId } = {}) => {
591
+ if (!Object.values(FooterActionType).includes(actionType)) {
592
+ throw new TypeError('footerActionSection actionType must be one of ' + Object.values(FooterActionType).join(', '))
593
+ }
594
+ return AIRich.newLayout('Single', {
595
+ action_type: actionType,
596
+ action_id: actionId ?? randomUUID(),
597
+ button_text: String(buttonText),
598
+ __typename: 'GenAIFooterActionPrimitive'
599
+ })
600
+ }
601
+
602
+ export const BLOKS_A2UI_TYPE = 'im_a2ui'
603
+ export const BLOKS_A2UI_REPLY_ACTION = 'a2ui_reply_action'
604
+ export const BLOKS_A2UI_SUPPORTED_ELEMENTS = Object.freeze(['info_card', 'list_card'])
605
+
606
+ const bloksPayloadData = (data) => {
607
+ if (data === undefined || data === null) {
608
+ return ''
609
+ }
610
+ if (typeof data === 'string') {
611
+ return data
612
+ }
613
+ if (typeof data !== 'object' || Array.isArray(data)) {
614
+ throw new TypeError('bloks data must be a JSON string or a plain object')
615
+ }
616
+ return JSON.stringify(data)
617
+ }
618
+
619
+ const bloksType = (type, caller) => {
620
+ if (typeof type !== 'string' || type.trim() === '') {
621
+ throw new TypeError(caller + ' requires a non-empty bloks type')
622
+ }
623
+ return type
624
+ }
625
+
626
+ export const bloksSection = (type, data, { uuid, initialResponse = '', versioningId = '' } = {}) =>
627
+ AIRich.newLayout('Single', {
628
+ type: bloksType(type, 'bloksSection'),
629
+ data: bloksPayloadData(data),
630
+ uuid: uuid ?? randomUUID(),
631
+ initial_response: String(initialResponse),
632
+ versioning_id: String(versioningId),
633
+ __typename: 'FOABloksPrimitive'
634
+ })
635
+
636
+ export const bloksWidget = ({ type, data, uuid, fallback = '' } = {}) => ({
637
+ type: bloksType(type, 'bloksWidget'),
638
+ data: bloksPayloadData(data),
639
+ uuid: uuid ?? randomUUID(),
640
+ fallback: String(fallback)
641
+ })
642
+
643
+ export const A2UI_VERSION = 'v0.9'
644
+ export const A2UI_BASIC_CATALOG = 'https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json'
645
+ export const A2UI_ROOT_ID = 'root'
646
+
647
+ const a2uiNode = (component) => (id, extra = {}) => {
648
+ if (typeof id !== 'string' || id.trim() === '') {
649
+ throw new TypeError('every a2ui component needs a non-empty id')
650
+ }
651
+ return trimEmpty({ id, component, ...extra })
652
+ }
653
+
654
+ export const a2uiText = (id, text, { variant = 'body' } = {}) =>
655
+ a2uiNode('Text')(id, { text: String(text), variant })
656
+
657
+ export const a2uiImage = (id, url, { variant = 'header', fit = 'cover' } = {}) => {
658
+ if (typeof url !== 'string' || url.trim() === '') {
659
+ throw new TypeError('a2uiImage requires a url')
660
+ }
661
+ return a2uiNode('Image')(id, { url, variant, fit })
662
+ }
663
+
664
+ const a2uiContainer = (component) => (id, children = []) => {
665
+ if (!Array.isArray(children)) {
666
+ throw new TypeError('a2ui container children must be an array of component ids')
667
+ }
668
+ return a2uiNode(component)(id, { children: children.map(String) })
669
+ }
670
+
671
+ export const a2uiColumn = a2uiContainer('Column')
672
+ export const a2uiRow = a2uiContainer('Row')
673
+
674
+ export const a2uiSurface = (components, { surfaceId, catalogId = A2UI_BASIC_CATALOG, sendDataModel = false, version = A2UI_VERSION } = {}) => {
675
+ if (!Array.isArray(components) || components.length === 0) {
676
+ throw new TypeError('a2uiSurface requires at least one component')
677
+ }
678
+ if (!components.some(component => component?.id === A2UI_ROOT_ID)) {
679
+ throw new TypeError('a2ui components must include one with id "' + A2UI_ROOT_ID + '"')
680
+ }
681
+ return {
682
+ version,
683
+ createSurface: {
684
+ surfaceId: surfaceId ?? 'card-' + randomUUID(),
685
+ catalogId,
686
+ sendDataModel: !!sendDataModel,
687
+ components
688
+ }
689
+ }
690
+ }
691
+
692
+ export const a2uiWidget = (components, { uuid, surfaceId, catalogId, sendDataModel, version, fallback = '' } = {}) => {
693
+ const id = uuid ?? randomUUID()
694
+ return bloksWidget({
695
+ type: BLOKS_A2UI_TYPE,
696
+ uuid: id,
697
+ fallback,
698
+ data: a2uiSurface(components, { surfaceId: surfaceId ?? 'card-' + id, catalogId, sendDataModel, version })
699
+ })
700
+ }
701
+
702
+ export const sendA2UI = async (sock, jid, components, { buttons = [], contextInfo, messageId, additionalNodes = [], ...options } = {}) => {
703
+ if (!sock) {
704
+ throw new TypeError('sendA2UI requires a socket as the first argument')
705
+ }
706
+ if (!jid) {
707
+ throw new TypeError('sendA2UI requires a target jid')
708
+ }
709
+ if (!Array.isArray(buttons)) {
710
+ throw new TypeError('sendA2UI buttons must be an array of native flow buttons')
711
+ }
712
+
713
+ const widget = a2uiWidget(components, options)
714
+
715
+ const msg = generateWAMessageFromContent(
716
+ jid,
717
+ {
718
+ interactiveMessage: trimEmpty({
719
+ nativeFlowMessage: { buttons, messageParamsJson: JSON.stringify({}), messageVersion: 1 },
720
+ bloksWidget: widget,
721
+ contextInfo
722
+ })
723
+ },
724
+ { messageId, ...options }
725
+ )
726
+
727
+ await sock.relayMessage(msg.key.remoteJid, msg.message, {
728
+ messageId: msg.key.id,
729
+ additionalNodes: [
730
+ {
731
+ tag: 'biz',
732
+ attrs: {},
733
+ content: [{ tag: 'interactive', attrs: { type: 'native_flow', v: '1' }, content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }] }]
734
+ },
735
+ ...additionalNodes
736
+ ],
737
+ ...options
738
+ })
739
+
740
+ return msg
741
+ }
742
+
743
+ export const sendBloksWidget = async (sock, jid, { type, data, uuid, fallback = '', body, contextInfo, messageId, additionalNodes = [], ...options } = {}) => {
744
+ if (!sock) {
745
+ throw new TypeError('sendBloksWidget requires a socket as the first argument')
746
+ }
747
+ if (!jid) {
748
+ throw new TypeError('sendBloksWidget requires a target jid')
749
+ }
750
+
751
+ const widget = bloksWidget({ type, data, uuid, fallback })
752
+ const text = body === undefined ? widget.fallback : String(body)
753
+
754
+ const msg = generateWAMessageFromContent(
755
+ jid,
756
+ {
757
+ interactiveMessage: {
758
+ bloksWidget: widget,
759
+ ...(text ? { body: { text } } : {}),
760
+ ...(contextInfo ? { contextInfo } : {})
761
+ }
762
+ },
763
+ { messageId, ...options }
764
+ )
765
+
766
+ await sock.relayMessage(msg.key.remoteJid, msg.message, {
767
+ messageId: msg.key.id,
768
+ additionalNodes: [
769
+ {
770
+ tag: 'biz',
771
+ attrs: {},
772
+ content: [{ tag: 'interactive', attrs: { type: 'native_flow', v: '1' }, content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }] }]
773
+ },
774
+ ...additionalNodes
775
+ ],
776
+ ...options
777
+ })
778
+
779
+ return msg
780
+ }
781
+
782
+ export const decodeBloksWidget = (msg) => {
783
+ const message = msg?.message ?? msg
784
+ const interactive =
785
+ message?.interactiveMessage ??
786
+ message?.viewOnceMessage?.message?.interactiveMessage ??
787
+ message?.viewOnceMessageV2?.message?.interactiveMessage
788
+
789
+ const widget = interactive?.bloksWidget
790
+ if (!widget) {
791
+ return null
792
+ }
793
+
794
+ let params = null
795
+ try {
796
+ params = widget.data ? JSON.parse(widget.data) : null
797
+ }
798
+ catch {
799
+ params = null
800
+ }
801
+
802
+ return {
803
+ type: widget.type ?? '',
804
+ uuid: widget.uuid ?? '',
805
+ fallback: widget.fallback ?? '',
806
+ data: widget.data ?? '',
807
+ params
808
+ }
809
+ }
810
+
811
+ export const decodeAIRich = (msg) => {
812
+ const message = msg?.message ?? msg
813
+ const rich =
814
+ message?.botForwardedMessage?.message?.richResponseMessage ??
815
+ message?.botForwardedMessage?.richResponseMessage ??
816
+ message?.richResponseMessage
817
+
818
+ if (!rich) {
819
+ return null
820
+ }
821
+
822
+ let unified = null
823
+ const data = rich.unifiedResponse?.data
824
+ if (data) {
825
+ try {
826
+ unified = JSON.parse(Buffer.from(data, 'base64').toString('utf-8'))
827
+ }
828
+ catch {
829
+ unified = null
830
+ }
831
+ }
832
+
833
+ const sections = Array.isArray(unified?.sections) ? unified.sections : []
834
+ const footerSections = Array.isArray(unified?.footer_sections) ? unified.footer_sections : []
835
+ const embeddedScreens = Array.isArray(unified?.embedded_screens) ? unified.embedded_screens : []
836
+
837
+ const readPrimitives = (section) => {
838
+ const view = section?.view_model
839
+ if (Array.isArray(view?.primitives)) return view.primitives
840
+ if (view?.primitive) return [view.primitive]
841
+ return []
842
+ }
843
+
844
+ return {
845
+ responseId: unified?.response_id,
846
+ layouts: sections.map(section => String(section?.view_model?.__typename ?? '').replace(/^GenAI(.*)LayoutViewModel$/, '$1')),
847
+ typenames: [...new Set(sections.flatMap(section => readPrimitives(section).map(primitive => primitive?.__typename).filter(Boolean)))],
848
+ footerTypenames: [...new Set(footerSections.flatMap(section => readPrimitives(section).map(primitive => primitive?.__typename).filter(Boolean)))],
849
+ sections,
850
+ footerSections,
851
+ embeddedScreens,
852
+ submessages: rich.submessages ?? [],
853
+ unified
854
+ }
855
+ }
856
+
857
+ const A2UI_TEXT_KEYS = Object.freeze(['text', 'label', 'title'])
858
+
859
+ const readPrimitiveText = (primitive) => {
860
+ if (!primitive || typeof primitive !== 'object') {
861
+ return ''
862
+ }
863
+ if (typeof primitive.text === 'string') {
864
+ return primitive.text
865
+ }
866
+ if (typeof primitive.title === 'string') {
867
+ return primitive.title
868
+ }
869
+ return ''
870
+ }
871
+
872
+ const readA2UIText = (components) => components
873
+ .filter(component => component?.component === 'Text' || component?.component === 'Heading')
874
+ .map(component => A2UI_TEXT_KEYS.map(key => component[key]).find(value => typeof value === 'string') ?? '')
875
+ .filter(Boolean)
876
+
877
+ export const readRichMessage = (msg) => {
878
+ const raw = msg?.message ?? msg
879
+ if (!raw || typeof raw !== 'object') {
880
+ return null
881
+ }
882
+
883
+ const content = extractMessageContent(raw) ?? raw
884
+ const rich = decodeAIRich(raw)
885
+ const widget = decodeBloksWidget(raw)
886
+ const interactive =
887
+ content?.interactiveMessage ??
888
+ raw?.interactiveMessage ??
889
+ raw?.viewOnceMessage?.message?.interactiveMessage ??
890
+ raw?.viewOnceMessageV2?.message?.interactiveMessage
891
+
892
+ if (!rich && !widget && !interactive) {
893
+ return null
894
+ }
895
+
896
+ const buttons = (interactive?.nativeFlowMessage?.buttons ?? []).map(button => {
897
+ let params = null
898
+ try {
899
+ params = button?.buttonParamsJson ? JSON.parse(button.buttonParamsJson) : null
900
+ }
901
+ catch {
902
+ params = null
903
+ }
904
+ return { name: button?.name ?? '', params }
905
+ })
906
+
907
+ const a2uiComponents = widget?.type === BLOKS_A2UI_TYPE && Array.isArray(widget.params?.createSurface?.components)
908
+ ? widget.params.createSurface.components
909
+ : []
910
+
911
+ const primitives = (rich?.sections ?? []).flatMap(section => {
912
+ const view = section?.view_model
913
+ if (Array.isArray(view?.primitives)) return view.primitives
914
+ return view?.primitive ? [view.primitive] : []
915
+ })
916
+
917
+ const lines = [
918
+ ...primitives.map(readPrimitiveText),
919
+ ...readA2UIText(a2uiComponents),
920
+ interactive?.body?.text ?? '',
921
+ interactive?.footer?.text ?? ''
922
+ ].filter(Boolean)
923
+
924
+ const kind = a2uiComponents.length ? 'a2ui' : widget ? 'bloks' : rich ? 'airich' : 'interactive'
925
+
926
+ return trimEmpty({
927
+ kind,
928
+ text: lines.join('\n'),
929
+ title: raw?.messageContextInfo?.botMetadata?.messageDisclaimerText || interactive?.header?.title || '',
930
+ buttons,
931
+ html: primitives.filter(p => typeof p?.payload === 'string').map(p => p.payload),
932
+ typenames: rich?.typenames ?? [],
933
+ sections: rich?.sections ?? [],
934
+ footerSections: rich?.footerSections ?? [],
935
+ embeddedScreens: rich?.embeddedScreens ?? [],
936
+ submessages: rich?.submessages ?? [],
937
+ responseId: rich?.responseId,
938
+ a2ui: a2uiComponents.length
939
+ ? {
940
+ surfaceId: widget.params.createSurface.surfaceId,
941
+ catalogId: widget.params.createSurface.catalogId,
942
+ version: widget.params.version,
943
+ components: a2uiComponents
944
+ }
945
+ : undefined,
946
+ bloks: widget ? { type: widget.type, uuid: widget.uuid, fallback: widget.fallback, params: widget.params } : undefined
947
+ })
948
+ }