@skycodee/baileys 8.0.0 → 8.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 (114) hide show
  1. package/package.json +4 -4
  2. package/src/Defaults/baileys-version.json +1 -0
  3. package/src/Defaults/index.ts +149 -0
  4. package/src/Signal/Group/ciphertext-message.ts +9 -0
  5. package/src/Signal/Group/group-session-builder.ts +56 -0
  6. package/src/Signal/Group/group_cipher.ts +117 -0
  7. package/src/Signal/Group/index.ts +11 -0
  8. package/src/Signal/Group/keyhelper.ts +28 -0
  9. package/src/Signal/Group/sender-chain-key.ts +34 -0
  10. package/src/Signal/Group/sender-key-distribution-message.ts +95 -0
  11. package/src/Signal/Group/sender-key-message.ts +96 -0
  12. package/src/Signal/Group/sender-key-name.ts +66 -0
  13. package/src/Signal/Group/sender-key-record.ts +69 -0
  14. package/src/Signal/Group/sender-key-state.ts +134 -0
  15. package/src/Signal/Group/sender-message-key.ts +36 -0
  16. package/src/Signal/libsignal.ts +521 -0
  17. package/src/Signal/lid-mapping.ts +328 -0
  18. package/src/Socket/Client/index.ts +2 -0
  19. package/src/Socket/Client/types.ts +22 -0
  20. package/src/Socket/Client/websocket.ts +63 -0
  21. package/src/Socket/business.ts +424 -0
  22. package/src/Socket/chats.ts +1272 -0
  23. package/src/Socket/communities.ts +477 -0
  24. package/src/Socket/groups.ts +361 -0
  25. package/src/Socket/index.ts +15 -0
  26. package/src/Socket/messages-recv.ts +1668 -0
  27. package/src/Socket/messages-send.ts +1296 -0
  28. package/src/Socket/mex.ts +58 -0
  29. package/src/Socket/newsletter.ts +229 -0
  30. package/src/Socket/socket.ts +1184 -0
  31. package/src/Types/Auth.ts +116 -0
  32. package/src/Types/Bussines.ts +20 -0
  33. package/src/Types/Call.ts +15 -0
  34. package/src/Types/Chat.ts +138 -0
  35. package/src/Types/Contact.ts +24 -0
  36. package/src/Types/Events.ts +159 -0
  37. package/src/Types/GroupMetadata.ts +70 -0
  38. package/src/Types/Label.ts +48 -0
  39. package/src/Types/LabelAssociation.ts +35 -0
  40. package/src/Types/Message.ts +380 -0
  41. package/src/Types/Newsletter.ts +98 -0
  42. package/src/Types/Product.ts +85 -0
  43. package/src/Types/Signal.ts +76 -0
  44. package/src/Types/Socket.ts +150 -0
  45. package/src/Types/State.ts +43 -0
  46. package/src/Types/USync.ts +27 -0
  47. package/src/Types/globals.d.ts +8 -0
  48. package/src/Types/index.ts +67 -0
  49. package/src/Utils/auth-utils.ts +368 -0
  50. package/src/Utils/browser-utils.ts +31 -0
  51. package/src/Utils/business.ts +286 -0
  52. package/src/Utils/chat-utils.ts +974 -0
  53. package/src/Utils/crypto.ts +147 -0
  54. package/src/Utils/decode-wa-message.ts +355 -0
  55. package/src/Utils/event-buffer.ts +692 -0
  56. package/src/Utils/generics.ts +474 -0
  57. package/src/Utils/history.ts +161 -0
  58. package/src/Utils/identity-change-handler.ts +83 -0
  59. package/src/Utils/index.ts +19 -0
  60. package/src/Utils/link-preview.ts +111 -0
  61. package/src/Utils/logger.ts +13 -0
  62. package/src/Utils/lt-hash.ts +8 -0
  63. package/src/Utils/make-mutex.ts +42 -0
  64. package/src/Utils/message-retry-manager.ts +295 -0
  65. package/src/Utils/messages-media.ts +984 -0
  66. package/src/Utils/messages.ts +1097 -0
  67. package/src/Utils/noise-handler.ts +268 -0
  68. package/src/Utils/pre-key-manager.ts +126 -0
  69. package/src/Utils/process-message.ts +670 -0
  70. package/src/Utils/reporting-utils.ts +344 -0
  71. package/src/Utils/signal.ts +214 -0
  72. package/src/Utils/sync-action-utils.ts +74 -0
  73. package/src/Utils/tc-token-utils.ts +34 -0
  74. package/src/Utils/use-multi-file-auth-state.ts +136 -0
  75. package/src/Utils/validate-connection.ts +253 -0
  76. package/src/WABinary/constants.ts +1305 -0
  77. package/src/WABinary/decode.ts +308 -0
  78. package/src/WABinary/encode.ts +258 -0
  79. package/src/WABinary/generic-utils.ts +141 -0
  80. package/src/WABinary/index.ts +5 -0
  81. package/src/WABinary/jid-utils.ts +128 -0
  82. package/src/WABinary/types.ts +17 -0
  83. package/src/WAM/BinaryInfo.ts +12 -0
  84. package/src/WAM/constants.ts +22889 -0
  85. package/src/WAM/encode.ts +169 -0
  86. package/src/WAM/index.ts +3 -0
  87. package/src/WAUSync/Protocols/USyncContactProtocol.ts +32 -0
  88. package/src/WAUSync/Protocols/USyncDeviceProtocol.ts +78 -0
  89. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.ts +35 -0
  90. package/src/WAUSync/Protocols/USyncStatusProtocol.ts +44 -0
  91. package/src/WAUSync/Protocols/UsyncBotProfileProtocol.ts +76 -0
  92. package/src/WAUSync/Protocols/UsyncLIDProtocol.ts +33 -0
  93. package/src/WAUSync/Protocols/index.ts +4 -0
  94. package/src/WAUSync/USyncQuery.ts +133 -0
  95. package/src/WAUSync/USyncUser.ts +32 -0
  96. package/src/WAUSync/index.ts +3 -0
  97. package/src/__tests__/Signal/Group/sender-key-state-regression.test.ts +22 -0
  98. package/src/__tests__/Signal/lid-mapping.test.ts +47 -0
  99. package/src/__tests__/Socket/identity-change-handling.test.ts +207 -0
  100. package/src/__tests__/TestUtils/session.ts +47 -0
  101. package/src/__tests__/Utils/generics.test.ts +70 -0
  102. package/src/__tests__/Utils/history.test.ts +362 -0
  103. package/src/__tests__/Utils/messages-media.test.ts +405 -0
  104. package/src/__tests__/Utils/noise-handler.test.ts +339 -0
  105. package/src/__tests__/Utils/process-message.test.ts +138 -0
  106. package/src/__tests__/Utils/process-sync-action.test.ts +359 -0
  107. package/src/__tests__/Utils/reporting-utils.test.ts +160 -0
  108. package/src/__tests__/Utils/signal.test.ts +69 -0
  109. package/src/__tests__/Utils/sync-action-utils.test.ts +183 -0
  110. package/src/__tests__/binary/connection-deadlock.test.ts +54 -0
  111. package/src/__tests__/e2e/fetch-wa-web-version.test-e2e.ts +60 -0
  112. package/src/__tests__/e2e/send-receive-message.test-e2e.ts +644 -0
  113. package/src/__tests__/proto-tojson-long.test.ts +31 -0
  114. package/src/index.ts +13 -0
