amiudmodz 6.2.1 → 6.2.2

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