@12-apps/messaging 1.4.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,78 @@
1
+ import { ChannelMediaFailure, DEFAULT_MEDIA_TIMEOUT_MS, type ChannelMedia } from "../core/channel";
2
+ import type { BaileysLogger, BaileysMessage, BaileysModule } from "./baileys-port";
3
+ import { longNumber, unwrapMessage } from "./normalize";
4
+
5
+ /**
6
+ * Inbound audio, for `fetchMedia`. A Baileys media message is downloaded from
7
+ * the message itself (its URL and media key), so the session keeps the most
8
+ * recent audio messages IN MEMORY, by message id, and nothing else: the media
9
+ * key never reaches the inbox or the host's database. After a restart an
10
+ * older audio is `NOT_FOUND`.
11
+ */
12
+ export class AudioCache<Msg extends BaileysMessage> {
13
+ private readonly messages = new Map<string, Msg>();
14
+
15
+ constructor(private readonly size: number) {}
16
+
17
+ /** Keep `message` if it is an audio. The oldest is dropped past the size. */
18
+ remember(message: Msg): void {
19
+ const id = message.key?.id;
20
+ if (!id || !audioOf(message)) return;
21
+ this.messages.set(id, message);
22
+ while (this.messages.size > this.size) this.messages.delete(this.messages.keys().next().value as string);
23
+ }
24
+
25
+ get(id: string): Msg | undefined {
26
+ return this.messages.get(id);
27
+ }
28
+ }
29
+
30
+ /** The audio content of a message, unwrapped, or null. */
31
+ export function audioOf(message: BaileysMessage): Record<string, unknown> | null {
32
+ const audio = unwrapMessage(message.message).audioMessage;
33
+ return typeof audio === "object" && audio !== null ? (audio as Record<string, unknown>) : null;
34
+ }
35
+
36
+ async function withDeadline<T>(work: Promise<T>, ms: number): Promise<T> {
37
+ let timer: ReturnType<typeof setTimeout> | undefined;
38
+ const deadline = new Promise<never>((_, reject) => {
39
+ timer = setTimeout(() => reject(new ChannelMediaFailure("TIMEOUT", `media download passed its ${ms} ms deadline`)), ms);
40
+ });
41
+ try {
42
+ return await Promise.race([work, deadline]);
43
+ } finally {
44
+ clearTimeout(timer);
45
+ }
46
+ }
47
+
48
+ function refuseOverCap(size: number | null, maxBytes: number, what: "declares" | "is"): void {
49
+ if (size !== null && size > maxBytes) throw new ChannelMediaFailure("TOO_LARGE", `the media ${what} ${size} bytes, over ${maxBytes}`);
50
+ }
51
+
52
+ export interface DownloadAudioInput<Msg extends BaileysMessage> {
53
+ baileys: Pick<BaileysModule<unknown, Msg>, "downloadMediaMessage">;
54
+ message: Msg | undefined;
55
+ maxBytes: number;
56
+ timeoutMs?: number | undefined;
57
+ logger?: BaileysLogger | undefined;
58
+ reupload?: ((message: Msg) => Promise<Msg>) | undefined;
59
+ }
60
+
61
+ /** Download one cached audio into memory. Throws `ChannelMediaFailure`; never stores anything. */
62
+ export async function downloadAudio<Msg extends BaileysMessage>(input: DownloadAudioInput<Msg>): Promise<ChannelMedia> {
63
+ const audio = input.message ? audioOf(input.message) : null;
64
+ if (!input.message || !audio) throw new ChannelMediaFailure("NOT_FOUND", "no recent audio with this id in this session");
65
+ refuseOverCap(longNumber(audio.fileLength as number | null), input.maxBytes, "declares");
66
+ const ctx = {
67
+ ...(input.logger ? { logger: input.logger } : {}),
68
+ ...(input.reupload ? { reuploadRequest: input.reupload } : {}),
69
+ };
70
+ const bytes = await withDeadline(input.baileys.downloadMediaMessage(input.message, "buffer", {}, ctx), input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS).catch(
71
+ (error: unknown) => {
72
+ throw error instanceof ChannelMediaFailure ? error : new ChannelMediaFailure("DOWNLOAD_FAILED", "the media could not be downloaded");
73
+ },
74
+ );
75
+ refuseOverCap(bytes.length, input.maxBytes, "is");
76
+ const mimeType = typeof audio.mimetype === "string" && audio.mimetype ? audio.mimetype : "application/octet-stream";
77
+ return { bytes: new Uint8Array(bytes), mimeType, size: bytes.length };
78
+ }
@@ -0,0 +1,183 @@
1
+ import type { InboundContent, NormalizedEvent, ReceiptStatus, StatusEvent } from "../core/types";
2
+ import { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from "../whatsapp/opt-out";
3
+ import type { BaileysMessage, BaileysMessageKey, BaileysMessageUpdate, LongLike } from "./baileys-port";
4
+
5
+ /**
6
+ * Baileys' socket events → the engine's normalized events: the SAME
7
+ * `NormalizedEvent`s the Cloud webhook's parser produces, so the inbox, the
8
+ * dedupe, the conversations and the retention cannot tell the transports apart.
9
+ *
10
+ * Read defensively: an unknown shape is skipped, never thrown on. What is
11
+ * left out, on purpose:
12
+ * - groups, broadcast lists, Status and channels (`@g.us`, `@broadcast`,
13
+ * `@newsletter`): the engine's conversation is one contact;
14
+ * - messages the account sent itself (`fromMe`): from another linked device,
15
+ * or the echo of a send of ours, which the engine already recorded;
16
+ * - history sync (`messages.upsert` of type `append`): only live messages;
17
+ * - protocol messages (a deletion, an edit, a key distribution).
18
+ */
19
+
20
+ type Json = Record<string, unknown>;
21
+ const isObject = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value);
22
+ const text = (value: unknown): string | null => (typeof value === "string" && value.length > 0 ? value : null);
23
+
24
+ const PN_SUFFIX = "@s.whatsapp.net";
25
+ const LID_SUFFIX = "@lid";
26
+
27
+ /** A JID's user part, without the device (`5511…:12@s.whatsapp.net` → `5511…`). */
28
+ export function jidUser(jid: string): string {
29
+ const user = jid.slice(0, jid.indexOf("@") >= 0 ? jid.indexOf("@") : jid.length);
30
+ const colon = user.indexOf(":");
31
+ return colon >= 0 ? user.slice(0, colon) : user;
32
+ }
33
+
34
+ /**
35
+ * The contact's address, as the engine stores it. A phone-number JID becomes
36
+ * its digits (`5511987654321`), the same address the Cloud API's `wa_id` is.
37
+ * A contact WhatsApp only names by a LID keeps the whole LID JID
38
+ * (`123456@lid`): the send path routes it back as is. Null for anything that
39
+ * is not one person.
40
+ */
41
+ export function contactAddress(key: BaileysMessageKey): string | null {
42
+ const candidates = [key.remoteJid, key.remoteJidAlt].filter((jid): jid is string => typeof jid === "string");
43
+ const pn = candidates.find((jid) => jid.endsWith(PN_SUFFIX));
44
+ if (pn) return jidUser(pn) || null;
45
+ const lid = candidates.find((jid) => jid.endsWith(LID_SUFFIX));
46
+ return lid ? `${jidUser(lid)}${LID_SUFFIX}` : null;
47
+ }
48
+
49
+ /** The JID a send goes to, for an address `contactAddress` produced (or plain digits). */
50
+ export function addressJid(address: string): string {
51
+ if (address.includes("@")) return address;
52
+ const digits = address.replace(/\D/g, "");
53
+ return `${digits}${PN_SUFFIX}`;
54
+ }
55
+
56
+ /** A protobuf Long (a timestamp in seconds, a byte length) as a positive number, or null. */
57
+ export function longNumber(value: LongLike): number | null {
58
+ if (typeof value === "number") return Number.isFinite(value) && value > 0 ? value : null;
59
+ if (typeof value === "string") return longNumber(Number(value));
60
+ if (isObject(value) && typeof value.low === "number" && typeof value.high === "number") {
61
+ return longNumber(value.high * 2 ** 32 + (value.low >>> 0));
62
+ }
63
+ return null;
64
+ }
65
+
66
+ /** Wrappers whose inner `message` is the real content. */
67
+ const WRAPPERS = ["ephemeralMessage", "viewOnceMessage", "viewOnceMessageV2", "viewOnceMessageV2Extension", "documentWithCaptionMessage", "editedMessage"];
68
+ /** Fields of a message that are never its content. */
69
+ const NOT_CONTENT = new Set(["messageContextInfo", "senderKeyDistributionMessage"]);
70
+ /** Content that is not a message a person reads: skipped whole. */
71
+ const SKIPPED = new Set(["protocolMessage", "reactionMessage", "pollUpdateMessage", "keepInChatMessage"]);
72
+
73
+ /** A message's real content, out of its ephemeral, view-once or edit wrappers. `{}` for anything else. */
74
+ export function unwrapMessage(message: unknown): Json {
75
+ if (!isObject(message)) return {};
76
+ for (const wrapper of WRAPPERS) {
77
+ const inner = message[wrapper];
78
+ if (isObject(inner) && isObject(inner.message)) return unwrapMessage(inner.message);
79
+ }
80
+ return message;
81
+ }
82
+
83
+ type Reader = (body: unknown) => InboundContent | null;
84
+
85
+ const interactive = (replyId: unknown, title: unknown): InboundContent | null =>
86
+ text(replyId) ? { kind: "INTERACTIVE", replyId: replyId as string, title: text(title) ?? "" } : null;
87
+
88
+ /** How each content type a person reads is read. A type not listed is OTHER. */
89
+ const READERS: Readonly<Record<string, Reader>> = {
90
+ conversation: (body) => (text(body) ? { kind: "TEXT", text: body as string } : null),
91
+ extendedTextMessage: (body) => (isObject(body) && text(body.text) ? { kind: "TEXT", text: body.text as string } : null),
92
+ buttonsResponseMessage: (body) => (isObject(body) ? interactive(body.selectedButtonId, body.selectedDisplayText) : null),
93
+ templateButtonReplyMessage: (body) => (isObject(body) ? interactive(body.selectedId, body.selectedDisplayText) : null),
94
+ listResponseMessage: (body) =>
95
+ isObject(body) && isObject(body.singleSelectReply) ? interactive(body.singleSelectReply.selectedRowId, body.title) : null,
96
+ // The media id is filled with the message id by the caller.
97
+ audioMessage: (body) => (isObject(body) ? { kind: "AUDIO", mediaId: "", mimeType: text(body.mimetype) } : null),
98
+ };
99
+
100
+ /** The message's content, or null to skip it. */
101
+ export function contentOf(raw: unknown): InboundContent | null {
102
+ const message = unwrapMessage(raw);
103
+ const type = Object.keys(message).find((key) => !NOT_CONTENT.has(key) && message[key] !== null && message[key] !== undefined);
104
+ if (!type || SKIPPED.has(type)) return null;
105
+ const reader = READERS[type];
106
+ return reader ? reader(message[type]) : { kind: "OTHER", channelType: type.replace(/Message$/, "") || type };
107
+ }
108
+
109
+ export interface NormalizeOptions {
110
+ /** The whole-message words that opt a contact out. Default: the Cloud adapter's. */
111
+ optOutKeywords?: readonly string[];
112
+ }
113
+
114
+ /** One message → its inbound event, or null when it is not one a contact sent to this account. */
115
+ function inboundEvent(accountId: string, message: BaileysMessage, keywords: readonly string[]): NormalizedEvent | null {
116
+ if (!isObject(message) || !isObject(message.key) || message.key.fromMe) return null;
117
+ const id = text(message.key.id);
118
+ const contactId = contactAddress(message.key);
119
+ const seconds = longNumber(message.messageTimestamp);
120
+ const content = contentOf(message.message);
121
+ if (!id || !contactId || seconds === null || !content) return null;
122
+ return {
123
+ type: "message",
124
+ accountId,
125
+ contactId,
126
+ contactName: text(message.pushName),
127
+ externalId: id,
128
+ sentAt: new Date(seconds * 1000),
129
+ // An audio's media id is the message's own id: the session keeps the message to download it.
130
+ content: content.kind === "AUDIO" ? { ...content, mediaId: id } : content,
131
+ optOut: content.kind === "TEXT" && isOptOutText(content.text, keywords),
132
+ };
133
+ }
134
+
135
+ /** One live `messages.upsert` → inbound message events. `accountId` is the linked account's digits. */
136
+ export function normalizeUpsert(
137
+ accountId: string,
138
+ upsert: { messages: readonly BaileysMessage[]; type: string },
139
+ options: NormalizeOptions = {},
140
+ ): NormalizedEvent[] {
141
+ if (upsert.type !== "notify") return [];
142
+ const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;
143
+ return upsert.messages.map((message) => inboundEvent(accountId, message, keywords)).filter((event): event is NormalizedEvent => event !== null);
144
+ }
145
+
146
+ /** `proto.WebMessageInfo.Status` → a receipt. PENDING (1) and unknown values are not receipts. */
147
+ export function receiptOf(status: unknown): ReceiptStatus | null {
148
+ switch (status) {
149
+ case 0:
150
+ return "FAILED";
151
+ case 2:
152
+ return "SENT";
153
+ case 3:
154
+ return "DELIVERED";
155
+ case 4:
156
+ case 5:
157
+ return "READ";
158
+ default:
159
+ return null;
160
+ }
161
+ }
162
+
163
+ /** One `messages.update` → receipts for the messages this account sent. `at` is when the socket saw it. */
164
+ export function normalizeUpdates(accountId: string, updates: readonly BaileysMessageUpdate[], at: Date): StatusEvent[] {
165
+ const events: StatusEvent[] = [];
166
+ for (const entry of updates) {
167
+ if (!isObject(entry) || !isObject(entry.key) || !entry.key.fromMe || !isObject(entry.update)) continue;
168
+ const id = text(entry.key.id);
169
+ const status = receiptOf(entry.update.status);
170
+ if (!id || !status) continue;
171
+ events.push({
172
+ type: "status",
173
+ accountId,
174
+ externalId: id,
175
+ status,
176
+ at,
177
+ contactId: contactAddress(entry.key),
178
+ error: status === "FAILED" ? "ERROR" : null,
179
+ callbackData: null,
180
+ });
181
+ }
182
+ return events;
183
+ }
@@ -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
+ }