@vanzxy/baileys 1.3.8 → 1.3.9

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,2297 @@
1
+ /**
2
+ * lib/Utils/MessageBuilder.js — AIRich / Button / ButtonV2 / Carousel / Toolkit
3
+ *
4
+ * Part of @vanzxy/baileys 1.3.9. Third-party attribution for the base
5
+ * implementation this file was adapted from is kept in /NOTICE.md
6
+ * (not inline here) per the original author's license terms.
7
+ *
8
+ * Vanz@Merge 15-08-26 --- Ported into @vanzxy/baileys 1.3.9 from the
9
+ * @blurose/baileys 1.1.13 fork (base, feature-complete) with perf defaults
10
+ * and message-authenticity fields backported from arslan-baileys 1.1.0 and
11
+ * this project's own rich-message-utils.js. See changes tagged "Vanz@" below.
12
+ */
13
+
14
+ 'use strict';
15
+
16
+ const MESSAGE_BUILDER_VERSION = '4.6';
17
+
18
+ import { generateWAMessageFromContent, prepareWAMessageMedia } from './messages.js';
19
+ import { botMetadataSignature, botMetadataCertificate } from './rich-message-utils.js';
20
+ import crypto from 'crypto';
21
+ import { PassThrough, Readable } from 'stream';
22
+ // Vanz@Fix 15-08-26 --- sharp/fluent-ffmpeg were statically imported in the blurose source.
23
+ // Both are optional peer deps here (see package.json peerDependenciesMeta); a static import
24
+ // throws at module-load time when they're not installed, which would crash the entire
25
+ // lib/Utils barrel export (and therefore bot startup) even for users who never call
26
+ // AIRich.addImage()/addVideo()/Toolkit.*. Lazy-load them instead, matching the pattern
27
+ // already used in messages-media.js's getImageProcessingLibrary().
28
+ let _sharp;
29
+ const getSharp = async () => {
30
+ if (_sharp === undefined) {
31
+ _sharp = await import('sharp').then((m) => m.default ?? m).catch(() => null);
32
+ }
33
+ if (!_sharp)
34
+ throw new Error('sharp is required for this operation. Install it with: npm i sharp');
35
+ return _sharp;
36
+ };
37
+ let _ffmpeg;
38
+ const getFfmpeg = async () => {
39
+ if (_ffmpeg === undefined) {
40
+ _ffmpeg = await import('fluent-ffmpeg').then((m) => m.default ?? m).catch(() => null);
41
+ }
42
+ if (!_ffmpeg)
43
+ throw new Error('fluent-ffmpeg is required for this operation. Install it with: npm i fluent-ffmpeg');
44
+ return _ffmpeg;
45
+ };
46
+
47
+ function extractIE(text, { extract = true, hyperlink = true, citation = true, latex = true } = {}) {
48
+ if (!extract) {
49
+ return {
50
+ text,
51
+ ie: [],
52
+ inline_entities: [],
53
+ };
54
+ }
55
+
56
+ const createIE = (type, ie) => {
57
+ if (type == 'hyperlink') {
58
+ return {
59
+ key: ie.key,
60
+ metadata: {
61
+ display_name: ie.text,
62
+ is_trusted: ie.is_trusted,
63
+ url: ie.url,
64
+ __typename: 'GenAIInlineLinkItem',
65
+ },
66
+ };
67
+ }
68
+
69
+ if (type == 'citation') {
70
+ return {
71
+ key: ie.key,
72
+ metadata: {
73
+ reference_id: ie.reference_id,
74
+ reference_url: ie.url,
75
+ reference_title: ie.url,
76
+ reference_display_name: ie.url,
77
+ sources: [],
78
+ __typename: 'GenAISearchCitationItem',
79
+ },
80
+ };
81
+ }
82
+
83
+ if (type == 'latex') {
84
+ return {
85
+ key: ie.key,
86
+ metadata: {
87
+ latex_expression: ie.text,
88
+ latex_image: {
89
+ url: ie.url,
90
+ width: Number(ie.width) || 100,
91
+ height: Number(ie.height) || 100,
92
+ },
93
+ font_height: Number(ie.font_height) || 83.333333333333,
94
+ padding: Number(ie.padding) || 15,
95
+ __typename: 'GenAILatexItem',
96
+ },
97
+ };
98
+ }
99
+ };
100
+
101
+ let ie = [];
102
+ let inline_entities = [];
103
+ let result = '';
104
+ let last = 0;
105
+ let citation_index = 1;
106
+ let hyperlink_index = 0;
107
+ let latex_index = 0;
108
+ let stack = [];
109
+
110
+ for (let i = 0; i < text.length; i++) {
111
+ if (text[i] == '[' && text[i - 1] != '\\') {
112
+ stack.push(i);
113
+ } else if (text[i] == ']' && (text[i + 1] == '(' || text[i + 1] == '<')) {
114
+ let start = stack.pop();
115
+
116
+ if (start == null) continue;
117
+
118
+ let open = text[i + 1];
119
+ let close = open == '(' ? ')' : '>';
120
+ let type = open == '(' ? 'link' : 'latex';
121
+ let end = i + 2;
122
+ let depth = 1;
123
+
124
+ while (end < text.length && depth) {
125
+ if (text[end] == open && text[end - 1] != '\\') depth++;
126
+ else if (text[end] == close && text[end - 1] != '\\') depth--;
127
+ end++;
128
+ }
129
+
130
+ if (depth) continue;
131
+
132
+ let raw = text.slice(start + 1, i).trim();
133
+ let url = text.slice(i + 2, end - 1).trim();
134
+
135
+ let key;
136
+ let tag;
137
+ let data;
138
+
139
+ if (type == 'latex') {
140
+ if (!latex) continue;
141
+
142
+ let [txt = '', width = null, height = null, font_height = null, padding = null] = raw.split('|');
143
+
144
+ key = `\u004E\u0049\u0058\u0045\u004C_LATEX_${latex_index++}`;
145
+ tag = `{{${key}}}${txt || 'image'}{{/${key}}}`;
146
+
147
+ data = {
148
+ type: 'latex',
149
+ ie: {
150
+ key,
151
+ text: txt,
152
+ url,
153
+ width,
154
+ height,
155
+ font_height,
156
+ padding,
157
+ },
158
+ };
159
+ } else if (raw) {
160
+ if (!hyperlink) continue;
161
+
162
+ const trusted = !url.startsWith('!');
163
+
164
+ if (!trusted) {
165
+ url = url.slice(1);
166
+ }
167
+
168
+ key = `\u004E\u0049\u0058\u0045\u004C_HYPERLINK_${hyperlink_index++}`;
169
+ tag = `{{${key}}}${url}{{/${key}}}`;
170
+
171
+ data = {
172
+ type: 'hyperlink',
173
+ ie: {
174
+ key,
175
+ text: raw,
176
+ url,
177
+ is_trusted: trusted,
178
+ },
179
+ };
180
+ } else {
181
+ if (!citation) continue;
182
+
183
+ key = `\u004E\u0049\u0058\u0045\u004C_CITATION_${citation_index - 1}`;
184
+ tag = `{{${key}}}${url}{{/${key}}}`;
185
+
186
+ data = {
187
+ type: 'citation',
188
+ ie: {
189
+ reference_id: citation_index++,
190
+ key,
191
+ text: '',
192
+ url,
193
+ },
194
+ };
195
+ }
196
+
197
+ result += text.slice(last, start) + tag;
198
+ last = end;
199
+
200
+ ie.push(data);
201
+
202
+ const entity = createIE(data.type, data.ie);
203
+
204
+ if (entity) {
205
+ inline_entities.push(entity);
206
+ }
207
+
208
+ i = end - 1;
209
+ }
210
+ }
211
+
212
+ result += text.slice(last);
213
+
214
+ return {
215
+ text: result,
216
+ ie,
217
+ inline_entities,
218
+ };
219
+ }
220
+
221
+ async function waitAllPromises(input) {
222
+ const isPromise = (v) => v && typeof v.then === 'function';
223
+ const isObject = (v) => v && typeof v === 'object';
224
+
225
+ const deep = async (v) => {
226
+ if (isPromise(v)) return deep(await v);
227
+ if (Array.isArray(v)) return Promise.all(v.map(deep));
228
+ if (isObject(v)) {
229
+ const entries = await Promise.all(Object.entries(v).map(async ([k, val]) => [k, await deep(val)]));
230
+ return Object.fromEntries(entries);
231
+ }
232
+ return v;
233
+ };
234
+
235
+ return deep(await input);
236
+ }
237
+
238
+ class Toolkit {
239
+ constructor() {}
240
+
241
+ static extractIE(text, { extract = true, hyperlink = true, citation = true, latex = true } = {}) {
242
+ return extractIE(text, { extract, hyperlink, citation, latex });
243
+ }
244
+
245
+ static async resize(buffer, x, y, fit = 'cover') {
246
+ const sharp = await getSharp();
247
+ return await sharp(buffer)
248
+ .resize(x, y, {
249
+ fit,
250
+ position: 'center',
251
+ background: { r: 0, g: 0, b: 0, alpha: 0 },
252
+ })
253
+ .png()
254
+ .toBuffer();
255
+ }
256
+
257
+ static async waitAllPromises(input) {
258
+ return await waitAllPromises(input);
259
+ }
260
+
261
+ static async fetchBuffer(url, options = {}, { silent = true } = {}) {
262
+ try {
263
+ let response = await fetch(url, options);
264
+ if (!response.ok) throw Error(`HTTP ${response.status}`);
265
+ return Buffer.from(await response.arrayBuffer());
266
+ } catch (error) {
267
+ if (silent) return Buffer.alloc(0);
268
+ throw error;
269
+ }
270
+ }
271
+
272
+ static async toUrl(_client, path, mediaType = 'document') {
273
+ if (!path) throw new Error('Url or buffer needed');
274
+
275
+ const media = await prepareWAMessageMedia(
276
+ {
277
+ [mediaType]: Buffer.isBuffer(path) ? path : { url: path },
278
+ },
279
+ {
280
+ upload: _client.waUploadToServer,
281
+ jid: '\u0040\u006e\u0065\u0077\u0073\u006c\u0065\u0074\u0074\u0065\u0072',
282
+ }
283
+ );
284
+
285
+ return Object.values(media)[0]?.url;
286
+ }
287
+
288
+ static async resolveMedia(_client, media, mediaType = 'image', { resolveUrl = false, resolveWAUrl = false, result = 'url', resize = false, width = 300, height = 300 } = {}) {
289
+ const isUrl = (str) => /^https?:\/\/.+/i.test(str);
290
+
291
+ const isWAUrl = (str) => /^https?:\/\/[^/]*\.whatsapp\.net\//i.test(str);
292
+
293
+ if (Array.isArray(media)) {
294
+ return Promise.all(
295
+ media.map((item) =>
296
+ Toolkit.resolveMedia(_client, item, mediaType, {
297
+ resolveUrl,
298
+ resolveWAUrl,
299
+ result,
300
+ resize,
301
+ width,
302
+ height,
303
+ })
304
+ )
305
+ );
306
+ }
307
+
308
+ const originalIsBuffer = Buffer.isBuffer(media);
309
+
310
+ if (typeof media === 'string' && isUrl(media)) {
311
+ if (isWAUrl(media)) {
312
+ if (resolveWAUrl) {
313
+ media = await Toolkit.fetchBuffer(media, {}, { silent: true });
314
+ } else if (!resolveUrl) {
315
+ if (result === 'url') return media;
316
+
317
+ media = await Toolkit.fetchBuffer(media, {}, { silent: true });
318
+ }
319
+ } else {
320
+ if (!resolveUrl) {
321
+ if (result === 'url') return media;
322
+
323
+ media = await Toolkit.fetchBuffer(media, {}, { silent: true });
324
+ } else {
325
+ media = await Toolkit.fetchBuffer(media, {}, { silent: true });
326
+ }
327
+ }
328
+ }
329
+
330
+ if (typeof media === 'string' && !isUrl(media)) {
331
+ media = Buffer.from(media, 'base64');
332
+ }
333
+
334
+ if (!Buffer.isBuffer(media) || !media.length) {
335
+ return;
336
+ }
337
+
338
+ if (resize && Buffer.isBuffer(media)) {
339
+ media = await Toolkit.resize(media, width, height);
340
+ }
341
+
342
+ if (result === 'buffer') {
343
+ return media;
344
+ }
345
+
346
+ if (result === 'base64') {
347
+ return media.toString('base64');
348
+ }
349
+
350
+ if (originalIsBuffer) {
351
+ return Toolkit.toUrl(_client, media, mediaType);
352
+ }
353
+
354
+ return Toolkit.toUrl(_client, media, mediaType);
355
+ }
356
+
357
+ static getMp4Duration(buffer, { silent = true } = {}) {
358
+ try {
359
+ if (!Buffer.isBuffer(buffer) || buffer.length < 8) {
360
+ if (silent) return 0;
361
+ throw new Error('Invalid buffer');
362
+ }
363
+
364
+ let offset = 0;
365
+
366
+ while (offset < buffer.length - 8) {
367
+ const size = buffer.readUInt32BE(offset);
368
+
369
+ if (size < 8 || offset + size > buffer.length) {
370
+ if (silent) return 0;
371
+ throw new Error('Invalid atom size');
372
+ }
373
+
374
+ const type = buffer.toString('ascii', offset + 4, offset + 8);
375
+
376
+ if (type === 'moov') {
377
+ let moovOffset = offset + 8;
378
+ const moovEnd = offset + size;
379
+
380
+ while (moovOffset < moovEnd - 8) {
381
+ const childSize = buffer.readUInt32BE(moovOffset);
382
+
383
+ if (childSize < 8 || moovOffset + childSize > moovEnd) {
384
+ if (silent) return 0;
385
+ throw new Error('Invalid child atom size');
386
+ }
387
+
388
+ const childType = buffer.toString('ascii', moovOffset + 4, moovOffset + 8);
389
+
390
+ if (childType === 'mvhd') {
391
+ const version = buffer.readUInt8(moovOffset + 8);
392
+
393
+ if (version === 0) {
394
+ const timescale = buffer.readUInt32BE(moovOffset + 20);
395
+ const duration = buffer.readUInt32BE(moovOffset + 24);
396
+
397
+ if (!timescale) {
398
+ if (silent) return 0;
399
+ throw new Error('Invalid timescale');
400
+ }
401
+
402
+ return duration / timescale;
403
+ }
404
+
405
+ if (version === 1) {
406
+ const timescale = buffer.readUInt32BE(moovOffset + 32);
407
+ const duration = Number(buffer.readBigUInt64BE(moovOffset + 36));
408
+
409
+ if (!timescale) {
410
+ if (silent) return 0;
411
+ throw new Error('Invalid timescale');
412
+ }
413
+
414
+ return duration / timescale;
415
+ }
416
+ }
417
+
418
+ moovOffset += childSize;
419
+ }
420
+ }
421
+
422
+ offset += size;
423
+ }
424
+
425
+ if (silent) return 0;
426
+
427
+ throw new Error('No mvhd found!');
428
+ } catch (err) {
429
+ if (silent) return 0;
430
+ throw err;
431
+ }
432
+ }
433
+
434
+ static getMp4Preview(videoBuffer, { time, result = 'buffer', resize = true, width = 300, height = 300, silent = true } = {}) {
435
+ return new Promise((resolve, reject) => {
436
+ const fail = (err) => {
437
+ if (silent) {
438
+ return resolve(result === 'base64' ? '' : Buffer.alloc(0));
439
+ }
440
+ return reject(err);
441
+ };
442
+
443
+ try {
444
+ if (!Buffer.isBuffer(videoBuffer) || !videoBuffer.length) {
445
+ return fail(new Error('videoBuffer tidak valid atau kosong'));
446
+ }
447
+
448
+ const inputStream = new Readable({ read() {} });
449
+ inputStream.push(videoBuffer);
450
+ inputStream.push(null);
451
+
452
+ const outputStream = new PassThrough();
453
+ const chunks = [];
454
+
455
+ outputStream.on('data', (chunk) => chunks.push(chunk));
456
+
457
+ outputStream.on('end', async () => {
458
+ try {
459
+ let output = Buffer.concat(chunks);
460
+
461
+ if (!output.length) {
462
+ return fail(new Error('Output kosong — cek format atau timestamp video'));
463
+ }
464
+
465
+ if (resize) {
466
+ output = await Toolkit.resize(output, width, height);
467
+ }
468
+
469
+ return resolve(result === 'base64' ? output.toString('base64') : output);
470
+ } catch (err) {
471
+ return fail(err);
472
+ }
473
+ });
474
+
475
+ outputStream.on('error', fail);
476
+
477
+ time ??= Math.min(Toolkit.getMp4Duration(videoBuffer) * 0.2, 10);
478
+
479
+ getFfmpeg()
480
+ .then((ffmpeg) => {
481
+ ffmpeg(inputStream)
482
+ .outputOptions([`-ss ${time}`, '-vframes 1', '-vcodec png', '-f image2pipe'])
483
+ .on('error', (err) => fail(new Error(`ffmpeg error: ${err.message}`)))
484
+ .pipe(outputStream, { end: true });
485
+ })
486
+ .catch(fail);
487
+ } catch (err) {
488
+ return fail(err);
489
+ }
490
+ });
491
+ }
492
+ }
493
+
494
+ class BaseBuilder {
495
+ constructor() {
496
+ this._title = '';
497
+ this._subtitle = '';
498
+ this._body = '';
499
+ this._footer = '';
500
+ this._contextInfo = {};
501
+ this._extraPayload = {};
502
+ }
503
+
504
+ setTitle(title) {
505
+ if (typeof title !== 'string') {
506
+ throw new TypeError('Title must be a string');
507
+ }
508
+ this._title = title;
509
+ return this;
510
+ }
511
+
512
+ setSubtitle(subtitle) {
513
+ if (typeof subtitle !== 'string') {
514
+ throw new TypeError('Subtitle must be a string');
515
+ }
516
+ this._subtitle = subtitle;
517
+ return this;
518
+ }
519
+
520
+ setBody(body) {
521
+ if (typeof body !== 'string') {
522
+ throw new TypeError('Body must be a string');
523
+ }
524
+ this._body = body;
525
+ return this;
526
+ }
527
+
528
+ setFooter(footer) {
529
+ if (typeof footer !== 'string') {
530
+ throw new TypeError('Footer must be a string');
531
+ }
532
+ this._footer = footer;
533
+ return this;
534
+ }
535
+
536
+ setContextInfo(obj) {
537
+ if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
538
+ throw new TypeError('ContextInfo must be a plain object');
539
+ }
540
+
541
+ this._contextInfo = obj;
542
+ return this;
543
+ }
544
+
545
+ addPayload(obj) {
546
+ if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
547
+ throw new TypeError('Payload must be a plain object');
548
+ }
549
+
550
+ Object.assign(this._extraPayload, obj);
551
+
552
+ return this;
553
+ }
554
+ }
555
+
556
+ class Button extends BaseBuilder {
557
+ #client;
558
+
559
+ constructor(client) {
560
+ super();
561
+ if (!client) {
562
+ throw new Error('Socket is required');
563
+ }
564
+ this.#client = client;
565
+
566
+ this._buttons = [];
567
+ this._data;
568
+ this._currentSelectionIndex = -1;
569
+ this._currentSectionIndex = -1;
570
+ this._params = {};
571
+ }
572
+
573
+ setVideo(path, options = {}) {
574
+ if (!path) throw new Error('Url or buffer needed');
575
+ Buffer.isBuffer(path) ? (this._data = { video: path, ...options }) : (this._data = { video: { url: path }, ...options });
576
+ return this;
577
+ }
578
+
579
+ setImage(path, options = {}) {
580
+ if (!path) throw new Error('Url or buffer needed');
581
+ Buffer.isBuffer(path) ? (this._data = { image: path, ...options }) : (this._data = { image: { url: path }, ...options });
582
+ return this;
583
+ }
584
+
585
+ setDocument(path, options = {}) {
586
+ if (!path) throw new Error('Url or buffer needed');
587
+ Buffer.isBuffer(path) ? (this._data = { document: path, ...options }) : (this._data = { document: { url: path }, ...options });
588
+ return this;
589
+ }
590
+
591
+ setMedia(obj) {
592
+ if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
593
+ throw new TypeError('Media must be a plain object');
594
+ }
595
+
596
+ this._data = obj;
597
+ return this;
598
+ }
599
+
600
+ clearButtons() {
601
+ this._buttons = [];
602
+ return this;
603
+ }
604
+
605
+ setParams(obj) {
606
+ this._params = obj;
607
+ return this;
608
+ }
609
+
610
+ addButton(name, params) {
611
+ this._buttons.push({
612
+ name,
613
+ buttonParamsJson: typeof params === 'string' ? params : JSON.stringify(params),
614
+ });
615
+
616
+ return this;
617
+ }
618
+
619
+ makeRow(header = '', title = '', description = '', id = '') {
620
+ if (this._currentSelectionIndex === -1 || this._currentSectionIndex === -1) {
621
+ throw new Error('You need to create a selection and a section first');
622
+ }
623
+ const buttonParams = JSON.parse(this._buttons[this._currentSelectionIndex].buttonParamsJson);
624
+ buttonParams.sections[this._currentSectionIndex].rows.push({ header, title, description, id });
625
+ this._buttons[this._currentSelectionIndex].buttonParamsJson = JSON.stringify(buttonParams);
626
+ return this;
627
+ }
628
+
629
+ makeSection(title = '', highlight_label = '') {
630
+ if (this._currentSelectionIndex === -1) {
631
+ throw new Error('You need to create a selection first');
632
+ }
633
+ const buttonParams = JSON.parse(this._buttons[this._currentSelectionIndex].buttonParamsJson);
634
+ buttonParams.sections.push({ title, highlight_label, rows: [] });
635
+ this._currentSectionIndex = buttonParams.sections.length - 1;
636
+ this._buttons[this._currentSelectionIndex].buttonParamsJson = JSON.stringify(buttonParams);
637
+ return this;
638
+ }
639
+
640
+ addSelection(title, options = {}) {
641
+ this._buttons.push({ ...options, name: 'single_select', buttonParamsJson: JSON.stringify({ title, sections: [] }) });
642
+ this._currentSelectionIndex = this._buttons.length - 1;
643
+ this._currentSectionIndex = -1;
644
+ return this;
645
+ }
646
+
647
+ addReply(display_text = '', id = '', options = {}) {
648
+ this._buttons.push({
649
+ name: 'quick_reply',
650
+ buttonParamsJson: JSON.stringify({
651
+ display_text,
652
+ id,
653
+ ...options,
654
+ }),
655
+ });
656
+ return this;
657
+ }
658
+
659
+ addCall(display_text = '', id = '', options = {}) {
660
+ this._buttons.push({
661
+ name: 'cta_call',
662
+ buttonParamsJson: JSON.stringify({
663
+ display_text,
664
+ id,
665
+ ...options,
666
+ }),
667
+ });
668
+ return this;
669
+ }
670
+
671
+ addReminder(display_text = '', id = '', options = {}) {
672
+ this._buttons.push({
673
+ name: 'cta_reminder',
674
+ buttonParamsJson: JSON.stringify({
675
+ display_text,
676
+ id,
677
+ ...options,
678
+ }),
679
+ });
680
+ return this;
681
+ }
682
+
683
+ addCancelReminder(display_text = '', id = '', options = {}) {
684
+ this._buttons.push({
685
+ name: 'cta_cancel_reminder',
686
+ buttonParamsJson: JSON.stringify({
687
+ display_text,
688
+ id,
689
+ ...options,
690
+ }),
691
+ });
692
+ return this;
693
+ }
694
+
695
+ addAddress(display_text = '', id = '', options = {}) {
696
+ this._buttons.push({
697
+ name: 'address_message',
698
+ buttonParamsJson: JSON.stringify({
699
+ display_text,
700
+ id,
701
+ ...options,
702
+ }),
703
+ });
704
+ return this;
705
+ }
706
+
707
+ addLocation(options = {}) {
708
+ this._buttons.push({
709
+ name: 'send_location',
710
+ buttonParamsJson: JSON.stringify(options),
711
+ });
712
+ return this;
713
+ }
714
+
715
+ addUrl(display_text = '', url = '', webview_interaction = false, options = {}) {
716
+ this._buttons.push({
717
+ ...options,
718
+ name: 'cta_url',
719
+ buttonParamsJson: JSON.stringify({
720
+ display_text,
721
+ url,
722
+ webview_interaction,
723
+ ...options,
724
+ }),
725
+ });
726
+ return this;
727
+ }
728
+
729
+ addCopy(display_text = '', copy_code = '', options = {}) {
730
+ this._buttons.push({
731
+ name: 'cta_copy',
732
+ buttonParamsJson: JSON.stringify({
733
+ display_text,
734
+ copy_code,
735
+ ...options,
736
+ }),
737
+ });
738
+ return this;
739
+ }
740
+
741
+ static paramsList = {
742
+ limited_time_offer: {
743
+ text: 'string',
744
+ url: 'string',
745
+ copy_code: 'string',
746
+ expiration_time: 'number',
747
+ },
748
+ bottom_sheet: {
749
+ in_thread_buttons_limit: 'number',
750
+ divider_indices: ['number'],
751
+ list_title: 'string',
752
+ button_title: 'string',
753
+ },
754
+ tap_target_configuration: {
755
+ title: 'string',
756
+ description: 'string',
757
+ canonical_url: 'string',
758
+ domain: 'string',
759
+ buttonIndex: 'number',
760
+ },
761
+ };
762
+
763
+ async toCard() {
764
+ return {
765
+ body: {
766
+ text: this._body,
767
+ },
768
+ footer: {
769
+ text: this._footer,
770
+ },
771
+ header: {
772
+ title: this._title,
773
+ subtitle: this._subtitle,
774
+ hasMediaAttachment: !!this._data,
775
+ ...(this._data
776
+ ? await prepareWAMessageMedia(this._data, { upload: this.#client.waUploadToServer }).catch((e) => {
777
+ if (String(e).includes('Invalid media type')) return this._data;
778
+ throw e;
779
+ })
780
+ : {}),
781
+ },
782
+ nativeFlowMessage: {
783
+ messageParamsJson: JSON.stringify(this._params),
784
+ buttons: this._buttons,
785
+ },
786
+ };
787
+ }
788
+
789
+ async build(jid, { ...options } = {}) {
790
+ const message = await this.toCard();
791
+
792
+ return generateWAMessageFromContent(
793
+ jid,
794
+ {
795
+ ...this._extraPayload,
796
+ interactiveMessage: {
797
+ ...message,
798
+ contextInfo: this._contextInfo,
799
+ },
800
+ },
801
+ { ...options }
802
+ );
803
+ }
804
+
805
+ async send(jid, { ...options } = {}) {
806
+ const msg = await this.build(jid, options);
807
+
808
+ await this.#client.relayMessage(msg.key.remoteJid, msg.message, {
809
+ messageId: msg.key.id,
810
+ additionalNodes: [
811
+ {
812
+ tag: 'biz',
813
+ attrs: {},
814
+ content: [
815
+ {
816
+ tag: 'interactive',
817
+ attrs: { type: 'native_flow', v: '1' },
818
+ content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }],
819
+ },
820
+ ],
821
+ },
822
+ ],
823
+ ...options,
824
+ });
825
+ return msg;
826
+ }
827
+ }
828
+
829
+ class ButtonV2 extends BaseBuilder {
830
+ #client;
831
+
832
+ constructor(client) {
833
+ super();
834
+ if (!client) {
835
+ throw new Error('Socket is required');
836
+ }
837
+
838
+ this.#client = client;
839
+ this._image;
840
+ this._data;
841
+ this._buttons = [];
842
+ }
843
+
844
+ addButton(displayText = '', buttonId = crypto.randomUUID()) {
845
+ this._buttons.push({
846
+ buttonId,
847
+ buttonText: { displayText },
848
+ type: 1,
849
+ });
850
+ return this;
851
+ }
852
+
853
+ addRawButton(obj) {
854
+ if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
855
+ throw new TypeError('Buttons must be a plain object');
856
+ }
857
+
858
+ this._buttons.push(obj);
859
+ return this;
860
+ }
861
+
862
+ setThumbnail(path) {
863
+ if (!path) throw new Error('Url or buffer needed');
864
+ this._image = path;
865
+ return this;
866
+ }
867
+
868
+ setMedia(obj) {
869
+ if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
870
+ throw new TypeError('Media must be a plain object');
871
+ }
872
+
873
+ this._data = obj;
874
+ return this;
875
+ }
876
+
877
+ async build(jid, { ...options } = {}) {
878
+ let _thumbnail = this._image ? await Toolkit.resize(Buffer.isBuffer(this._image) ? this._image : await Toolkit.fetchBuffer(this._image, {}, { silent: true }), 300, 300) : null;
879
+ const msg = generateWAMessageFromContent(
880
+ jid,
881
+ {
882
+ ...this._extraPayload,
883
+ buttonsMessage: {
884
+ contentText: this._body,
885
+ footerText: this._footer,
886
+ ...(this._data
887
+ ? this._data
888
+ : {
889
+ headerType: 6,
890
+ locationMessage: {
891
+ degreesLatitude: 0,
892
+ degreesLongitude: 0,
893
+ name: this._title,
894
+ address: this._subtitle,
895
+ jpegThumbnail: _thumbnail,
896
+ },
897
+ }),
898
+ viewOnce: true,
899
+ contextInfo: this._contextInfo,
900
+ buttons: [...this._buttons],
901
+ },
902
+ },
903
+ { ...options }
904
+ );
905
+ return msg;
906
+ }
907
+
908
+ async send(jid, { ...options } = {}) {
909
+ if (this._buttons.length < 1) throw new Error('ButtonV2 requires at least one button');
910
+ const msg = await this.build(jid, options);
911
+
912
+ await this.#client.relayMessage(msg.key.remoteJid, msg.message, {
913
+ messageId: msg.key.id,
914
+ additionalNodes: [
915
+ {
916
+ tag: 'biz',
917
+ attrs: {},
918
+ content: [
919
+ {
920
+ tag: 'interactive',
921
+ attrs: { type: 'native_flow', v: '1' },
922
+ content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }],
923
+ },
924
+ ],
925
+ },
926
+ ],
927
+ ...options,
928
+ });
929
+ return msg;
930
+ }
931
+ }
932
+
933
+ class Carousel extends BaseBuilder {
934
+ #client;
935
+
936
+ constructor(client) {
937
+ super();
938
+ if (!client) {
939
+ throw new Error('Socket is required');
940
+ }
941
+
942
+ this.#client = client;
943
+ this._cards = [];
944
+ }
945
+
946
+ addCard(card) {
947
+ const cards = Array.isArray(card) ? card : [card];
948
+ const baseIndex = this._cards.length;
949
+
950
+ for (const [index, c] of cards.entries()) {
951
+ if (!c?.header?.hasMediaAttachment) {
952
+ throw new Error(`Card [${baseIndex + index}] must include an image or video in header`);
953
+ }
954
+ }
955
+
956
+ this._cards.push(...cards);
957
+ return this;
958
+ }
959
+
960
+ build(jid, { ...options } = {}) {
961
+ return generateWAMessageFromContent(
962
+ jid,
963
+ {
964
+ ...this._extraPayload,
965
+ interactiveMessage: {
966
+ header: {
967
+ hasMediaAttachment: false,
968
+ },
969
+ body: { text: this._body },
970
+ footer: { text: this._footer },
971
+ contextInfo: this._contextInfo,
972
+ carouselMessage: {
973
+ cards: this._cards,
974
+ },
975
+ },
976
+ },
977
+ { ...options }
978
+ );
979
+ }
980
+
981
+ async send(jid, { ...options } = {}) {
982
+ const msg = this.build(jid, options);
983
+
984
+ await this.#client.relayMessage(msg.key.remoteJid, msg.message, {
985
+ messageId: msg.key.id,
986
+ additionalNodes: [
987
+ {
988
+ tag: 'biz',
989
+ attrs: {},
990
+ content: [
991
+ {
992
+ tag: 'interactive',
993
+ attrs: { type: 'native_flow', v: '1' },
994
+ content: [{ tag: 'native_flow', attrs: { v: '9', name: 'mixed' } }],
995
+ },
996
+ ],
997
+ },
998
+ ],
999
+ ...options,
1000
+ });
1001
+ return msg;
1002
+ }
1003
+ }
1004
+
1005
+ class AIRich extends BaseBuilder {
1006
+ #client;
1007
+
1008
+ constructor(client) {
1009
+ if (!client) {
1010
+ throw new Error('Socket is required');
1011
+ }
1012
+
1013
+ super();
1014
+ this.#client = client;
1015
+ this._contextInfo = {};
1016
+ this._submessages = [];
1017
+ this._sections = [];
1018
+ this._richResponseSources = [];
1019
+ }
1020
+
1021
+ addSubmessage(submessage) {
1022
+ const items = Array.isArray(submessage) ? submessage : [submessage];
1023
+
1024
+ for (const item of items) {
1025
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) {
1026
+ throw new TypeError('Submessage must be a plain object or array of plain objects');
1027
+ }
1028
+
1029
+ this._submessages.push(item);
1030
+ }
1031
+
1032
+ return this;
1033
+ }
1034
+
1035
+ addSection(section) {
1036
+ const items = Array.isArray(section) ? section : [section];
1037
+
1038
+ for (const item of items) {
1039
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) {
1040
+ throw new TypeError('Section must be a plain object or array of plain objects');
1041
+ }
1042
+
1043
+ this._sections.push(item);
1044
+ }
1045
+
1046
+ return this;
1047
+ }
1048
+
1049
+ addText(text, { hyperlink = true, citation = true, latex = true } = {}) {
1050
+ if (typeof text != 'string') {
1051
+ throw new TypeError('Text must be a string');
1052
+ }
1053
+
1054
+ const { text: extractedText, inline_entities } = extractIE(text, {
1055
+ hyperlink,
1056
+ citation,
1057
+ latex,
1058
+ });
1059
+
1060
+ this._submessages.push({
1061
+ messageType: 2,
1062
+ messageText: extractedText,
1063
+ });
1064
+
1065
+ this._sections.push(
1066
+ AIRich.newLayout('Single', {
1067
+ text: extractedText,
1068
+ ...(inline_entities.length && {
1069
+ inline_entities,
1070
+ }),
1071
+ __typename: 'GenAIMarkdownTextUXPrimitive',
1072
+ })
1073
+ );
1074
+
1075
+ return this;
1076
+ }
1077
+
1078
+ addCode(language, code) {
1079
+ if (typeof language !== 'string' || typeof code !== 'string') {
1080
+ throw new TypeError('Language and code must be a string');
1081
+ }
1082
+
1083
+ const meta = AIRich.tokenizer(code, language);
1084
+
1085
+ this._submessages.push({
1086
+ messageType: 5,
1087
+ codeMetadata: {
1088
+ codeLanguage: language,
1089
+ codeBlocks: meta.codeBlock,
1090
+ },
1091
+ });
1092
+
1093
+ this._sections.push(
1094
+ AIRich.newLayout('Single', {
1095
+ language,
1096
+ code_blocks: meta.unified_codeBlock,
1097
+ __typename: 'GenAICodeUXPrimitive',
1098
+ })
1099
+ );
1100
+
1101
+ return this;
1102
+ }
1103
+
1104
+ addTable(table, { hyperlink = true, citation = true, latex = true } = {}) {
1105
+ if (!Array.isArray(table)) {
1106
+ throw new TypeError('Table must be an array');
1107
+ }
1108
+
1109
+ const meta = AIRich.toTableMetadata(table, { hyperlink, citation, latex });
1110
+
1111
+ this._submessages.push({
1112
+ messageType: 4,
1113
+ tableMetadata: {
1114
+ title: meta.title,
1115
+ rows: meta.rows,
1116
+ },
1117
+ });
1118
+
1119
+ this._sections.push(
1120
+ AIRich.newLayout('Single', {
1121
+ rows: meta.unified_rows,
1122
+ __typename: 'GenATableUXPrimitive',
1123
+ })
1124
+ );
1125
+
1126
+ return this;
1127
+ }
1128
+
1129
+ addSource(sources = []) {
1130
+ if (!(Array.isArray(sources) && (sources.every((item) => typeof item === 'string') || sources.every((item) => Array.isArray(item) && item.every((v) => typeof v === 'string'))))) {
1131
+ throw new TypeError('Sources must be a string array or an array of string arrays');
1132
+ }
1133
+
1134
+ if (sources.every((item) => typeof item === 'string')) {
1135
+ sources = [sources];
1136
+ }
1137
+
1138
+ const source = sources.map(([icon, url, text]) => ({
1139
+ source_type: 'THIRD_PARTY',
1140
+ source_display_name: text ?? '',
1141
+ source_subtitle: 'AI',
1142
+ source_url: url ?? '',
1143
+ favicon: {
1144
+ url: Toolkit.resolveMedia(this.#client, icon ?? '', 'image'),
1145
+ mime_type: 'image/jpeg',
1146
+ width: 16,
1147
+ height: 16,
1148
+ },
1149
+ }));
1150
+
1151
+ this._sections.push(
1152
+ AIRich.newLayout('Single', {
1153
+ sources: source,
1154
+ __typename: 'GenAISearchResultPrimitive',
1155
+ })
1156
+ );
1157
+
1158
+ return this;
1159
+ }
1160
+
1161
+ addReels(reelsItems = []) {
1162
+ if (
1163
+ !(
1164
+ (reelsItems && typeof reelsItems === 'object' && !Array.isArray(reelsItems)) ||
1165
+ (Array.isArray(reelsItems) && reelsItems.every((item) => item && typeof item === 'object' && !Array.isArray(item)))
1166
+ )
1167
+ ) {
1168
+ throw new TypeError('Reels items must be an object or an array of objects');
1169
+ }
1170
+
1171
+ if (!Array.isArray(reelsItems)) {
1172
+ reelsItems = [reelsItems];
1173
+ }
1174
+
1175
+ const reels = reelsItems.map((item) => ({
1176
+ ...item,
1177
+ _avatar: Toolkit.resolveMedia(this.#client, item.profileIconUrl ?? item.profile_url ?? item.profile ?? '', 'image'),
1178
+ _thumbnail: Toolkit.resolveMedia(this.#client, item.thumbnailUrl ?? item.thumbnail ?? '', 'image'),
1179
+ }));
1180
+
1181
+ this._submessages.push({
1182
+ messageType: 9,
1183
+ contentItemsMetadata: {
1184
+ contentType: 1,
1185
+ itemsMetadata: reels.map((item) => ({
1186
+ reelItem: {
1187
+ title: item.username ?? '',
1188
+ profileIconUrl: item._avatar,
1189
+ thumbnailUrl: item._thumbnail,
1190
+ videoUrl: item.videoUrl ?? item.url ?? '',
1191
+ },
1192
+ })),
1193
+ },
1194
+ });
1195
+
1196
+ reels.forEach((item, idx) => {
1197
+ this._richResponseSources.push({
1198
+ provider: 'Evernight AI',
1199
+ thumbnailCDNURL: item._thumbnail,
1200
+ sourceProviderURL: item.videoUrl ?? item.url ?? '',
1201
+ sourceQuery: '',
1202
+ faviconCDNURL: item._avatar,
1203
+ citationNumber: idx + 1,
1204
+ sourceTitle: item.username ?? '',
1205
+ });
1206
+ });
1207
+
1208
+ this._sections.push(
1209
+ AIRich.newLayout(
1210
+ 'HScroll',
1211
+ reels.map((item) => ({
1212
+ reels_url: item.videoUrl ?? item.url ?? '',
1213
+ thumbnail_url: item._thumbnail,
1214
+ creator: item.username ?? item.title ?? '',
1215
+ avatar_url: item._avatar,
1216
+ reels_title: item.reels_title ?? item.title ?? '',
1217
+ likes_count: item.likes_count ?? item.like ?? 0,
1218
+ shares_count: item.shares_count ?? item.share ?? 0,
1219
+ view_count: item.view_count ?? item.view ?? 0,
1220
+ reel_source: item.reel_source ?? item.source ?? 'IG',
1221
+ is_verified: !!(item.is_verified || item.verified),
1222
+ __typename: 'GenAIReelPrimitive',
1223
+ }))
1224
+ )
1225
+ );
1226
+
1227
+ return this;
1228
+ }
1229
+
1230
+ addImage(imageUrl, { resolveUrl = false } = {}) {
1231
+ if (!(typeof imageUrl === 'string' || Buffer.isBuffer(imageUrl) || (Array.isArray(imageUrl) && imageUrl.every((v) => typeof v === 'string' || Buffer.isBuffer(v))))) {
1232
+ throw new TypeError('imageUrl must be string | buffer | array of string/buffer');
1233
+ }
1234
+
1235
+ const list = Array.isArray(imageUrl)
1236
+ ? imageUrl.map((v) => {
1237
+ const url = Toolkit.resolveMedia(this.#client, v, 'image', { resolveUrl });
1238
+ return {
1239
+ imagePreviewUrl: url,
1240
+ imageHighResUrl: url,
1241
+ sourceUrl: url,
1242
+ };
1243
+ })
1244
+ : (() => {
1245
+ const url = Toolkit.resolveMedia(this.#client, imageUrl, 'image', { resolveUrl });
1246
+ return [
1247
+ {
1248
+ imagePreviewUrl: url,
1249
+ imageHighResUrl: url,
1250
+ sourceUrl: url,
1251
+ },
1252
+ ];
1253
+ })();
1254
+
1255
+ this._submessages.push({
1256
+ messageType: 1,
1257
+ gridImageMetadata: {
1258
+ gridImageUrl: {
1259
+ imagePreviewUrl: list[0]?.imagePreviewUrl,
1260
+ },
1261
+ imageUrls: list,
1262
+ },
1263
+ });
1264
+
1265
+ list.forEach(({ imagePreviewUrl }) => {
1266
+ this._sections.push(
1267
+ AIRich.newLayout('Single', {
1268
+ media: {
1269
+ url: imagePreviewUrl,
1270
+ mime_type: 'image/png',
1271
+ },
1272
+ imagine_type: 'IMAGE',
1273
+ status: { status: 'READY' },
1274
+ __typename: 'GenAIImaginePrimitive',
1275
+ })
1276
+ );
1277
+ });
1278
+
1279
+ return this;
1280
+ }
1281
+
1282
+ // Vanz@Perf 15-08-26 --- autoFill defaults to false (arslan-baileys behavior): skips the
1283
+ // fetch-full-video + ffmpeg-frame-extraction + duration-parse round trip per video, which
1284
+ // was the main source of blurose's slower response time. Pass { autoFill: true } to opt
1285
+ // back into the complete/slow path (real thumbnail + duration + file_length).
1286
+ addVideo(videoUrl, { autoFill = false } = {}) {
1287
+ const isObjectVideo = (v) => v && typeof v === 'object' && v.url;
1288
+
1289
+ const isValidPrimitive =
1290
+ typeof videoUrl === 'string' ||
1291
+ Buffer.isBuffer(videoUrl) ||
1292
+ isObjectVideo(videoUrl) ||
1293
+ (Array.isArray(videoUrl) && videoUrl.every((v) => typeof v === 'string' || Buffer.isBuffer(v) || isObjectVideo(v)));
1294
+
1295
+ if (!isValidPrimitive) {
1296
+ throw new TypeError('videoUrl must be string | buffer | object | array');
1297
+ }
1298
+
1299
+ const items = Array.isArray(videoUrl) ? videoUrl : [videoUrl];
1300
+
1301
+ this._submessages.push({
1302
+ messageType: 2,
1303
+ messageText: '[ Video tidak dapat dimuat ]',
1304
+ });
1305
+
1306
+ items.forEach((item) => {
1307
+ const isObject = isObjectVideo(item);
1308
+
1309
+ const url = isObject ? Toolkit.resolveMedia(this.#client, item.url ?? '', 'video') : Toolkit.resolveMedia(this.#client, item, 'video');
1310
+
1311
+ const bufferPromise = autoFill ? Promise.resolve(url).then((u) => Toolkit.fetchBuffer(u)) : null;
1312
+
1313
+ const file_length = isObject && item.file_length != null ? item.file_length : autoFill ? bufferPromise.then((b) => b?.length ?? 0) : 0;
1314
+
1315
+ const duration =
1316
+ isObject && item.duration != null
1317
+ ? item.duration
1318
+ : autoFill
1319
+ ? bufferPromise.then((b) =>
1320
+ Toolkit.getMp4Duration(b, {
1321
+ silent: true,
1322
+ })
1323
+ )
1324
+ : 0;
1325
+
1326
+ const thumbnail =
1327
+ isObject && item.thumbnail
1328
+ ? Toolkit.resolveMedia(this.#client, item.thumbnail, 'image', {
1329
+ result: 'base64',
1330
+ resize: true,
1331
+ width: 300,
1332
+ height: 300,
1333
+ })
1334
+ : autoFill
1335
+ ? bufferPromise
1336
+ ? bufferPromise.then((b) =>
1337
+ Toolkit.getMp4Preview(b, {
1338
+ time: 0,
1339
+ result: 'base64',
1340
+ })
1341
+ )
1342
+ : null
1343
+ : null;
1344
+
1345
+ this._sections.push(
1346
+ AIRich.newLayout('Single', {
1347
+ media: {
1348
+ url,
1349
+ mime_type: isObject ? (item.mime_type ?? 'video/mp4') : 'video/mp4',
1350
+ file_length,
1351
+ duration,
1352
+ },
1353
+ imagine_type: 'ANIMATE',
1354
+ status: { status: 'READY' },
1355
+ thumbnail: {
1356
+ raw_media: thumbnail,
1357
+ },
1358
+ __typename: 'GenAIImaginePrimitive',
1359
+ })
1360
+ );
1361
+ });
1362
+
1363
+ return this;
1364
+ }
1365
+
1366
+ addProduct(data = {}) {
1367
+ if (!((data && typeof data === 'object' && !Array.isArray(data)) || (Array.isArray(data) && data.every((item) => item && typeof item === 'object' && !Array.isArray(item))))) {
1368
+ throw new TypeError('Product items must be an object or an array of objects');
1369
+ }
1370
+
1371
+ this._submessages.push({
1372
+ messageType: 2,
1373
+ messageText: '[ Produk tidak dapat dimuat ]',
1374
+ });
1375
+
1376
+ const items = Array.isArray(data) ? data : [data];
1377
+
1378
+ const product = items.map((item) => ({
1379
+ title: item.title,
1380
+ brand: item.brand,
1381
+ price: item.price,
1382
+ sale_price: item.sale_price,
1383
+ product_url: item.product_url ?? item.url,
1384
+ image: {
1385
+ url: Toolkit.resolveMedia(this.#client, item.image_url ?? item.image, 'image'),
1386
+ },
1387
+ additional_images: [
1388
+ {
1389
+ url: Toolkit.resolveMedia(this.#client, item.icon_url ?? item.icon, 'image'),
1390
+ },
1391
+ ],
1392
+ __typename: 'GenAIProductItemCardPrimitive',
1393
+ }));
1394
+
1395
+ this._sections.push(AIRich.newLayout(Array.isArray(data) ? 'HScroll' : 'Single', Array.isArray(data) ? product : product[0]));
1396
+
1397
+ return this;
1398
+ }
1399
+
1400
+ addPost(data = {}) {
1401
+ if (!((data && typeof data === 'object' && !Array.isArray(data)) || (Array.isArray(data) && data.every((item) => item && typeof item === 'object' && !Array.isArray(item))))) {
1402
+ throw new TypeError('Post items must be an object or an array of objects');
1403
+ }
1404
+
1405
+ const posts = Array.isArray(data) ? data : [data];
1406
+
1407
+ this._submessages.push({
1408
+ messageType: 2,
1409
+ messageText: '[ Postingan tidak dapat dimuat ]',
1410
+ });
1411
+
1412
+ const primitives = posts.map((p) => ({
1413
+ title: p.title ?? '',
1414
+ subtitle: p.subtitle ?? '',
1415
+ username: p.username ?? '',
1416
+ profile_picture_url: Toolkit.resolveMedia(this.#client, p.profile_picture_url ?? p.profile_url ?? p.profile ?? '', 'image'),
1417
+ is_verified: !!(p.is_verified || p.verified),
1418
+ thumbnail_url: Toolkit.resolveMedia(this.#client, p.thumbnail_url ?? p.thumbnail ?? '', 'image'),
1419
+ post_caption: p.post_caption ?? p.caption ?? '',
1420
+ likes_count: p.likes_count ?? p.like ?? 0,
1421
+ comments_count: p.comments_count ?? p.comment ?? 0,
1422
+ shares_count: p.shares_count ?? p.share ?? 0,
1423
+ post_url: p.post_url ?? p.url ?? '',
1424
+ post_deeplink: p.post_deeplink ?? p.deeplink ?? '',
1425
+ source_app: p.source_app || p.source || 'INSTAGRAM',
1426
+ footer_label: p.footer_label ?? p.footer ?? '',
1427
+ footer_icon: Toolkit.resolveMedia(this.#client, p.footer_icon ?? p.icon ?? '', 'image'),
1428
+ is_carousel: posts.length > 1,
1429
+ orientation: p.orientation ?? 'LANDSCAPE',
1430
+ post_type: p.post_type ?? 'VIDEO',
1431
+ __typename: 'GenAIPostPrimitive',
1432
+ }));
1433
+
1434
+ this._sections.push(AIRich.newLayout('HScroll', primitives));
1435
+
1436
+ return this;
1437
+ }
1438
+
1439
+ addTip(text) {
1440
+ this._submessages.push({
1441
+ messageType: 2,
1442
+ messageText: text,
1443
+ });
1444
+
1445
+ this._sections.push(
1446
+ AIRich.newLayout('Single', {
1447
+ text,
1448
+ __typename: 'GenAIMetadataTextPrimitive',
1449
+ })
1450
+ );
1451
+
1452
+ return this;
1453
+ }
1454
+
1455
+ addSuggest(suggestion, { scroll = true, layout } = {}) {
1456
+ if (!(typeof suggestion === 'string' || (Array.isArray(suggestion) && suggestion.every((v) => typeof v === 'string')))) {
1457
+ throw new TypeError('Suggestion must be a string or array of strings');
1458
+ }
1459
+
1460
+ const suggest = Array.isArray(suggestion)
1461
+ ? suggestion.map((text) => ({
1462
+ prompt_text: text,
1463
+ prompt_type: 'SUGGESTED_PROMPT',
1464
+ __typename: 'GenAIFollowUpSuggestionPillPrimitive',
1465
+ }))
1466
+ : [
1467
+ {
1468
+ prompt_text: suggestion,
1469
+ prompt_type: 'SUGGESTED_PROMPT',
1470
+ __typename: 'GenAIFollowUpSuggestionPillPrimitive',
1471
+ },
1472
+ ];
1473
+
1474
+ const type = layout ?? (suggest.length === 1 ? 'Single' : scroll ? 'HScroll' : 'ActionRow');
1475
+
1476
+ this._sections.push(AIRich.newLayout(type, type === 'Single' ? suggest[0] : suggest, { __typename: 'GenAIUnifiedResponseSection' }));
1477
+
1478
+ return this;
1479
+ }
1480
+
1481
+ async build({ forwarded = true, notification = false, includesUnifiedResponse = true, includesSubmessages = true, quoted, quotedParticipant, ...options } = {}) {
1482
+ const forward = forwarded
1483
+ ? {
1484
+ forwardingScore: 1,
1485
+ isForwarded: true,
1486
+ forwardedAiBotMessageInfo: { botJid: '0@bot' },
1487
+ forwardOrigin: 4,
1488
+ }
1489
+ : {};
1490
+
1491
+ const notif = notification
1492
+ ? {
1493
+ sessionTransparencyMetadata: {
1494
+ disclaimerText: '~ Ahmad tumbuh kembang',
1495
+ hcaId: `hca_${Date.now()}`,
1496
+ sessionTransparencyType: 1,
1497
+ },
1498
+ }
1499
+ : {};
1500
+
1501
+ const qObj = quoted
1502
+ ? {
1503
+ stanzaId: quoted?.key?.id || quoted?.id,
1504
+ participant: quotedParticipant || quoted?.key?.participant || quoted?.key?.remoteJid,
1505
+ quotedType: 0,
1506
+ quotedMessage: typeof quoted === 'object' && quoted !== null ? (quoted.message ?? quoted) : undefined,
1507
+ }
1508
+ : {};
1509
+
1510
+ const sections = this._footer
1511
+ ? [
1512
+ ...(await waitAllPromises(this._sections)),
1513
+ AIRich.newLayout('Single', {
1514
+ text: this._footer,
1515
+ __typename: 'GenAIMetadataTextPrimitive',
1516
+ }),
1517
+ ]
1518
+ : [...(await waitAllPromises(this._sections))];
1519
+
1520
+ // Vanz@Merge 15-08-26 --- Neither blurose nor arslan sign the bot metadata with
1521
+ // verificationMetadata (proofs/certificateChain). Backported from this project's own
1522
+ // rich-message-utils.js botMetadataSignature/botMetadataCertificate helpers, plus a
1523
+ // botResponseId tying the signed metadata to unifiedResponse.response_id.
1524
+ const responseId = crypto.randomUUID();
1525
+
1526
+ return {
1527
+ messageContextInfo: {
1528
+ deviceListMetadata: {},
1529
+ deviceListMetadataVersion: 2,
1530
+ botMetadata: {
1531
+ messageDisclaimerText: this._title,
1532
+ richResponseSourcesMetadata: { sources: this._richResponseSources },
1533
+ botResponseId: responseId,
1534
+ verificationMetadata: {
1535
+ proofs: [
1536
+ {
1537
+ certificateChain: [botMetadataCertificate(), botMetadataCertificate(892)],
1538
+ version: 1,
1539
+ useCase: 1,
1540
+ signature: botMetadataSignature(),
1541
+ },
1542
+ ],
1543
+ },
1544
+ ...notif,
1545
+ },
1546
+ },
1547
+ ...this._extraPayload,
1548
+ botForwardedMessage: {
1549
+ message: {
1550
+ richResponseMessage: {
1551
+ messageType: 1,
1552
+ submessages: includesSubmessages ? await waitAllPromises(this._submessages) : [],
1553
+ unifiedResponse: {
1554
+ data: includesUnifiedResponse ? Buffer.from(JSON.stringify({ response_id: responseId, sections })).toString('base64') : '',
1555
+ },
1556
+ contextInfo: {
1557
+ ...forward,
1558
+ ...qObj,
1559
+ ...this._contextInfo,
1560
+ },
1561
+ },
1562
+ },
1563
+ },
1564
+ };
1565
+ }
1566
+
1567
+ async send(jid, { forwarded, notification, includesUnifiedResponse, includesSubmessages, ...options } = {}) {
1568
+ const msg = await this.build({ forwarded, notification, includesUnifiedResponse, includesSubmessages, ...options });
1569
+
1570
+ return await this.#client.relayMessage(jid, msg, { ...options });
1571
+ }
1572
+
1573
+ static tokenizer(code, lang = 'javascript') {
1574
+ const keywordsMap = {
1575
+ javascript: new Set([
1576
+ 'break',
1577
+ 'case',
1578
+ 'catch',
1579
+ 'continue',
1580
+ 'debugger',
1581
+ 'delete',
1582
+ 'do',
1583
+ 'else',
1584
+ 'finally',
1585
+ 'for',
1586
+ 'function',
1587
+ 'if',
1588
+ 'in',
1589
+ 'instanceof',
1590
+ 'new',
1591
+ 'return',
1592
+ 'switch',
1593
+ 'this',
1594
+ 'throw',
1595
+ 'try',
1596
+ 'typeof',
1597
+ 'var',
1598
+ 'void',
1599
+ 'while',
1600
+ 'with',
1601
+ 'true',
1602
+ 'false',
1603
+ 'null',
1604
+ 'undefined',
1605
+ 'class',
1606
+ 'const',
1607
+ 'let',
1608
+ 'super',
1609
+ 'extends',
1610
+ 'export',
1611
+ 'import',
1612
+ 'yield',
1613
+ 'static',
1614
+ 'constructor',
1615
+ 'async',
1616
+ 'await',
1617
+ 'get',
1618
+ 'set',
1619
+ ]),
1620
+
1621
+ typescript: new Set([
1622
+ 'abstract',
1623
+ 'any',
1624
+ 'as',
1625
+ 'asserts',
1626
+ 'bigint',
1627
+ 'boolean',
1628
+ 'declare',
1629
+ 'enum',
1630
+ 'implements',
1631
+ 'infer',
1632
+ 'interface',
1633
+ 'is',
1634
+ 'keyof',
1635
+ 'module',
1636
+ 'namespace',
1637
+ 'never',
1638
+ 'readonly',
1639
+ 'require',
1640
+ 'number',
1641
+ 'object',
1642
+ 'override',
1643
+ 'private',
1644
+ 'protected',
1645
+ 'public',
1646
+ 'satisfies',
1647
+ 'string',
1648
+ 'symbol',
1649
+ 'type',
1650
+ 'unknown',
1651
+ 'using',
1652
+ 'from',
1653
+ 'break',
1654
+ 'case',
1655
+ 'catch',
1656
+ 'continue',
1657
+ 'do',
1658
+ 'else',
1659
+ 'finally',
1660
+ 'for',
1661
+ 'function',
1662
+ 'if',
1663
+ 'new',
1664
+ 'return',
1665
+ 'switch',
1666
+ 'this',
1667
+ 'throw',
1668
+ 'try',
1669
+ 'var',
1670
+ 'void',
1671
+ 'while',
1672
+ 'class',
1673
+ 'const',
1674
+ 'let',
1675
+ 'extends',
1676
+ 'import',
1677
+ 'export',
1678
+ 'async',
1679
+ 'await',
1680
+ ]),
1681
+
1682
+ python: new Set([
1683
+ 'False',
1684
+ 'None',
1685
+ 'True',
1686
+ 'and',
1687
+ 'as',
1688
+ 'assert',
1689
+ 'async',
1690
+ 'await',
1691
+ 'break',
1692
+ 'class',
1693
+ 'continue',
1694
+ 'def',
1695
+ 'del',
1696
+ 'elif',
1697
+ 'else',
1698
+ 'except',
1699
+ 'finally',
1700
+ 'for',
1701
+ 'from',
1702
+ 'global',
1703
+ 'if',
1704
+ 'import',
1705
+ 'in',
1706
+ 'is',
1707
+ 'lambda',
1708
+ 'nonlocal',
1709
+ 'not',
1710
+ 'or',
1711
+ 'pass',
1712
+ 'raise',
1713
+ 'return',
1714
+ 'try',
1715
+ 'while',
1716
+ 'with',
1717
+ 'yield',
1718
+ ]),
1719
+
1720
+ java: new Set([
1721
+ 'abstract',
1722
+ 'assert',
1723
+ 'boolean',
1724
+ 'break',
1725
+ 'byte',
1726
+ 'case',
1727
+ 'catch',
1728
+ 'char',
1729
+ 'class',
1730
+ 'const',
1731
+ 'continue',
1732
+ 'default',
1733
+ 'do',
1734
+ 'double',
1735
+ 'else',
1736
+ 'enum',
1737
+ 'extends',
1738
+ 'final',
1739
+ 'finally',
1740
+ 'float',
1741
+ 'for',
1742
+ 'goto',
1743
+ 'if',
1744
+ 'implements',
1745
+ 'import',
1746
+ 'instanceof',
1747
+ 'int',
1748
+ 'interface',
1749
+ 'long',
1750
+ 'native',
1751
+ 'new',
1752
+ 'package',
1753
+ 'private',
1754
+ 'protected',
1755
+ 'public',
1756
+ 'return',
1757
+ 'short',
1758
+ 'static',
1759
+ 'strictfp',
1760
+ 'super',
1761
+ 'switch',
1762
+ 'synchronized',
1763
+ 'this',
1764
+ 'throw',
1765
+ 'throws',
1766
+ 'transient',
1767
+ 'try',
1768
+ 'void',
1769
+ 'volatile',
1770
+ 'while',
1771
+ ]),
1772
+
1773
+ golang: new Set([
1774
+ 'break',
1775
+ 'case',
1776
+ 'chan',
1777
+ 'const',
1778
+ 'continue',
1779
+ 'default',
1780
+ 'defer',
1781
+ 'else',
1782
+ 'fallthrough',
1783
+ 'for',
1784
+ 'func',
1785
+ 'go',
1786
+ 'goto',
1787
+ 'if',
1788
+ 'import',
1789
+ 'interface',
1790
+ 'map',
1791
+ 'package',
1792
+ 'range',
1793
+ 'return',
1794
+ 'select',
1795
+ 'struct',
1796
+ 'switch',
1797
+ 'type',
1798
+ 'var',
1799
+ ]),
1800
+
1801
+ c: new Set([
1802
+ 'auto',
1803
+ 'break',
1804
+ 'case',
1805
+ 'char',
1806
+ 'const',
1807
+ 'continue',
1808
+ 'default',
1809
+ 'do',
1810
+ 'double',
1811
+ 'else',
1812
+ 'enum',
1813
+ 'extern',
1814
+ 'float',
1815
+ 'for',
1816
+ 'goto',
1817
+ 'if',
1818
+ 'int',
1819
+ 'long',
1820
+ 'register',
1821
+ 'return',
1822
+ 'short',
1823
+ 'signed',
1824
+ 'sizeof',
1825
+ 'static',
1826
+ 'struct',
1827
+ 'switch',
1828
+ 'typedef',
1829
+ 'union',
1830
+ 'unsigned',
1831
+ 'void',
1832
+ 'volatile',
1833
+ 'while',
1834
+ ]),
1835
+
1836
+ cpp: new Set([
1837
+ 'alignas',
1838
+ 'alignof',
1839
+ 'and',
1840
+ 'auto',
1841
+ 'bool',
1842
+ 'break',
1843
+ 'case',
1844
+ 'catch',
1845
+ 'class',
1846
+ 'const',
1847
+ 'constexpr',
1848
+ 'continue',
1849
+ 'delete',
1850
+ 'do',
1851
+ 'double',
1852
+ 'else',
1853
+ 'enum',
1854
+ 'explicit',
1855
+ 'export',
1856
+ 'extern',
1857
+ 'false',
1858
+ 'float',
1859
+ 'for',
1860
+ 'friend',
1861
+ 'if',
1862
+ 'inline',
1863
+ 'int',
1864
+ 'long',
1865
+ 'mutable',
1866
+ 'namespace',
1867
+ 'new',
1868
+ 'noexcept',
1869
+ 'nullptr',
1870
+ 'operator',
1871
+ 'private',
1872
+ 'protected',
1873
+ 'public',
1874
+ 'return',
1875
+ 'short',
1876
+ 'signed',
1877
+ 'sizeof',
1878
+ 'static',
1879
+ 'struct',
1880
+ 'switch',
1881
+ 'template',
1882
+ 'this',
1883
+ 'throw',
1884
+ 'true',
1885
+ 'try',
1886
+ 'typedef',
1887
+ 'typename',
1888
+ 'union',
1889
+ 'unsigned',
1890
+ 'using',
1891
+ 'virtual',
1892
+ 'void',
1893
+ 'while',
1894
+ ]),
1895
+
1896
+ php: new Set([
1897
+ 'abstract',
1898
+ 'and',
1899
+ 'array',
1900
+ 'as',
1901
+ 'break',
1902
+ 'callable',
1903
+ 'case',
1904
+ 'catch',
1905
+ 'class',
1906
+ 'clone',
1907
+ 'const',
1908
+ 'continue',
1909
+ 'declare',
1910
+ 'default',
1911
+ 'do',
1912
+ 'echo',
1913
+ 'else',
1914
+ 'elseif',
1915
+ 'empty',
1916
+ 'enddeclare',
1917
+ 'endfor',
1918
+ 'endforeach',
1919
+ 'endif',
1920
+ 'endswitch',
1921
+ 'endwhile',
1922
+ 'extends',
1923
+ 'final',
1924
+ 'finally',
1925
+ 'fn',
1926
+ 'for',
1927
+ 'foreach',
1928
+ 'function',
1929
+ 'global',
1930
+ 'goto',
1931
+ 'if',
1932
+ 'implements',
1933
+ 'include',
1934
+ 'include_once',
1935
+ 'instanceof',
1936
+ 'interface',
1937
+ 'match',
1938
+ 'namespace',
1939
+ 'new',
1940
+ 'null',
1941
+ 'or',
1942
+ 'private',
1943
+ 'protected',
1944
+ 'public',
1945
+ 'require',
1946
+ 'require_once',
1947
+ 'return',
1948
+ 'static',
1949
+ 'switch',
1950
+ 'throw',
1951
+ 'trait',
1952
+ 'try',
1953
+ 'use',
1954
+ 'var',
1955
+ 'while',
1956
+ 'yield',
1957
+ ]),
1958
+
1959
+ rust: new Set([
1960
+ 'as',
1961
+ 'break',
1962
+ 'const',
1963
+ 'continue',
1964
+ 'crate',
1965
+ 'else',
1966
+ 'enum',
1967
+ 'extern',
1968
+ 'false',
1969
+ 'fn',
1970
+ 'for',
1971
+ 'if',
1972
+ 'impl',
1973
+ 'in',
1974
+ 'let',
1975
+ 'loop',
1976
+ 'match',
1977
+ 'mod',
1978
+ 'move',
1979
+ 'mut',
1980
+ 'pub',
1981
+ 'ref',
1982
+ 'return',
1983
+ 'self',
1984
+ 'Self',
1985
+ 'static',
1986
+ 'struct',
1987
+ 'super',
1988
+ 'trait',
1989
+ 'true',
1990
+ 'type',
1991
+ 'unsafe',
1992
+ 'use',
1993
+ 'where',
1994
+ 'while',
1995
+ ]),
1996
+
1997
+ html: new Set([
1998
+ 'html',
1999
+ 'head',
2000
+ 'body',
2001
+ 'div',
2002
+ 'span',
2003
+ 'p',
2004
+ 'a',
2005
+ 'img',
2006
+ 'video',
2007
+ 'audio',
2008
+ 'script',
2009
+ 'style',
2010
+ 'link',
2011
+ 'meta',
2012
+ 'form',
2013
+ 'input',
2014
+ 'button',
2015
+ 'table',
2016
+ 'tr',
2017
+ 'td',
2018
+ 'th',
2019
+ 'ul',
2020
+ 'ol',
2021
+ 'li',
2022
+ 'section',
2023
+ 'article',
2024
+ 'header',
2025
+ 'footer',
2026
+ 'nav',
2027
+ 'main',
2028
+ ]),
2029
+
2030
+ bash: new Set([
2031
+ 'if',
2032
+ 'then',
2033
+ 'else',
2034
+ 'elif',
2035
+ 'fi',
2036
+ 'for',
2037
+ 'while',
2038
+ 'do',
2039
+ 'done',
2040
+ 'case',
2041
+ 'esac',
2042
+ 'function',
2043
+ 'in',
2044
+ 'select',
2045
+ 'until',
2046
+ 'break',
2047
+ 'continue',
2048
+ 'return',
2049
+ 'export',
2050
+ 'readonly',
2051
+ 'local',
2052
+ 'declare',
2053
+ ]),
2054
+
2055
+ markdown: new Set(['#', '##', '###', '####', '#####', '######']),
2056
+ };
2057
+
2058
+ if (!lang || lang === 'txt' || lang === 'text' || lang === 'plaintext') {
2059
+ return {
2060
+ codeBlock: [
2061
+ {
2062
+ codeContent: code,
2063
+ highlightType: 0,
2064
+ },
2065
+ ],
2066
+ unified_codeBlock: [
2067
+ {
2068
+ content: code,
2069
+ type: 'DEFAULT',
2070
+ },
2071
+ ],
2072
+ };
2073
+ }
2074
+
2075
+ const TYPE_MAP = {
2076
+ 0: 'DEFAULT',
2077
+ 1: 'KEYWORD',
2078
+ 2: 'METHOD',
2079
+ 3: 'STR',
2080
+ 4: 'NUMBER',
2081
+ 5: 'COMMENT',
2082
+ };
2083
+
2084
+ const keywords = keywordsMap[lang.toLowerCase()] || new Set();
2085
+ const tokens = [];
2086
+
2087
+ let i = 0;
2088
+
2089
+ const push = (content, type) => {
2090
+ if (!content) return;
2091
+
2092
+ const last = tokens[tokens.length - 1];
2093
+
2094
+ if (last && last.highlightType === type) {
2095
+ last.codeContent += content;
2096
+ } else {
2097
+ tokens.push({
2098
+ codeContent: content,
2099
+ highlightType: type,
2100
+ });
2101
+ }
2102
+ };
2103
+
2104
+ const isIdentifier = (char) => {
2105
+ switch (lang.toLowerCase()) {
2106
+ case 'css':
2107
+ return /[a-zA-Z0-9_$-]/.test(char);
2108
+
2109
+ case 'html':
2110
+ return /[a-zA-Z0-9_$:-]/.test(char);
2111
+
2112
+ default:
2113
+ return /[a-zA-Z0-9_$]/.test(char);
2114
+ }
2115
+ };
2116
+
2117
+ while (i < code.length) {
2118
+ const c = code[i];
2119
+
2120
+ if (/\s/.test(c)) {
2121
+ let s = i;
2122
+
2123
+ while (i < code.length && /\s/.test(code[i])) {
2124
+ i++;
2125
+ }
2126
+
2127
+ push(code.slice(s, i), 0);
2128
+ continue;
2129
+ }
2130
+
2131
+ if ((c === '/' && code[i + 1] === '/') || (c === '#' && ['python', 'bash'].includes(lang))) {
2132
+ let s = i;
2133
+
2134
+ while (i < code.length && code[i] !== '\n') {
2135
+ i++;
2136
+ }
2137
+
2138
+ push(code.slice(s, i), 5);
2139
+ continue;
2140
+ }
2141
+
2142
+ if (c === '"' || c === "'" || c === '`') {
2143
+ let s = i;
2144
+ const q = c;
2145
+
2146
+ i++;
2147
+
2148
+ while (i < code.length) {
2149
+ if (code[i] === '\\' && i + 1 < code.length) {
2150
+ i += 2;
2151
+ } else if (code[i] === q) {
2152
+ i++;
2153
+ break;
2154
+ } else {
2155
+ i++;
2156
+ }
2157
+ }
2158
+
2159
+ push(code.slice(s, i), 3);
2160
+ continue;
2161
+ }
2162
+
2163
+ if (/[0-9]/.test(c)) {
2164
+ let s = i;
2165
+
2166
+ while (i < code.length && /[0-9._]/.test(code[i])) {
2167
+ i++;
2168
+ }
2169
+
2170
+ push(code.slice(s, i), 4);
2171
+ continue;
2172
+ }
2173
+
2174
+ if (/[a-zA-Z_$]/.test(c)) {
2175
+ let s = i;
2176
+
2177
+ while (i < code.length && isIdentifier(code[i])) {
2178
+ i++;
2179
+ }
2180
+
2181
+ const word = code.slice(s, i);
2182
+
2183
+ let type = 0;
2184
+
2185
+ if (keywords.has(word)) {
2186
+ type = 1;
2187
+ } else if (lang === 'css') {
2188
+ let j = i;
2189
+
2190
+ while (j < code.length && /\s/.test(code[j])) {
2191
+ j++;
2192
+ }
2193
+
2194
+ if (code[j] === ':') {
2195
+ type = 1;
2196
+ }
2197
+ } else if (lang === 'html') {
2198
+ let p = s - 1;
2199
+
2200
+ while (p >= 0 && /\s/.test(code[p])) {
2201
+ p--;
2202
+ }
2203
+
2204
+ if (code[p] === '<' || (code[p] === '/' && code[p - 1] === '<')) {
2205
+ type = 1;
2206
+ }
2207
+ }
2208
+
2209
+ if (type === 0) {
2210
+ let j = i;
2211
+
2212
+ while (j < code.length && /\s/.test(code[j])) {
2213
+ j++;
2214
+ }
2215
+
2216
+ if (code[j] === '(') {
2217
+ type = 2;
2218
+ }
2219
+ }
2220
+
2221
+ push(word, type);
2222
+ continue;
2223
+ }
2224
+
2225
+ push(c, 0);
2226
+ i++;
2227
+ }
2228
+
2229
+ return {
2230
+ codeBlock: tokens,
2231
+ unified_codeBlock: tokens.map((t) => ({
2232
+ content: t.codeContent,
2233
+ type: TYPE_MAP[t.highlightType],
2234
+ })),
2235
+ };
2236
+ }
2237
+
2238
+ static toTableMetadata(arr, { hyperlink = true, citation = true, latex = true } = {}) {
2239
+ if (!Array.isArray(arr) || !arr.every((row) => Array.isArray(row) && row.every((cell) => typeof cell === 'string'))) {
2240
+ throw new TypeError('Table must be a nested array of strings');
2241
+ }
2242
+
2243
+ const [header, ...rows] = arr;
2244
+
2245
+ const maxLen = Math.max(header.length, ...rows.map((r) => r.length));
2246
+
2247
+ const normalize = (r) => [...r, ...Array(maxLen - r.length).fill('')];
2248
+
2249
+ const unified_rows = [
2250
+ {
2251
+ is_header: true,
2252
+ cells: normalize(header),
2253
+ },
2254
+ ...rows.map((r) => ({
2255
+ is_header: false,
2256
+ cells: normalize(r),
2257
+ })),
2258
+ ].map((row) => {
2259
+ const markdown_cells = row.cells.map((cell) => {
2260
+ const extracted = extractIE(cell, { hyperlink, citation, latex });
2261
+
2262
+ return {
2263
+ text: extracted.text,
2264
+ ...(extracted.inline_entities.length ? { inline_entities: extracted.inline_entities } : {}),
2265
+ };
2266
+ });
2267
+
2268
+ return {
2269
+ ...row,
2270
+ ...(markdown_cells.some((c) => c.inline_entities?.length) ? { markdown_cells } : {}),
2271
+ };
2272
+ });
2273
+
2274
+ const rowsMeta = unified_rows.map((r) => ({
2275
+ items: r.cells,
2276
+ ...(r.is_header ? { isHeading: true } : {}),
2277
+ }));
2278
+
2279
+ return {
2280
+ title: '',
2281
+ rows: rowsMeta,
2282
+ unified_rows,
2283
+ };
2284
+ }
2285
+
2286
+ static newLayout(name, data, extra = {}) {
2287
+ return {
2288
+ ...extra,
2289
+ view_model: {
2290
+ [Array.isArray(data) ? 'primitives' : 'primitive']: data,
2291
+ __typename: `GenAI${name}LayoutViewModel`,
2292
+ },
2293
+ };
2294
+ }
2295
+ }
2296
+
2297
+ export { MESSAGE_BUILDER_VERSION, Button, ButtonV2, Carousel, AIRich, Toolkit };