@zervonexx/baileys 5.0.0 → 5.0.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.
Files changed (127) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +4124 -4112
  3. package/WAProto/WAProto.json +1 -0
  4. package/WAProto/WAProto.proto +7160 -0
  5. package/WAProto/WAProtoCompile.js +264 -322
  6. package/WAProto/index.js +55 -95
  7. package/lib/Builders/AIRich.js +673 -673
  8. package/lib/Builders/auto.js +49 -49
  9. package/lib/Builders/base.js +144 -144
  10. package/lib/Builders/builders.js +588 -588
  11. package/lib/Builders/index.js +3 -3
  12. package/lib/Defaults/index.js +249 -248
  13. package/lib/Signal/index.js +2 -2
  14. package/lib/Signal/libsignal.js +526 -526
  15. package/lib/Signal/lid-mapping.js +282 -282
  16. package/lib/Socket/Client/index.js +1 -1
  17. package/lib/Socket/Client/types.js +9 -9
  18. package/lib/Socket/Client/websocket.js +83 -83
  19. package/lib/Socket/business.js +151 -151
  20. package/lib/Socket/chats.js +854 -854
  21. package/lib/Socket/communities.js +146 -146
  22. package/lib/Socket/groups.js +293 -293
  23. package/lib/Socket/index.js +17 -14
  24. package/lib/Socket/messages-recv.js +993 -993
  25. package/lib/Socket/messages-send.js +722 -722
  26. package/lib/Socket/mex.js +33 -33
  27. package/lib/Socket/newsletter.js +783 -783
  28. package/lib/Socket/registration.js +154 -154
  29. package/lib/Socket/socket.js +797 -797
  30. package/lib/Socket/spam-report.js +143 -143
  31. package/lib/Socket/username.js +81 -81
  32. package/lib/Socket/zervonex-handler.js +57 -57
  33. package/lib/Store/index.js +6 -6
  34. package/lib/Store/make-cache-manager-store.js +80 -80
  35. package/lib/Store/make-in-memory-store.js +426 -426
  36. package/lib/Store/make-ordered-dictionary.js +81 -81
  37. package/lib/Store/object-repository.js +30 -30
  38. package/lib/Store/reporting-info-store.js +37 -37
  39. package/lib/Types/Auth.js +1 -1
  40. package/lib/Types/Bussines.js +1 -1
  41. package/lib/Types/Call.js +1 -1
  42. package/lib/Types/Chat.js +7 -7
  43. package/lib/Types/Contact.js +1 -1
  44. package/lib/Types/Events.js +1 -1
  45. package/lib/Types/GroupMetadata.js +1 -1
  46. package/lib/Types/Label.js +24 -24
  47. package/lib/Types/LabelAssociation.js +6 -6
  48. package/lib/Types/Message.js +14 -14
  49. package/lib/Types/Newsletter.js +99 -99
  50. package/lib/Types/Product.js +1 -1
  51. package/lib/Types/Signal.js +1 -1
  52. package/lib/Types/Socket.js +14 -14
  53. package/lib/Types/State.js +26 -26
  54. package/lib/Types/USync.js +1 -1
  55. package/lib/Types/index.js +30 -30
  56. package/lib/Utils/auth-utils.js +159 -159
  57. package/lib/Utils/baileys-event-stream.js +32 -32
  58. package/lib/Utils/bot-capabilities.js +40 -40
  59. package/lib/Utils/bot-planning-replay.js +43 -43
  60. package/lib/Utils/browser-utils.js +29 -29
  61. package/lib/Utils/business.js +74 -74
  62. package/lib/Utils/chat-utils.js +316 -316
  63. package/lib/Utils/companion-reg-client-utils.js +19 -19
  64. package/lib/Utils/consumer-application.js +37 -37
  65. package/lib/Utils/crypto.js +52 -52
  66. package/lib/Utils/cstoken.js +14 -14
  67. package/lib/Utils/decode-wa-message.js +199 -199
  68. package/lib/Utils/event-buffer.js +272 -272
  69. package/lib/Utils/extras.js +186 -186
  70. package/lib/Utils/generics.js +195 -194
  71. package/lib/Utils/history.js +50 -50
  72. package/lib/Utils/identity-change-handler.js +18 -18
  73. package/lib/Utils/index.js +40 -40
  74. package/lib/Utils/link-preview.js +50 -50
  75. package/lib/Utils/logger.js +3 -2
  76. package/lib/Utils/lt-hash.js +3 -3
  77. package/lib/Utils/make-mutex.js +15 -15
  78. package/lib/Utils/message-composer.js +61 -61
  79. package/lib/Utils/message-retry-manager.js +47 -47
  80. package/lib/Utils/messages-media.js +501 -501
  81. package/lib/Utils/messages.js +944 -942
  82. package/lib/Utils/meta-ai-msmsg.js +121 -121
  83. package/lib/Utils/meta-compositing.js +74 -74
  84. package/lib/Utils/modern-messages.js +234 -234
  85. package/lib/Utils/native-flow.js +80 -80
  86. package/lib/Utils/noise-handler.js +160 -160
  87. package/lib/Utils/pre-key-manager.js +75 -75
  88. package/lib/Utils/process-message.js +400 -400
  89. package/lib/Utils/reporting-utils.js +170 -170
  90. package/lib/Utils/signal.js +166 -166
  91. package/lib/Utils/spam-report-utils.js +165 -165
  92. package/lib/Utils/sync-action-utils.js +33 -33
  93. package/lib/Utils/tc-token-utils.js +153 -153
  94. package/lib/Utils/use-keyv-auth-state.js +199 -199
  95. package/lib/Utils/use-multi-file-auth-state.js +83 -83
  96. package/lib/Utils/validate-connection.js +171 -171
  97. package/lib/WABinary/constants.js +1320 -1320
  98. package/lib/WABinary/decode.js +151 -151
  99. package/lib/WABinary/encode.js +139 -139
  100. package/lib/WABinary/generic-utils.js +202 -202
  101. package/lib/WABinary/index.js +6 -6
  102. package/lib/WABinary/jid-utils.js +235 -235
  103. package/lib/WABinary/types.js +4 -4
  104. package/lib/WAM/BinaryInfo.js +9 -9
  105. package/lib/WAM/constants.js +22852 -22852
  106. package/lib/WAM/encode.js +149 -149
  107. package/lib/WAM/index.js +3 -3
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -30
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -48
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -23
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -28
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -15
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -24
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -9
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -21
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -19
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -19
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -22
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -16
  120. package/lib/WAUSync/Protocols/index.js +12 -12
  121. package/lib/WAUSync/USyncQuery.js +88 -88
  122. package/lib/WAUSync/USyncUser.js +20 -20
  123. package/lib/WAUSync/index.js +3 -3
  124. package/lib/index.js +66 -66
  125. package/package.json +187 -192
  126. package/WAProto/fetcher.js +0 -68
  127. package/WAProto/parser.js +0 -334
