@openclaw/whatsapp 2026.5.2 → 2026.5.3-beta.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 (302) hide show
  1. package/dist/access-control-BQ3tCkH8.js +288 -0
  2. package/dist/account-config-CNQ33oav.js +47 -0
  3. package/dist/account-ids-DG18xddX.js +5 -0
  4. package/dist/accounts-BDqgpFEB.js +116 -0
  5. package/dist/action-runtime-DTGNgG-i.js +74 -0
  6. package/dist/action-runtime-api.js +2 -0
  7. package/dist/action-runtime.runtime.js +2 -0
  8. package/dist/active-listener-N7GFKsuN.js +11 -0
  9. package/dist/agent-tools-login-DpRxLNRB.js +89 -0
  10. package/dist/api.js +148 -0
  11. package/dist/audio-preflight.runtime-Bcdsl_ri.js +7 -0
  12. package/dist/auth-presence.js +32 -0
  13. package/dist/auth-store-BjCb50Ry.js +381 -0
  14. package/dist/channel-DQ-5Xoj9.js +542 -0
  15. package/dist/channel-config-api.js +2 -0
  16. package/dist/channel-plugin-api.js +2 -0
  17. package/dist/channel-react-action-Df20qAy9.js +42 -0
  18. package/dist/channel.runtime-DKXRnA8x.js +55 -0
  19. package/dist/channel.setup-DOHR2BGp.js +20 -0
  20. package/dist/command-policy-O8sRnqUV.js +8 -0
  21. package/dist/config-schema-Dmo66Ubb.js +27 -0
  22. package/dist/connection-controller-BiHAsTM8.js +596 -0
  23. package/dist/connection-controller-registry-D_iIGz5m.js +22 -0
  24. package/dist/constants-DLGCIbfl.js +4 -0
  25. package/dist/constants.js +2 -0
  26. package/dist/contract-api.js +19 -0
  27. package/dist/creds-files-_2V8jzQa.js +19 -0
  28. package/dist/directory-config-DVs4ffXu.js +37 -0
  29. package/dist/directory-contract-api.js +2 -0
  30. package/dist/doctor-A9tXm9Om.js +48 -0
  31. package/dist/doctor-contract-api.js +10 -0
  32. package/dist/group-session-contract-B8QBn0I2.js +15 -0
  33. package/dist/identity-QHAlV7Fu.js +75 -0
  34. package/dist/index.js +18 -0
  35. package/dist/legacy-session-surface-api.js +8 -0
  36. package/dist/legacy-state-migrations-api.js +2 -0
  37. package/dist/light-runtime-api.js +5 -0
  38. package/dist/login-DymdrKca.js +52 -0
  39. package/dist/login-qr-DIS0Iv-7.js +378 -0
  40. package/dist/login-qr-api.js +2 -0
  41. package/dist/login-qr-runtime.js +16 -0
  42. package/dist/monitor-C4Fhg_lD.js +3349 -0
  43. package/dist/normalize-CWYiGkXw.js +2 -0
  44. package/dist/normalize-target-BPVHNsM5.js +74 -0
  45. package/dist/outbound-adapter-BssVnZdz.js +29 -0
  46. package/dist/outbound-base-Bq1UYEK5.js +119 -0
  47. package/dist/outbound-media-contract-CGss_QHy.js +163 -0
  48. package/dist/outbound-payload-test-api.js +2 -0
  49. package/dist/quoted-message-TENQzyxV.js +108 -0
  50. package/dist/reaction-level-CRVEVAfi.js +16 -0
  51. package/dist/reply-resolver.runtime-BRCgoO4C.js +2 -0
  52. package/dist/resolve-outbound-target-CN-Wo6IY.js +39 -0
  53. package/dist/rolldown-runtime-RkAeH_Qm.js +27 -0
  54. package/dist/runtime-6fZ67abR.js +8 -0
  55. package/dist/runtime-api.js +15 -0
  56. package/dist/runtime-group-policy-Gp1lQ0at.js +11 -0
  57. package/dist/secret-contract-api.js +5 -0
  58. package/dist/security-contract-DqH8JDX6.js +26 -0
  59. package/dist/security-contract-api.js +2 -0
  60. package/dist/send-CIyLFxdZ.js +234 -0
  61. package/dist/session-contract-B0efQf9P.js +27 -0
  62. package/dist/session-errors-CSuKZPub.js +63 -0
  63. package/dist/session.runtime-C1eSE_KK.js +13 -0
  64. package/dist/setup-core-DZKvpzbH.js +46 -0
  65. package/dist/setup-entry.js +23 -0
  66. package/dist/setup-plugin-api.js +2 -0
  67. package/dist/setup-surface-ieFnIW4g.js +344 -0
  68. package/dist/shared-D_wzSVar.js +307 -0
  69. package/dist/state-migrations-DnCdvoYD.js +39 -0
  70. package/dist/targets.js +2 -0
  71. package/dist/test-api.js +3 -0
  72. package/dist/text-runtime-C1zNiZeO.js +116 -0
  73. package/package.json +14 -6
  74. package/action-runtime-api.ts +0 -1
  75. package/action-runtime.runtime.ts +0 -1
  76. package/api.ts +0 -213
  77. package/auth-presence.ts +0 -80
  78. package/channel-config-api.ts +0 -1
  79. package/channel-plugin-api.ts +0 -3
  80. package/config-api.ts +0 -4
  81. package/constants.ts +0 -1
  82. package/contract-api.ts +0 -29
  83. package/directory-contract-api.ts +0 -4
  84. package/doctor-contract-api.ts +0 -8
  85. package/index.test.ts +0 -13
  86. package/index.ts +0 -16
  87. package/legacy-session-surface-api.ts +0 -6
  88. package/legacy-state-migrations-api.ts +0 -1
  89. package/light-runtime-api.ts +0 -12
  90. package/login-qr-api.ts +0 -1
  91. package/login-qr-runtime.ts +0 -23
  92. package/outbound-payload-test-api.ts +0 -1
  93. package/runtime-api.ts +0 -84
  94. package/secret-contract-api.ts +0 -4
  95. package/security-contract-api.ts +0 -4
  96. package/setup-entry.test.ts +0 -21
  97. package/setup-entry.ts +0 -21
  98. package/setup-plugin-api.ts +0 -3
  99. package/src/account-config.ts +0 -77
  100. package/src/account-ids.ts +0 -13
  101. package/src/account-types.ts +0 -5
  102. package/src/accounts.test.ts +0 -182
  103. package/src/accounts.ts +0 -176
  104. package/src/accounts.whatsapp-auth.test.ts +0 -59
  105. package/src/action-runtime-target-auth.ts +0 -27
  106. package/src/action-runtime.test.ts +0 -330
  107. package/src/action-runtime.ts +0 -76
  108. package/src/active-listener.test.ts +0 -65
  109. package/src/active-listener.ts +0 -17
  110. package/src/agent-tools-login.test.ts +0 -81
  111. package/src/agent-tools-login.ts +0 -113
  112. package/src/approval-auth.test.ts +0 -24
  113. package/src/approval-auth.ts +0 -27
  114. package/src/auth-store.runtime.ts +0 -1
  115. package/src/auth-store.test.ts +0 -311
  116. package/src/auth-store.ts +0 -502
  117. package/src/auto-reply/config.runtime.ts +0 -16
  118. package/src/auto-reply/constants.ts +0 -1
  119. package/src/auto-reply/deliver-reply.test.ts +0 -843
  120. package/src/auto-reply/deliver-reply.ts +0 -279
  121. package/src/auto-reply/loggers.ts +0 -6
  122. package/src/auto-reply/mentions.ts +0 -131
  123. package/src/auto-reply/monitor/ack-reaction.test.ts +0 -170
  124. package/src/auto-reply/monitor/ack-reaction.ts +0 -99
  125. package/src/auto-reply/monitor/audio-preflight.runtime.ts +0 -9
  126. package/src/auto-reply/monitor/broadcast.ts +0 -153
  127. package/src/auto-reply/monitor/commands.ts +0 -19
  128. package/src/auto-reply/monitor/echo.ts +0 -64
  129. package/src/auto-reply/monitor/group-activation.runtime.ts +0 -1
  130. package/src/auto-reply/monitor/group-activation.test.ts +0 -189
  131. package/src/auto-reply/monitor/group-activation.ts +0 -73
  132. package/src/auto-reply/monitor/group-gating.audio-preflight.test.ts +0 -103
  133. package/src/auto-reply/monitor/group-gating.runtime.ts +0 -8
  134. package/src/auto-reply/monitor/group-gating.ts +0 -217
  135. package/src/auto-reply/monitor/group-members.test.ts +0 -56
  136. package/src/auto-reply/monitor/group-members.ts +0 -65
  137. package/src/auto-reply/monitor/inbound-context.test.ts +0 -97
  138. package/src/auto-reply/monitor/inbound-context.ts +0 -92
  139. package/src/auto-reply/monitor/inbound-dispatch.runtime.ts +0 -21
  140. package/src/auto-reply/monitor/inbound-dispatch.test.ts +0 -895
  141. package/src/auto-reply/monitor/inbound-dispatch.ts +0 -422
  142. package/src/auto-reply/monitor/last-route.test.ts +0 -37
  143. package/src/auto-reply/monitor/last-route.ts +0 -61
  144. package/src/auto-reply/monitor/message-line.runtime.ts +0 -38
  145. package/src/auto-reply/monitor/message-line.ts +0 -54
  146. package/src/auto-reply/monitor/on-message.audio-preflight.test.ts +0 -354
  147. package/src/auto-reply/monitor/on-message.ts +0 -291
  148. package/src/auto-reply/monitor/peer.ts +0 -17
  149. package/src/auto-reply/monitor/process-message.audio-preflight.test.ts +0 -420
  150. package/src/auto-reply/monitor/process-message.test.ts +0 -355
  151. package/src/auto-reply/monitor/process-message.ts +0 -531
  152. package/src/auto-reply/monitor/runtime-api.ts +0 -30
  153. package/src/auto-reply/monitor-state.test.ts +0 -64
  154. package/src/auto-reply/monitor-state.ts +0 -106
  155. package/src/auto-reply/monitor.ts +0 -600
  156. package/src/auto-reply/reply-resolver.runtime.ts +0 -1
  157. package/src/auto-reply/types.ts +0 -48
  158. package/src/auto-reply/util.ts +0 -63
  159. package/src/auto-reply/web-auto-reply-monitor.test.ts +0 -687
  160. package/src/auto-reply/web-auto-reply-utils.test.ts +0 -392
  161. package/src/auto-reply.broadcast-groups.combined.test.ts +0 -246
  162. package/src/auto-reply.broadcast-groups.test-harness.ts +0 -47
  163. package/src/auto-reply.impl.ts +0 -6
  164. package/src/auto-reply.test-harness.ts +0 -421
  165. package/src/auto-reply.ts +0 -1
  166. package/src/auto-reply.web-auto-reply.compresses-common-formats-jpeg-cap.test.ts +0 -427
  167. package/src/auto-reply.web-auto-reply.connection-and-logging.e2e.test.ts +0 -908
  168. package/src/auto-reply.web-auto-reply.last-route.test.ts +0 -184
  169. package/src/channel-actions.runtime.ts +0 -7
  170. package/src/channel-actions.test.ts +0 -216
  171. package/src/channel-actions.ts +0 -84
  172. package/src/channel-outbound.test.ts +0 -131
  173. package/src/channel-outbound.ts +0 -36
  174. package/src/channel-react-action.runtime.ts +0 -7
  175. package/src/channel-react-action.test.ts +0 -294
  176. package/src/channel-react-action.ts +0 -84
  177. package/src/channel.runtime.ts +0 -117
  178. package/src/channel.setup.test.ts +0 -461
  179. package/src/channel.setup.ts +0 -28
  180. package/src/channel.ts +0 -339
  181. package/src/command-policy.ts +0 -7
  182. package/src/config-accessors.test.ts +0 -34
  183. package/src/config-accessors.ts +0 -22
  184. package/src/config-schema.test.ts +0 -121
  185. package/src/config-schema.ts +0 -6
  186. package/src/config-ui-hints.ts +0 -24
  187. package/src/connection-controller-registry.test.ts +0 -27
  188. package/src/connection-controller-registry.ts +0 -49
  189. package/src/connection-controller.test.ts +0 -282
  190. package/src/connection-controller.ts +0 -679
  191. package/src/creds-files.ts +0 -19
  192. package/src/creds-persistence.ts +0 -102
  193. package/src/directory-config.test.ts +0 -60
  194. package/src/directory-config.ts +0 -40
  195. package/src/directory-contract.test.ts +0 -56
  196. package/src/doctor-contract.ts +0 -11
  197. package/src/doctor.test.ts +0 -74
  198. package/src/doctor.ts +0 -56
  199. package/src/group-intro.ts +0 -15
  200. package/src/group-policy.test.ts +0 -36
  201. package/src/group-policy.ts +0 -40
  202. package/src/group-session-contract.ts +0 -20
  203. package/src/group-session-key.test.ts +0 -53
  204. package/src/group-session-key.ts +0 -41
  205. package/src/heartbeat.ts +0 -34
  206. package/src/identity.ts +0 -164
  207. package/src/inbound/access-control.test-harness.ts +0 -37
  208. package/src/inbound/access-control.test.ts +0 -375
  209. package/src/inbound/access-control.ts +0 -237
  210. package/src/inbound/dedupe.ts +0 -132
  211. package/src/inbound/extract.test.ts +0 -282
  212. package/src/inbound/extract.ts +0 -488
  213. package/src/inbound/lifecycle.ts +0 -39
  214. package/src/inbound/media.node.test.ts +0 -83
  215. package/src/inbound/media.ts +0 -102
  216. package/src/inbound/monitor.ts +0 -890
  217. package/src/inbound/runtime-api.ts +0 -7
  218. package/src/inbound/save-media.runtime.ts +0 -1
  219. package/src/inbound/send-api.test.ts +0 -319
  220. package/src/inbound/send-api.ts +0 -145
  221. package/src/inbound/send-result.ts +0 -61
  222. package/src/inbound/types.ts +0 -106
  223. package/src/inbound-context.contract.test.ts +0 -32
  224. package/src/inbound-policy.ts +0 -231
  225. package/src/inbound.media.test.ts +0 -320
  226. package/src/inbound.test.ts +0 -290
  227. package/src/inbound.ts +0 -9
  228. package/src/login-qr.test.ts +0 -483
  229. package/src/login-qr.ts +0 -542
  230. package/src/login.coverage.test.ts +0 -133
  231. package/src/login.test.ts +0 -89
  232. package/src/login.ts +0 -70
  233. package/src/logout.test.ts +0 -162
  234. package/src/media.test.ts +0 -480
  235. package/src/media.ts +0 -10
  236. package/src/monitor-inbox.allows-messages-from-senders-allowfrom-list.test-support.ts +0 -400
  237. package/src/monitor-inbox.append-upsert.test-support.ts +0 -133
  238. package/src/monitor-inbox.behavior.test.ts +0 -5
  239. package/src/monitor-inbox.blocks-messages-from-unauthorized-senders-not-allowfrom.test-support.ts +0 -362
  240. package/src/monitor-inbox.captures-media-path-image-messages.test-support.ts +0 -306
  241. package/src/monitor-inbox.streams-inbound-messages.test-support.ts +0 -729
  242. package/src/monitor-inbox.test-harness.ts +0 -304
  243. package/src/normalize-target.ts +0 -123
  244. package/src/normalize.ts +0 -7
  245. package/src/outbound-adapter.poll.test.ts +0 -62
  246. package/src/outbound-adapter.sendpayload.test.ts +0 -195
  247. package/src/outbound-adapter.ts +0 -36
  248. package/src/outbound-base.test.ts +0 -560
  249. package/src/outbound-base.ts +0 -244
  250. package/src/outbound-media-contract.ts +0 -278
  251. package/src/outbound-media.runtime.ts +0 -36
  252. package/src/outbound-payload.contract.test.ts +0 -61
  253. package/src/outbound-send-deps.ts +0 -1
  254. package/src/outbound-test-support.ts +0 -16
  255. package/src/pairing-security.test-harness.ts +0 -59
  256. package/src/qr-image.ts +0 -1
  257. package/src/qr-terminal.ts +0 -1
  258. package/src/quoted-message.test.ts +0 -83
  259. package/src/quoted-message.ts +0 -184
  260. package/src/reaction-level.test.ts +0 -94
  261. package/src/reaction-level.ts +0 -21
  262. package/src/reconnect.test.ts +0 -51
  263. package/src/reconnect.ts +0 -55
  264. package/src/resolve-outbound-target.test.ts +0 -288
  265. package/src/resolve-outbound-target.ts +0 -58
  266. package/src/resolve-target.test.ts +0 -120
  267. package/src/runtime-api.ts +0 -59
  268. package/src/runtime-group-policy.ts +0 -16
  269. package/src/runtime.ts +0 -9
  270. package/src/security-contract.ts +0 -47
  271. package/src/security-fix.ts +0 -71
  272. package/src/send.test.ts +0 -534
  273. package/src/send.ts +0 -292
  274. package/src/session-contract.test.ts +0 -31
  275. package/src/session-contract.ts +0 -43
  276. package/src/session-errors.ts +0 -125
  277. package/src/session-route.test.ts +0 -41
  278. package/src/session-route.ts +0 -32
  279. package/src/session.runtime.ts +0 -8
  280. package/src/session.test.ts +0 -559
  281. package/src/session.ts +0 -330
  282. package/src/setup-core.ts +0 -52
  283. package/src/setup-finalize.ts +0 -446
  284. package/src/setup-surface.test.ts +0 -367
  285. package/src/setup-surface.ts +0 -69
  286. package/src/setup-test-helpers.ts +0 -216
  287. package/src/shared.ts +0 -291
  288. package/src/socket-timing.test.ts +0 -49
  289. package/src/socket-timing.ts +0 -38
  290. package/src/state-migrations.ts +0 -54
  291. package/src/status-issues.test.ts +0 -137
  292. package/src/status-issues.ts +0 -185
  293. package/src/system-prompt.test.ts +0 -199
  294. package/src/system-prompt.ts +0 -31
  295. package/src/targets-runtime.ts +0 -180
  296. package/src/test-helpers.ts +0 -690
  297. package/src/text-runtime.test.ts +0 -162
  298. package/src/text-runtime.ts +0 -11
  299. package/src/vcard.ts +0 -84
  300. package/targets.ts +0 -5
  301. package/test-api.ts +0 -2
  302. package/tsconfig.json +0 -16
