@12-apps/messaging 1.4.0 → 1.6.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.
- package/README.md +42 -0
- package/dist/{channel-CZjNEBLC.d.ts → channel-BWhnnuip.d.ts} +22 -2
- package/dist/chunk-RXJNLPY4.js +560 -0
- package/dist/chunk-RXJNLPY4.js.map +1 -0
- package/dist/{engine-BJse1HAX.d.ts → engine-BybESJ7p.d.ts} +27 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +65 -8
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/server/index.d.ts +2 -2
- package/dist/whatsapp/index.d.ts +1 -1
- package/dist/whatsapp/index.js +22 -536
- package/dist/whatsapp/index.js.map +1 -1
- package/dist/whatsapp-web/index.d.ts +504 -0
- package/dist/whatsapp-web/index.js +956 -0
- package/dist/whatsapp-web/index.js.map +1 -0
- package/package.json +5 -1
- package/src/core/inbound.ts +6 -1
- package/src/core/ports.ts +16 -0
- package/src/core/sent-elsewhere.ts +87 -0
- package/src/core/types.ts +22 -1
- package/src/index.ts +1 -0
- package/src/whatsapp-web/adapter.ts +62 -0
- package/src/whatsapp-web/auth-state.ts +92 -0
- package/src/whatsapp-web/baileys-port.ts +168 -0
- package/src/whatsapp-web/choices.ts +126 -0
- package/src/whatsapp-web/envelope.ts +97 -0
- package/src/whatsapp-web/history.ts +171 -0
- package/src/whatsapp-web/index.ts +50 -0
- package/src/whatsapp-web/media.ts +78 -0
- package/src/whatsapp-web/normalize.ts +223 -0
- package/src/whatsapp-web/own-sends.ts +124 -0
- package/src/whatsapp-web/session.ts +391 -0
- package/src/whatsapp-web/timers.ts +19 -0
|
@@ -0,0 +1,391 @@
|
|
|
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 BaileysMessageKey,
|
|
12
|
+
type BaileysModule,
|
|
13
|
+
type BaileysSocket,
|
|
14
|
+
} from "./baileys-port";
|
|
15
|
+
import { applyChoices, ChoiceMemory } from "./choices";
|
|
16
|
+
import { encodeEnvelope } from "./envelope";
|
|
17
|
+
import { HistoryRequests, type HistoryAnchor, type WhatsAppWebHistoryMessage } from "./history";
|
|
18
|
+
import { OwnSends } from "./own-sends";
|
|
19
|
+
import { AudioCache, downloadAudio } from "./media";
|
|
20
|
+
import { addressJid, jidUser, normalizeSentElsewhere, normalizeUpdates, normalizeUpsert, replyAddress } from "./normalize";
|
|
21
|
+
import type { WhatsAppWebTimers } from "./timers";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* ONE linked WhatsApp account, over Baileys: the socket, its pairing, its
|
|
25
|
+
* reconnects, and the bridge to the engine.
|
|
26
|
+
*
|
|
27
|
+
* Inbound, the session normalizes every live socket event and hands the host
|
|
28
|
+
* a raw body (`deliver`) that the host stores through `engine.receive(channel,
|
|
29
|
+
* rawBody)`, exactly as the webhook edge does for the Cloud API: the inbox,
|
|
30
|
+
* the processing job and the reconciliation sweep are the same. Outbound,
|
|
31
|
+
* the adapter sends through the session's socket.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/** Where the session stands. `qr` and `pairing-code` wait for the person to link the device on their phone. */
|
|
35
|
+
export type WhatsAppWebStatus =
|
|
36
|
+
| { state: "idle" }
|
|
37
|
+
| { state: "connecting" }
|
|
38
|
+
/** Show `qr` as a QR code; WhatsApp › Linked devices › Link a device. It rotates: a new status replaces it. */
|
|
39
|
+
| { state: "qr"; qr: string }
|
|
40
|
+
/** Type `code` on the phone: WhatsApp › Linked devices › Link with phone number. */
|
|
41
|
+
| { state: "pairing-code"; code: string }
|
|
42
|
+
| { state: "open"; accountId: string }
|
|
43
|
+
| { state: "reconnecting"; attempt: number; code: number | null }
|
|
44
|
+
/** The phone unlinked this device (or WhatsApp logged it out). The keys were cleared: the next start pairs again. */
|
|
45
|
+
| { state: "logged-out"; code: number | null }
|
|
46
|
+
/** Stopped for good: another client took the session (440), the account is refused (403), or reconnects ran out. */
|
|
47
|
+
| { state: "failed"; code: number | null; reason: "replaced" | "forbidden" | "reconnects-exhausted" | "start-failed" }
|
|
48
|
+
| { state: "stopped" };
|
|
49
|
+
|
|
50
|
+
export interface WhatsAppWebSessionConfig<Auth = BaileysAuthState, Msg extends BaileysMessage = BaileysMessage> {
|
|
51
|
+
/** The Baileys module the host installed: `import * as baileys from "baileys"`. */
|
|
52
|
+
baileys: BaileysModule<Auth, Msg>;
|
|
53
|
+
/** Where the linked device's keys live. The host's: see {@link AuthStateStore}. */
|
|
54
|
+
authStore: AuthStateStore;
|
|
55
|
+
/**
|
|
56
|
+
* Store one inbound raw body: `(rawBody) => engine.receive(channel, rawBody)`.
|
|
57
|
+
* Called one at a time, in socket order, except that a phone-sent message held
|
|
58
|
+
* while a send was in flight comes when it is judged (see the README). A socket
|
|
59
|
+
* does not redeliver, so a throw is reported through `onError` and that body is lost.
|
|
60
|
+
*/
|
|
61
|
+
deliver(rawBody: string): Promise<unknown>;
|
|
62
|
+
/** Every status change. Show the QR or the pairing code from here. */
|
|
63
|
+
onStatus?(status: WhatsAppWebStatus): void;
|
|
64
|
+
/** A failure the session could not hand to a caller: a delivery or a creds save. Never carries a key. */
|
|
65
|
+
onError?(error: unknown, where: "deliver" | "save-creds" | "pairing-code" | "presence" | "mark-read" | "history"): void;
|
|
66
|
+
/** Pair with a code typed on the phone instead of a QR: the account's number, digits with country code. */
|
|
67
|
+
pairingPhoneNumber?: string;
|
|
68
|
+
/** Opt-out words, as the Cloud adapter's `optOutKeywords`. */
|
|
69
|
+
optOutKeywords?: readonly string[];
|
|
70
|
+
/** A pino-compatible logger for Baileys. Default: Baileys' own. */
|
|
71
|
+
logger?: BaileysLogger;
|
|
72
|
+
/** How the linked device is named on the phone: `[client, browser, version]`. */
|
|
73
|
+
browser?: [string, string, string];
|
|
74
|
+
/** Reconnects after an unexpected close. Default 5 attempts, from 2 s, doubling. */
|
|
75
|
+
reconnect?: { maxAttempts?: number; delayMs?: number };
|
|
76
|
+
/** How many recent audio messages are kept in memory for `downloadMedia`. Default 200. */
|
|
77
|
+
mediaCacheSize?: number;
|
|
78
|
+
/** How many contacts' last offered choices are kept to read a typed "1" as a tap. Default 500. */
|
|
79
|
+
choiceMemorySize?: number;
|
|
80
|
+
/** How long offered choices stay answerable by number or title. Default 2 hours. */
|
|
81
|
+
choiceTtlMs?: number;
|
|
82
|
+
/** For tests. */
|
|
83
|
+
now?(): Date;
|
|
84
|
+
sleep?(ms: number): Promise<void>;
|
|
85
|
+
/** The deadlines (a history request's, an echo-suspect's 30 s hold). Default: the global timers. For tests. */
|
|
86
|
+
timers?: WhatsAppWebTimers;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface WhatsAppWebSession {
|
|
90
|
+
/** Open the socket: resume the stored device, or pair a new one. Idempotent while running. */
|
|
91
|
+
start(): Promise<void>;
|
|
92
|
+
/** Close the socket and keep the keys: `start` resumes without pairing. */
|
|
93
|
+
stop(): Promise<void>;
|
|
94
|
+
/** Unlink this device on WhatsApp and clear its keys. */
|
|
95
|
+
logout(): Promise<void>;
|
|
96
|
+
status(): WhatsAppWebStatus;
|
|
97
|
+
/** The linked account's digits once open (`5511987654321`), else null. */
|
|
98
|
+
accountId(): string | null;
|
|
99
|
+
/** Send one message. Throws `ChannelSendFailure`. */
|
|
100
|
+
send(to: string, content: OutboundContent): Promise<{ externalId: string }>;
|
|
101
|
+
/**
|
|
102
|
+
* Show "digitando…" (`composing`) or its end (`paused`) to one contact. Fire and forget: it never
|
|
103
|
+
* rejects. A failure goes to `onError` (`presence`); a session that is not open reports `NOT_CONNECTED` there.
|
|
104
|
+
*/
|
|
105
|
+
sendPresence(contactId: string, state: "composing" | "paused"): Promise<void>;
|
|
106
|
+
/** Mark messages of one contact read, by their ids. Same failure rules as `sendPresence` (`mark-read`). */
|
|
107
|
+
markRead(contactId: string, externalIds: readonly string[]): Promise<void>;
|
|
108
|
+
/**
|
|
109
|
+
* Read up to `count` messages of one chat that came BEFORE `anchor`, from the phone, on demand. Text only, both
|
|
110
|
+
* sides, media as a placeholder `kind`, oldest first. Nothing is stored here or delivered to the engine. Resolves
|
|
111
|
+
* `[]` when the session is not open, the phone does not answer within `timeoutMs`, or the call fails (`history`);
|
|
112
|
+
* a late answer is dropped.
|
|
113
|
+
*/
|
|
114
|
+
fetchHistory(contactId: string, anchor: HistoryAnchor, count: number, timeoutMs: number): Promise<WhatsAppWebHistoryMessage[]>;
|
|
115
|
+
/** Download a recent inbound audio by its media id (the message id). Throws `ChannelMediaFailure`. */
|
|
116
|
+
downloadMedia(mediaId: string, options: { maxBytes: number; timeoutMs?: number }): Promise<ChannelMedia>;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The text a personal account sends for an outbound message. Reply buttons
|
|
121
|
+
* and lists are a Business API feature: here their choices become numbered
|
|
122
|
+
* lines under the text, and the contact's answer arrives as TEXT.
|
|
123
|
+
*/
|
|
124
|
+
export function renderOutboundText(content: OutboundContent): string {
|
|
125
|
+
if (content.kind === "TEXT") return content.text;
|
|
126
|
+
if (content.kind === "BUTTONS") return [content.text, "", ...content.buttons.map((button, i) => `${i + 1}. ${button.title}`)].join("\n");
|
|
127
|
+
let n = 0;
|
|
128
|
+
const sections = content.sections.map((section) => [
|
|
129
|
+
"",
|
|
130
|
+
...(section.title ? [`*${section.title}*`] : []),
|
|
131
|
+
...section.rows.map((row) => `${++n}. ${row.title}${row.description ? ` — ${row.description}` : ""}`),
|
|
132
|
+
]);
|
|
133
|
+
return [content.text, ...sections.flat()].join("\n");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
137
|
+
|
|
138
|
+
/** The close codes after which the session stops for good, and how it reports each. */
|
|
139
|
+
const TERMINAL: Readonly<Record<number, Extract<WhatsAppWebStatus, { state: "failed" }>["reason"]>> = {
|
|
140
|
+
[DISCONNECT.connectionReplaced]: "replaced",
|
|
141
|
+
[DISCONNECT.forbidden]: "forbidden",
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
class BaileysSession<Auth, Msg extends BaileysMessage> implements WhatsAppWebSession {
|
|
145
|
+
private socket: BaileysSocket<Msg> | null = null;
|
|
146
|
+
private current: WhatsAppWebStatus = { state: "idle" };
|
|
147
|
+
private account: string | null = null;
|
|
148
|
+
private attempts = 0;
|
|
149
|
+
private stopping = false;
|
|
150
|
+
private pairingRequested = false;
|
|
151
|
+
private deliveries: Promise<void> = Promise.resolve();
|
|
152
|
+
private readonly audio: AudioCache<Msg>;
|
|
153
|
+
private readonly choices: ChoiceMemory;
|
|
154
|
+
private readonly history: HistoryRequests;
|
|
155
|
+
private readonly ownSends: OwnSends;
|
|
156
|
+
|
|
157
|
+
constructor(private readonly config: WhatsAppWebSessionConfig<Auth, Msg>) {
|
|
158
|
+
this.history = new HistoryRequests(config.timers);
|
|
159
|
+
this.ownSends = new OwnSends((events) => this.deliver(applyChoices(this.choices, events)), config.timers ? { timers: config.timers } : {});
|
|
160
|
+
this.audio = new AudioCache(config.mediaCacheSize ?? 200);
|
|
161
|
+
this.choices = new ChoiceMemory({
|
|
162
|
+
...(config.choiceMemorySize !== undefined ? { maxContacts: config.choiceMemorySize } : {}),
|
|
163
|
+
...(config.choiceTtlMs !== undefined ? { ttlMs: config.choiceTtlMs } : {}),
|
|
164
|
+
now: () => (config.now ?? (() => new Date()))(),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
status = (): WhatsAppWebStatus => this.current;
|
|
169
|
+
accountId = (): string | null => this.account;
|
|
170
|
+
|
|
171
|
+
async start(): Promise<void> {
|
|
172
|
+
if (this.socket) return;
|
|
173
|
+
this.stopping = false;
|
|
174
|
+
this.attempts = 0;
|
|
175
|
+
this.pairingRequested = false;
|
|
176
|
+
try {
|
|
177
|
+
await this.open();
|
|
178
|
+
} catch (error) {
|
|
179
|
+
this.socket = null;
|
|
180
|
+
this.setStatus({ state: "failed", code: null, reason: "start-failed" });
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async stop(): Promise<void> {
|
|
186
|
+
const sock = this.detach();
|
|
187
|
+
if (sock) await sock.end(undefined);
|
|
188
|
+
this.setStatus({ state: "stopped" });
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async logout(): Promise<void> {
|
|
192
|
+
const sock = this.detach();
|
|
193
|
+
if (sock) await sock.logout();
|
|
194
|
+
await clearAuthState(this.config.authStore);
|
|
195
|
+
this.setStatus({ state: "logged-out", code: null });
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async send(to: string, content: OutboundContent): Promise<{ externalId: string }> {
|
|
199
|
+
const sock = this.socket;
|
|
200
|
+
if (!sock || this.current.state !== "open") throw new ChannelSendFailure("NOT_CONNECTED", "the WhatsApp Web session is not open");
|
|
201
|
+
const { externalId, key } = await this.ownSends.track(() => this.dispatch(sock, to, content));
|
|
202
|
+
const contact = replyAddress(to, key);
|
|
203
|
+
if (contact) this.choices.offer(contact, content);
|
|
204
|
+
return { externalId };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private async dispatch(sock: BaileysSocket<Msg>, to: string, content: OutboundContent): Promise<{ externalId: string; key: BaileysMessageKey }> {
|
|
208
|
+
const sent = await sock.sendMessage(addressJid(to), { text: renderOutboundText(content) }).catch((error: unknown) => {
|
|
209
|
+
const code = disconnectCode({ error: error as Error });
|
|
210
|
+
throw new ChannelSendFailure(code === null ? "SEND_FAILED" : String(code), "the WhatsApp Web socket refused the send");
|
|
211
|
+
});
|
|
212
|
+
const externalId = sent?.key?.id;
|
|
213
|
+
if (!externalId) throw new ChannelSendFailure("NO_MESSAGE_ID", "the WhatsApp Web socket returned no message id");
|
|
214
|
+
return { externalId, key: sent?.key ?? {} };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
sendPresence(contactId: string, state: "composing" | "paused"): Promise<void> {
|
|
218
|
+
return this.fireAndForget("presence", (sock) => sock.sendPresenceUpdate(state, addressJid(contactId)));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
markRead(contactId: string, externalIds: readonly string[]): Promise<void> {
|
|
222
|
+
if (externalIds.length === 0) return Promise.resolve();
|
|
223
|
+
const remoteJid = addressJid(contactId);
|
|
224
|
+
return this.fireAndForget("mark-read", (sock) => sock.readMessages(externalIds.map((id) => ({ remoteJid, id, fromMe: false }))));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** One call on the open socket whose failure is reported, never thrown. */
|
|
228
|
+
private async fireAndForget(where: "presence" | "mark-read", call: (sock: BaileysSocket<Msg>) => Promise<void>): Promise<void> {
|
|
229
|
+
const sock = this.socket;
|
|
230
|
+
try {
|
|
231
|
+
if (!sock || this.current.state !== "open") throw new ChannelSendFailure("NOT_CONNECTED", "the WhatsApp Web session is not open");
|
|
232
|
+
await call(sock);
|
|
233
|
+
} catch (error) {
|
|
234
|
+
this.config.onError?.(error, where);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async fetchHistory(contactId: string, anchor: HistoryAnchor, count: number, timeoutMs: number): Promise<WhatsAppWebHistoryMessage[]> {
|
|
239
|
+
const sock = this.socket;
|
|
240
|
+
if (!sock || this.current.state !== "open" || count <= 0) return [];
|
|
241
|
+
const key = { remoteJid: addressJid(contactId), id: anchor.externalId, fromMe: anchor.fromMe };
|
|
242
|
+
const call = () => sock.fetchMessageHistory(count, key, Math.floor(anchor.sentAt.getTime() / 1000));
|
|
243
|
+
return this.history.fetch(contactId, count, timeoutMs, call, (error) => this.config.onError?.(error, "history"));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
downloadMedia(mediaId: string, options: { maxBytes: number; timeoutMs?: number }): Promise<ChannelMedia> {
|
|
247
|
+
const sock = this.socket;
|
|
248
|
+
return downloadAudio({
|
|
249
|
+
baileys: this.config.baileys,
|
|
250
|
+
message: this.audio.get(mediaId),
|
|
251
|
+
maxBytes: options.maxBytes,
|
|
252
|
+
timeoutMs: options.timeoutMs,
|
|
253
|
+
logger: this.config.logger,
|
|
254
|
+
reupload: sock?.updateMediaMessage ? (message: Msg) => sock.updateMediaMessage!(message) : undefined,
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ── The socket ──────────────────────────────────────────────────────────
|
|
259
|
+
|
|
260
|
+
private detach(): BaileysSocket<Msg> | null {
|
|
261
|
+
this.stopping = true;
|
|
262
|
+
const sock = this.socket;
|
|
263
|
+
this.socket = null;
|
|
264
|
+
this.account = null;
|
|
265
|
+
this.history.flush();
|
|
266
|
+
this.ownSends.reset();
|
|
267
|
+
return sock;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private setStatus(status: WhatsAppWebStatus): void {
|
|
271
|
+
this.current = status;
|
|
272
|
+
this.config.onStatus?.(status);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
private async open(): Promise<void> {
|
|
276
|
+
this.setStatus({ state: "connecting" });
|
|
277
|
+
const { state, saveCreds } = await loadAuthState(this.config.baileys, this.config.authStore);
|
|
278
|
+
const sock = this.config.baileys.makeWASocket({
|
|
279
|
+
// The ONE boundary cast: the store holds Baileys' own values, which its key store types per category.
|
|
280
|
+
auth: state as Auth,
|
|
281
|
+
markOnlineOnConnect: false,
|
|
282
|
+
syncFullHistory: false,
|
|
283
|
+
...(this.config.logger ? { logger: this.config.logger } : {}),
|
|
284
|
+
...(this.config.browser ? { browser: this.config.browser } : {}),
|
|
285
|
+
});
|
|
286
|
+
this.socket = sock;
|
|
287
|
+
sock.ev.on("creds.update", () => {
|
|
288
|
+
saveCreds().catch((error: unknown) => this.config.onError?.(error, "save-creds"));
|
|
289
|
+
});
|
|
290
|
+
sock.ev.on("connection.update", (update) => {
|
|
291
|
+
if (sock === this.socket) void this.onConnection(sock, update);
|
|
292
|
+
});
|
|
293
|
+
sock.ev.on("messages.upsert", (upsert) => {
|
|
294
|
+
const account = this.linked(sock);
|
|
295
|
+
if (!account) return;
|
|
296
|
+
if (upsert.type === "notify") upsert.messages.forEach((message) => this.audio.remember(message));
|
|
297
|
+
const options = this.config.optOutKeywords ? { optOutKeywords: this.config.optOutKeywords } : {};
|
|
298
|
+
// One message at a time: a phone message clears an offer only for the replies that come after it.
|
|
299
|
+
const events = upsert.messages.flatMap((message) => {
|
|
300
|
+
const one = { type: upsert.type, messages: [message] };
|
|
301
|
+
return [...normalizeUpsert(account, one, options), ...this.ownSends.accept(normalizeSentElsewhere(account, one))];
|
|
302
|
+
});
|
|
303
|
+
this.deliver(applyChoices(this.choices, events));
|
|
304
|
+
});
|
|
305
|
+
sock.ev.on("messaging-history.set", (set) => {
|
|
306
|
+
if (sock === this.socket) this.history.answer(set);
|
|
307
|
+
});
|
|
308
|
+
sock.ev.on("messages.update", (updates) => {
|
|
309
|
+
const account = this.linked(sock);
|
|
310
|
+
if (account) this.deliver(normalizeUpdates(account, updates, (this.config.now ?? (() => new Date()))()));
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** The account a CURRENT socket is linked to: from the open event, or its own user while still opening. */
|
|
315
|
+
private linked(sock: BaileysSocket<Msg>): string | null {
|
|
316
|
+
if (sock !== this.socket) return null;
|
|
317
|
+
return this.account ?? (sock.user?.id ? jidUser(sock.user.id) : null);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Hand one body to the host, after every earlier one: a socket's order is kept. */
|
|
321
|
+
private deliver(events: NormalizedEvent[]): void {
|
|
322
|
+
if (events.length === 0) return;
|
|
323
|
+
const body = encodeEnvelope(events);
|
|
324
|
+
this.deliveries = this.deliveries.then(() =>
|
|
325
|
+
this.config.deliver(body).then(
|
|
326
|
+
() => undefined,
|
|
327
|
+
(error: unknown) => this.config.onError?.(error, "deliver"),
|
|
328
|
+
),
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
private async onConnection(sock: BaileysSocket<Msg>, update: BaileysConnectionUpdate): Promise<void> {
|
|
333
|
+
if (update.qr) await this.onQr(sock, update.qr);
|
|
334
|
+
if (update.connection === "open") {
|
|
335
|
+
this.attempts = 0;
|
|
336
|
+
this.account = sock.user?.id ? jidUser(sock.user.id) : null;
|
|
337
|
+
this.setStatus(this.account ? { state: "open", accountId: this.account } : { state: "connecting" });
|
|
338
|
+
} else if (update.connection === "close") {
|
|
339
|
+
await this.onClose(disconnectCode(update.lastDisconnect));
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
private async onQr(sock: BaileysSocket<Msg>, qr: string): Promise<void> {
|
|
344
|
+
const phone = this.config.pairingPhoneNumber;
|
|
345
|
+
if (!phone) return this.setStatus({ state: "qr", qr });
|
|
346
|
+
if (this.pairingRequested) return;
|
|
347
|
+
this.pairingRequested = true;
|
|
348
|
+
try {
|
|
349
|
+
this.setStatus({ state: "pairing-code", code: await sock.requestPairingCode(phone.replace(/\D/g, "")) });
|
|
350
|
+
} catch (error) {
|
|
351
|
+
this.pairingRequested = false;
|
|
352
|
+
this.config.onError?.(error, "pairing-code");
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
private async onClose(code: number | null): Promise<void> {
|
|
357
|
+
this.socket = null;
|
|
358
|
+
this.account = null;
|
|
359
|
+
this.history.flush();
|
|
360
|
+
this.ownSends.reset();
|
|
361
|
+
if (this.stopping) return this.setStatus({ state: "stopped" });
|
|
362
|
+
if (code === DISCONNECT.loggedOut) {
|
|
363
|
+
await clearAuthState(this.config.authStore);
|
|
364
|
+
return this.setStatus({ state: "logged-out", code });
|
|
365
|
+
}
|
|
366
|
+
const terminal = code === null ? undefined : TERMINAL[code];
|
|
367
|
+
if (terminal) return this.setStatus({ state: "failed", code, reason: terminal });
|
|
368
|
+
if (code !== DISCONNECT.restartRequired && !(await this.backOff(code))) return;
|
|
369
|
+
await this.open();
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Wait before a reconnect; false when the attempts ran out or the session was stopped meanwhile. */
|
|
373
|
+
private async backOff(code: number | null): Promise<boolean> {
|
|
374
|
+
const maxAttempts = this.config.reconnect?.maxAttempts ?? 5;
|
|
375
|
+
this.attempts += 1;
|
|
376
|
+
if (this.attempts > maxAttempts) {
|
|
377
|
+
this.setStatus({ state: "failed", code, reason: "reconnects-exhausted" });
|
|
378
|
+
return false;
|
|
379
|
+
}
|
|
380
|
+
this.setStatus({ state: "reconnecting", attempt: this.attempts, code });
|
|
381
|
+
await (this.config.sleep ?? defaultSleep)((this.config.reconnect?.delayMs ?? 2_000) * 2 ** (this.attempts - 1));
|
|
382
|
+
if (!this.stopping) return true;
|
|
383
|
+
this.setStatus({ state: "stopped" });
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** One linked WhatsApp account over Baileys. Nothing connects until `start()`. */
|
|
389
|
+
export function createWhatsAppWebSession<Auth, Msg extends BaileysMessage>(config: WhatsAppWebSessionConfig<Auth, Msg>): WhatsAppWebSession {
|
|
390
|
+
return new BaileysSession(config);
|
|
391
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The timer pair the session's deadlines run on: a history request's timeout and
|
|
3
|
+
* the longest an echo-suspect event is held. Injectable so a test fires them by
|
|
4
|
+
* hand; every timer set here is cleared once what it guards settles.
|
|
5
|
+
*/
|
|
6
|
+
export interface WhatsAppWebTimers {
|
|
7
|
+
setTimeout(run: () => void, ms: number): unknown;
|
|
8
|
+
clearTimeout(handle: unknown): void;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const systemTimers: WhatsAppWebTimers = {
|
|
12
|
+
setTimeout: (run, ms) => {
|
|
13
|
+
const handle = setTimeout(run, ms);
|
|
14
|
+
// A pending hold or history deadline never keeps a short-lived host process alive.
|
|
15
|
+
(handle as { unref?: () => void }).unref?.();
|
|
16
|
+
return handle;
|
|
17
|
+
},
|
|
18
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
19
|
+
};
|