@hiroosy/baileys-lite 0.0.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +658 -10
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +702 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -0,0 +1,530 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { generateMessageIDV2 } from '../utils/wa-protocol-core.js'
3
+
4
+ const MESSAGE_EDIT_TYPE = 14
5
+
6
+ const newLayout = (name, data, extra = {}) => ({
7
+ ...extra,
8
+ view_model: { [Array.isArray(data) ? 'primitives' : 'primitive']: data, __typename: `GenAI${name}LayoutViewModel` }
9
+ })
10
+
11
+ const extractInlineEntities = (text, { hyperlink = true, citation = true, latex = true } = {}) => {
12
+ const toEntity = (type, ie) => {
13
+ if (type === 'hyperlink') {
14
+ return { key: ie.key, metadata: { display_name: ie.text, is_trusted: ie.is_trusted, url: ie.url, __typename: 'GenAIInlineLinkItem' } }
15
+ }
16
+ if (type === 'citation') {
17
+ return {
18
+ key: ie.key,
19
+ metadata: { reference_id: ie.reference_id, reference_url: ie.url, reference_title: ie.url, reference_display_name: ie.url, sources: [], __typename: 'GenAISearchCitationItem' }
20
+ }
21
+ }
22
+ if (type === 'latex') {
23
+ return {
24
+ key: ie.key,
25
+ metadata: {
26
+ latex_expression: ie.text,
27
+ latex_image: { url: ie.url, width: Number(ie.width) || 100, height: Number(ie.height) || 100 },
28
+ font_height: Number(ie.font_height) || 83.333333333333,
29
+ padding: Number(ie.padding) || 15,
30
+ __typename: 'GenAILatexItem'
31
+ }
32
+ }
33
+ }
34
+ }
35
+
36
+ const inline_entities = []
37
+ let result = ''
38
+ let last = 0
39
+ let citationIndex = 1
40
+ let hyperlinkIndex = 0
41
+ let latexIndex = 0
42
+ const stack = []
43
+
44
+ for (let i = 0; i < text.length; i++) {
45
+ if (text[i] === '[' && text[i - 1] !== '\\') {
46
+ stack.push(i)
47
+ continue
48
+ }
49
+ if (text[i] === ']' && (text[i + 1] === '(' || text[i + 1] === '<')) {
50
+ const start = stack.pop()
51
+ if (start == null) continue
52
+ const open = text[i + 1]
53
+ const close = open === '(' ? ')' : '>'
54
+ const kind = open === '(' ? 'link' : 'latex'
55
+ let end = i + 2
56
+ let depth = 1
57
+ while (end < text.length && depth) {
58
+ if (text[end] === open && text[end - 1] !== '\\') depth++
59
+ else if (text[end] === close && text[end - 1] !== '\\') depth--
60
+ end++
61
+ }
62
+ if (depth) continue
63
+
64
+ const raw = text.slice(start + 1, i).trim()
65
+ const url = text.slice(i + 2, end - 1).trim()
66
+ let key, tag, type, ie
67
+
68
+ if (kind === 'latex') {
69
+ if (!latex) continue
70
+ const [txt = '', width = null, height = null, fontHeight = null, padding = null] = raw.split('|')
71
+ key = `_LATEX_${latexIndex++}`
72
+ tag = `{{${key}}}${txt || 'image'}{{/${key}}}`
73
+ type = 'latex'
74
+ ie = { key, text: txt, url, width, height, font_height: fontHeight, padding }
75
+ } else if (raw) {
76
+ if (!hyperlink) continue
77
+ const trusted = !url.startsWith('!')
78
+ key = `_HYPERLINK_${hyperlinkIndex++}`
79
+ tag = `{{${key}}}${trusted ? url : url.slice(1)}{{/${key}}}`
80
+ type = 'hyperlink'
81
+ ie = { key, text: raw, url: trusted ? url : url.slice(1), is_trusted: trusted }
82
+ } else {
83
+ if (!citation) continue
84
+ key = `_CITATION_${citationIndex - 1}`
85
+ tag = `{{${key}}}${url}{{/${key}}}`
86
+ type = 'citation'
87
+ ie = { reference_id: citationIndex++, key, text: '', url }
88
+ }
89
+
90
+ result += text.slice(last, start) + tag
91
+ last = end
92
+ const entity = toEntity(type, ie)
93
+ if (entity) inline_entities.push(entity)
94
+ i = end - 1
95
+ }
96
+ }
97
+ result += text.slice(last)
98
+ return { text: result, inline_entities }
99
+ }
100
+
101
+ const toTableMetadata = (rows, { hyperlink = true, citation = true, latex = true } = {}) => {
102
+ if (!Array.isArray(rows) || !rows.every(row => Array.isArray(row) && row.every(cell => typeof cell === 'string'))) {
103
+ throw new TypeError('Table must be a nested array of strings')
104
+ }
105
+ const [header, ...body] = rows
106
+ const maxLen = Math.max(header.length, ...body.map(r => r.length))
107
+ const normalize = r => [...r, ...Array(maxLen - r.length).fill('')]
108
+
109
+ const unifiedRows = [{ is_header: true, cells: normalize(header) }, ...body.map(r => ({ is_header: false, cells: normalize(r) }))].map(row => {
110
+ const markdownCells = row.cells.map(cell => {
111
+ const extracted = extractInlineEntities(cell, { hyperlink, citation, latex })
112
+ return { text: extracted.text, ...(extracted.inline_entities.length ? { inline_entities: extracted.inline_entities } : {}) }
113
+ })
114
+ return { ...row, ...(markdownCells.some(c => c.inline_entities?.length) ? { markdown_cells: markdownCells } : {}) }
115
+ })
116
+
117
+ return {
118
+ title: '',
119
+ rows: unifiedRows.map(r => ({ items: r.cells, ...(r.is_header ? { isHeading: true } : {}) })),
120
+ unifiedRows
121
+ }
122
+ }
123
+
124
+ const KEYWORD_SETS = {
125
+ javascript: new Set(['break','case','catch','continue','debugger','delete','do','else','finally','for','function','if','in','instanceof','new','return','switch','this','throw','typeof','var','void','while','with','true','false','null','undefined','class','const','let','super','extends','export','import','yield','static','async','await','get','set']),
126
+ typescript: new Set(['abstract','any','as','asserts','bigint','boolean','declare','enum','implements','infer','interface','is','keyof','module','namespace','never','readonly','require','number','object','override','private','protected','public','satisfies','string','symbol','type','unknown','using','from','break','case','catch','continue','do','else','finally','for','function','if','new','return','switch','this','throw','try','var','void','while','class','const','let','extends','import','export','async','await']),
127
+ python: new Set(['False','None','True','and','as','assert','async','await','break','class','continue','def','del','elif','else','except','finally','for','from','global','if','import','in','is','lambda','nonlocal','not','or','pass','raise','return','try','while','with','yield']),
128
+ java: new Set(['abstract','assert','boolean','break','byte','case','catch','char','class','const','continue','default','do','double','else','enum','extends','final','finally','float','for','goto','if','implements','import','instanceof','int','interface','long','native','new','package','private','protected','public','return','short','static','strictfp','super','switch','synchronized','this','throw','throws','transient','try','void','volatile','while']),
129
+ go: new Set(['break','case','chan','const','continue','default','defer','else','fallthrough','for','func','go','goto','if','import','interface','map','package','range','return','select','struct','switch','type','var']),
130
+ golang: new Set(['break','case','chan','const','continue','default','defer','else','fallthrough','for','func','go','goto','if','import','interface','map','package','range','return','select','struct','switch','type','var']),
131
+ c: new Set(['auto','break','case','char','const','continue','default','do','double','else','enum','extern','float','for','goto','if','int','long','register','return','short','signed','sizeof','static','struct','switch','typedef','union','unsigned','void','volatile','while']),
132
+ cpp: new Set(['alignas','alignof','and','auto','bool','break','case','catch','class','const','constexpr','continue','delete','do','double','else','enum','explicit','export','extern','false','float','for','friend','if','inline','int','long','mutable','namespace','new','noexcept','nullptr','operator','private','protected','public','return','short','signed','sizeof','static','struct','switch','template','this','throw','true','try','typedef','typename','union','unsigned','using','virtual','void','while']),
133
+ php: new Set(['abstract','and','array','as','break','callable','case','catch','class','clone','const','continue','declare','default','do','echo','else','elseif','empty','enddeclare','endfor','endforeach','endif','endswitch','endwhile','extends','final','finally','fn','for','foreach','function','global','goto','if','implements','include','include_once','instanceof','interface','match','namespace','new','null','or','private','protected','public','require','require_once','return','static','switch','throw','trait','try','use','var','while','yield']),
134
+ rust: new Set(['as','break','const','continue','crate','else','enum','extern','false','fn','for','if','impl','in','let','loop','match','mod','move','mut','pub','ref','return','self','Self','static','struct','super','trait','true','type','unsafe','use','where','while']),
135
+ html: new Set(['html','head','body','div','span','p','a','img','video','audio','script','style','link','meta','form','input','button','table','tr','td','th','ul','ol','li','section','article','header','footer','nav','main']),
136
+ bash: new Set(['if','then','else','elif','fi','for','while','do','done','case','esac','function','in','select','until','break','continue','return','export','readonly','local','declare'])
137
+ }
138
+ const HL = { DEFAULT: 0, KEYWORD: 1, METHOD: 2, STRING: 3, NUMBER: 4, COMMENT: 5 }
139
+ const HL_NAME = ['DEFAULT', 'KEYWORD', 'METHOD', 'STR', 'NUMBER', 'COMMENT']
140
+
141
+ export const tokenizeAIRichCode = (code, lang = 'javascript') => {
142
+ const key = (lang || '').toLowerCase()
143
+ if (!key || key === 'txt' || key === 'text' || key === 'plaintext') return [{ codeContent: code, highlightType: HL.DEFAULT }]
144
+
145
+ const keywords = KEYWORD_SETS[key] || new Set()
146
+ const tokens = []
147
+ const isIdentifier = c => (key === 'css' ? /[a-zA-Z0-9_$-]/.test(c) : key === 'html' ? /[a-zA-Z0-9_$:-]/.test(c) : /[a-zA-Z0-9_$]/.test(c))
148
+ const push = (content, type) => {
149
+ if (!content) return
150
+ const last = tokens[tokens.length - 1]
151
+ if (last && last.highlightType === type) last.codeContent += content
152
+ else tokens.push({ codeContent: content, highlightType: type })
153
+ }
154
+
155
+ let i = 0
156
+ while (i < code.length) {
157
+ const c = code[i]
158
+ if (/\s/.test(c)) {
159
+ const s = i
160
+ while (i < code.length && /\s/.test(code[i])) i++
161
+ push(code.slice(s, i), HL.DEFAULT)
162
+ continue
163
+ }
164
+ if ((c === '/' && code[i + 1] === '/') || (c === '#' && (key === 'python' || key === 'bash'))) {
165
+ const s = i
166
+ while (i < code.length && code[i] !== '\n') i++
167
+ push(code.slice(s, i), HL.COMMENT)
168
+ continue
169
+ }
170
+ if (c === '"' || c === "'" || c === '`') {
171
+ const s = i
172
+ const q = c
173
+ i++
174
+ while (i < code.length) {
175
+ if (code[i] === '\\' && i + 1 < code.length) i += 2
176
+ else if (code[i] === q) {
177
+ i++
178
+ break
179
+ } else i++
180
+ }
181
+ push(code.slice(s, i), HL.STRING)
182
+ continue
183
+ }
184
+ if (/[0-9]/.test(c)) {
185
+ const s = i
186
+ while (i < code.length && /[0-9._]/.test(code[i])) i++
187
+ push(code.slice(s, i), HL.NUMBER)
188
+ continue
189
+ }
190
+ if (/[a-zA-Z_$]/.test(c)) {
191
+ const s = i
192
+ while (i < code.length && isIdentifier(code[i])) i++
193
+ const word = code.slice(s, i)
194
+ let type = HL.DEFAULT
195
+ if (keywords.has(word)) type = HL.KEYWORD
196
+ else {
197
+ let j = i
198
+ while (j < code.length && /\s/.test(code[j])) j++
199
+ if (code[j] === '(') type = HL.METHOD
200
+ }
201
+ push(word, type)
202
+ continue
203
+ }
204
+ push(c, HL.DEFAULT)
205
+ i++
206
+ }
207
+ return tokens
208
+ }
209
+
210
+ const mediaUrl = value => {
211
+ if (Buffer.isBuffer(value)) return `data:application/octet-stream;base64,${value.toString('base64')}`
212
+ if (value && typeof value === 'object' && typeof value.url === 'string') return value.url
213
+ return typeof value === 'string' ? value : undefined
214
+ }
215
+
216
+ export class AIRichBuilder {
217
+
218
+ constructor(client) {
219
+ this._client = client
220
+ this._title = ''
221
+ this._footer = ''
222
+ this._contextInfo = {}
223
+ this._submessages = []
224
+ this._sections = []
225
+ this._richResponseSources = []
226
+ this._embeddedScreens = []
227
+ }
228
+
229
+ setTitle(title) {
230
+ if (typeof title !== 'string') throw new TypeError('Title must be a string')
231
+ this._title = title
232
+ return this
233
+ }
234
+
235
+ setFooter(footer) {
236
+ if (typeof footer !== 'string') throw new TypeError('Footer must be a string')
237
+ this._footer = footer
238
+ return this
239
+ }
240
+
241
+ setContextInfo(obj) {
242
+ if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) throw new TypeError('ContextInfo must be a plain object')
243
+ this._contextInfo = obj
244
+ return this
245
+ }
246
+
247
+ addText(text, { hyperlink = true, citation = true, latex = true } = {}) {
248
+ if (typeof text !== 'string') throw new TypeError('Text must be a string')
249
+ const { text: extractedText, inline_entities } = extractInlineEntities(text, { hyperlink, citation, latex })
250
+ this._submessages.push({ messageType: 2, messageText: extractedText })
251
+ this._sections.push(newLayout('Single', { text: extractedText, ...(inline_entities.length ? { inline_entities } : {}), __typename: 'GenAIMarkdownTextUXPrimitive' }))
252
+ return this
253
+ }
254
+
255
+ addCode(language, code) {
256
+ if (typeof language !== 'string' || typeof code !== 'string') throw new TypeError('Language and code must be a string')
257
+ const codeBlocks = tokenizeAIRichCode(code, language)
258
+ this._submessages.push({ messageType: 5, codeMetadata: { codeLanguage: language, codeBlocks } })
259
+ this._sections.push(
260
+ newLayout('Single', {
261
+ language,
262
+ code_blocks: codeBlocks.map(b => ({ content: b.codeContent, type: HL_NAME[b.highlightType] })),
263
+ __typename: 'GenAICodeUXPrimitive'
264
+ })
265
+ )
266
+ return this
267
+ }
268
+
269
+ addTable(table, { hyperlink = true, citation = true, latex = true } = {}) {
270
+ if (!Array.isArray(table)) throw new TypeError('Table must be an array')
271
+ const meta = toTableMetadata(table, { hyperlink, citation, latex })
272
+ this._submessages.push({ messageType: 4, tableMetadata: { title: meta.title, rows: meta.rows } })
273
+ this._sections.push(newLayout('Single', { rows: meta.unifiedRows, __typename: 'GenATableUXPrimitive' }))
274
+ return this
275
+ }
276
+
277
+ addImage(image) {
278
+ if (!(typeof image === 'string' || Buffer.isBuffer(image) || (Array.isArray(image) && image.every(v => typeof v === 'string' || Buffer.isBuffer(v))))) {
279
+ throw new TypeError('image must be a string | buffer | array of string/buffer')
280
+ }
281
+ const list = (Array.isArray(image) ? image : [image]).map(mediaUrl).filter(Boolean)
282
+ this._submessages.push({ messageType: 1, gridImageMetadata: { gridImageUrl: { imagePreviewUrl: list[0] }, imageUrls: list.map(u => ({ imagePreviewUrl: u, imageHighResUrl: u, sourceUrl: u })) } })
283
+ for (const url of list) this._sections.push(newLayout('Single', { media: { url, mime_type: 'image/png' }, imagine_type: 'IMAGE', status: { status: 'READY' }, __typename: 'GenAIImaginePrimitive' }))
284
+ return this
285
+ }
286
+
287
+ addVideo(video) {
288
+ const items = Array.isArray(video) ? video : [video]
289
+ this._submessages.push({ messageType: 2, messageText: '[ VIDEO ]' })
290
+ for (const item of items) {
291
+ const isObj = item && typeof item === 'object' && !Buffer.isBuffer(item)
292
+ const url = mediaUrl(isObj ? item.url : item)
293
+ this._sections.push(
294
+ newLayout('Single', {
295
+ media: { url, mime_type: (isObj && item.mimeType) || 'video/mp4', file_length: (isObj && item.fileLength) || 0, duration: (isObj && item.duration) || 0 },
296
+ imagine_type: 'ANIMATE',
297
+ status: { status: 'READY' },
298
+ thumbnail: { raw_media: isObj ? item.thumbnail : undefined },
299
+ __typename: 'GenAIImaginePrimitive'
300
+ })
301
+ )
302
+ }
303
+ return this
304
+ }
305
+
306
+ addSource(sources = []) {
307
+ const isFlat = Array.isArray(sources) && sources.every(item => typeof item === 'string')
308
+ const list = isFlat ? [sources] : sources
309
+ if (!(Array.isArray(list) && list.every(item => Array.isArray(item) && item.every(v => typeof v === 'string')))) {
310
+ throw new TypeError('Sources must be a string array or an array of string arrays')
311
+ }
312
+ const mapped = list.map(([icon, url, text]) => ({
313
+ source_type: 'THIRD_PARTY',
314
+ source_display_name: text ?? '',
315
+ source_subtitle: 'AI',
316
+ source_url: url ?? '',
317
+ favicon: { url: icon ?? '', mime_type: 'image/jpeg', width: 16, height: 16 }
318
+ }))
319
+ this._sections.push(newLayout('Single', { sources: mapped, __typename: 'GenAISearchResultPrimitive' }))
320
+ return this
321
+ }
322
+
323
+ addProduct(data = {}) {
324
+ const items = Array.isArray(data) ? data : [data]
325
+ this._submessages.push({ messageType: 2, messageText: '[ PRODUCT ]' })
326
+ const products = items.map(item => ({
327
+ title: item.title,
328
+ brand: item.brand,
329
+ price: item.price,
330
+ sale_price: item.sale_price,
331
+ product_url: item.product_url ?? item.url,
332
+ image: { url: mediaUrl(item.image_url ?? item.image) },
333
+ additional_images: [{ url: mediaUrl(item.icon_url ?? item.icon) }],
334
+ __typename: 'GenAIProductItemCardPrimitive'
335
+ }))
336
+ this._sections.push(newLayout(Array.isArray(data) ? 'HScroll' : 'Single', Array.isArray(data) ? products : products[0]))
337
+ return this
338
+ }
339
+
340
+ addPost(data = {}) {
341
+ const posts = Array.isArray(data) ? data : [data]
342
+ this._submessages.push({ messageType: 2, messageText: '[ POST ]' })
343
+ const primitives = posts.map(p => ({
344
+ title: p.title ?? '',
345
+ subtitle: p.subtitle ?? '',
346
+ username: p.username ?? '',
347
+ profile_picture_url: mediaUrl(p.profile_picture_url ?? p.profile_url ?? p.profile),
348
+ is_verified: !!(p.is_verified || p.verified),
349
+ thumbnail_url: mediaUrl(p.thumbnail_url ?? p.thumbnail),
350
+ post_caption: p.post_caption ?? p.caption ?? '',
351
+ likes_count: p.likes_count ?? p.like ?? 0,
352
+ comments_count: p.comments_count ?? p.comment ?? 0,
353
+ shares_count: p.shares_count ?? p.share ?? 0,
354
+ post_url: p.post_url ?? p.url ?? '',
355
+ post_deeplink: p.post_deeplink ?? p.deeplink ?? '',
356
+ source_app: p.source_app || p.source || 'INSTAGRAM',
357
+ footer_label: p.footer_label ?? p.footer ?? '',
358
+ footer_icon: mediaUrl(p.footer_icon ?? p.icon),
359
+ is_carousel: posts.length > 1,
360
+ orientation: p.orientation ?? 'LANDSCAPE',
361
+ post_type: p.post_type ?? 'VIDEO',
362
+ __typename: 'GenAIPostPrimitive'
363
+ }))
364
+ this._sections.push(newLayout('HScroll', primitives))
365
+ return this
366
+ }
367
+
368
+ addReels(data = []) {
369
+ const items = Array.isArray(data) ? data : [data]
370
+ const reels = items.map(item => ({ ...item, _avatar: mediaUrl(item.profileIconUrl ?? item.profile_url ?? item.profile), _thumbnail: mediaUrl(item.thumbnailUrl ?? item.thumbnail) }))
371
+ this._submessages.push({
372
+ messageType: 9,
373
+ contentItemsMetadata: { contentType: 1, itemsMetadata: reels.map(item => ({ reelItem: { title: item.username ?? '', profileIconUrl: item._avatar, thumbnailUrl: item._thumbnail, videoUrl: item.videoUrl ?? item.url ?? '' } })) }
374
+ })
375
+ reels.forEach((item, idx) =>
376
+ this._richResponseSources.push({ thumbnailCdnUrl: item._thumbnail, sourceProviderUrl: item.videoUrl ?? item.url ?? '', sourceQuery: '', faviconCdnUrl: item._avatar, citationNumber: idx + 1, sourceTitle: item.username ?? '' })
377
+ )
378
+ this._sections.push(
379
+ newLayout(
380
+ 'HScroll',
381
+ reels.map(item => ({
382
+ reels_url: item.videoUrl ?? item.url ?? '',
383
+ thumbnail_url: item._thumbnail,
384
+ creator: item.username ?? item.title ?? '',
385
+ avatar_url: item._avatar,
386
+ reels_title: item.reels_title ?? item.title ?? '',
387
+ likes_count: item.likes_count ?? item.like ?? 0,
388
+ shares_count: item.shares_count ?? item.share ?? 0,
389
+ view_count: item.view_count ?? item.view ?? 0,
390
+ reel_source: item.reel_source ?? item.source ?? 'IG',
391
+ is_verified: !!(item.is_verified || item.verified),
392
+ __typename: 'GenAIReelPrimitive'
393
+ }))
394
+ )
395
+ )
396
+ return this
397
+ }
398
+
399
+ addTip(text) {
400
+ this._submessages.push({ messageType: 2, messageText: text })
401
+ this._sections.push(newLayout('Single', { text, __typename: 'GenAIMetadataTextPrimitive' }))
402
+ return this
403
+ }
404
+
405
+ addSuggest(suggestion, { scroll = true, layout } = {}) {
406
+ if (!(typeof suggestion === 'string' || (Array.isArray(suggestion) && suggestion.every(v => typeof v === 'string')))) {
407
+ throw new TypeError('Suggestion must be a string or array of strings')
408
+ }
409
+ const items = (Array.isArray(suggestion) ? suggestion : [suggestion]).map(text => ({ prompt_text: text, prompt_type: 'SUGGESTED_PROMPT', __typename: 'GenAIFollowUpSuggestionPillPrimitive' }))
410
+ const type = layout ?? (items.length === 1 ? 'Single' : scroll ? 'HScroll' : 'ActionRow')
411
+ this._sections.push(newLayout(type, type === 'Single' ? items[0] : items, { __typename: 'GenAIUnifiedResponseSection' }))
412
+ return this
413
+ }
414
+
415
+ addProcess(title) {
416
+ if (typeof title !== 'string') throw new TypeError('Process title must be a string')
417
+ this._submessages.push({ messageType: 2, messageText: title })
418
+ this._sections.push(newLayout('Single', { icon: null, is_in_progress: true, meta_search_apps: null, target_secondary_screen_id: null, target_secondary_screen_tab_id: null, title, __typename: 'GenAIBotProgressStatusPrimitive' }))
419
+ return this
420
+ }
421
+
422
+ addHtml(...args) {
423
+ let options = {}
424
+ if (args.length && typeof args[args.length - 1] === 'object' && !Array.isArray(args[args.length - 1])) options = args.pop()
425
+ const url = options.url ?? ''
426
+ const trustedSources = options.trustedSources ?? []
427
+
428
+ if (args.length === 1 && typeof args[0] === 'string') {
429
+ this._submessages.push({ messageType: 2, messageText: '[ HTML ]' })
430
+ this._sections.push(newLayout('Single', { payload: args[0], url, trusted_sources: trustedSources, __typename: 'GenAIaeacdsnwHtmlPrimitive' }))
431
+ return this
432
+ }
433
+ if (!args.every(item => Array.isArray(item) && typeof item[0] === 'string')) {
434
+ throw new TypeError('addHtml() expects a single HTML string, or one or more [html, title] pairs, with an optional trailing options object')
435
+ }
436
+ if (!this._embeddedScreens.length) this._embeddedScreens.push({ title: 'Preview', content: [{ __typename: 'FOAIDNixelButtonSheets', tabs: [] }] })
437
+ const tabs = this._embeddedScreens[0].content[0].tabs
438
+ this._submessages.push({ messageType: 2, messageText: '[ HTML ]' })
439
+ for (const [payload, title] of args) {
440
+ tabs.push({
441
+ id: `tab_${tabs.length}`,
442
+ tab_header: title ?? `Tab ${tabs.length + 1}`,
443
+ sections: [newLayout('Single', { payload, url, trusted_sources: trustedSources, __typename: 'GenAIaeacdsnwHtmlPrimitive' }, { __typename: 'GenAIUnifiedResponseSection' })],
444
+ step_entries: []
445
+ })
446
+ }
447
+ return this
448
+ }
449
+
450
+ build({ forwarded = true, quoted, quotedParticipant, botJid = '0@bot' } = {}) {
451
+ const forward = forwarded ? { forwardingScore: 1, isForwarded: true, forwardedAiBotMessageInfo: { botJid }, forwardOrigin: 4 } : {}
452
+ const qObj = quoted
453
+ ? { stanzaId: quoted?.key?.id || quoted?.id, participant: quotedParticipant || quoted?.key?.participant || quoted?.key?.remoteJid, quotedType: 0, quotedMessage: quoted?.message ?? quoted }
454
+ : {}
455
+
456
+ const sections = this._footer ? [...this._sections, newLayout('Single', { text: this._footer, __typename: 'GenAIMetadataTextPrimitive' })] : this._sections
457
+ const responseData = { response_id: randomUUID(), sections }
458
+ if (this._embeddedScreens.length) responseData.embedded_screens = this._embeddedScreens
459
+
460
+ const hasRenderableContent = sections.length > 0 || this._embeddedScreens.length > 0
461
+ const richResponseMessage = { messageType: 1, submessages: this._submessages, contextInfo: { ...forward, ...qObj, ...this._contextInfo } }
462
+ if (hasRenderableContent) richResponseMessage.unifiedResponse = { data: Buffer.from(JSON.stringify(responseData)).toString('base64') }
463
+
464
+ return {
465
+ messageContextInfo: { deviceListMetadata: {}, deviceListMetadataVersion: 2, botMetadata: { messageDisclaimerText: this._title, richResponseSourcesMetadata: { sources: this._richResponseSources } } },
466
+ botForwardedMessage: { message: { richResponseMessage } }
467
+ }
468
+ }
469
+
470
+ buildEdit(jid, targetKey, editedMessage) {
471
+ if (!jid) throw new Error('A jid is required to edit an aiRich message')
472
+ if (!targetKey?.id) throw new Error('A target message id is required to edit an aiRich message')
473
+ if (!editedMessage) throw new Error('editedMessage does not contain an aiRich response')
474
+ return {
475
+ botForwardedMessage: {
476
+ message: {
477
+ protocolMessage: {
478
+ key: { remoteJid: jid, fromMe: true, id: targetKey.id },
479
+ type: MESSAGE_EDIT_TYPE,
480
+ editedMessage,
481
+ timestampMs: Date.now()
482
+ }
483
+ }
484
+ }
485
+ }
486
+ }
487
+
488
+ async send(jid, { forwarded, quoted, quotedParticipant, botJid, ...sendOptions } = {}) {
489
+ if (!this._client) throw new Error('AIRichBuilder.send() needs a client — use sock.aiRich() or new AIRichBuilder(sock)')
490
+ const sent = await this._client.sendMessage(jid, { aiRich: this, forwarded, quoted, quotedParticipant, botJid }, sendOptions)
491
+ const richResponse = sent?.message?.botForwardedMessage?.message?.richResponseMessage
492
+ if (!sent?.key?.id || !richResponse?.unifiedResponse) return sent
493
+ try {
494
+ const userId = this._client.user?.id ?? this._client.authState?.creds?.me?.id
495
+ const edit = this.buildEdit(jid, sent.key, sent.message)
496
+ await this._client.relayMessage(jid, edit, {
497
+ messageId: generateMessageIDV2(userId),
498
+ additionalAttributes: { edit: '1' },
499
+ additionalNodes: sendOptions.additionalNodes,
500
+ useCachedGroupMetadata: sendOptions.useCachedGroupMetadata,
501
+ statusJidList: sendOptions.statusJidList
502
+ })
503
+ } catch (error) {
504
+ error.relayedKey = sent.key
505
+ throw error
506
+ }
507
+ return sent
508
+ }
509
+ }
510
+
511
+ export const aiRichBuilderFromSpec = spec => {
512
+ const b = new AIRichBuilder()
513
+ if (spec.title) b.setTitle(spec.title)
514
+ if (spec.footer) b.setFooter(spec.footer)
515
+ if (spec.contextInfo) b.setContextInfo(spec.contextInfo)
516
+ if (spec.text) b.addText(spec.text, spec.textOptions)
517
+ if (spec.code) b.addCode(spec.code.language, spec.code.code)
518
+ if (spec.table) b.addTable(spec.table, spec.tableOptions)
519
+ if (spec.image) b.addImage(spec.image)
520
+ if (spec.video) b.addVideo(spec.video)
521
+ if (spec.source) b.addSource(spec.source)
522
+ if (spec.product) b.addProduct(spec.product)
523
+ if (spec.post) b.addPost(spec.post)
524
+ if (spec.reels) b.addReels(spec.reels)
525
+ if (spec.tip) b.addTip(spec.tip)
526
+ if (spec.suggest) b.addSuggest(spec.suggest, spec.suggestOptions)
527
+ if (spec.process) b.addProcess(spec.process)
528
+ if (spec.html) b.addHtml(...(Array.isArray(spec.html[0]) ? spec.html : [spec.html]))
529
+ return b
530
+ }