@x4r1s3/baileys 0.0.0-stage → 1.0.1

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 (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1245 -2
  3. package/SECURITY.md +47 -0
  4. package/WAProto/V +1 -0
  5. package/WAProto/WAProto.proto +8892 -0
  6. package/WAProto/index.d.ts +104128 -0
  7. package/WAProto/index.js +334920 -0
  8. package/assets/rolling-circle.svg +133 -0
  9. package/assets/x4r1s3-banner.svg +32 -0
  10. package/engine-requirements.js +27 -0
  11. package/lib/Builders/A2UI.js +245 -0
  12. package/lib/Builders/AIRich.js +179 -0
  13. package/lib/Builders/Button.js +108 -0
  14. package/lib/Builders/CFC.js +284 -0
  15. package/lib/Builders/Carousel.js +81 -0
  16. package/lib/Call/THIRD_PARTY_LICENSE.txt +21 -0
  17. package/lib/Call/astralena-v3.mjs +96 -0
  18. package/lib/Call/audio-feeder.mjs +201 -0
  19. package/lib/Call/audio-recorder.mjs +250 -0
  20. package/lib/Call/fetch-wasm-resources.mjs +104 -0
  21. package/lib/Call/index.mjs +707 -0
  22. package/lib/Call/relay-transport.mjs +563 -0
  23. package/lib/Call/signaling.mjs +660 -0
  24. package/lib/Call/types.mjs +17 -0
  25. package/lib/Call/video-feeder.mjs +94 -0
  26. package/lib/Call/voip-resources.mjs +259 -0
  27. package/lib/Call/wasm-engine.mjs +1372 -0
  28. package/lib/Call/worker-bootstrap.mjs +1042 -0
  29. package/lib/Defaults/ban-checker.js +56 -0
  30. package/lib/Defaults/index.js +170 -0
  31. package/lib/Signal/Group/ciphertext-message.js +23 -0
  32. package/lib/Signal/Group/group-session-builder.js +41 -0
  33. package/lib/Signal/Group/group_cipher.js +93 -0
  34. package/lib/Signal/Group/index.js +23 -0
  35. package/lib/Signal/Group/keyhelper.js +29 -0
  36. package/lib/Signal/Group/sender-chain-key.js +37 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.js +74 -0
  38. package/lib/Signal/Group/sender-key-message.js +77 -0
  39. package/lib/Signal/Group/sender-key-name.js +59 -0
  40. package/lib/Signal/Group/sender-key-record.js +52 -0
  41. package/lib/Signal/Group/sender-key-state.js +95 -0
  42. package/lib/Signal/Group/sender-message-key.js +37 -0
  43. package/lib/Signal/libsignal.js +440 -0
  44. package/lib/Signal/lid-mapping.js +292 -0
  45. package/lib/Socket/Client/index.js +14 -0
  46. package/lib/Socket/Client/types.js +22 -0
  47. package/lib/Socket/Client/websocket.js +65 -0
  48. package/lib/Socket/aigroups.js +327 -0
  49. package/lib/Socket/ban-checker.js +165 -0
  50. package/lib/Socket/business.js +419 -0
  51. package/lib/Socket/chats.js +1921 -0
  52. package/lib/Socket/communities.js +443 -0
  53. package/lib/Socket/graphql.js +911 -0
  54. package/lib/Socket/groups.js +561 -0
  55. package/lib/Socket/index.js +49 -0
  56. package/lib/Socket/interactive-handler.js +612 -0
  57. package/lib/Socket/interop.js +575 -0
  58. package/lib/Socket/managed-account.js +220 -0
  59. package/lib/Socket/messages-recv.js +2193 -0
  60. package/lib/Socket/messages-send.js +4141 -0
  61. package/lib/Socket/mex.js +53 -0
  62. package/lib/Socket/newsletter.js +291 -0
  63. package/lib/Socket/privacy.js +458 -0
  64. package/lib/Socket/registration.js +440 -0
  65. package/lib/Socket/socket.js +1042 -0
  66. package/lib/Socket/status-actions.js +287 -0
  67. package/lib/Socket/username.js +241 -0
  68. package/lib/Store/index.js +16 -0
  69. package/lib/Store/make-cache-manager-store.js +101 -0
  70. package/lib/Store/make-in-memory-store.js +432 -0
  71. package/lib/Store/make-ordered-dictionary.js +90 -0
  72. package/lib/Store/object-repository.js +35 -0
  73. package/lib/Types/Auth.js +13 -0
  74. package/lib/Types/Bussines.js +13 -0
  75. package/lib/Types/Call.js +13 -0
  76. package/lib/Types/Chat.js +19 -0
  77. package/lib/Types/Contact.js +13 -0
  78. package/lib/Types/Events.js +13 -0
  79. package/lib/Types/GroupMetadata.js +13 -0
  80. package/lib/Types/Label.js +36 -0
  81. package/lib/Types/LabelAssociation.js +18 -0
  82. package/lib/Types/Message.js +30 -0
  83. package/lib/Types/Mex.js +53 -0
  84. package/lib/Types/Product.js +13 -0
  85. package/lib/Types/RichType.js +34 -0
  86. package/lib/Types/Signal.js +13 -0
  87. package/lib/Types/Socket.js +14 -0
  88. package/lib/Types/State.js +60 -0
  89. package/lib/Types/USync.js +13 -0
  90. package/lib/Types/index.js +37 -0
  91. package/lib/Utils/auth-utils.js +313 -0
  92. package/lib/Utils/ban-checker.js +48 -0
  93. package/lib/Utils/bot-capabilities.js +96 -0
  94. package/lib/Utils/bot-planning-replay.js +177 -0
  95. package/lib/Utils/browser-utils.js +40 -0
  96. package/lib/Utils/business.js +242 -0
  97. package/lib/Utils/c2582.js +147 -0
  98. package/lib/Utils/chat-utils.js +905 -0
  99. package/lib/Utils/companion-reg-client-utils.js +104 -0
  100. package/lib/Utils/consumer-application.js +114 -0
  101. package/lib/Utils/crypto.js +129 -0
  102. package/lib/Utils/decode-wa-message.js +496 -0
  103. package/lib/Utils/direct-chat-theme.js +164 -0
  104. package/lib/Utils/event-buffer.js +601 -0
  105. package/lib/Utils/experimental-proto.js +206 -0
  106. package/lib/Utils/games/miniapp.js +17 -0
  107. package/lib/Utils/games/slot-machine.js +270 -0
  108. package/lib/Utils/games/website-preview.js +306 -0
  109. package/lib/Utils/generics.js +402 -0
  110. package/lib/Utils/group-history.js +68 -0
  111. package/lib/Utils/group-wallpaper.js +168 -0
  112. package/lib/Utils/history.js +162 -0
  113. package/lib/Utils/identity-change-handler.js +60 -0
  114. package/lib/Utils/index.js +61 -0
  115. package/lib/Utils/jid-display-normalization.js +221 -0
  116. package/lib/Utils/link-preview.js +96 -0
  117. package/lib/Utils/logger.js +14 -0
  118. package/lib/Utils/lt-hash.js +19 -0
  119. package/lib/Utils/make-mutex.js +44 -0
  120. package/lib/Utils/message-composer.js +709 -0
  121. package/lib/Utils/message-inspect.js +79 -0
  122. package/lib/Utils/message-retry-manager.js +253 -0
  123. package/lib/Utils/message-security.js +167 -0
  124. package/lib/Utils/messages-media.js +1027 -0
  125. package/lib/Utils/messages.js +2467 -0
  126. package/lib/Utils/meta-ai-msmsg.js +215 -0
  127. package/lib/Utils/meta-compositing.js +239 -0
  128. package/lib/Utils/native-flow.js +158 -0
  129. package/lib/Utils/newsletter-live-update-utils.js +74 -0
  130. package/lib/Utils/newsletter-status-utils.js +152 -0
  131. package/lib/Utils/noise-handler.js +212 -0
  132. package/lib/Utils/offline-node-processor.js +51 -0
  133. package/lib/Utils/poll-manager.js +206 -0
  134. package/lib/Utils/portable-compat.js +12 -0
  135. package/lib/Utils/pre-key-manager.js +117 -0
  136. package/lib/Utils/process-message.js +610 -0
  137. package/lib/Utils/reporting-utils.js +269 -0
  138. package/lib/Utils/rich-message-utils.js +2841 -0
  139. package/lib/Utils/scheduled-message.js +107 -0
  140. package/lib/Utils/signal.js +212 -0
  141. package/lib/Utils/source-grep.js +57 -0
  142. package/lib/Utils/stanza-ack.js +49 -0
  143. package/lib/Utils/sticker-annotation.js +87 -0
  144. package/lib/Utils/sync-action-utils.js +59 -0
  145. package/lib/Utils/tc-token-utils.js +174 -0
  146. package/lib/Utils/use-multi-file-auth-state.js +132 -0
  147. package/lib/Utils/use-single-file-auth-state.js +108 -0
  148. package/lib/Utils/use-sqlite-auth-state.js +120 -0
  149. package/lib/Utils/validate-connection.js +221 -0
  150. package/lib/Utils/view-once-utils.js +218 -0
  151. package/lib/Utils/voip-rekey.js +32 -0
  152. package/lib/Utils/website-preview.js +27 -0
  153. package/lib/Utils/welcome-flow.js +228 -0
  154. package/lib/Utils/x4r1s3.js +144 -0
  155. package/lib/WABinary/constants.js +1475 -0
  156. package/lib/WABinary/decode.js +273 -0
  157. package/lib/WABinary/encode.js +231 -0
  158. package/lib/WABinary/generic-utils.js +242 -0
  159. package/lib/WABinary/index.js +17 -0
  160. package/lib/WABinary/jid-utils.js +107 -0
  161. package/lib/WABinary/types.js +13 -0
  162. package/lib/WAM/BinaryInfo.js +21 -0
  163. package/lib/WAM/constants.js +22864 -0
  164. package/lib/WAM/encode.js +161 -0
  165. package/lib/WAM/index.js +15 -0
  166. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +108 -0
  167. package/lib/WAUSync/Protocols/USyncContactProtocol.js +68 -0
  168. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +65 -0
  169. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +38 -0
  170. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +82 -0
  171. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +40 -0
  172. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +37 -0
  173. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +49 -0
  174. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +46 -0
  175. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +36 -0
  176. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -0
  177. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +40 -0
  178. package/lib/WAUSync/Protocols/index.js +24 -0
  179. package/lib/WAUSync/USyncQuery.js +213 -0
  180. package/lib/WAUSync/USyncUser.js +66 -0
  181. package/lib/WAUSync/index.js +15 -0
  182. package/lib/antiban.cjs +4726 -0
  183. package/lib/index.d.ts +1895 -0
  184. package/lib/index.js +41 -0
  185. package/package.json +125 -4
@@ -0,0 +1,709 @@
1
+ /**
2
+ * @X4R1S3
3
+ *
4
+ * File: lib/Utils/message-composer.js
5
+ * About: Message composer module for the X4R1S3 WhatsApp protocol client.
6
+ * Important exports: generateTableContent, generateListContent, generateCodeBlockContent, generateLatexContent, generateLatexImageContent, generateLatexInlineImageContent, captureUnifiedResponse, generateUnifiedResponseContent; …
7
+ * Directions: Import the listed exports and preserve protocol, validation, and compatibility invariants when modifying.
8
+ *
9
+ * Copyright and attribution notice.
10
+ * Do not copy, reproduce, redistribute, modify, or create derivative works
11
+ * from this source without explicit written permission.
12
+ */
13
+ import { proto } from '../../WAProto/index.js';
14
+ import { generateMessageIDV2 } from './generics.js';
15
+
16
+ // NOTE: tokenizeCode / CodeHighlightType / RichSubMessageType are intentionally
17
+ // kept module-local here — @X4R1S3/baileys already exports these from
18
+ // lib/Utils/rich-message-utils.js and lib/Types/RichType.js. The baron composer
19
+ // implementation is preserved internally so the generator helpers stay faithful.
20
+
21
+ const JS_KEYWORDS = new Set([
22
+ 'import',
23
+ 'export',
24
+ 'from',
25
+ 'default',
26
+ 'as',
27
+ 'const',
28
+ 'let',
29
+ 'var',
30
+ 'function',
31
+ 'class',
32
+ 'extends',
33
+ 'new',
34
+ 'return',
35
+ 'if',
36
+ 'else',
37
+ 'for',
38
+ 'while',
39
+ 'do',
40
+ 'switch',
41
+ 'case',
42
+ 'break',
43
+ 'continue',
44
+ 'try',
45
+ 'catch',
46
+ 'finally',
47
+ 'throw',
48
+ 'async',
49
+ 'await',
50
+ 'yield',
51
+ 'typeof',
52
+ 'instanceof',
53
+ 'in',
54
+ 'of',
55
+ 'delete',
56
+ 'void',
57
+ 'true',
58
+ 'false',
59
+ 'null',
60
+ 'undefined',
61
+ 'NaN',
62
+ 'Infinity',
63
+ 'this',
64
+ 'super',
65
+ 'static',
66
+ 'get',
67
+ 'set',
68
+ 'debugger',
69
+ 'with'
70
+ ]);
71
+
72
+ const PYTHON_KEYWORDS = new Set([
73
+ 'import',
74
+ 'from',
75
+ 'as',
76
+ 'def',
77
+ 'class',
78
+ 'return',
79
+ 'if',
80
+ 'elif',
81
+ 'else',
82
+ 'for',
83
+ 'while',
84
+ 'break',
85
+ 'continue',
86
+ 'try',
87
+ 'except',
88
+ 'finally',
89
+ 'raise',
90
+ 'with',
91
+ 'yield',
92
+ 'lambda',
93
+ 'pass',
94
+ 'del',
95
+ 'global',
96
+ 'nonlocal',
97
+ 'assert',
98
+ 'True',
99
+ 'False',
100
+ 'None',
101
+ 'and',
102
+ 'or',
103
+ 'not',
104
+ 'in',
105
+ 'is',
106
+ 'async',
107
+ 'await',
108
+ 'self',
109
+ 'print'
110
+ ]);
111
+
112
+ const LANGUAGE_KEYWORDS = {
113
+ javascript: JS_KEYWORDS,
114
+ typescript: JS_KEYWORDS,
115
+ js: JS_KEYWORDS,
116
+ ts: JS_KEYWORDS,
117
+ python: PYTHON_KEYWORDS,
118
+ py: PYTHON_KEYWORDS
119
+ };
120
+
121
+ const CodeHighlightType = {
122
+ DEFAULT: 0,
123
+ KEYWORD: 1,
124
+ METHOD: 2,
125
+ STRING: 3,
126
+ NUMBER: 4,
127
+ COMMENT: 5
128
+ };
129
+
130
+ const RichSubMessageType = {
131
+ UNKNOWN: 0,
132
+ GRID_IMAGE: 1,
133
+ TEXT: 2,
134
+ INLINE_IMAGE: 3,
135
+ TABLE: 4,
136
+ CODE: 5,
137
+ DYNAMIC: 6,
138
+ MAP: 7,
139
+ LATEX: 8,
140
+ CONTENT_ITEMS: 9
141
+ };
142
+
143
+ const tokenizeCode = (codeStr, language = 'javascript') => {
144
+ const keywords = LANGUAGE_KEYWORDS[language] || JS_KEYWORDS;
145
+ const blocks = [];
146
+ const lines = codeStr.split('\n');
147
+ for (let li = 0; li < lines.length; li++) {
148
+ const line = lines[li];
149
+ const isLast = li === lines.length - 1;
150
+ const nl = isLast ? '' : '\n';
151
+ if (!line.trim()) {
152
+ blocks.push({
153
+ highlightType: CodeHighlightType.DEFAULT,
154
+ codeContent: line + nl
155
+ });
156
+ continue;
157
+ }
158
+ if (line.trim().startsWith('//') || line.trim().startsWith('#')) {
159
+ blocks.push({
160
+ highlightType: CodeHighlightType.COMMENT,
161
+ codeContent: line + nl
162
+ });
163
+ continue;
164
+ }
165
+ const regex =
166
+ /(\/\/.*$|#.*$)|(["'`](?:[^"'`\\]|\\.)*["'`])|(\b\d+(?:\.\d+)?\b)|(\b[a-zA-Z_$][\w$]*\b)|([^\s\w$"'`]+)|(\s+)/g;
167
+ let match;
168
+ const tokens = [];
169
+ while ((match = regex.exec(line)) !== null) {
170
+ const val = match[0];
171
+ if (match[1]) {
172
+ tokens.push({
173
+ highlightType: CodeHighlightType.COMMENT,
174
+ codeContent: val
175
+ });
176
+ }
177
+ else if (match[2]) {
178
+ tokens.push({
179
+ highlightType: CodeHighlightType.STRING,
180
+ codeContent: val
181
+ });
182
+ }
183
+ else if (match[3]) {
184
+ tokens.push({
185
+ highlightType: CodeHighlightType.NUMBER,
186
+ codeContent: val
187
+ });
188
+ }
189
+ else if (match[4]) {
190
+ if (keywords.has(val)) {
191
+ tokens.push({
192
+ highlightType: CodeHighlightType.KEYWORD,
193
+ codeContent: val
194
+ });
195
+ }
196
+ else {
197
+ const after = line.slice(regex.lastIndex).trimStart();
198
+ if (after.startsWith('(')) {
199
+ tokens.push({
200
+ highlightType: CodeHighlightType.METHOD,
201
+ codeContent: val
202
+ });
203
+ }
204
+ else {
205
+ tokens.push({
206
+ highlightType: CodeHighlightType.DEFAULT,
207
+ codeContent: val
208
+ });
209
+ }
210
+ }
211
+ }
212
+ else {
213
+ tokens.push({
214
+ highlightType: CodeHighlightType.DEFAULT,
215
+ codeContent: val
216
+ });
217
+ }
218
+ }
219
+ if (tokens.length === 0) {
220
+ blocks.push({
221
+ highlightType: CodeHighlightType.DEFAULT,
222
+ codeContent: line + nl
223
+ });
224
+ continue;
225
+ }
226
+ const merged = [];
227
+ for (const t of tokens) {
228
+ const prev = merged.length > 0 ? merged[merged.length - 1] : undefined;
229
+ if (prev && prev.highlightType === t.highlightType) {
230
+ prev.codeContent += t.codeContent;
231
+ }
232
+ else {
233
+ merged.push({ ...t });
234
+ }
235
+ }
236
+ if (merged.length > 0) {
237
+ merged[merged.length - 1].codeContent += nl;
238
+ }
239
+ blocks.push(...merged);
240
+ }
241
+ return blocks;
242
+ };
243
+
244
+ const buildRichContextInfo = (quoted, options = {}) => {
245
+ const ctxInfo = {
246
+ forwardingScore: 1,
247
+ isForwarded: true,
248
+ forwardedAiBotMessageInfo: { botJid: options.botJid ? options.botJid : '867051314767696@bot' },
249
+ forwardOrigin: 4,
250
+ ...(options.mentions ? { mentionedJid: options.mentions } : {})
251
+ };
252
+ if (quoted?.key) {
253
+ ctxInfo.stanzaId = quoted.key.id;
254
+ ctxInfo.participant = quoted.key.participant || quoted.sender || quoted.key.remoteJid;
255
+ ctxInfo.quotedMessage = quoted.message;
256
+ }
257
+ return ctxInfo;
258
+ };
259
+
260
+ const buildBotForwardedMessage = (submessages, contextInfo, unifiedResponse) => {
261
+ const richResponse = {
262
+ messageType: 1,
263
+ submessages,
264
+ contextInfo
265
+ };
266
+ if (unifiedResponse) {
267
+ richResponse.unifiedResponse = unifiedResponse;
268
+ }
269
+ return {
270
+ botForwardedMessage: {
271
+ message: {
272
+ richResponseMessage: richResponse
273
+ }
274
+ }
275
+ };
276
+ };
277
+
278
+ export const generateTableContent = (title, headers, rows, quoted, options = {}) => {
279
+ const { footer, headerText } = options;
280
+ const safeHeaders = Array.isArray(headers) ? headers.map(String) : [];
281
+ const safeRows = Array.isArray(rows) ? rows : [];
282
+ const tableRows = [
283
+ { items: safeHeaders, isHeading: true },
284
+ ...safeRows.map(row => ({ items: Array.isArray(row) ? row.map(String) : [String(row)] }))
285
+ ];
286
+ const submessages = [];
287
+ if (headerText) {
288
+ submessages.push({ messageType: 2, messageText: headerText });
289
+ }
290
+ submessages.push({
291
+ messageType: 4,
292
+ tableMetadata: { title, rows: tableRows }
293
+ });
294
+ if (footer) {
295
+ submessages.push({ messageType: 2, messageText: footer });
296
+ }
297
+ const ctxInfo = buildRichContextInfo(quoted);
298
+ return {
299
+ message: buildBotForwardedMessage(submessages, ctxInfo),
300
+ messageId: generateMessageIDV2()
301
+ };
302
+ };
303
+
304
+ export const generateListContent = (title, items, quoted, options = {}) => {
305
+ const { footer, headerText } = options;
306
+ const tableRows = items.map(item => ({
307
+ items: Array.isArray(item) ? item.map(String) : [String(item)]
308
+ }));
309
+ const submessages = [];
310
+ if (headerText) {
311
+ submessages.push({ messageType: 2, messageText: headerText });
312
+ }
313
+ submessages.push({
314
+ messageType: 4,
315
+ tableMetadata: { title, rows: tableRows }
316
+ });
317
+ if (footer) {
318
+ submessages.push({ messageType: 2, messageText: footer });
319
+ }
320
+ const ctxInfo = buildRichContextInfo(quoted);
321
+ return {
322
+ message: buildBotForwardedMessage(submessages, ctxInfo),
323
+ messageId: generateMessageIDV2()
324
+ };
325
+ };
326
+
327
+ export const generateCodeBlockContent = (code, quoted, options = {}) => {
328
+ const { title, footer, language = 'javascript' } = options;
329
+ const submessages = [];
330
+ if (title) {
331
+ submessages.push({ messageType: 2, messageText: title });
332
+ }
333
+ submessages.push({
334
+ messageType: 5,
335
+ codeMetadata: {
336
+ codeLanguage: language,
337
+ codeBlocks: tokenizeCode(code, language)
338
+ }
339
+ });
340
+ if (footer) {
341
+ submessages.push({ messageType: 2, messageText: footer });
342
+ }
343
+ const ctxInfo = buildRichContextInfo(quoted);
344
+ return {
345
+ message: buildBotForwardedMessage(submessages, ctxInfo),
346
+ messageId: generateMessageIDV2()
347
+ };
348
+ };
349
+
350
+ export const generateLatexContent = (quoted, options = {}) => {
351
+ const { text, expressions = [], headerText, footer } = options;
352
+ const submessages = [];
353
+ if (headerText) {
354
+ submessages.push({ messageType: 2, messageText: headerText });
355
+ }
356
+ const latexExpressions = expressions.map(expr => {
357
+ const entry = {
358
+ latexExpression: expr.latexExpression,
359
+ url: expr.url,
360
+ width: expr.width,
361
+ height: expr.height
362
+ };
363
+ if (expr.fontHeight !== undefined) entry.fontHeight = expr.fontHeight;
364
+ if (expr.imageTopPadding !== undefined) entry.imageTopPadding = expr.imageTopPadding;
365
+ if (expr.imageLeadingPadding !== undefined) entry.imageLeadingPadding = expr.imageLeadingPadding;
366
+ if (expr.imageBottomPadding !== undefined) entry.imageBottomPadding = expr.imageBottomPadding;
367
+ if (expr.imageTrailingPadding !== undefined) entry.imageTrailingPadding = expr.imageTrailingPadding;
368
+ return entry;
369
+ });
370
+ submessages.push({
371
+ messageType: 8,
372
+ latexMetadata: {
373
+ text: text || '',
374
+ expressions: latexExpressions
375
+ }
376
+ });
377
+ if (footer) {
378
+ submessages.push({ messageType: 2, messageText: footer });
379
+ }
380
+ const ctxInfo = buildRichContextInfo(quoted);
381
+ return {
382
+ message: buildBotForwardedMessage(submessages, ctxInfo),
383
+ messageId: generateMessageIDV2()
384
+ };
385
+ };
386
+
387
+ const extractRichSubmessages = (generated) => generated?.message?.botForwardedMessage?.message?.richResponseMessage?.submessages || [];
388
+
389
+ /**
390
+ * Compose ordered RichAI submessage types into one forwarded rich response.
391
+ * `sections` preserves caller order; supported types include text, table, list,
392
+ * code, LaTeX, images, dynamic media, maps, and content-item carousels.
393
+ */
394
+ export const generateRichAIResponseContent = (content, quoted, options = {}) => {
395
+ if (!content || typeof content !== 'object' || Array.isArray(content)) {
396
+ throw new TypeError('sendRichAIResponse content must be an object');
397
+ }
398
+ const shorthandTypes = ['table', 'list', 'codeBlock', 'latex', 'plain', 'text', 'gridImage', 'inlineImage', 'dynamic', 'map', 'contentItems'];
399
+ const sections = Array.isArray(content.sections)
400
+ ? content.sections
401
+ : shorthandTypes
402
+ .filter(type => Object.hasOwn(content, type))
403
+ .map(type => ({ type, value: content[type] }));
404
+ if (sections.length === 0) {
405
+ throw new TypeError(`sendRichAIResponse expected one or more of: ${shorthandTypes.join(', ')}`);
406
+ }
407
+ const submessages = [];
408
+ const normalizeImageUrl = (value, fieldName) => {
409
+ const descriptor = typeof value === 'string' ? { sourceUrl: value } : value;
410
+ if (!descriptor || typeof descriptor !== 'object' || Array.isArray(descriptor)) {
411
+ throw new TypeError(`sendRichAIResponse ${fieldName} must be a URL string or image URL object`);
412
+ }
413
+ const baseUrl = descriptor.sourceUrl || descriptor.source_url || descriptor.url || descriptor.imageUrl || descriptor.image || '';
414
+ const previewUrl = descriptor.imagePreviewUrl || descriptor.previewUrl || descriptor.preview_url || baseUrl;
415
+ const highResUrl = descriptor.imageHighResUrl || descriptor.highResUrl || descriptor.high_res_url || descriptor.fullUrl || descriptor.full_url || baseUrl;
416
+ const sourceUrl = descriptor.sourceUrl || descriptor.source_url || baseUrl || previewUrl || highResUrl;
417
+ if (!previewUrl && !highResUrl && !sourceUrl) {
418
+ throw new TypeError(`sendRichAIResponse ${fieldName} requires an image URL`);
419
+ }
420
+ return {
421
+ ...(previewUrl ? { imagePreviewUrl: String(previewUrl) } : {}),
422
+ ...(highResUrl ? { imageHighResUrl: String(highResUrl) } : {}),
423
+ ...(sourceUrl ? { sourceUrl: String(sourceUrl) } : {})
424
+ };
425
+ };
426
+ for (const [index, section] of sections.entries()) {
427
+ if (!section || typeof section !== 'object' || Array.isArray(section)) {
428
+ throw new TypeError(`sendRichAIResponse section ${index} must be an object`);
429
+ }
430
+ const { type, options: sectionOptions, value: explicitValue, ...inlinePayload } = section;
431
+ const payload = Object.hasOwn(section, 'value')
432
+ ? explicitValue
433
+ : (type && Object.hasOwn(section, type) ? section[type] : inlinePayload);
434
+ const generatorOptions = {
435
+ ...options,
436
+ ...(sectionOptions && typeof sectionOptions === 'object' && !Array.isArray(sectionOptions) ? sectionOptions : {})
437
+ };
438
+ let generated;
439
+ const sectionSubmessages = [];
440
+ if (type === 'table') {
441
+ const { title = '', headers = [], rows = [], ...rest } = payload && typeof payload === 'object' ? payload : {};
442
+ generated = generateTableContent(title, headers, rows, quoted, { ...generatorOptions, ...rest });
443
+ }
444
+ else if (type === 'list') {
445
+ const { title = '', items = [], ...rest } = payload && typeof payload === 'object' ? payload : {};
446
+ if (!Array.isArray(items)) {
447
+ throw new TypeError(`sendRichAIResponse section ${index} list.items must be an array`);
448
+ }
449
+ generated = generateListContent(title, items, quoted, { ...generatorOptions, ...rest });
450
+ }
451
+ else if (type === 'codeBlock') {
452
+ const { language = 'javascript', code = '', ...rest } = payload && typeof payload === 'object' ? payload : {};
453
+ generated = generateCodeBlockContent(code || '', quoted, { ...generatorOptions, language, ...rest });
454
+ }
455
+ else if (type === 'latex') {
456
+ const latex = payload;
457
+ const text = typeof latex === 'string' ? latex : latex?.text || '';
458
+ const expressions = typeof latex === 'string'
459
+ ? [{ latexExpression: latex }]
460
+ : latex?.expressions || [{ latexExpression: text }];
461
+ generated = generateLatexContent(quoted, {
462
+ ...generatorOptions,
463
+ text,
464
+ expressions,
465
+ ...(latex && typeof latex === 'object' && !Array.isArray(latex) ? latex : {})
466
+ });
467
+ }
468
+ else if (type === 'plain' || type === 'text') {
469
+ const text = typeof payload === 'string' ? payload : payload?.text ?? payload?.messageText;
470
+ if (text === undefined || text === null) {
471
+ throw new TypeError(`sendRichAIResponse section ${index} plain text requires text or value`);
472
+ }
473
+ sectionSubmessages.push({
474
+ messageType: RichSubMessageType.TEXT,
475
+ messageText: String(text),
476
+ ...(Array.isArray(payload?.inlineEntities) ? { inlineEntities: payload.inlineEntities } : {})
477
+ });
478
+ }
479
+ else if (type === 'gridImage') {
480
+ const grid = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : {};
481
+ const rawImageUrls = Array.isArray(payload) ? payload : grid.imageUrls ?? grid.images;
482
+ const rawGridImageUrl = grid.gridImageUrl;
483
+ if (rawImageUrls !== undefined && !Array.isArray(rawImageUrls)) {
484
+ throw new TypeError(`sendRichAIResponse section ${index} gridImage.imageUrls must be an array`);
485
+ }
486
+ if ((!rawImageUrls || rawImageUrls.length === 0) && !rawGridImageUrl) {
487
+ throw new TypeError(`sendRichAIResponse section ${index} gridImage requires imageUrls or gridImageUrl`);
488
+ }
489
+ if (rawImageUrls && rawImageUrls.length > 0 && rawImageUrls.length < 2) {
490
+ throw new TypeError(`sendRichAIResponse section ${index} gridImage.imageUrls requires at least two images`);
491
+ }
492
+ sectionSubmessages.push({
493
+ messageType: RichSubMessageType.GRID_IMAGE,
494
+ gridImageMetadata: {
495
+ ...(rawGridImageUrl ? { gridImageUrl: normalizeImageUrl(rawGridImageUrl, 'gridImage.gridImageUrl') } : {}),
496
+ ...(rawImageUrls?.length ? { imageUrls: rawImageUrls.map((image) => normalizeImageUrl(image, 'gridImage.imageUrls')) } : {})
497
+ }
498
+ });
499
+ }
500
+ else if (type === 'inlineImage') {
501
+ const image = typeof payload === 'string' ? { url: payload } : (payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : {});
502
+ const rawImageUrl = image.imageUrl ?? image.url ?? image.image;
503
+ if (rawImageUrl === undefined || rawImageUrl === null || rawImageUrl === '') {
504
+ throw new TypeError(`sendRichAIResponse section ${index} inlineImage requires imageUrl or url`);
505
+ }
506
+ sectionSubmessages.push({
507
+ messageType: RichSubMessageType.INLINE_IMAGE,
508
+ imageMetadata: {
509
+ imageUrl: normalizeImageUrl(rawImageUrl, 'inlineImage.imageUrl'),
510
+ ...(image.imageText ?? image.text ? { imageText: String(image.imageText ?? image.text) } : {}),
511
+ ...(image.alignment !== undefined ? { alignment: image.alignment } : {}),
512
+ ...(image.tapLinkUrl ? { tapLinkUrl: String(image.tapLinkUrl) } : {})
513
+ }
514
+ });
515
+ }
516
+ else if (type === 'dynamic') {
517
+ const dynamic = typeof payload === 'string' ? { url: payload } : (payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : {});
518
+ const url = dynamic.url || dynamic.imageUrl || dynamic.mediaUrl;
519
+ if (typeof url !== 'string' || !url.trim()) {
520
+ throw new TypeError(`sendRichAIResponse section ${index} dynamic requires a URL`);
521
+ }
522
+ const dynamicTypeName = String(dynamic.mediaType || dynamic.dynamicType || dynamic.kind || dynamic.type || 'IMAGE').toUpperCase();
523
+ const dynamicTypes = proto.AIRichResponseDynamicMetadata.AIRichResponseDynamicMetadataType;
524
+ const dynamicType = dynamicTypeName === 'GIF'
525
+ ? dynamicTypes.AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_GIF
526
+ : dynamicTypeName === 'IMAGE'
527
+ ? dynamicTypes.AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_IMAGE
528
+ : undefined;
529
+ if (dynamicType === undefined) {
530
+ throw new TypeError(`sendRichAIResponse section ${index} dynamic mediaType must be IMAGE or GIF`);
531
+ }
532
+ const version = Number(dynamic.version ?? 1);
533
+ if (!Number.isFinite(version) || version < 0) {
534
+ throw new TypeError(`sendRichAIResponse section ${index} dynamic.version must be a non-negative number`);
535
+ }
536
+ const loopCount = dynamic.loopCount == null ? undefined : Number(dynamic.loopCount);
537
+ if (loopCount !== undefined && (!Number.isFinite(loopCount) || loopCount < 0)) {
538
+ throw new TypeError(`sendRichAIResponse section ${index} dynamic.loopCount must be a non-negative number`);
539
+ }
540
+ sectionSubmessages.push({
541
+ messageType: RichSubMessageType.DYNAMIC,
542
+ dynamicMetadata: {
543
+ type: dynamicType,
544
+ version,
545
+ url,
546
+ ...(loopCount === undefined ? {} : { loopCount })
547
+ }
548
+ });
549
+ }
550
+ else if (type === 'map') {
551
+ const map = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload.mapMetadata || payload : {};
552
+ if (map.centerLatitude == null || map.centerLongitude == null ||
553
+ !Number.isFinite(Number(map.centerLatitude)) || !Number.isFinite(Number(map.centerLongitude))) {
554
+ throw new TypeError(`sendRichAIResponse section ${index} map requires finite centerLatitude and centerLongitude`);
555
+ }
556
+ const mapText = map.text ?? (payload && typeof payload === 'object' ? payload.text : undefined);
557
+ if (mapText) sectionSubmessages.push({ messageType: RichSubMessageType.TEXT, messageText: String(mapText) });
558
+ sectionSubmessages.push({
559
+ messageType: RichSubMessageType.MAP,
560
+ mapMetadata: {
561
+ centerLatitude: Number(map.centerLatitude),
562
+ centerLongitude: Number(map.centerLongitude),
563
+ ...(map.latitudeDelta == null ? {} : { latitudeDelta: Number(map.latitudeDelta) }),
564
+ ...(map.longitudeDelta == null ? {} : { longitudeDelta: Number(map.longitudeDelta) }),
565
+ showInfoList: Boolean(map.showInfoList),
566
+ annotations: (Array.isArray(map.annotations) ? map.annotations : []).map((annotation, annotationIndex) => ({
567
+ annotationNumber: annotation?.annotationNumber ?? annotationIndex + 1,
568
+ latitude: Number(annotation?.latitude),
569
+ longitude: Number(annotation?.longitude),
570
+ title: String(annotation?.title || ''),
571
+ body: String(annotation?.body || '')
572
+ }))
573
+ }
574
+ });
575
+ }
576
+ else if (type === 'contentItems') {
577
+ const items = Array.isArray(payload) ? payload : payload?.itemsMetadata ?? payload?.items;
578
+ if (!Array.isArray(items) || items.length === 0) {
579
+ throw new TypeError(`sendRichAIResponse section ${index} contentItems requires a non-empty items or itemsMetadata array`);
580
+ }
581
+ const contentType = payload && typeof payload === 'object' && !Array.isArray(payload)
582
+ ? payload.contentType ?? proto.AIRichResponseContentItemsMetadata.ContentType.CAROUSEL
583
+ : proto.AIRichResponseContentItemsMetadata.ContentType.CAROUSEL;
584
+ sectionSubmessages.push({
585
+ messageType: RichSubMessageType.CONTENT_ITEMS,
586
+ contentItemsMetadata: {
587
+ itemsMetadata: items.map((item) => {
588
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
589
+ throw new TypeError(`sendRichAIResponse section ${index} contentItems entries must be objects`);
590
+ }
591
+ return Object.hasOwn(item, 'reelItem') ? item : { reelItem: item };
592
+ }),
593
+ contentType
594
+ }
595
+ });
596
+ }
597
+ else {
598
+ throw new TypeError(`sendRichAIResponse section ${index} has unknown type '${String(type)}'; expected ${shorthandTypes.join(', ')}`);
599
+ }
600
+ if (generated) sectionSubmessages.push(...extractRichSubmessages(generated));
601
+ submessages.push(...sectionSubmessages);
602
+ }
603
+ if (submessages.length === 0) {
604
+ throw new TypeError('sendRichAIResponse did not produce any rich content sections');
605
+ }
606
+ return {
607
+ message: buildBotForwardedMessage(submessages, buildRichContextInfo(quoted, options)),
608
+ messageId: generateMessageIDV2()
609
+ };
610
+ };
611
+
612
+ export const generateLatexImageContent = async (quoted, options, uploadFn, renderLatexToPng) => {
613
+ const { text, expressions, headerText, footer } = options;
614
+ const submessages = [];
615
+ if (headerText) {
616
+ submessages.push({ messageType: 2, messageText: headerText });
617
+ }
618
+ const latexExpressions = await Promise.all(
619
+ expressions.map(async expr => {
620
+ const { buffer, width, height } = await renderLatexToPng(expr.latexExpression);
621
+ const uploadResult = await uploadFn(buffer, 'image');
622
+ const imageUrl = uploadResult.url || uploadResult.directPath;
623
+ return {
624
+ latexExpression: expr.latexExpression,
625
+ url: imageUrl,
626
+ width,
627
+ height
628
+ };
629
+ })
630
+ );
631
+ submessages.push({
632
+ messageType: 8,
633
+ latexMetadata: {
634
+ text: text || '',
635
+ expressions: latexExpressions
636
+ }
637
+ });
638
+ if (footer) {
639
+ submessages.push({ messageType: 2, messageText: footer });
640
+ }
641
+ const ctxInfo = buildRichContextInfo(quoted);
642
+ return {
643
+ message: buildBotForwardedMessage(submessages, ctxInfo),
644
+ messageId: generateMessageIDV2()
645
+ };
646
+ };
647
+
648
+ export const generateLatexInlineImageContent = async (quoted, options, uploadFn, renderLatexToPng) => {
649
+ const { text, expressions, headerText, footer } = options;
650
+ const submessages = [];
651
+ if (headerText) {
652
+ submessages.push({ messageType: 2, messageText: headerText });
653
+ }
654
+ if (text) {
655
+ submessages.push({ messageType: 2, messageText: text });
656
+ }
657
+ for (const expr of expressions) {
658
+ const { buffer, width, height } = await renderLatexToPng(expr.latexExpression);
659
+ const uploadResult = await uploadFn(buffer, 'image');
660
+ const imageUrl = uploadResult.url || uploadResult.directPath;
661
+ submessages.push({
662
+ messageType: 3,
663
+ imageMetadata: {
664
+ imageUrl: {
665
+ imagePreviewUrl: imageUrl,
666
+ imageHighResUrl: imageUrl
667
+ },
668
+ imageText: expr.latexExpression,
669
+ alignment: 2
670
+ }
671
+ });
672
+ }
673
+ if (footer) {
674
+ submessages.push({ messageType: 2, messageText: footer });
675
+ }
676
+ const ctxInfo = buildRichContextInfo(quoted);
677
+ return {
678
+ message: buildBotForwardedMessage(submessages, ctxInfo),
679
+ messageId: generateMessageIDV2()
680
+ };
681
+ };
682
+
683
+ export const captureUnifiedResponse = (msg) => {
684
+ const botFwd = msg?.botForwardedMessage?.message;
685
+ if (!botFwd) return null;
686
+ const rich = botFwd.richResponseMessage;
687
+ if (!rich?.unifiedResponse?.data) return null;
688
+ return {
689
+ unifiedResponse: { data: rich.unifiedResponse.data },
690
+ submessages: rich.submessages || [],
691
+ contextInfo: rich.contextInfo || {}
692
+ };
693
+ };
694
+
695
+ export const generateUnifiedResponseContent = (quoted, captured) => {
696
+ const ctxInfo = buildRichContextInfo(quoted);
697
+ return {
698
+ message: buildBotForwardedMessage(captured.submessages, ctxInfo, captured.unifiedResponse),
699
+ messageId: generateMessageIDV2()
700
+ };
701
+ };
702
+
703
+ export const generateRichMessageContent = (submessages, quoted, options) => {
704
+ const ctxInfo = buildRichContextInfo(quoted, options);
705
+ return {
706
+ message: buildBotForwardedMessage(submessages, ctxInfo),
707
+ messageId: generateMessageIDV2()
708
+ };
709
+ };