@12-apps/messaging 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,306 @@
1
+ import { ChannelSendFailure, type ChannelMedia } from "../core/channel";
2
+ import type { NormalizedEvent, OutboundContent } from "../core/types";
3
+ import { clearAuthState, loadAuthState, type AuthStateStore } from "./auth-state";
4
+ import {
5
+ DISCONNECT,
6
+ disconnectCode,
7
+ type BaileysAuthState,
8
+ type BaileysConnectionUpdate,
9
+ type BaileysLogger,
10
+ type BaileysMessage,
11
+ type BaileysModule,
12
+ type BaileysSocket,
13
+ } from "./baileys-port";
14
+ import { encodeEnvelope } from "./envelope";
15
+ import { AudioCache, downloadAudio } from "./media";
16
+ import { addressJid, jidUser, normalizeUpdates, normalizeUpsert } from "./normalize";
17
+
18
+ /**
19
+ * ONE linked WhatsApp account, over Baileys: the socket, its pairing, its
20
+ * reconnects, and the bridge to the engine.
21
+ *
22
+ * Inbound, the session normalizes every live socket event and hands the host
23
+ * a raw body (`deliver`) that the host stores through `engine.receive(channel,
24
+ * rawBody)`, exactly as the webhook edge does for the Cloud API: the inbox,
25
+ * the processing job and the reconciliation sweep are the same. Outbound,
26
+ * the adapter sends through the session's socket.
27
+ */
28
+
29
+ /** Where the session stands. `qr` and `pairing-code` wait for the person to link the device on their phone. */
30
+ export type WhatsAppWebStatus =
31
+ | { state: "idle" }
32
+ | { state: "connecting" }
33
+ /** Show `qr` as a QR code; WhatsApp › Linked devices › Link a device. It rotates: a new status replaces it. */
34
+ | { state: "qr"; qr: string }
35
+ /** Type `code` on the phone: WhatsApp › Linked devices › Link with phone number. */
36
+ | { state: "pairing-code"; code: string }
37
+ | { state: "open"; accountId: string }
38
+ | { state: "reconnecting"; attempt: number; code: number | null }
39
+ /** The phone unlinked this device (or WhatsApp logged it out). The keys were cleared: the next start pairs again. */
40
+ | { state: "logged-out"; code: number | null }
41
+ /** Stopped for good: another client took the session (440), the account is refused (403), or reconnects ran out. */
42
+ | { state: "failed"; code: number | null; reason: "replaced" | "forbidden" | "reconnects-exhausted" | "start-failed" }
43
+ | { state: "stopped" };
44
+
45
+ export interface WhatsAppWebSessionConfig<Auth = BaileysAuthState, Msg extends BaileysMessage = BaileysMessage> {
46
+ /** The Baileys module the host installed: `import * as baileys from "baileys"`. */
47
+ baileys: BaileysModule<Auth, Msg>;
48
+ /** Where the linked device's keys live. The host's: see {@link AuthStateStore}. */
49
+ authStore: AuthStateStore;
50
+ /**
51
+ * Store one inbound raw body: `(rawBody) => engine.receive(channel, rawBody)`.
52
+ * Called in socket order, one at a time. A socket does not redeliver, so a
53
+ * throw is reported through `onError` and that body is lost.
54
+ */
55
+ deliver(rawBody: string): Promise<unknown>;
56
+ /** Every status change. Show the QR or the pairing code from here. */
57
+ onStatus?(status: WhatsAppWebStatus): void;
58
+ /** A failure the session could not hand to a caller: a delivery or a creds save. Never carries a key. */
59
+ onError?(error: unknown, where: "deliver" | "save-creds" | "pairing-code"): void;
60
+ /** Pair with a code typed on the phone instead of a QR: the account's number, digits with country code. */
61
+ pairingPhoneNumber?: string;
62
+ /** Opt-out words, as the Cloud adapter's `optOutKeywords`. */
63
+ optOutKeywords?: readonly string[];
64
+ /** A pino-compatible logger for Baileys. Default: Baileys' own. */
65
+ logger?: BaileysLogger;
66
+ /** How the linked device is named on the phone: `[client, browser, version]`. */
67
+ browser?: [string, string, string];
68
+ /** Reconnects after an unexpected close. Default 5 attempts, from 2 s, doubling. */
69
+ reconnect?: { maxAttempts?: number; delayMs?: number };
70
+ /** How many recent audio messages are kept in memory for `downloadMedia`. Default 200. */
71
+ mediaCacheSize?: number;
72
+ /** For tests. */
73
+ now?(): Date;
74
+ sleep?(ms: number): Promise<void>;
75
+ }
76
+
77
+ export interface WhatsAppWebSession {
78
+ /** Open the socket: resume the stored device, or pair a new one. Idempotent while running. */
79
+ start(): Promise<void>;
80
+ /** Close the socket and keep the keys: `start` resumes without pairing. */
81
+ stop(): Promise<void>;
82
+ /** Unlink this device on WhatsApp and clear its keys. */
83
+ logout(): Promise<void>;
84
+ status(): WhatsAppWebStatus;
85
+ /** The linked account's digits once open (`5511987654321`), else null. */
86
+ accountId(): string | null;
87
+ /** Send one message. Throws `ChannelSendFailure`. */
88
+ send(to: string, content: OutboundContent): Promise<{ externalId: string }>;
89
+ /** Download a recent inbound audio by its media id (the message id). Throws `ChannelMediaFailure`. */
90
+ downloadMedia(mediaId: string, options: { maxBytes: number; timeoutMs?: number }): Promise<ChannelMedia>;
91
+ }
92
+
93
+ /**
94
+ * The text a personal account sends for an outbound message. Reply buttons
95
+ * and lists are a Business API feature: here their choices become numbered
96
+ * lines under the text, and the contact's answer arrives as TEXT.
97
+ */
98
+ export function renderOutboundText(content: OutboundContent): string {
99
+ if (content.kind === "TEXT") return content.text;
100
+ if (content.kind === "BUTTONS") return [content.text, "", ...content.buttons.map((button, i) => `${i + 1}. ${button.title}`)].join("\n");
101
+ let n = 0;
102
+ const sections = content.sections.map((section) => [
103
+ "",
104
+ ...(section.title ? [`*${section.title}*`] : []),
105
+ ...section.rows.map((row) => `${++n}. ${row.title}${row.description ? ` — ${row.description}` : ""}`),
106
+ ]);
107
+ return [content.text, ...sections.flat()].join("\n");
108
+ }
109
+
110
+ const defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
111
+
112
+ /** The close codes after which the session stops for good, and how it reports each. */
113
+ const TERMINAL: Readonly<Record<number, Extract<WhatsAppWebStatus, { state: "failed" }>["reason"]>> = {
114
+ [DISCONNECT.connectionReplaced]: "replaced",
115
+ [DISCONNECT.forbidden]: "forbidden",
116
+ };
117
+
118
+ class BaileysSession<Auth, Msg extends BaileysMessage> implements WhatsAppWebSession {
119
+ private socket: BaileysSocket<Msg> | null = null;
120
+ private current: WhatsAppWebStatus = { state: "idle" };
121
+ private account: string | null = null;
122
+ private attempts = 0;
123
+ private stopping = false;
124
+ private pairingRequested = false;
125
+ private deliveries: Promise<void> = Promise.resolve();
126
+ private readonly audio: AudioCache<Msg>;
127
+
128
+ constructor(private readonly config: WhatsAppWebSessionConfig<Auth, Msg>) {
129
+ this.audio = new AudioCache(config.mediaCacheSize ?? 200);
130
+ }
131
+
132
+ status = (): WhatsAppWebStatus => this.current;
133
+ accountId = (): string | null => this.account;
134
+
135
+ async start(): Promise<void> {
136
+ if (this.socket) return;
137
+ this.stopping = false;
138
+ this.attempts = 0;
139
+ this.pairingRequested = false;
140
+ try {
141
+ await this.open();
142
+ } catch (error) {
143
+ this.socket = null;
144
+ this.setStatus({ state: "failed", code: null, reason: "start-failed" });
145
+ throw error;
146
+ }
147
+ }
148
+
149
+ async stop(): Promise<void> {
150
+ const sock = this.detach();
151
+ if (sock) await sock.end(undefined);
152
+ this.setStatus({ state: "stopped" });
153
+ }
154
+
155
+ async logout(): Promise<void> {
156
+ const sock = this.detach();
157
+ if (sock) await sock.logout();
158
+ await clearAuthState(this.config.authStore);
159
+ this.setStatus({ state: "logged-out", code: null });
160
+ }
161
+
162
+ async send(to: string, content: OutboundContent): Promise<{ externalId: string }> {
163
+ const sock = this.socket;
164
+ if (!sock || this.current.state !== "open") throw new ChannelSendFailure("NOT_CONNECTED", "the WhatsApp Web session is not open");
165
+ const sent = await sock.sendMessage(addressJid(to), { text: renderOutboundText(content) }).catch((error: unknown) => {
166
+ const code = disconnectCode({ error: error as Error });
167
+ throw new ChannelSendFailure(code === null ? "SEND_FAILED" : String(code), "the WhatsApp Web socket refused the send");
168
+ });
169
+ const externalId = sent?.key?.id;
170
+ if (!externalId) throw new ChannelSendFailure("NO_MESSAGE_ID", "the WhatsApp Web socket returned no message id");
171
+ return { externalId };
172
+ }
173
+
174
+ downloadMedia(mediaId: string, options: { maxBytes: number; timeoutMs?: number }): Promise<ChannelMedia> {
175
+ const sock = this.socket;
176
+ return downloadAudio({
177
+ baileys: this.config.baileys,
178
+ message: this.audio.get(mediaId),
179
+ maxBytes: options.maxBytes,
180
+ timeoutMs: options.timeoutMs,
181
+ logger: this.config.logger,
182
+ reupload: sock?.updateMediaMessage ? (message: Msg) => sock.updateMediaMessage!(message) : undefined,
183
+ });
184
+ }
185
+
186
+ // ── The socket ──────────────────────────────────────────────────────────
187
+
188
+ private detach(): BaileysSocket<Msg> | null {
189
+ this.stopping = true;
190
+ const sock = this.socket;
191
+ this.socket = null;
192
+ this.account = null;
193
+ return sock;
194
+ }
195
+
196
+ private setStatus(status: WhatsAppWebStatus): void {
197
+ this.current = status;
198
+ this.config.onStatus?.(status);
199
+ }
200
+
201
+ private async open(): Promise<void> {
202
+ this.setStatus({ state: "connecting" });
203
+ const { state, saveCreds } = await loadAuthState(this.config.baileys, this.config.authStore);
204
+ const sock = this.config.baileys.makeWASocket({
205
+ // The ONE boundary cast: the store holds Baileys' own values, which its key store types per category.
206
+ auth: state as Auth,
207
+ markOnlineOnConnect: false,
208
+ syncFullHistory: false,
209
+ ...(this.config.logger ? { logger: this.config.logger } : {}),
210
+ ...(this.config.browser ? { browser: this.config.browser } : {}),
211
+ });
212
+ this.socket = sock;
213
+ sock.ev.on("creds.update", () => {
214
+ saveCreds().catch((error: unknown) => this.config.onError?.(error, "save-creds"));
215
+ });
216
+ sock.ev.on("connection.update", (update) => {
217
+ if (sock === this.socket) void this.onConnection(sock, update);
218
+ });
219
+ sock.ev.on("messages.upsert", (upsert) => {
220
+ const account = this.linked(sock);
221
+ if (!account) return;
222
+ if (upsert.type === "notify") upsert.messages.forEach((message) => this.audio.remember(message));
223
+ this.deliver(normalizeUpsert(account, upsert, this.config.optOutKeywords ? { optOutKeywords: this.config.optOutKeywords } : {}));
224
+ });
225
+ sock.ev.on("messages.update", (updates) => {
226
+ const account = this.linked(sock);
227
+ if (account) this.deliver(normalizeUpdates(account, updates, (this.config.now ?? (() => new Date()))()));
228
+ });
229
+ }
230
+
231
+ /** The account a CURRENT socket is linked to: from the open event, or its own user while still opening. */
232
+ private linked(sock: BaileysSocket<Msg>): string | null {
233
+ if (sock !== this.socket) return null;
234
+ return this.account ?? (sock.user?.id ? jidUser(sock.user.id) : null);
235
+ }
236
+
237
+ /** Hand one body to the host, after every earlier one: a socket's order is kept. */
238
+ private deliver(events: NormalizedEvent[]): void {
239
+ if (events.length === 0) return;
240
+ const body = encodeEnvelope(events);
241
+ this.deliveries = this.deliveries.then(() =>
242
+ this.config.deliver(body).then(
243
+ () => undefined,
244
+ (error: unknown) => this.config.onError?.(error, "deliver"),
245
+ ),
246
+ );
247
+ }
248
+
249
+ private async onConnection(sock: BaileysSocket<Msg>, update: BaileysConnectionUpdate): Promise<void> {
250
+ if (update.qr) await this.onQr(sock, update.qr);
251
+ if (update.connection === "open") {
252
+ this.attempts = 0;
253
+ this.account = sock.user?.id ? jidUser(sock.user.id) : null;
254
+ this.setStatus(this.account ? { state: "open", accountId: this.account } : { state: "connecting" });
255
+ } else if (update.connection === "close") {
256
+ await this.onClose(disconnectCode(update.lastDisconnect));
257
+ }
258
+ }
259
+
260
+ private async onQr(sock: BaileysSocket<Msg>, qr: string): Promise<void> {
261
+ const phone = this.config.pairingPhoneNumber;
262
+ if (!phone) return this.setStatus({ state: "qr", qr });
263
+ if (this.pairingRequested) return;
264
+ this.pairingRequested = true;
265
+ try {
266
+ this.setStatus({ state: "pairing-code", code: await sock.requestPairingCode(phone.replace(/\D/g, "")) });
267
+ } catch (error) {
268
+ this.pairingRequested = false;
269
+ this.config.onError?.(error, "pairing-code");
270
+ }
271
+ }
272
+
273
+ private async onClose(code: number | null): Promise<void> {
274
+ this.socket = null;
275
+ this.account = null;
276
+ if (this.stopping) return this.setStatus({ state: "stopped" });
277
+ if (code === DISCONNECT.loggedOut) {
278
+ await clearAuthState(this.config.authStore);
279
+ return this.setStatus({ state: "logged-out", code });
280
+ }
281
+ const terminal = code === null ? undefined : TERMINAL[code];
282
+ if (terminal) return this.setStatus({ state: "failed", code, reason: terminal });
283
+ if (code !== DISCONNECT.restartRequired && !(await this.backOff(code))) return;
284
+ await this.open();
285
+ }
286
+
287
+ /** Wait before a reconnect; false when the attempts ran out or the session was stopped meanwhile. */
288
+ private async backOff(code: number | null): Promise<boolean> {
289
+ const maxAttempts = this.config.reconnect?.maxAttempts ?? 5;
290
+ this.attempts += 1;
291
+ if (this.attempts > maxAttempts) {
292
+ this.setStatus({ state: "failed", code, reason: "reconnects-exhausted" });
293
+ return false;
294
+ }
295
+ this.setStatus({ state: "reconnecting", attempt: this.attempts, code });
296
+ await (this.config.sleep ?? defaultSleep)((this.config.reconnect?.delayMs ?? 2_000) * 2 ** (this.attempts - 1));
297
+ if (!this.stopping) return true;
298
+ this.setStatus({ state: "stopped" });
299
+ return false;
300
+ }
301
+ }
302
+
303
+ /** One linked WhatsApp account over Baileys. Nothing connects until `start()`. */
304
+ export function createWhatsAppWebSession<Auth, Msg extends BaileysMessage>(config: WhatsAppWebSessionConfig<Auth, Msg>): WhatsAppWebSession {
305
+ return new BaileysSession(config);
306
+ }