@@ -1,40 +1,40 @@
1
- export * from './generics.js'
2
- export * from './decode-wa-message.js'
3
- export * from './messages.js'
4
- export * from './messages-media.js'
5
- export * from './validate-connection.js'
6
- export * from './crypto.js'
7
- export * from './signal.js'
8
- export * from './make-mutex.js'
9
- export * from './logger.js'
10
- export * from './noise-handler.js'
11
- export * from './history.js'
12
- export * from './chat-utils.js'
13
- export * from './cstoken.js'
14
- export * from './lt-hash.js'
15
- export * from './auth-utils.js'
16
- export * from './baileys-event-stream.js'
17
- export * from './use-multi-file-auth-state.js'
18
- export * from './use-keyv-auth-state.js'
19
- export * from './link-preview.js'
20
- export * from './event-buffer.js'
21
- export * from './process-message.js'
22
- export * from './message-retry-manager.js'
23
- export * from './browser-utils.js'
24
- export * from './identity-change-handler.js'
25
- export * from './reporting-utils.js'
26
- export * from './companion-reg-client-utils.js'
27
- export * from './tc-token-utils.js'
28
- export * from './meta-ai-msmsg.js'
29
- export * from './spam-report-utils.js'
30
- export * from './modern-messages.js'
31
- export * from './extras.js'
32
- export * from './native-flow.js'
33
- export * from './consumer-application.js'
34
- export * from './bot-capabilities.js'
35
- export * from './meta-compositing.js'
36
- export * from './bot-planning-replay.js'
37
- export * from './message-composer.js'
38
- export * from './business.js'
39
- export * from './pre-key-manager.js'
40
- export * from './sync-action-utils.js'
1
+ export * from './generics.js'
2
+ export * from './decode-wa-message.js'
3
+ export * from './messages.js'
4
+ export * from './messages-media.js'
5
+ export * from './validate-connection.js'
6
+ export * from './crypto.js'
7
+ export * from './signal.js'
8
+ export * from './make-mutex.js'
9
+ export * from './logger.js'
10
+ export * from './noise-handler.js'
11
+ export * from './history.js'
12
+ export * from './chat-utils.js'
13
+ export * from './cstoken.js'
14
+ export * from './lt-hash.js'
15
+ export * from './auth-utils.js'
16
+ export * from './baileys-event-stream.js'
17
+ export * from './use-multi-file-auth-state.js'
18
+ export * from './use-keyv-auth-state.js'
19
+ export * from './link-preview.js'
20
+ export * from './event-buffer.js'
21
+ export * from './process-message.js'
22
+ export * from './message-retry-manager.js'
23
+ export * from './browser-utils.js'
24
+ export * from './identity-change-handler.js'
25
+ export * from './reporting-utils.js'
26
+ export * from './companion-reg-client-utils.js'
27
+ export * from './tc-token-utils.js'
28
+ export * from './meta-ai-msmsg.js'
29
+ export * from './spam-report-utils.js'
30
+ export * from './modern-messages.js'
31
+ export * from './extras.js'
32
+ export * from './native-flow.js'
33
+ export * from './consumer-application.js'
34
+ export * from './bot-capabilities.js'
35
+ export * from './meta-compositing.js'
36
+ export * from './bot-planning-replay.js'
37
+ export * from './message-composer.js'
38
+ export * from './business.js'
39
+ export * from './pre-key-manager.js'
40
+ export * from './sync-action-utils.js'
@@ -1,51 +1,51 @@
1
- import { unfurl } from 'unfurl.js'
2
- import { prepareWAMessageMedia } from './messages.js'
3
- import { extractImageThumb, getHttpStream } from './messages-media.js'
4
-
5
- const THUMBNAIL_WIDTH = 192
6
- const TIMEOUT = 8_000
7
- const MAX_INFLIGHT = 1000
8
- const _inflight = new Map()
9
-
10
- const _normalize = text => { const t = text.trim(); return /^https?:\/\//i.test(t) ? t : `https://${t}` }
11
- const _extractImage = data => data?.open_graph?.images?.[0]?.url ?? data?.twitter_card?.images?.[0]?.url ?? data?.oEmbed?.thumbnails?.[0]?.url ?? data?.favicon ?? null
12
- const _previewType = image => image ? 5 : 0
13
- const _compressedThumb = async (url, opts) => (await extractImageThumb(getHttpStream(url, opts.fetchOpts), opts.thumbnailWidth ?? THUMBNAIL_WIDTH)).buffer
14
-
15
- const _resolveThumbnail = async (image, opts) => {
16
- if (!image) return {}
17
- if (opts.uploadImage) {
18
- try {
19
- const { imageMessage } = await prepareWAMessageMedia({ image: { url: image } }, { upload: opts.uploadImage, mediaTypeOverride: 'thumbnail-link', options: opts.fetchOpts })
20
- const jpeg = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : await _compressedThumb(image, opts).catch(() => undefined)
21
- return { jpegThumbnail: jpeg, highQualityThumbnail: imageMessage ?? undefined }
22
- } catch { }
23
- }
24
- try { return { jpegThumbnail: await _compressedThumb(image, opts) } } catch { return {} }
25
- }
26
-
27
- const _fetchMeta = async (url, opts) => {
28
- try {
29
- const data = await unfurl(url, { timeout: opts.fetchOpts?.timeout ?? TIMEOUT })
30
- const title = (data?.open_graph?.title !== data?.title ? data?.open_graph?.title : data?.title) ?? data?.oEmbed?.title
31
- if (!title) return undefined
32
- return { url: data?.open_graph?.url ?? url, title, description: data?.open_graph?.description ?? data?.description ?? data?.oEmbed?.author_name ?? '', image: _extractImage(data) }
33
- } catch (err) { opts.logger?.warn({ err: err?.message || err, url }, 'unfurl failed'); return undefined }
34
- }
35
-
36
- const _buildResult = async (meta, text, opts) => ({
37
- 'canonical-url': meta.url, 'matched-text': text,
38
- title: meta.title, description: meta.description,
39
- originalThumbnailUrl: meta.image, previewType: _previewType(meta.image),
40
- ...await _resolveThumbnail(meta.image, opts)
41
- })
42
-
43
- export const getUrlInfo = (text, opts = {}) => {
44
- const url = _normalize(text)
45
- if (_inflight.has(url)) return _inflight.get(url)
46
- if (_inflight.size >= MAX_INFLIGHT) return Promise.resolve(undefined)
47
- const o = { fetchOpts: { timeout: TIMEOUT, ...opts.fetchOpts }, thumbnailWidth: opts.thumbnailWidth ?? THUMBNAIL_WIDTH, uploadImage: opts.uploadImage, logger: opts.logger }
48
- const promise = (async () => { const meta = await _fetchMeta(url, o); return meta ? _buildResult(meta, text, o) : undefined })().finally(() => _inflight.delete(url))
49
- _inflight.set(url, promise)
50
- return promise
1
+ import { unfurl } from 'unfurl.js'
2
+ import { prepareWAMessageMedia } from './messages.js'
3
+ import { extractImageThumb, getHttpStream } from './messages-media.js'
4
+
5
+ const THUMBNAIL_WIDTH = 192
6
+ const TIMEOUT = 8_000
7
+ const MAX_INFLIGHT = 1000
8
+ const _inflight = new Map()
9
+
10
+ const _normalize = text => { const t = text.trim(); return /^https?:\/\//i.test(t) ? t : `https://${t}` }
11
+ const _extractImage = data => data?.open_graph?.images?.[0]?.url ?? data?.twitter_card?.images?.[0]?.url ?? data?.oEmbed?.thumbnails?.[0]?.url ?? data?.favicon ?? null
12
+ const _previewType = image => image ? 5 : 0
13
+ const _compressedThumb = async (url, opts) => (await extractImageThumb(getHttpStream(url, opts.fetchOpts), opts.thumbnailWidth ?? THUMBNAIL_WIDTH)).buffer
14
+
15
+ const _resolveThumbnail = async (image, opts) => {
16
+ if (!image) return {}
17
+ if (opts.uploadImage) {
18
+ try {
19
+ const { imageMessage } = await prepareWAMessageMedia({ image: { url: image } }, { upload: opts.uploadImage, mediaTypeOverride: 'thumbnail-link', options: opts.fetchOpts })
20
+ const jpeg = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : await _compressedThumb(image, opts).catch(() => undefined)
21
+ return { jpegThumbnail: jpeg, highQualityThumbnail: imageMessage ?? undefined }
22
+ } catch { }
23
+ }
24
+ try { return { jpegThumbnail: await _compressedThumb(image, opts) } } catch { return {} }
25
+ }
26
+
27
+ const _fetchMeta = async (url, opts) => {
28
+ try {
29
+ const data = await unfurl(url, { timeout: opts.fetchOpts?.timeout ?? TIMEOUT })
30
+ const title = (data?.open_graph?.title !== data?.title ? data?.open_graph?.title : data?.title) ?? data?.oEmbed?.title
31
+ if (!title) return undefined
32
+ return { url: data?.open_graph?.url ?? url, title, description: data?.open_graph?.description ?? data?.description ?? data?.oEmbed?.author_name ?? '', image: _extractImage(data) }
33
+ } catch (err) { opts.logger?.warn({ err: err?.message || err, url }, 'unfurl failed'); return undefined }
34
+ }
35
+
36
+ const _buildResult = async (meta, text, opts) => ({
37
+ 'canonical-url': meta.url, 'matched-text': text,
38
+ title: meta.title, description: meta.description,
39
+ originalThumbnailUrl: meta.image, previewType: _previewType(meta.image),
40
+ ...await _resolveThumbnail(meta.image, opts)
41
+ })
42
+
43
+ export const getUrlInfo = (text, opts = {}) => {
44
+ const url = _normalize(text)
45
+ if (_inflight.has(url)) return _inflight.get(url)
46
+ if (_inflight.size >= MAX_INFLIGHT) return Promise.resolve(undefined)
47
+ const o = { fetchOpts: { timeout: TIMEOUT, ...opts.fetchOpts }, thumbnailWidth: opts.thumbnailWidth ?? THUMBNAIL_WIDTH, uploadImage: opts.uploadImage, logger: opts.logger }
48
+ const promise = (async () => { const meta = await _fetchMeta(url, o); return meta ? _buildResult(meta, text, o) : undefined })().finally(() => _inflight.delete(url))
49
+ _inflight.set(url, promise)
50
+ return promise
51
51
  }
@@ -1,3 +1,4 @@
1
- import P from 'pino';
2
- export const logger = P({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
1
+ import P from 'pino';
2
+ const logger = P({ timestamp: () => `,"time":"${new Date().toJSON()}"` });
3
+ export { logger };
3
4
  export default logger;
@@ -1,3 +1,3 @@
1
- import { LTHashAntiTampering } from 'whatsapp-rust-bridge';
2
-
3
- export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering();
1
+ import { LTHashAntiTampering } from 'whatsapp-rust-bridge';
2
+
3
+ export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering();
@@ -1,16 +1,16 @@
1
- export const makeMutex = () => {
2
- let task = Promise.resolve()
3
- return {
4
- mutex(code) {
5
- task = task.catch(() => { }).then(code)
6
- return task
7
- }
8
- }
9
- }
10
-
11
- export const makeKeyedMutex = () => {
12
- const map = {}
13
- return {
14
- mutex(key, code) { if (!map[key]) map[key] = makeMutex(); return map[key].mutex(code) }
15
- }
1
+ export const makeMutex = () => {
2
+ let task = Promise.resolve()
3
+ return {
4
+ mutex(code) {
5
+ task = task.catch(() => { }).then(code)
6
+ return task
7
+ }
8
+ }
9
+ }
10
+
11
+ export const makeKeyedMutex = () => {
12
+ const map = {}
13
+ return {
14
+ mutex(key, code) { if (!map[key]) map[key] = makeMutex(); return map[key].mutex(code) }
15
+ }
16
16
  }
@@ -1,62 +1,62 @@
1
- import { generateMessageIDV2, tokenizeCode } from './generics.js'
2
- import { RichSubMessageType } from './bot-capabilities.js'
3
- import { proto } from '../../WAProto/index.js'
4
-
5
- const buildRichContextInfo = (quoted, options = {}) => {
6
- const ctx = { forwardingScore: 1, isForwarded: true, forwardedAiBotMessageInfo: { botJid: options.botJid || '867051314767696@bot' }, forwardOrigin: 4, ...(options.mentions ? { mentionedJid: options.mentions } : {}) }
7
- if (quoted?.key) { ctx.stanzaId = quoted.key.id; ctx.participant = quoted.key.participant || quoted.sender || quoted.key.remoteJid; ctx.quotedMessage = quoted.message }
8
- return ctx
9
- }
10
-
11
- const buildBotForwardedMessage = (submessages, contextInfo, unifiedResponse) => {
12
- const rich = { messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD, submessages, contextInfo }
13
- if (unifiedResponse) rich.unifiedResponse = unifiedResponse
14
- return { botForwardedMessage: { message: { richResponseMessage: rich } } }
15
- }
16
-
17
- const wrap = (sub, quoted, options) => ({ message: buildBotForwardedMessage(sub, buildRichContextInfo(quoted, options)), messageId: generateMessageIDV2() })
18
- const text = msg => ({ messageType: RichSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: msg })
19
- const table = (title, rows) => ({ messageType: RichSubMessageType.AI_RICH_RESPONSE_TABLE, tableMetadata: { title, rows } })
20
-
21
- export const generateTableContent = (title, headers, rows, quoted, options = {}) => {
22
- const { footer, headerText } = options
23
- const sub = [...(headerText ? [text(headerText)] : []), table(title, [{ items: headers, isHeading: true }, ...rows.map(row => ({ items: row.map(String) }))]), ...(footer ? [text(footer)] : [])]
24
- return wrap(sub, quoted, options)
25
- }
26
-
27
- export const generateListContent = (title, items, quoted, options = {}) => {
28
- const { footer, headerText } = options
29
- const sub = [...(headerText ? [text(headerText)] : []), table(title, items.map(item => ({ items: Array.isArray(item) ? item.map(String) : [String(item)] }))), ...(footer ? [text(footer)] : [])]
30
- return wrap(sub, quoted, options)
31
- }
32
-
33
- export const generateCodeBlockContent = (code, quoted, options = {}) => {
34
- const { title, footer, language = 'javascript' } = options
35
- const { codeBlocks } = tokenizeCode(code, language)
36
- const sub = [...(title ? [text(title)] : []), { messageType: RichSubMessageType.AI_RICH_RESPONSE_CODE, codeMetadata: { codeLanguage: language, codeBlocks } }, ...(footer ? [text(footer)] : [])]
37
- return wrap(sub, quoted, options)
38
- }
39
-
40
- export const generateLatexContent = (quoted, options = {}) => {
41
- const { text: txt, expressions = [], headerText, footer } = options
42
- const latexExpressions = expressions.map(({ latexExpression, url, width, height, fontHeight, imageTopPadding, imageLeadingPadding, imageBottomPadding, imageTrailingPadding }) => {
43
- const e = { latexExpression, url, width, height }
44
- if (fontHeight !== undefined) e.fontHeight = fontHeight
45
- if (imageTopPadding !== undefined) e.imageTopPadding = imageTopPadding
46
- if (imageLeadingPadding !== undefined) e.imageLeadingPadding = imageLeadingPadding
47
- if (imageBottomPadding !== undefined) e.imageBottomPadding = imageBottomPadding
48
- if (imageTrailingPadding !== undefined) e.imageTrailingPadding = imageTrailingPadding
49
- return e
50
- })
51
- const sub = [...(headerText ? [text(headerText)] : []), { messageType: RichSubMessageType.AI_RICH_RESPONSE_LATEX, latexMetadata: { text: txt || '', expressions: latexExpressions } }, ...(footer ? [text(footer)] : [])]
52
- return wrap(sub, quoted, options)
53
- }
54
-
55
- export const captureUnifiedResponse = msg => {
56
- const rich = msg?.botForwardedMessage?.message?.richResponseMessage
57
- if (!rich?.unifiedResponse?.data) return null
58
- return { unifiedResponse: { data: rich.unifiedResponse.data }, submessages: rich.submessages || [], contextInfo: rich.contextInfo || {} }
59
- }
60
-
61
- export const generateUnifiedResponseContent = (quoted, captured) => wrap(captured.submessages, quoted, { unifiedResponse: captured.unifiedResponse })
1
+ import { generateMessageIDV2, tokenizeCode } from './generics.js'
2
+ import { RichSubMessageType } from './bot-capabilities.js'
3
+ import { proto } from '../../WAProto/index.js'
4
+
5
+ const buildRichContextInfo = (quoted, options = {}) => {
6
+ const ctx = { forwardingScore: 1, isForwarded: true, forwardedAiBotMessageInfo: { botJid: options.botJid || '867051314767696@bot' }, forwardOrigin: 4, ...(options.mentions ? { mentionedJid: options.mentions } : {}) }
7
+ if (quoted?.key) { ctx.stanzaId = quoted.key.id; ctx.participant = quoted.key.participant || quoted.sender || quoted.key.remoteJid; ctx.quotedMessage = quoted.message }
8
+ return ctx
9
+ }
10
+
11
+ const buildBotForwardedMessage = (submessages, contextInfo, unifiedResponse) => {
12
+ const rich = { messageType: proto.AIRichResponseMessageType.AI_RICH_RESPONSE_TYPE_STANDARD, submessages, contextInfo }
13
+ if (unifiedResponse) rich.unifiedResponse = unifiedResponse
14
+ return { botForwardedMessage: { message: { richResponseMessage: rich } } }
15
+ }
16
+
17
+ const wrap = (sub, quoted, options) => ({ message: buildBotForwardedMessage(sub, buildRichContextInfo(quoted, options)), messageId: generateMessageIDV2() })
18
+ const text = msg => ({ messageType: RichSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: msg })
19
+ const table = (title, rows) => ({ messageType: RichSubMessageType.AI_RICH_RESPONSE_TABLE, tableMetadata: { title, rows } })
20
+
21
+ export const generateTableContent = (title, headers, rows, quoted, options = {}) => {
22
+ const { footer, headerText } = options
23
+ const sub = [...(headerText ? [text(headerText)] : []), table(title, [{ items: headers, isHeading: true }, ...rows.map(row => ({ items: row.map(String) }))]), ...(footer ? [text(footer)] : [])]
24
+ return wrap(sub, quoted, options)
25
+ }
26
+
27
+ export const generateListContent = (title, items, quoted, options = {}) => {
28
+ const { footer, headerText } = options
29
+ const sub = [...(headerText ? [text(headerText)] : []), table(title, items.map(item => ({ items: Array.isArray(item) ? item.map(String) : [String(item)] }))), ...(footer ? [text(footer)] : [])]
30
+ return wrap(sub, quoted, options)
31
+ }
32
+
33
+ export const generateCodeBlockContent = (code, quoted, options = {}) => {
34
+ const { title, footer, language = 'javascript' } = options
35
+ const { codeBlocks } = tokenizeCode(code, language)
36
+ const sub = [...(title ? [text(title)] : []), { messageType: RichSubMessageType.AI_RICH_RESPONSE_CODE, codeMetadata: { codeLanguage: language, codeBlocks } }, ...(footer ? [text(footer)] : [])]
37
+ return wrap(sub, quoted, options)
38
+ }
39
+
40
+ export const generateLatexContent = (quoted, options = {}) => {
41
+ const { text: txt, expressions = [], headerText, footer } = options
42
+ const latexExpressions = expressions.map(({ latexExpression, url, width, height, fontHeight, imageTopPadding, imageLeadingPadding, imageBottomPadding, imageTrailingPadding }) => {
43
+ const e = { latexExpression, url, width, height }
44
+ if (fontHeight !== undefined) e.fontHeight = fontHeight
45
+ if (imageTopPadding !== undefined) e.imageTopPadding = imageTopPadding
46
+ if (imageLeadingPadding !== undefined) e.imageLeadingPadding = imageLeadingPadding
47
+ if (imageBottomPadding !== undefined) e.imageBottomPadding = imageBottomPadding
48
+ if (imageTrailingPadding !== undefined) e.imageTrailingPadding = imageTrailingPadding
49
+ return e
50
+ })
51
+ const sub = [...(headerText ? [text(headerText)] : []), { messageType: RichSubMessageType.AI_RICH_RESPONSE_LATEX, latexMetadata: { text: txt || '', expressions: latexExpressions } }, ...(footer ? [text(footer)] : [])]
52
+ return wrap(sub, quoted, options)
53
+ }
54
+
55
+ export const captureUnifiedResponse = msg => {
56
+ const rich = msg?.botForwardedMessage?.message?.richResponseMessage
57
+ if (!rich?.unifiedResponse?.data) return null
58
+ return { unifiedResponse: { data: rich.unifiedResponse.data }, submessages: rich.submessages || [], contextInfo: rich.contextInfo || {} }
59
+ }
60
+
61
+ export const generateUnifiedResponseContent = (quoted, captured) => wrap(captured.submessages, quoted, { unifiedResponse: captured.unifiedResponse })
62
62
  export const generateRichMessageContent = (submessages, quoted, options) => wrap(submessages, quoted, options)
@@ -1,48 +1,48 @@
1
- import { LRUCache } from 'lru-cache'
2
-
3
- const RECENT_MESSAGES_SIZE = 512
4
- const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000
5
- const PHONE_REQUEST_DELAY = 3000
6
-
7
- export class MessageRetryManager {
8
- constructor(logger, maxMsgRetryCount) {
9
- this.logger = logger
10
- this.maxMsgRetryCount = maxMsgRetryCount
11
- this.recentMessagesMap = new LRUCache({ max: RECENT_MESSAGES_SIZE })
12
- this.sessionRecreateHistory = new LRUCache({ ttl: RECREATE_SESSION_TIMEOUT * 2, ttlAutopurge: true })
13
- this.retryCounters = new LRUCache({ ttl: 15 * 60 * 1000, ttlAutopurge: true, updateAgeOnGet: true })
14
- this.pendingPhoneRequests = {}
15
- this.statistics = { totalRetries: 0, successfulRetries: 0, failedRetries: 0, mediaRetries: 0, sessionRecreations: 0, phoneRequests: 0 }
16
- }
17
-
18
- keyToString(key) { return `${key.to}:${key.id}` }
19
-
20
- addRecentMessage(to, id, message) { this.recentMessagesMap.set(this.keyToString({ to, id }), { message, timestamp: Date.now() }) }
21
- getRecentMessage(to, id) { return this.recentMessagesMap.get(this.keyToString({ to, id })) }
22
-
23
- shouldRecreateSession(jid, retryCount, hasSession) {
24
- if (!hasSession) { this.sessionRecreateHistory.set(jid, Date.now()); this.statistics.sessionRecreations++; return { reason: "we don't have a Signal session with them", recreate: true } }
25
- if (retryCount < 2) return { reason: '', recreate: false }
26
- const now = Date.now()
27
- const prevTime = this.sessionRecreateHistory.get(jid)
28
- if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) { this.sessionRecreateHistory.set(jid, now); this.statistics.sessionRecreations++; return { reason: 'retry count > 1 and over an hour since last recreation', recreate: true } }
29
- return { reason: '', recreate: false }
30
- }
31
-
32
- incrementRetryCount(messageId) { this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1); this.statistics.totalRetries++; return this.retryCounters.get(messageId) }
33
- getRetryCount(messageId) { return this.retryCounters.get(messageId) || 0 }
34
- hasExceededMaxRetries(messageId) { return this.getRetryCount(messageId) >= this.maxMsgRetryCount }
35
-
36
- markRetrySuccess(messageId) { this.statistics.successfulRetries++; this.retryCounters.delete(messageId); this.cancelPendingPhoneRequest(messageId) }
37
- markRetryFailed(messageId) { this.statistics.failedRetries++; this.retryCounters.delete(messageId) }
38
-
39
- schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
40
- this.cancelPendingPhoneRequest(messageId)
41
- this.pendingPhoneRequests[messageId] = setTimeout(() => { delete this.pendingPhoneRequests[messageId]; this.statistics.phoneRequests++; callback() }, delay)
42
- }
43
-
44
- cancelPendingPhoneRequest(messageId) {
45
- const timeout = this.pendingPhoneRequests[messageId]
46
- if (timeout) { clearTimeout(timeout); delete this.pendingPhoneRequests[messageId] }
47
- }
1
+ import { LRUCache } from 'lru-cache'
2
+
3
+ const RECENT_MESSAGES_SIZE = 512
4
+ const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000
5
+ const PHONE_REQUEST_DELAY = 3000
6
+
7
+ export class MessageRetryManager {
8
+ constructor(logger, maxMsgRetryCount) {
9
+ this.logger = logger
10
+ this.maxMsgRetryCount = maxMsgRetryCount
11
+ this.recentMessagesMap = new LRUCache({ max: RECENT_MESSAGES_SIZE })
12
+ this.sessionRecreateHistory = new LRUCache({ ttl: RECREATE_SESSION_TIMEOUT * 2, ttlAutopurge: true })
13
+ this.retryCounters = new LRUCache({ ttl: 15 * 60 * 1000, ttlAutopurge: true, updateAgeOnGet: true })
14
+ this.pendingPhoneRequests = {}
15
+ this.statistics = { totalRetries: 0, successfulRetries: 0, failedRetries: 0, mediaRetries: 0, sessionRecreations: 0, phoneRequests: 0 }
16
+ }
17
+
18
+ keyToString(key) { return `${key.to}:${key.id}` }
19
+
20
+ addRecentMessage(to, id, message) { this.recentMessagesMap.set(this.keyToString({ to, id }), { message, timestamp: Date.now() }) }
21
+ getRecentMessage(to, id) { return this.recentMessagesMap.get(this.keyToString({ to, id })) }
22
+
23
+ shouldRecreateSession(jid, retryCount, hasSession) {
24
+ if (!hasSession) { this.sessionRecreateHistory.set(jid, Date.now()); this.statistics.sessionRecreations++; return { reason: "we don't have a Signal session with them", recreate: true } }
25
+ if (retryCount < 2) return { reason: '', recreate: false }
26
+ const now = Date.now()
27
+ const prevTime = this.sessionRecreateHistory.get(jid)
28
+ if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) { this.sessionRecreateHistory.set(jid, now); this.statistics.sessionRecreations++; return { reason: 'retry count > 1 and over an hour since last recreation', recreate: true } }
29
+ return { reason: '', recreate: false }
30
+ }
31
+
32
+ incrementRetryCount(messageId) { this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1); this.statistics.totalRetries++; return this.retryCounters.get(messageId) }
33
+ getRetryCount(messageId) { return this.retryCounters.get(messageId) || 0 }
34
+ hasExceededMaxRetries(messageId) { return this.getRetryCount(messageId) >= this.maxMsgRetryCount }
35
+
36
+ markRetrySuccess(messageId) { this.statistics.successfulRetries++; this.retryCounters.delete(messageId); this.cancelPendingPhoneRequest(messageId) }
37
+ markRetryFailed(messageId) { this.statistics.failedRetries++; this.retryCounters.delete(messageId) }
38
+
39
+ schedulePhoneRequest(messageId, callback, delay = PHONE_REQUEST_DELAY) {
40
+ this.cancelPendingPhoneRequest(messageId)
41
+ this.pendingPhoneRequests[messageId] = setTimeout(() => { delete this.pendingPhoneRequests[messageId]; this.statistics.phoneRequests++; callback() }, delay)
42
+ }
43
+
44
+ cancelPendingPhoneRequest(messageId) {
45
+ const timeout = this.pendingPhoneRequests[messageId]
46
+ if (timeout) { clearTimeout(timeout); delete this.pendingPhoneRequests[messageId] }
47
+ }
48
48
  }