@@ -1,890 +0,0 @@
1
- import type {
2
- AnyMessageContent,
3
- MiscMessageGenerationOptions,
4
- proto,
5
- GroupMetadata,
6
- WAMessage,
7
- WASocket,
8
- } from "@whiskeysockets/baileys";
9
- import { recordChannelActivity } from "openclaw/plugin-sdk/channel-activity-runtime";
10
- import { formatLocationText } from "openclaw/plugin-sdk/channel-inbound";
11
- import { createInboundDebouncer } from "openclaw/plugin-sdk/channel-inbound-debounce";
12
- import { defaultRuntime } from "openclaw/plugin-sdk/runtime-env";
13
- import { createSubsystemLogger } from "openclaw/plugin-sdk/runtime-env";
14
- import { getChildLogger } from "openclaw/plugin-sdk/text-runtime";
15
- import { readWebSelfIdentityForDecision, WhatsAppAuthUnstableError } from "../auth-store.js";
16
- import { getPrimaryIdentityId, resolveComparableIdentity } from "../identity.js";
17
- import { cacheInboundMessageMeta } from "../quoted-message.js";
18
- import { DEFAULT_RECONNECT_POLICY, computeBackoff, sleepWithAbort } from "../reconnect.js";
19
- import type { OpenClawConfig } from "../runtime-api.js";
20
- import { createWaSocket, formatError, getStatusCode, waitForWaConnection } from "../session.js";
21
- import { resolveWhatsAppSocketTiming } from "../socket-timing.js";
22
- import { resolveJidToE164 } from "../text-runtime.js";
23
- import { checkInboundAccessControl } from "./access-control.js";
24
- import {
25
- claimRecentInboundMessage,
26
- commitRecentInboundMessage,
27
- isRecentOutboundMessage,
28
- releaseRecentInboundMessage,
29
- rememberRecentOutboundMessage,
30
- WhatsAppRetryableInboundError,
31
- } from "./dedupe.js";
32
- import {
33
- describeReplyContext,
34
- extractLocationData,
35
- extractContactContext,
36
- extractMediaPlaceholder,
37
- extractMentionedJids,
38
- extractText,
39
- hasInboundUserContent,
40
- } from "./extract.js";
41
- import { attachEmitterListener, closeInboundMonitorSocket } from "./lifecycle.js";
42
- import { downloadInboundMedia, downloadQuotedInboundMedia } from "./media.js";
43
- import { DisconnectReason, isJidGroup, saveMediaBuffer } from "./runtime-api.js";
44
- import { createWebSendApi } from "./send-api.js";
45
- import { normalizeWhatsAppSendResult } from "./send-result.js";
46
- import type { WebInboundMessage, WebListenerCloseReason } from "./types.js";
47
-
48
- const LOGGED_OUT_STATUS = DisconnectReason?.loggedOut ?? 401;
49
- const RECONNECT_IN_PROGRESS_ERROR = "no active socket - reconnection in progress";
50
- const GROUP_META_TTL_MS = 5 * 60 * 1000; // 5 minutes
51
- export const WHATSAPP_GROUP_METADATA_CACHE_MAX_ENTRIES = 500;
52
-
53
- type WhatsAppGroupMetadataCacheEntry = {
54
- subject?: string;
55
- expires: number;
56
- };
57
- export type WhatsAppGroupMetadataCache = Map<string, WhatsAppGroupMetadataCacheEntry>;
58
- type LocalGroupMetadataCacheEntry = WhatsAppGroupMetadataCacheEntry & {
59
- participants?: string[];
60
- };
61
-
62
- function rememberGroupMetadataCacheEntry<T extends WhatsAppGroupMetadataCacheEntry>(
63
- cache: Map<string, T>,
64
- jid: string,
65
- entry: T,
66
- ): void {
67
- if (cache.has(jid)) {
68
- cache.delete(jid);
69
- }
70
- cache.set(jid, entry);
71
-
72
- while (cache.size > WHATSAPP_GROUP_METADATA_CACHE_MAX_ENTRIES) {
73
- const oldest = cache.keys().next();
74
- if (oldest.done) {
75
- break;
76
- }
77
- cache.delete(oldest.value);
78
- }
79
- }
80
-
81
- function readGroupMetadataCacheEntry<T extends WhatsAppGroupMetadataCacheEntry>(
82
- cache: Map<string, T>,
83
- jid: string,
84
- ): T | null {
85
- const entry = cache.get(jid);
86
- if (!entry) {
87
- return null;
88
- }
89
- if (entry.expires <= Date.now()) {
90
- cache.delete(jid);
91
- return null;
92
- }
93
- cache.delete(jid);
94
- cache.set(jid, entry);
95
- return entry;
96
- }
97
-
98
- function logWhatsAppVerbose(enabled: boolean | undefined, message: string) {
99
- if (!enabled) {
100
- return;
101
- }
102
- defaultRuntime.log(message);
103
- }
104
-
105
- function isGroupJid(jid: string): boolean {
106
- return (typeof isJidGroup === "function" ? isJidGroup(jid) : jid.endsWith("@g.us")) === true;
107
- }
108
-
109
- function isRetryableSendDisconnectError(err: unknown): boolean {
110
- return /closed|reset|timed\s*out|disconnect|no active socket/i.test(formatError(err));
111
- }
112
-
113
- function shouldClearSocketRefAfterSendFailure(err: unknown): boolean {
114
- return /closed|reset|disconnect|no active socket/i.test(formatError(err));
115
- }
116
-
117
- function isNonEmptyString(value: string | undefined): value is string {
118
- return Boolean(value);
119
- }
120
-
121
- type MonitorWebInboxOptions = {
122
- cfg: OpenClawConfig;
123
- verbose: boolean;
124
- accountId: string;
125
- authDir: string;
126
- onMessage: (msg: WebInboundMessage) => Promise<void>;
127
- mediaMaxMb?: number;
128
- /** Keep the global presence unavailable so self-chat sessions do not mute phone pushes. */
129
- selfChatMode?: boolean;
130
- /** Send read receipts for incoming messages (default true). */
131
- sendReadReceipts?: boolean;
132
- /** Debounce window (ms) for batching rapid consecutive messages from the same sender (0 to disable). */
133
- debounceMs?: number;
134
- /** Optional debounce gating predicate. */
135
- shouldDebounce?: (msg: WebInboundMessage) => boolean;
136
- /** Optional shared socket reference so reply closures can follow reconnects. */
137
- socketRef?: { current: WASocket | null };
138
- /** Whether send retries should wait for a reconnect. */
139
- shouldRetryDisconnect?: () => boolean;
140
- /** Reconnect timing for waiting through transient socket replacement gaps. */
141
- disconnectRetryPolicy?: {
142
- initialMs: number;
143
- maxMs: number;
144
- factor: number;
145
- jitter: number;
146
- maxAttempts: number;
147
- };
148
- /** Abort in-flight reconnect waits when shutdown becomes terminal. */
149
- disconnectRetryAbortSignal?: AbortSignal;
150
- /** Shared group metadata cache used only for inbound metadata fallback after fetch failures. */
151
- groupMetadataCache?: WhatsAppGroupMetadataCache;
152
- };
153
-
154
- export async function attachWebInboxToSocket(
155
- options: MonitorWebInboxOptions & {
156
- sock: WASocket;
157
- },
158
- ) {
159
- const inboundLogger = getChildLogger({ module: "web-inbound" });
160
- const inboundConsoleLog = createSubsystemLogger("gateway/channels/whatsapp").child("inbound");
161
- const sock = options.sock;
162
- const connectedAtMs = Date.now();
163
- if (options.socketRef) {
164
- options.socketRef.current = sock;
165
- }
166
- const getCurrentSock = () => (options.socketRef ? options.socketRef.current : sock);
167
- const shouldRetryDisconnect = () => options.shouldRetryDisconnect?.() === true;
168
- const disconnectRetryPolicy = options.disconnectRetryPolicy ?? DEFAULT_RECONNECT_POLICY;
169
- const sendRetryMaxAttempts =
170
- disconnectRetryPolicy.maxAttempts > 0
171
- ? disconnectRetryPolicy.maxAttempts
172
- : DEFAULT_RECONNECT_POLICY.maxAttempts;
173
-
174
- let onCloseResolve: ((reason: WebListenerCloseReason) => void) | null = null;
175
- const onClose = new Promise<WebListenerCloseReason>((resolve) => {
176
- onCloseResolve = resolve;
177
- });
178
- const resolveClose = (reason: WebListenerCloseReason) => {
179
- if (!onCloseResolve) {
180
- return;
181
- }
182
- const resolver = onCloseResolve;
183
- onCloseResolve = null;
184
- resolver(reason);
185
- };
186
- const presence = options.selfChatMode ? "unavailable" : "available";
187
-
188
- try {
189
- await sock.sendPresenceUpdate(presence);
190
- logWhatsAppVerbose(options.verbose, `Sent global '${presence}' presence on connect`);
191
- } catch (err) {
192
- logWhatsAppVerbose(
193
- options.verbose,
194
- `Failed to send '${presence}' presence on connect: ${String(err)}`,
195
- );
196
- }
197
-
198
- const selfIdentity = await readWebSelfIdentityForDecision(
199
- options.authDir,
200
- sock.user as { id?: string | null; lid?: string | null } | undefined,
201
- );
202
- if (selfIdentity.outcome === "unstable") {
203
- throw new WhatsAppAuthUnstableError(
204
- "WhatsApp auth state is still stabilizing; retrying inbox attach.",
205
- );
206
- }
207
- const self = selfIdentity.identity;
208
- type QueuedInboundMessage = WebInboundMessage & {
209
- dedupeKey?: string;
210
- };
211
-
212
- const finalizeInboundDedupe = async (
213
- entries: QueuedInboundMessage[],
214
- error?: unknown,
215
- ): Promise<void> => {
216
- const dedupeKeys = [
217
- ...new Set(entries.map((entry) => entry.dedupeKey).filter(isNonEmptyString)),
218
- ];
219
- if (dedupeKeys.length === 0) {
220
- return;
221
- }
222
- if (error instanceof WhatsAppRetryableInboundError) {
223
- dedupeKeys.forEach((dedupeKey) => releaseRecentInboundMessage(dedupeKey, error));
224
- return;
225
- }
226
- await Promise.all(dedupeKeys.map((dedupeKey) => commitRecentInboundMessage(dedupeKey)));
227
- };
228
-
229
- const debouncer = createInboundDebouncer<QueuedInboundMessage>({
230
- debounceMs: options.debounceMs ?? 0,
231
- buildKey: (msg) => {
232
- const sender = msg.sender;
233
- const senderKey =
234
- msg.chatType === "group"
235
- ? (getPrimaryIdentityId(sender ?? null) ??
236
- msg.senderJid ??
237
- msg.senderE164 ??
238
- msg.senderName ??
239
- msg.from)
240
- : msg.from;
241
- if (!senderKey) {
242
- return null;
243
- }
244
- const conversationKey = msg.chatType === "group" ? msg.chatId : msg.from;
245
- return `${msg.accountId}:${conversationKey}:${senderKey}`;
246
- },
247
- shouldDebounce: options.shouldDebounce,
248
- onFlush: async (entries) => {
249
- const last = entries.at(-1);
250
- if (!last) {
251
- return;
252
- }
253
- try {
254
- if (entries.length === 1) {
255
- await options.onMessage(last);
256
- await finalizeInboundDedupe(entries);
257
- return;
258
- }
259
- const mentioned = new Set<string>();
260
- for (const entry of entries) {
261
- for (const jid of entry.mentions ?? entry.mentionedJids ?? []) {
262
- mentioned.add(jid);
263
- }
264
- }
265
- const combinedBody = entries
266
- .map((entry) => entry.body)
267
- .filter(Boolean)
268
- .join("\n");
269
- const combinedMessage: WebInboundMessage = {
270
- ...last,
271
- body: combinedBody,
272
- mentions: mentioned.size > 0 ? Array.from(mentioned) : undefined,
273
- mentionedJids: mentioned.size > 0 ? Array.from(mentioned) : undefined,
274
- isBatched: true,
275
- };
276
- await options.onMessage(combinedMessage);
277
- await finalizeInboundDedupe(entries);
278
- } catch (error) {
279
- await finalizeInboundDedupe(entries, error);
280
- throw error;
281
- }
282
- },
283
- onError: (err) => {
284
- inboundLogger.error({ error: String(err) }, "failed handling inbound web message");
285
- inboundConsoleLog.error(`Failed handling inbound web message: ${String(err)}`);
286
- },
287
- });
288
- const groupMetadataCache = options.groupMetadataCache ?? new Map();
289
- const groupMetaCache = new Map<string, LocalGroupMetadataCacheEntry>();
290
- const lidLookup = sock.signalRepository?.lidMapping;
291
-
292
- const resolveInboundJid = async (jid: string | null | undefined): Promise<string | null> =>
293
- resolveJidToE164(jid, { authDir: options.authDir, lidLookup });
294
-
295
- const rememberOutboundMessage = (remoteJid: string, result: unknown) => {
296
- const messageId =
297
- typeof result === "object" && result && "key" in result
298
- ? ((result as { key?: { id?: string } }).key?.id ?? "")
299
- : "";
300
- if (!messageId) {
301
- return;
302
- }
303
- rememberRecentOutboundMessage({
304
- accountId: options.accountId,
305
- remoteJid,
306
- messageId,
307
- });
308
- };
309
-
310
- const sendTrackedMessage = async (
311
- jid: string,
312
- content: AnyMessageContent,
313
- sendOptions?: MiscMessageGenerationOptions,
314
- ) => {
315
- let lastErr: unknown = new Error(RECONNECT_IN_PROGRESS_ERROR);
316
- for (let attempt = 1; ; attempt++) {
317
- const currentSock = getCurrentSock();
318
- if (currentSock) {
319
- try {
320
- const result = sendOptions
321
- ? await currentSock.sendMessage(jid, content, sendOptions)
322
- : await currentSock.sendMessage(jid, content);
323
- rememberOutboundMessage(jid, result);
324
- return result;
325
- } catch (err) {
326
- if (!shouldRetryDisconnect() || !isRetryableSendDisconnectError(err)) {
327
- throw err;
328
- }
329
- lastErr = err;
330
- if (
331
- shouldClearSocketRefAfterSendFailure(err) &&
332
- options.socketRef?.current === currentSock
333
- ) {
334
- options.socketRef.current = null;
335
- }
336
- }
337
- } else if (!shouldRetryDisconnect()) {
338
- throw lastErr;
339
- }
340
-
341
- if (attempt >= sendRetryMaxAttempts) {
342
- throw lastErr;
343
- }
344
- const delayMs = computeBackoff(disconnectRetryPolicy, attempt);
345
- logWhatsAppVerbose(
346
- options.verbose,
347
- `Waiting ${delayMs}ms for WhatsApp reconnect before retrying send to ${jid}: ${formatError(lastErr)}`,
348
- );
349
- try {
350
- await sleepWithAbort(delayMs, options.disconnectRetryAbortSignal);
351
- } catch {
352
- throw lastErr;
353
- }
354
- }
355
- };
356
-
357
- const summarizeGroupMeta = async (meta: GroupMetadata) => {
358
- const participants =
359
- (
360
- await Promise.all(
361
- meta.participants?.map(async (p) => {
362
- const mapped = await resolveInboundJid(p.id);
363
- return mapped ?? p.id;
364
- }) ?? [],
365
- )
366
- ).filter(Boolean) ?? [];
367
- return {
368
- subject: meta.subject,
369
- participants,
370
- expires: Date.now() + GROUP_META_TTL_MS,
371
- };
372
- };
373
-
374
- const summarizeGroupMetaForReconnectCache = (
375
- meta: GroupMetadata,
376
- ): WhatsAppGroupMetadataCacheEntry => ({
377
- subject: meta.subject,
378
- expires: Date.now() + GROUP_META_TTL_MS,
379
- });
380
-
381
- const getGroupMeta = async (jid: string) => {
382
- const cached = readGroupMetadataCacheEntry(groupMetaCache, jid);
383
- if (cached) {
384
- return cached;
385
- }
386
- try {
387
- const meta = await sock.groupMetadata(jid);
388
- const entry = await summarizeGroupMeta(meta);
389
- rememberGroupMetadataCacheEntry(groupMetadataCache, jid, {
390
- subject: entry.subject,
391
- expires: entry.expires,
392
- });
393
- rememberGroupMetadataCacheEntry(groupMetaCache, jid, entry);
394
- return entry;
395
- } catch (err) {
396
- const hydrated = readGroupMetadataCacheEntry(groupMetadataCache, jid);
397
- if (hydrated) {
398
- rememberGroupMetadataCacheEntry(groupMetaCache, jid, hydrated);
399
- logWhatsAppVerbose(
400
- options.verbose,
401
- `Using cached group metadata for ${jid} after fetch failure: ${String(err)}`,
402
- );
403
- return hydrated;
404
- }
405
- logWhatsAppVerbose(
406
- options.verbose,
407
- `Failed to fetch group metadata for ${jid}: ${String(err)}`,
408
- );
409
- return { expires: Date.now() + GROUP_META_TTL_MS };
410
- }
411
- };
412
-
413
- type NormalizedInboundMessage = {
414
- id?: string;
415
- remoteJid: string;
416
- group: boolean;
417
- participantJid?: string;
418
- from: string;
419
- senderE164: string | null;
420
- groupSubject?: string;
421
- groupParticipants?: string[];
422
- messageTimestampMs?: number;
423
- access: Awaited<ReturnType<typeof checkInboundAccessControl>>;
424
- };
425
-
426
- const normalizeInboundMessage = async (
427
- msg: WAMessage,
428
- ): Promise<NormalizedInboundMessage | null> => {
429
- const id = msg.key?.id ?? undefined;
430
- const remoteJid = msg.key?.remoteJid;
431
- if (!remoteJid) {
432
- return null;
433
- }
434
- if (remoteJid.endsWith("@status") || remoteJid.endsWith("@broadcast")) {
435
- return null;
436
- }
437
-
438
- const group = isGroupJid(remoteJid);
439
- // Drop echoes of messages the gateway itself sent (tracked by sendTrackedMessage).
440
- // Applies to both groups and DMs/self-chat — without this, self-chat mode
441
- // re-processes the bot's own replies as new inbound user messages.
442
- if (
443
- Boolean(msg.key?.fromMe) &&
444
- id &&
445
- isRecentOutboundMessage({
446
- accountId: options.accountId,
447
- remoteJid,
448
- messageId: id,
449
- })
450
- ) {
451
- logWhatsAppVerbose(
452
- options.verbose,
453
- `Skipping recent outbound WhatsApp echo ${id} for ${remoteJid}`,
454
- );
455
- return null;
456
- }
457
- // Gate pairing access-control on extractable inbound user content. Baileys
458
- // delivers receipts, typing indicators, presence updates, and protocol
459
- // messages on the same `messages.upsert` stream as real messages; without
460
- // this gate, `checkInboundAccessControl` can send an unsolicited pairing
461
- // verification reply to a `dmPolicy: pairing` peer who never typed
462
- // anything (e.g. when Master sends an outbound message to a new JID and
463
- // the receipt round-trip arrives before the recipient ever replies).
464
- // Echoes of our own outbound messages are already handled above.
465
- if (!hasInboundUserContent(msg.message ?? undefined)) {
466
- return null;
467
- }
468
-
469
- const participantJid = msg.key?.participant ?? undefined;
470
- const from = group ? remoteJid : await resolveInboundJid(remoteJid);
471
- if (!from) {
472
- return null;
473
- }
474
- const senderE164 = group
475
- ? participantJid
476
- ? await resolveInboundJid(participantJid)
477
- : null
478
- : from;
479
-
480
- let groupSubject: string | undefined;
481
- let groupParticipants: string[] | undefined;
482
- if (group) {
483
- const meta = await getGroupMeta(remoteJid);
484
- groupSubject = meta.subject;
485
- groupParticipants = meta.participants;
486
- }
487
- const messageTimestampMs = msg.messageTimestamp
488
- ? Number(msg.messageTimestamp) * 1000
489
- : undefined;
490
-
491
- const access = await checkInboundAccessControl({
492
- cfg: options.cfg,
493
- accountId: options.accountId,
494
- from,
495
- selfE164: self.e164 ?? null,
496
- senderE164,
497
- group,
498
- pushName: msg.pushName ?? undefined,
499
- isFromMe: Boolean(msg.key?.fromMe),
500
- messageTimestampMs,
501
- connectedAtMs,
502
- verbose: options.verbose,
503
- sock: {
504
- sendMessage: (jid: string, content: AnyMessageContent) => sendTrackedMessage(jid, content),
505
- },
506
- remoteJid,
507
- });
508
- if (!access.allowed) {
509
- return null;
510
- }
511
-
512
- return {
513
- id,
514
- remoteJid,
515
- group,
516
- participantJid,
517
- from,
518
- senderE164,
519
- groupSubject,
520
- groupParticipants,
521
- messageTimestampMs,
522
- access,
523
- };
524
- };
525
-
526
- const maybeMarkInboundAsRead = async (inbound: NormalizedInboundMessage) => {
527
- const { id, remoteJid, participantJid, access } = inbound;
528
- if (id && !access.isSelfChat && options.sendReadReceipts !== false) {
529
- try {
530
- await sock.readMessages([{ remoteJid, id, participant: participantJid, fromMe: false }]);
531
- const suffix = participantJid ? ` (participant ${participantJid})` : "";
532
- logWhatsAppVerbose(
533
- options.verbose,
534
- `Marked message ${id} as read for ${remoteJid}${suffix}`,
535
- );
536
- } catch (err) {
537
- logWhatsAppVerbose(options.verbose, `Failed to mark message ${id} read: ${String(err)}`);
538
- }
539
- } else if (id && access.isSelfChat && options.verbose) {
540
- // Self-chat mode: never auto-send read receipts (blue ticks) on behalf of the owner.
541
- logWhatsAppVerbose(options.verbose, `Self-chat mode: skipping read receipt for ${id}`);
542
- }
543
- };
544
-
545
- type EnrichedInboundMessage = {
546
- body: string;
547
- location?: ReturnType<typeof extractLocationData>;
548
- contactContext?: ReturnType<typeof extractContactContext>;
549
- replyContext?: ReturnType<typeof describeReplyContext>;
550
- mediaPath?: string;
551
- mediaType?: string;
552
- mediaFileName?: string;
553
- };
554
-
555
- const enrichInboundMessage = async (msg: WAMessage): Promise<EnrichedInboundMessage | null> => {
556
- const location = extractLocationData(msg.message ?? undefined);
557
- const locationText = location ? formatLocationText(location) : undefined;
558
- const contactContext = extractContactContext(msg.message ?? undefined);
559
- let body = extractText(msg.message ?? undefined);
560
- if (locationText) {
561
- body = [body, locationText].filter(Boolean).join("\n").trim();
562
- }
563
- if (!body) {
564
- body = extractMediaPlaceholder(msg.message ?? undefined);
565
- if (!body) {
566
- return null;
567
- }
568
- }
569
- const replyContext = describeReplyContext(msg.message as proto.IMessage | undefined);
570
-
571
- let mediaPath: string | undefined;
572
- let mediaType: string | undefined;
573
- let mediaFileName: string | undefined;
574
- const saveInboundMedia = async (
575
- inboundMedia: Awaited<ReturnType<typeof downloadInboundMedia>>,
576
- ) => {
577
- if (!inboundMedia) {
578
- return;
579
- }
580
- const maxMb =
581
- typeof options.mediaMaxMb === "number" && options.mediaMaxMb > 0 ? options.mediaMaxMb : 50;
582
- const maxBytes = maxMb * 1024 * 1024;
583
- const saved = await saveMediaBuffer(
584
- inboundMedia.buffer,
585
- inboundMedia.mimetype,
586
- "inbound",
587
- maxBytes,
588
- inboundMedia.fileName,
589
- );
590
- mediaPath = saved.path;
591
- mediaType = inboundMedia.mimetype;
592
- mediaFileName = inboundMedia.fileName;
593
- };
594
- try {
595
- const inboundMedia = await downloadInboundMedia(msg as proto.IWebMessageInfo, sock);
596
- await saveInboundMedia(inboundMedia);
597
- if (!mediaPath && replyContext) {
598
- await saveInboundMedia(
599
- await downloadQuotedInboundMedia(msg as proto.IWebMessageInfo, sock),
600
- );
601
- }
602
- } catch (err) {
603
- logWhatsAppVerbose(options.verbose, `Inbound media download failed: ${String(err)}`);
604
- }
605
-
606
- return {
607
- body,
608
- location: location ?? undefined,
609
- contactContext,
610
- replyContext,
611
- mediaPath,
612
- mediaType,
613
- mediaFileName,
614
- };
615
- };
616
-
617
- const enqueueInboundMessage = async (
618
- msg: WAMessage,
619
- inbound: NormalizedInboundMessage,
620
- enriched: EnrichedInboundMessage,
621
- ) => {
622
- const chatJid = inbound.remoteJid;
623
- const sendComposing = async () => {
624
- const currentSock = getCurrentSock();
625
- if (!currentSock) {
626
- return;
627
- }
628
- try {
629
- await currentSock.sendPresenceUpdate("composing", chatJid);
630
- } catch (err) {
631
- logWhatsAppVerbose(options.verbose, `Presence update failed: ${String(err)}`);
632
- }
633
- };
634
- const reply = async (text: string, options?: MiscMessageGenerationOptions) => {
635
- const result = await sendTrackedMessage(chatJid, { text }, options);
636
- return normalizeWhatsAppSendResult(result, "text");
637
- };
638
- const sendMedia = async (
639
- payload: AnyMessageContent,
640
- options?: MiscMessageGenerationOptions,
641
- ) => {
642
- const result = await sendTrackedMessage(chatJid, payload, options);
643
- return normalizeWhatsAppSendResult(result, "media");
644
- };
645
- const timestamp = inbound.messageTimestampMs;
646
- const mentionedJids = extractMentionedJids(msg.message as proto.IMessage | undefined);
647
- const senderName = msg.pushName ?? undefined;
648
-
649
- inboundLogger.info(
650
- {
651
- from: inbound.from,
652
- to: self.e164 ?? "me",
653
- body: enriched.body,
654
- mediaPath: enriched.mediaPath,
655
- mediaType: enriched.mediaType,
656
- mediaFileName: enriched.mediaFileName,
657
- timestamp,
658
- },
659
- "inbound message",
660
- );
661
- const inboundMessage: QueuedInboundMessage = {
662
- id: inbound.id,
663
- from: inbound.from,
664
- conversationId: inbound.from,
665
- to: self.e164 ?? "me",
666
- accountId: inbound.access.resolvedAccountId,
667
- accessControlPassed: true,
668
- body: enriched.body,
669
- pushName: senderName,
670
- timestamp,
671
- chatType: inbound.group ? "group" : "direct",
672
- chatId: inbound.remoteJid,
673
- sender: resolveComparableIdentity({
674
- jid: inbound.participantJid,
675
- e164: inbound.senderE164 ?? undefined,
676
- name: senderName,
677
- }),
678
- senderJid: inbound.participantJid,
679
- senderE164: inbound.senderE164 ?? undefined,
680
- senderName,
681
- replyTo: enriched.replyContext ?? undefined,
682
- replyToId: enriched.replyContext?.id,
683
- replyToBody: enriched.replyContext?.body,
684
- replyToSender: enriched.replyContext?.sender?.label ?? undefined,
685
- replyToSenderJid: enriched.replyContext?.sender?.jid ?? undefined,
686
- replyToSenderE164: enriched.replyContext?.sender?.e164 ?? undefined,
687
- groupSubject: inbound.groupSubject,
688
- groupParticipants: inbound.groupParticipants,
689
- mentions: mentionedJids ?? undefined,
690
- mentionedJids: mentionedJids ?? undefined,
691
- self,
692
- selfJid: self.jid ?? undefined,
693
- selfLid: self.lid ?? undefined,
694
- selfE164: self.e164 ?? undefined,
695
- fromMe: Boolean(msg.key?.fromMe),
696
- location: enriched.location ?? undefined,
697
- untrustedStructuredContext: enriched.contactContext
698
- ? [
699
- {
700
- label: "WhatsApp contact",
701
- source: "whatsapp",
702
- type: enriched.contactContext.kind,
703
- payload: enriched.contactContext,
704
- },
705
- ]
706
- : undefined,
707
- sendComposing,
708
- reply,
709
- sendMedia,
710
- mediaPath: enriched.mediaPath,
711
- mediaType: enriched.mediaType,
712
- mediaFileName: enriched.mediaFileName,
713
- dedupeKey: inbound.id ? `${options.accountId}:${inbound.remoteJid}:${inbound.id}` : undefined,
714
- };
715
- if (inboundMessage.id) {
716
- cacheInboundMessageMeta(inboundMessage.accountId, inboundMessage.chatId, inboundMessage.id, {
717
- participant: inboundMessage.senderJid,
718
- participantE164:
719
- inboundMessage.chatType === "direct" ? inboundMessage.senderE164 : undefined,
720
- body: inboundMessage.body,
721
- fromMe: inboundMessage.fromMe,
722
- });
723
- }
724
- try {
725
- const task = Promise.resolve(debouncer.enqueue(inboundMessage));
726
- void task.catch((err) => {
727
- inboundLogger.error({ error: String(err) }, "failed handling inbound web message");
728
- inboundConsoleLog.error(`Failed handling inbound web message: ${String(err)}`);
729
- });
730
- } catch (err) {
731
- inboundLogger.error({ error: String(err) }, "failed handling inbound web message");
732
- inboundConsoleLog.error(`Failed handling inbound web message: ${String(err)}`);
733
- }
734
- };
735
-
736
- const handleMessagesUpsert = async (upsert: { type?: string; messages?: Array<WAMessage> }) => {
737
- if (upsert.type !== "notify" && upsert.type !== "append") {
738
- return;
739
- }
740
- for (const msg of upsert.messages ?? []) {
741
- recordChannelActivity({
742
- channel: "whatsapp",
743
- accountId: options.accountId,
744
- direction: "inbound",
745
- });
746
- const inbound = await normalizeInboundMessage(msg);
747
- if (!inbound) {
748
- continue;
749
- }
750
-
751
- await maybeMarkInboundAsRead(inbound);
752
-
753
- // If this is history/offline catch-up, mark read above but skip auto-reply.
754
- if (upsert.type === "append") {
755
- const APPEND_RECENT_GRACE_MS = 60_000;
756
- const msgTsRaw = msg.messageTimestamp;
757
- const msgTsNum = msgTsRaw != null ? Number(msgTsRaw) : Number.NaN;
758
- const msgTsMs = Number.isFinite(msgTsNum) ? msgTsNum * 1000 : 0;
759
- if (msgTsMs < connectedAtMs - APPEND_RECENT_GRACE_MS) {
760
- continue;
761
- }
762
- }
763
-
764
- const enriched = await enrichInboundMessage(msg);
765
- if (!enriched) {
766
- continue;
767
- }
768
-
769
- const dedupeKey = inbound.id ? `${options.accountId}:${inbound.remoteJid}:${inbound.id}` : "";
770
- if (dedupeKey && !(await claimRecentInboundMessage(dedupeKey))) {
771
- continue;
772
- }
773
-
774
- await enqueueInboundMessage(msg, inbound, enriched);
775
- }
776
- };
777
- const handleConnectionUpdate = (
778
- update: Partial<import("@whiskeysockets/baileys").ConnectionState>,
779
- ) => {
780
- try {
781
- if (update.connection === "close") {
782
- if (options.socketRef?.current === sock) {
783
- options.socketRef.current = null;
784
- }
785
- const status = getStatusCode(update.lastDisconnect?.error);
786
- resolveClose({
787
- status,
788
- isLoggedOut: status === LOGGED_OUT_STATUS,
789
- error: update.lastDisconnect?.error,
790
- });
791
- }
792
- } catch (err) {
793
- inboundLogger.error({ error: String(err) }, "connection.update handler error");
794
- resolveClose({ status: undefined, isLoggedOut: false, error: err });
795
- }
796
- };
797
- const detachMessagesUpsert = attachEmitterListener(
798
- sock.ev as unknown as {
799
- on: (event: string, listener: (...args: unknown[]) => void) => void;
800
- off?: (event: string, listener: (...args: unknown[]) => void) => void;
801
- removeListener?: (event: string, listener: (...args: unknown[]) => void) => void;
802
- },
803
- "messages.upsert",
804
- handleMessagesUpsert as unknown as (...args: unknown[]) => void,
805
- );
806
- const detachConnectionUpdate = attachEmitterListener(
807
- sock.ev as unknown as {
808
- on: (event: string, listener: (...args: unknown[]) => void) => void;
809
- off?: (event: string, listener: (...args: unknown[]) => void) => void;
810
- removeListener?: (event: string, listener: (...args: unknown[]) => void) => void;
811
- },
812
- "connection.update",
813
- handleConnectionUpdate as unknown as (...args: unknown[]) => void,
814
- );
815
-
816
- void (async () => {
817
- try {
818
- const groups = await sock.groupFetchAllParticipating();
819
- for (const [jid, meta] of Object.entries(groups ?? {})) {
820
- if (meta) {
821
- rememberGroupMetadataCacheEntry(
822
- groupMetadataCache,
823
- jid,
824
- summarizeGroupMetaForReconnectCache(meta),
825
- );
826
- }
827
- }
828
- logWhatsAppVerbose(
829
- options.verbose,
830
- `Hydrated ${Object.keys(groups ?? {}).length} participating groups on connect`,
831
- );
832
- } catch (err) {
833
- const error = String(err);
834
- inboundLogger.warn({ error }, "failed hydrating participating groups on connect");
835
- inboundConsoleLog.warn(`Failed hydrating participating groups on connect: ${error}`);
836
- logWhatsAppVerbose(
837
- options.verbose,
838
- `Failed to hydrate participating groups on connect: ${error}`,
839
- );
840
- }
841
- })();
842
-
843
- const sendApi = createWebSendApi({
844
- sock: {
845
- sendMessage: (
846
- jid: string,
847
- content: AnyMessageContent,
848
- options?: MiscMessageGenerationOptions,
849
- ) => sendTrackedMessage(jid, content, options),
850
- sendPresenceUpdate: async (presence, jid?: string) => {
851
- const currentSock = getCurrentSock();
852
- if (!currentSock) {
853
- throw new Error(RECONNECT_IN_PROGRESS_ERROR);
854
- }
855
- return currentSock.sendPresenceUpdate(presence, jid);
856
- },
857
- },
858
- defaultAccountId: options.accountId,
859
- });
860
-
861
- return {
862
- close: async () => {
863
- try {
864
- detachMessagesUpsert();
865
- detachConnectionUpdate();
866
- closeInboundMonitorSocket(sock);
867
- } catch (err) {
868
- logWhatsAppVerbose(options.verbose, `Socket close failed: ${String(err)}`);
869
- }
870
- },
871
- onClose,
872
- signalClose: (reason?: WebListenerCloseReason) => {
873
- resolveClose(reason ?? { status: undefined, isLoggedOut: false, error: "closed" });
874
- },
875
- // IPC surface (sendMessage/sendPoll/sendReaction/sendComposingTo)
876
- ...sendApi,
877
- } as const;
878
- }
879
-
880
- export async function monitorWebInbox(options: MonitorWebInboxOptions) {
881
- const sock = await createWaSocket(false, options.verbose, {
882
- authDir: options.authDir,
883
- ...resolveWhatsAppSocketTiming(options.cfg),
884
- });
885
- await waitForWaConnection(sock);
886
- return attachWebInboxToSocket({
887
- ...options,
888
- sock,
889
- });
890
- }