@@ -0,0 +1,19 @@
1
+ export * from './generics'
2
+ export * from './decode-wa-message'
3
+ export * from './messages'
4
+ export * from './messages-media'
5
+ export * from './validate-connection'
6
+ export * from './crypto'
7
+ export * from './signal'
8
+ export * from './noise-handler'
9
+ export * from './history'
10
+ export * from './chat-utils'
11
+ export * from './lt-hash'
12
+ export * from './auth-utils'
13
+ export * from './use-multi-file-auth-state'
14
+ export * from './link-preview'
15
+ export * from './event-buffer'
16
+ export * from './process-message'
17
+ export * from './message-retry-manager'
18
+ export * from './browser-utils'
19
+ export * from './identity-change-handler'
@@ -0,0 +1,111 @@
1
+ import type { WAMediaUploadFunction, WAUrlInfo } from '../Types'
2
+ import type { ILogger } from './logger'
3
+ import { prepareWAMessageMedia } from './messages'
4
+ import { extractImageThumb, getHttpStream } from './messages-media'
5
+
6
+ const THUMBNAIL_WIDTH_PX = 192
7
+
8
+ /** Fetches an image and generates a thumbnail for it */
9
+ const getCompressedJpegThumbnail = async (url: string, { thumbnailWidth, fetchOpts }: URLGenerationOptions) => {
10
+ const stream = await getHttpStream(url, fetchOpts)
11
+ const result = await extractImageThumb(stream, thumbnailWidth)
12
+ return result
13
+ }
14
+
15
+ export type URLGenerationOptions = {
16
+ thumbnailWidth: number
17
+ fetchOpts: {
18
+ /** Timeout in ms */
19
+ timeout: number
20
+ proxyUrl?: string
21
+ headers?: HeadersInit
22
+ }
23
+ uploadImage?: WAMediaUploadFunction
24
+ logger?: ILogger
25
+ }
26
+
27
+ /**
28
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
29
+ * Return undefined if the fetch failed or no URL was found
30
+ * @param text first matched URL in text
31
+ * @returns the URL info required to generate link preview
32
+ */
33
+ export const getUrlInfo = async (
34
+ text: string,
35
+ opts: URLGenerationOptions = {
36
+ thumbnailWidth: THUMBNAIL_WIDTH_PX,
37
+ fetchOpts: { timeout: 3000 }
38
+ }
39
+ ): Promise<WAUrlInfo | undefined> => {
40
+ try {
41
+ // retries
42
+ const retries = 0
43
+ const maxRetry = 5
44
+
45
+ const { getLinkPreview } = await import('link-preview-js')
46
+ let previewLink = text
47
+ if (!text.startsWith('https://') && !text.startsWith('http://')) {
48
+ previewLink = 'https://' + previewLink
49
+ }
50
+
51
+ const info = await getLinkPreview(previewLink, {
52
+ ...opts.fetchOpts,
53
+ followRedirects: 'follow',
54
+ handleRedirects: (baseURL: string, forwardedURL: string) => {
55
+ const urlObj = new URL(baseURL)
56
+ const forwardedURLObj = new URL(forwardedURL)
57
+ if (retries >= maxRetry) {
58
+ return false
59
+ }
60
+
61
+ if (
62
+ forwardedURLObj.hostname === urlObj.hostname ||
63
+ forwardedURLObj.hostname === 'www.' + urlObj.hostname ||
64
+ 'www.' + forwardedURLObj.hostname === urlObj.hostname
65
+ ) {
66
+ retries + 1
67
+ return true
68
+ } else {
69
+ return false
70
+ }
71
+ },
72
+ headers: opts.fetchOpts?.headers as {}
73
+ })
74
+ if (info && 'title' in info && info.title) {
75
+ const [image] = info.images
76
+
77
+ const urlInfo: WAUrlInfo = {
78
+ 'canonical-url': info.url,
79
+ 'matched-text': text,
80
+ title: info.title,
81
+ description: info.description,
82
+ originalThumbnailUrl: image
83
+ }
84
+
85
+ if (opts.uploadImage) {
86
+ const { imageMessage } = await prepareWAMessageMedia(
87
+ { image: { url: image! } },
88
+ {
89
+ upload: opts.uploadImage,
90
+ mediaTypeOverride: 'thumbnail-link',
91
+ options: opts.fetchOpts
92
+ }
93
+ )
94
+ urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail ? Buffer.from(imageMessage.jpegThumbnail) : undefined
95
+ urlInfo.highQualityThumbnail = imageMessage || undefined
96
+ } else {
97
+ try {
98
+ urlInfo.jpegThumbnail = image ? (await getCompressedJpegThumbnail(image, opts)).buffer : undefined
99
+ } catch (error: any) {
100
+ opts.logger?.debug({ err: error.stack, url: previewLink }, 'error in generating thumbnail')
101
+ }
102
+ }
103
+
104
+ return urlInfo
105
+ }
106
+ } catch (error: any) {
107
+ if (!error.message.includes('receive a valid')) {
108
+ throw error
109
+ }
110
+ }
111
+ }
@@ -0,0 +1,13 @@
1
+ import P from 'pino'
2
+
3
+ export interface ILogger {
4
+ level: string
5
+ child(obj: Record<string, unknown>): ILogger
6
+ trace(obj: unknown, msg?: string): void
7
+ debug(obj: unknown, msg?: string): void
8
+ info(obj: unknown, msg?: string): void
9
+ warn(obj: unknown, msg?: string): void
10
+ error(obj: unknown, msg?: string): void
11
+ }
12
+
13
+ export default P({ timestamp: () => `,"time":"${new Date().toJSON()}"` })
@@ -0,0 +1,8 @@
1
+ import { LTHashAntiTampering } from 'whatsapp-rust-bridge'
2
+
3
+ /**
4
+ * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
5
+ * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
6
+ * if the same series of mutations was made sequentially.
7
+ */
8
+ export const LT_HASH_ANTI_TAMPERING = new LTHashAntiTampering()
@@ -0,0 +1,42 @@
1
+ import { Mutex as AsyncMutex } from 'async-mutex'
2
+
3
+ export const makeMutex = () => {
4
+ const mutex = new AsyncMutex()
5
+
6
+ return {
7
+ mutex<T>(code: () => Promise<T> | T): Promise<T> {
8
+ return mutex.runExclusive(code)
9
+ }
10
+ }
11
+ }
12
+
13
+ export type Mutex = ReturnType<typeof makeMutex>
14
+
15
+ export const makeKeyedMutex = () => {
16
+ const map = new Map<string, { mutex: AsyncMutex; refCount: number }>()
17
+
18
+ return {
19
+ async mutex<T>(key: string, task: () => Promise<T> | T): Promise<T> {
20
+ let entry = map.get(key)
21
+
22
+ if (!entry) {
23
+ entry = { mutex: new AsyncMutex(), refCount: 0 }
24
+ map.set(key, entry)
25
+ }
26
+
27
+ entry.refCount++
28
+
29
+ try {
30
+ return await entry.mutex.runExclusive(task)
31
+ } finally {
32
+ entry.refCount--
33
+ // only delete it if this is still the current entry
34
+ if (entry.refCount === 0 && map.get(key) === entry) {
35
+ map.delete(key)
36
+ }
37
+ }
38
+ }
39
+ }
40
+ }
41
+
42
+ export type KeyedMutex = ReturnType<typeof makeKeyedMutex>
@@ -0,0 +1,295 @@
1
+ import { LRUCache } from 'lru-cache'
2
+ import type { proto } from '../../WAProto/index.js'
3
+ import type { ILogger } from './logger'
4
+
5
+ /** Number of sent messages to cache in memory for handling retry receipts */
6
+ const RECENT_MESSAGES_SIZE = 512
7
+
8
+ const MESSAGE_KEY_SEPARATOR = '\u0000'
9
+
10
+ /** Timeout for session recreation - 1 hour */
11
+ const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000 // 1 hour in milliseconds
12
+ const PHONE_REQUEST_DELAY = 3000
13
+ export interface RecentMessageKey {
14
+ to: string
15
+ id: string
16
+ }
17
+
18
+ export interface RecentMessage {
19
+ message: proto.IMessage
20
+ timestamp: number
21
+ }
22
+
23
+ export interface SessionRecreateHistory {
24
+ [jid: string]: number // timestamp
25
+ }
26
+
27
+ export interface RetryCounter {
28
+ [messageId: string]: number
29
+ }
30
+
31
+ export type PendingPhoneRequest = Record<string, ReturnType<typeof setTimeout>>
32
+
33
+ export interface RetryStatistics {
34
+ totalRetries: number
35
+ successfulRetries: number
36
+ failedRetries: number
37
+ mediaRetries: number
38
+ sessionRecreations: number
39
+ phoneRequests: number
40
+ }
41
+
42
+ // Retry reason codes matching WhatsApp Web's Signal error codes.
43
+ export enum RetryReason {
44
+ UnknownError = 0,
45
+ SignalErrorNoSession = 1,
46
+ SignalErrorInvalidKey = 2,
47
+ SignalErrorInvalidKeyId = 3,
48
+ /** MAC verification failed - most common cause of decryption failures */
49
+ SignalErrorInvalidMessage = 4,
50
+ SignalErrorInvalidSignature = 5,
51
+ SignalErrorFutureMessage = 6,
52
+ /** Explicit MAC failure - session is definitely out of sync */
53
+ SignalErrorBadMac = 7,
54
+ SignalErrorInvalidSession = 8,
55
+ SignalErrorInvalidMsgKey = 9,
56
+ BadBroadcastEphemeralSetting = 10,
57
+ UnknownCompanionNoPrekey = 11,
58
+ AdvFailure = 12,
59
+ StatusRevokeDelay = 13
60
+ }
61
+
62
+ /** Error codes that indicate a MAC failure and require immediate session recreation */
63
+ const MAC_ERROR_CODES = new Set([RetryReason.SignalErrorInvalidMessage, RetryReason.SignalErrorBadMac])
64
+
65
+ export class MessageRetryManager {
66
+ private recentMessagesMap = new LRUCache<string, RecentMessage>({
67
+ max: RECENT_MESSAGES_SIZE,
68
+ ttl: 5 * 60 * 1000,
69
+ ttlAutopurge: true,
70
+ dispose: (_value: RecentMessage, key: string) => {
71
+ const separatorIndex = key.lastIndexOf(MESSAGE_KEY_SEPARATOR)
72
+ if (separatorIndex > -1) {
73
+ const messageId = key.slice(separatorIndex + MESSAGE_KEY_SEPARATOR.length)
74
+ this.messageKeyIndex.delete(messageId)
75
+ }
76
+ }
77
+ })
78
+ private messageKeyIndex = new Map<string, string>()
79
+ private sessionRecreateHistory = new LRUCache<string, number>({
80
+ ttl: RECREATE_SESSION_TIMEOUT * 2,
81
+ ttlAutopurge: true
82
+ })
83
+ private retryCounters = new LRUCache<string, number>({
84
+ ttl: 15 * 60 * 1000,
85
+ ttlAutopurge: true,
86
+ updateAgeOnGet: true
87
+ }) // 15 minutes TTL
88
+ private pendingPhoneRequests: PendingPhoneRequest = {}
89
+ private readonly maxMsgRetryCount: number = 5
90
+ private statistics: RetryStatistics = {
91
+ totalRetries: 0,
92
+ successfulRetries: 0,
93
+ failedRetries: 0,
94
+ mediaRetries: 0,
95
+ sessionRecreations: 0,
96
+ phoneRequests: 0
97
+ }
98
+
99
+ constructor(
100
+ private logger: ILogger,
101
+ maxMsgRetryCount: number
102
+ ) {
103
+ this.maxMsgRetryCount = maxMsgRetryCount
104
+ }
105
+
106
+ /**
107
+ * Add a recent message to the cache for retry handling
108
+ */
109
+ addRecentMessage(to: string, id: string, message: proto.IMessage): void {
110
+ const key: RecentMessageKey = { to, id }
111
+ const keyStr = this.keyToString(key)
112
+
113
+ // Add new message
114
+ this.recentMessagesMap.set(keyStr, {
115
+ message,
116
+ timestamp: Date.now()
117
+ })
118
+ this.messageKeyIndex.set(id, keyStr)
119
+
120
+ this.logger.debug(`Added message to retry cache: ${to}/${id}`)
121
+ }
122
+
123
+ /**
124
+ * Get a recent message from the cache
125
+ */
126
+ getRecentMessage(to: string, id: string): RecentMessage | undefined {
127
+ const key: RecentMessageKey = { to, id }
128
+ const keyStr = this.keyToString(key)
129
+ return this.recentMessagesMap.get(keyStr)
130
+ }
131
+
132
+ /**
133
+ * Check if a session should be recreated based on retry count, history, and error code.
134
+ * MAC errors (codes 4 and 7) trigger immediate session recreation regardless of timeout.
135
+ */
136
+ shouldRecreateSession(
137
+ jid: string,
138
+ hasSession: boolean,
139
+ errorCode?: RetryReason
140
+ ): { reason: string; recreate: boolean } {
141
+ // If we don't have a session, always recreate
142
+ if (!hasSession) {
143
+ this.sessionRecreateHistory.set(jid, Date.now())
144
+ this.statistics.sessionRecreations++
145
+ return {
146
+ reason: "we don't have a Signal session with them",
147
+ recreate: true
148
+ }
149
+ }
150
+
151
+ // IMMEDIATE recreation for MAC errors - session is definitely out of sync
152
+ if (errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)) {
153
+ this.sessionRecreateHistory.set(jid, Date.now())
154
+ this.statistics.sessionRecreations++
155
+ this.logger.warn(
156
+ { jid, errorCode: RetryReason[errorCode] },
157
+ 'MAC error detected, forcing immediate session recreation'
158
+ )
159
+ return {
160
+ reason: `MAC error (code ${errorCode}: ${RetryReason[errorCode]}), immediate session recreation`,
161
+ recreate: true
162
+ }
163
+ }
164
+
165
+ const now = Date.now()
166
+ const prevTime = this.sessionRecreateHistory.get(jid)
167
+
168
+ // If no previous recreation or it's been more than an hour
169
+ if (!prevTime || now - prevTime > RECREATE_SESSION_TIMEOUT) {
170
+ this.sessionRecreateHistory.set(jid, now)
171
+ this.statistics.sessionRecreations++
172
+ return {
173
+ reason: 'retry count > 1 and over an hour since last recreation',
174
+ recreate: true
175
+ }
176
+ }
177
+
178
+ return { reason: '', recreate: false }
179
+ }
180
+
181
+ /**
182
+ * Parse error code from retry receipt's retry node.
183
+ * Returns undefined if no error code is present.
184
+ */
185
+ parseRetryErrorCode(errorAttr: string | undefined): RetryReason | undefined {
186
+ if (errorAttr === undefined || errorAttr === '') {
187
+ return undefined
188
+ }
189
+
190
+ const code = parseInt(errorAttr, 10)
191
+ if (Number.isNaN(code)) {
192
+ return undefined
193
+ }
194
+
195
+ // Validate it's a known RetryReason
196
+ if (code >= RetryReason.UnknownError && code <= RetryReason.StatusRevokeDelay) {
197
+ return code as RetryReason
198
+ }
199
+
200
+ return RetryReason.UnknownError
201
+ }
202
+
203
+ /**
204
+ * Check if an error code indicates a MAC failure
205
+ */
206
+ isMacError(errorCode: RetryReason | undefined): boolean {
207
+ return errorCode !== undefined && MAC_ERROR_CODES.has(errorCode)
208
+ }
209
+
210
+ /**
211
+ * Increment retry counter for a message
212
+ */
213
+ incrementRetryCount(messageId: string): number {
214
+ this.retryCounters.set(messageId, (this.retryCounters.get(messageId) || 0) + 1)
215
+ this.statistics.totalRetries++
216
+ return this.retryCounters.get(messageId)!
217
+ }
218
+
219
+ /**
220
+ * Get retry count for a message
221
+ */
222
+ getRetryCount(messageId: string): number {
223
+ return this.retryCounters.get(messageId) || 0
224
+ }
225
+
226
+ /**
227
+ * Check if message has exceeded maximum retry attempts
228
+ */
229
+ hasExceededMaxRetries(messageId: string): boolean {
230
+ return this.getRetryCount(messageId) >= this.maxMsgRetryCount
231
+ }
232
+
233
+ /**
234
+ * Mark retry as successful
235
+ */
236
+ markRetrySuccess(messageId: string): void {
237
+ this.statistics.successfulRetries++
238
+ // Clean up retry counter for successful message
239
+ this.retryCounters.delete(messageId)
240
+ this.cancelPendingPhoneRequest(messageId)
241
+ this.removeRecentMessage(messageId)
242
+ }
243
+
244
+ /**
245
+ * Mark retry as failed
246
+ */
247
+ markRetryFailed(messageId: string): void {
248
+ this.statistics.failedRetries++
249
+ this.retryCounters.delete(messageId)
250
+ this.cancelPendingPhoneRequest(messageId)
251
+ this.removeRecentMessage(messageId)
252
+ }
253
+
254
+ /**
255
+ * Schedule a phone request with delay
256
+ */
257
+ schedulePhoneRequest(messageId: string, callback: () => void, delay: number = PHONE_REQUEST_DELAY): void {
258
+ // Cancel any existing request for this message
259
+ this.cancelPendingPhoneRequest(messageId)
260
+
261
+ this.pendingPhoneRequests[messageId] = setTimeout(() => {
262
+ delete this.pendingPhoneRequests[messageId]
263
+ this.statistics.phoneRequests++
264
+ callback()
265
+ }, delay)
266
+
267
+ this.logger.debug(`Scheduled phone request for message ${messageId} with ${delay}ms delay`)
268
+ }
269
+
270
+ /**
271
+ * Cancel pending phone request
272
+ */
273
+ cancelPendingPhoneRequest(messageId: string): void {
274
+ const timeout = this.pendingPhoneRequests[messageId]
275
+ if (timeout) {
276
+ clearTimeout(timeout)
277
+ delete this.pendingPhoneRequests[messageId]
278
+ this.logger.debug(`Cancelled pending phone request for message ${messageId}`)
279
+ }
280
+ }
281
+
282
+ private keyToString(key: RecentMessageKey): string {
283
+ return `${key.to}${MESSAGE_KEY_SEPARATOR}${key.id}`
284
+ }
285
+
286
+ private removeRecentMessage(messageId: string): void {
287
+ const keyStr = this.messageKeyIndex.get(messageId)
288
+ if (!keyStr) {
289
+ return
290
+ }
291
+
292
+ this.recentMessagesMap.delete(keyStr)
293
+ this.messageKeyIndex.delete(messageId)
294
+ }
295
+ }