chat-adapter-wwebjs 0.0.0-stage → 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,1392 @@
1
+ // src/adapter.ts
2
+ import {
3
+ cardToFallbackText,
4
+ extractCard,
5
+ ResourceNotFoundError,
6
+ ValidationError as ValidationError2
7
+ } from "@chat-adapter/shared";
8
+ import {
9
+ ConsoleLogger,
10
+ defaultEmojiResolver,
11
+ Message
12
+ } from "chat";
13
+
14
+ // src/format-converter.ts
15
+ import {
16
+ BaseFormatConverter,
17
+ getNodeChildren,
18
+ parseMarkdown,
19
+ tableToAscii
20
+ } from "chat";
21
+ var MAX_MARKDOWN_LENGTH = 16e3;
22
+ function plain(value) {
23
+ return { children: [{ children: [{ type: "text", value }], type: "paragraph" }], type: "root" };
24
+ }
25
+ var WWebJSFormatConverter = class extends BaseFormatConverter {
26
+ /** Text from anyone: past `MAX_MARKDOWN_LENGTH`, or when the parser gives up, it stays plain rather than stalling or throwing. */
27
+ toAst(platformText) {
28
+ if (platformText.length > MAX_MARKDOWN_LENGTH) return plain(platformText);
29
+ try {
30
+ return parseMarkdown(
31
+ platformText.replace(/(?<!\*)\*(?!\*)([^*\n]+?)\*(?!\*)/g, "**$1**").replace(/(?<!~)~(?!~)([^~\n]+?)~(?!~)/g, "~~$1~~")
32
+ );
33
+ } catch {
34
+ return plain(platformText);
35
+ }
36
+ }
37
+ fromAst(ast) {
38
+ return this.fromAstWithNodeConverter(ast, (node) => this.toWhatsApp(node));
39
+ }
40
+ toWhatsApp(node) {
41
+ switch (node.type) {
42
+ case "blockquote":
43
+ return this.join(node, "\n\n").split("\n").map((line) => `> ${line}`).join("\n");
44
+ case "break":
45
+ return "\n";
46
+ case "code":
47
+ return `\`\`\`
48
+ ${node.value}
49
+ \`\`\``;
50
+ case "delete":
51
+ return `~${this.join(node)}~`;
52
+ case "emphasis":
53
+ return `_${this.join(node)}_`;
54
+ case "heading":
55
+ return `*${this.join(node)}*`;
56
+ case "image":
57
+ return node.url || this.join(node);
58
+ case "inlineCode":
59
+ return `\`${node.value}\``;
60
+ case "link": {
61
+ const text = this.join(node);
62
+ return !node.url || [text, `mailto:${text}`].includes(node.url) ? text : `${text} (${node.url})`;
63
+ }
64
+ case "list":
65
+ return this.renderList(node, 0, (child) => this.toWhatsApp(child));
66
+ case "strong":
67
+ return `*${this.join(node)}*`;
68
+ case "table":
69
+ return `\`\`\`
70
+ ${tableToAscii(node)}
71
+ \`\`\``;
72
+ case "thematicBreak":
73
+ return "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500";
74
+ default:
75
+ return this.defaultNodeToText(node, (child) => this.toWhatsApp(child));
76
+ }
77
+ }
78
+ join(node, separator = "") {
79
+ return getNodeChildren(node).map((child) => this.toWhatsApp(child)).join(separator);
80
+ }
81
+ };
82
+
83
+ // src/jid.ts
84
+ var BROADCAST_SUFFIX = "@broadcast";
85
+ var GROUP_SUFFIX = "@g.us";
86
+ var NEWSLETTER_SUFFIX = "@newsletter";
87
+ var USER_SUFFIX = "@c.us";
88
+ function isGroupId(chatId) {
89
+ return chatId.endsWith(GROUP_SUFFIX);
90
+ }
91
+ function isNewsletterId(chatId) {
92
+ return chatId.endsWith(NEWSLETTER_SUFFIX);
93
+ }
94
+ function isBroadcastId(chatId) {
95
+ return chatId.endsWith(BROADCAST_SUFFIX);
96
+ }
97
+ function serialize(id) {
98
+ if (typeof id === "string") return id;
99
+ const wid = id;
100
+ return wid?._serialized ?? wid?.$1 ?? "";
101
+ }
102
+ function isUserId(chatId) {
103
+ return !isGroupId(chatId) && !isNewsletterId(chatId) && !isBroadcastId(chatId);
104
+ }
105
+ function toChatId(value) {
106
+ return value.includes("@") ? value : `${value.replace(/\D/g, "")}${USER_SUFFIX}`;
107
+ }
108
+ function toUser(chatId) {
109
+ return chatId.split("@")[0] ?? chatId;
110
+ }
111
+ function extractMentions(text) {
112
+ const mentions = /* @__PURE__ */ new Set();
113
+ const rendered = text.replace(/<@([^\s<>]+)>/g, (_match, id) => {
114
+ const chatId = toChatId(id);
115
+ mentions.add(chatId);
116
+ return `@${toUser(chatId)}`;
117
+ });
118
+ const named = new Set([...mentions].map(toUser));
119
+ for (const [, user] of rendered.matchAll(/@(\d{6,})\b/g)) {
120
+ if (user && !named.has(user)) mentions.add(`${user}${USER_SUFFIX}`);
121
+ }
122
+ return { mentions: [...mentions], text: rendered };
123
+ }
124
+
125
+ // src/media.ts
126
+ import { extractFiles, extractPostableAttachments, ValidationError } from "@chat-adapter/shared";
127
+
128
+ // src/wwebjs.ts
129
+ import wwebjs from "whatsapp-web.js";
130
+ var { Client, Location, MessageMedia, Poll, ScheduledEvent } = wwebjs;
131
+
132
+ // src/media.ts
133
+ var ATTACHMENT_TYPES = {
134
+ audio: "audio",
135
+ document: "file",
136
+ image: "image",
137
+ ptt: "audio",
138
+ sticker: "image",
139
+ video: "video"
140
+ };
141
+ var MIME_TYPES = {
142
+ aac: "audio/aac",
143
+ gif: "image/gif",
144
+ jpeg: "image/jpeg",
145
+ jpg: "image/jpeg",
146
+ json: "application/json",
147
+ m4a: "audio/mp4",
148
+ mp3: "audio/mpeg",
149
+ mp4: "video/mp4",
150
+ ogg: "audio/ogg",
151
+ opus: "audio/ogg",
152
+ pdf: "application/pdf",
153
+ png: "image/png",
154
+ txt: "text/plain",
155
+ wav: "audio/wav",
156
+ webm: "video/webm",
157
+ webp: "image/webp"
158
+ };
159
+ var DEFAULT_MIME_TYPE = "application/octet-stream";
160
+ var DEFAULT_MAX_MEDIA_BYTES = 64 * 1024 * 1024;
161
+ var URL_TIMEOUT_MS = 3e4;
162
+ function toAttachments(message, maxBytes) {
163
+ if (!message.hasMedia) return [];
164
+ const data = message.rawData ?? {};
165
+ return [
166
+ {
167
+ fetchData: () => download(message, maxBytes),
168
+ fetchMetadata: { messageId: message.id._serialized },
169
+ height: data.height,
170
+ mimeType: data.mimetype,
171
+ name: data.filename,
172
+ size: data.size,
173
+ type: ATTACHMENT_TYPES[message.type] ?? "file",
174
+ url: void 0,
175
+ width: data.width
176
+ }
177
+ ];
178
+ }
179
+ async function download(message, maxBytes = DEFAULT_MAX_MEDIA_BYTES) {
180
+ const size = (message.rawData ?? {}).size;
181
+ if (size && size > maxBytes) throw tooLarge(message.id._serialized, size, maxBytes);
182
+ const { downloadMediaStream } = message;
183
+ if (downloadMediaStream) {
184
+ const streamed = await downloadMediaStream.call(message);
185
+ if (!streamed) throw unavailable(message.id._serialized);
186
+ return collect(streamed.stream, maxBytes, message.id._serialized);
187
+ }
188
+ const media = await message.downloadMedia();
189
+ if (!media?.data) throw unavailable(message.id._serialized);
190
+ const data = Buffer.from(media.data, "base64");
191
+ if (data.length > maxBytes) throw tooLarge(message.id._serialized, data.length, maxBytes);
192
+ return data;
193
+ }
194
+ function toMediaList(message, maxBytes) {
195
+ return Promise.all(
196
+ [...extractPostableAttachments(message), ...extractFiles(message)].map(
197
+ (source) => toMedia(source, maxBytes)
198
+ )
199
+ );
200
+ }
201
+ async function toMedia(source, maxBytes = DEFAULT_MAX_MEDIA_BYTES) {
202
+ if ("filename" in source) {
203
+ return new MessageMedia(
204
+ source.mimeType ?? mimeTypeOf(source.filename),
205
+ await toBase64(source.data),
206
+ source.filename
207
+ );
208
+ }
209
+ const data = source.data ?? await source.fetchData?.();
210
+ if (!data) {
211
+ if (!source.url) {
212
+ throw new ValidationError("wwebjs", "Attachment has no data, fetchData, or url to send.");
213
+ }
214
+ return fetchMedia(source.url, source, maxBytes);
215
+ }
216
+ return new MessageMedia(
217
+ source.mimeType ?? mimeTypeOf(source.name),
218
+ await toBase64(data),
219
+ source.name ?? null,
220
+ source.size ?? null
221
+ );
222
+ }
223
+ function isCaptionable(media) {
224
+ return !isAudio(media);
225
+ }
226
+ function isAudio(media) {
227
+ return media.mimetype.startsWith("audio/");
228
+ }
229
+ function mimeTypeOf(filename) {
230
+ const extension = filename?.split(".").pop()?.toLowerCase();
231
+ return extension && Object.hasOwn(MIME_TYPES, extension) && MIME_TYPES[extension] || DEFAULT_MIME_TYPE;
232
+ }
233
+ async function fetchMedia(url, source, maxBytes) {
234
+ const response = await fetch(url, { signal: AbortSignal.timeout(URL_TIMEOUT_MS) });
235
+ if (!response.ok || !response.body) {
236
+ throw new ValidationError("wwebjs", `Could not fetch ${url}: HTTP ${response.status}.`);
237
+ }
238
+ const data = await collect(response.body, maxBytes, url);
239
+ const name = source.name ?? new URL(url).pathname.split("/").pop() ?? null;
240
+ const mimeType = source.mimeType ?? response.headers.get("content-type")?.split(";")[0] ?? mimeTypeOf(name ?? void 0);
241
+ return new MessageMedia(mimeType, data.toString("base64"), name);
242
+ }
243
+ async function collect(stream, maxBytes, label) {
244
+ const chunks = [];
245
+ let total = 0;
246
+ for await (const chunk of stream) {
247
+ total += chunk.length;
248
+ if (total > maxBytes) throw tooLarge(label, total, maxBytes);
249
+ chunks.push(Buffer.from(chunk));
250
+ }
251
+ return Buffer.concat(chunks);
252
+ }
253
+ function tooLarge(label, size, maxBytes) {
254
+ return new ValidationError(
255
+ "wwebjs",
256
+ `Media for ${label} is ${size} bytes or more, over the ${maxBytes}-byte limit.`
257
+ );
258
+ }
259
+ function unavailable(messageId) {
260
+ return new ValidationError(
261
+ "wwebjs",
262
+ `Media for message ${messageId} is no longer available for download.`
263
+ );
264
+ }
265
+ async function toBase64(data) {
266
+ if (Buffer.isBuffer(data)) return data.toString("base64");
267
+ if (data instanceof ArrayBuffer) return Buffer.from(data).toString("base64");
268
+ return Buffer.from(await data.arrayBuffer()).toString("base64");
269
+ }
270
+
271
+ // src/shutdown.ts
272
+ var SIGNALS = ["SIGHUP", "SIGINT", "SIGTERM"];
273
+ var sessions = /* @__PURE__ */ new Set();
274
+ async function onSignal(signal) {
275
+ for (const name of SIGNALS) process.off(name, onSignal);
276
+ await Promise.allSettled([...sessions].map((close) => close()));
277
+ if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
278
+ }
279
+ function closeOnSignal(close) {
280
+ if (sessions.size === 0) for (const name of SIGNALS) process.on(name, onSignal);
281
+ sessions.add(close);
282
+ return () => {
283
+ sessions.delete(close);
284
+ if (sessions.size === 0) for (const name of SIGNALS) process.off(name, onSignal);
285
+ };
286
+ }
287
+
288
+ // src/adapter.ts
289
+ var ACK_STATUSES = {
290
+ [-1]: "error",
291
+ 0: "pending",
292
+ 1: "sent",
293
+ 2: "delivered",
294
+ 3: "read",
295
+ 4: "played"
296
+ };
297
+ var GROUP_EVENTS = {
298
+ group_admin_changed: "admin_changed",
299
+ group_join: "join",
300
+ group_leave: "leave",
301
+ group_membership_request: "membership_request",
302
+ group_update: "update"
303
+ };
304
+ var SYSTEM_TYPES = /* @__PURE__ */ new Set([
305
+ "broadcast_notification",
306
+ "call_log",
307
+ "ciphertext",
308
+ "debug",
309
+ "e2e_notification",
310
+ "gp2",
311
+ "group_notification",
312
+ "notification",
313
+ "notification_template",
314
+ "protocol",
315
+ "revoked"
316
+ ]);
317
+ var DEFAULT_LIMIT = 50;
318
+ var MAX_HISTORY = 1e3;
319
+ var MAX_MENTION_LOOKUPS = 20;
320
+ var LOOKUP_TIMEOUT_MS = 5e3;
321
+ var EDIT_RETRIES = 3;
322
+ var EDIT_RETRY_MS = 250;
323
+ var FRESH_MS = 5e3;
324
+ var CONNECT_TIMEOUT_MS = 12e4;
325
+ var WATCHDOG_INTERVAL_MS = 6e4;
326
+ var RECONNECT_MIN_MS = 5e3;
327
+ var RECONNECT_MAX_MS = 3e5;
328
+ var MAX_POLL_OPTIONS = 12;
329
+ var MIN_POLL_OPTIONS = 2;
330
+ var CATCH_UP_MS = 864e5;
331
+ var MAX_CATCH_UP_CHATS = 100;
332
+ var MAX_CATCH_UP_MESSAGES = 50;
333
+ var RECOMMENDED_CHROMIUM_ARGS = [
334
+ "--renderer-process-limit=1",
335
+ "--disable-gpu",
336
+ "--disable-component-update"
337
+ ];
338
+ var WWebJSAdapter = class {
339
+ name;
340
+ lockScope = "channel";
341
+ /** The underlying whatsapp-web.js client, for anything this adapter does not wrap. */
342
+ client;
343
+ userName;
344
+ _config;
345
+ _converter = new WWebJSFormatConverter();
346
+ _ackHandlers = [];
347
+ _callHandlers = [];
348
+ _groupHandlers = [];
349
+ _pollVoteHandlers = [];
350
+ _chat = null;
351
+ _logger;
352
+ _connection = null;
353
+ _botLid;
354
+ _closed = false;
355
+ _retry;
356
+ _initialized = false;
357
+ _state = "idle";
358
+ _watchdog;
359
+ _strikes = 0;
360
+ _unsignal;
361
+ _seen;
362
+ _saving = Promise.resolve();
363
+ constructor(config = {}) {
364
+ const name = config.adapterName ?? "wwebjs";
365
+ if (name.includes(":")) {
366
+ throw new ValidationError2("wwebjs", `Invalid adapterName "${name}". ":" is not allowed.`);
367
+ }
368
+ this._config = config;
369
+ this.name = name;
370
+ this.userName = config.userName ?? "wwebjs-bot";
371
+ this._logger = config.logger ?? new ConsoleLogger("info").child(name);
372
+ this.client = config.client ?? new Client(this._clientOptions());
373
+ this._listen();
374
+ }
375
+ /** Where the session stands; a health check reads `connection === "connected"`. */
376
+ get connection() {
377
+ return this._state;
378
+ }
379
+ get botUserId() {
380
+ return this.client.info?.wid?._serialized;
381
+ }
382
+ async initialize(chat) {
383
+ this._chat = chat;
384
+ this._logger = chat.getLogger(this.name);
385
+ }
386
+ /**
387
+ * Launch the browser session and wait until WhatsApp is ready.
388
+ *
389
+ * Call this after registering handlers on your `Chat` instance, so no
390
+ * message arrives before there is something to receive it. Repeated calls
391
+ * share one connection attempt.
392
+ */
393
+ async connect() {
394
+ if (!this._chat) {
395
+ this._logger.warn(
396
+ "Connecting before Chat initialized \u2014 inbound messages are dropped until chat.initialize() runs."
397
+ );
398
+ }
399
+ this._closed = false;
400
+ clearTimeout(this._retry);
401
+ this._retry = void 0;
402
+ this._watch();
403
+ if (this._config.handleSignals !== false) {
404
+ this._unsignal ??= closeOnSignal(() => this.disconnect());
405
+ }
406
+ this._connection ??= this._connect().catch((error) => {
407
+ this._connection = null;
408
+ if (this._state !== "logged_out" && !this._closed) this._state = "disconnected";
409
+ throw error;
410
+ });
411
+ return this._connection;
412
+ }
413
+ /** Close the browser session. */
414
+ async disconnect() {
415
+ this._closed = true;
416
+ this._state = "closed";
417
+ clearTimeout(this._retry);
418
+ clearInterval(this._watchdog);
419
+ this._watchdog = void 0;
420
+ this._connection = null;
421
+ this._unsignal?.();
422
+ this._unsignal = void 0;
423
+ await this.client.destroy();
424
+ }
425
+ encodeThreadId(platformData) {
426
+ return `${this.name}:${platformData.chatId}`;
427
+ }
428
+ decodeThreadId(threadId) {
429
+ const prefix = `${this.name}:`;
430
+ if (!threadId.startsWith(prefix)) {
431
+ throw new ValidationError2("wwebjs", `Invalid WhatsApp thread ID: ${threadId}`);
432
+ }
433
+ return { chatId: threadId.slice(prefix.length) };
434
+ }
435
+ channelIdFromThreadId(threadId) {
436
+ return threadId;
437
+ }
438
+ isDM(threadId) {
439
+ const { chatId } = this.decodeThreadId(threadId);
440
+ return !isGroupId(chatId) && !isNewsletterId(chatId) && !isBroadcastId(chatId);
441
+ }
442
+ getChannelVisibility(threadId) {
443
+ return isNewsletterId(this.decodeThreadId(threadId).chatId) ? "external" : "private";
444
+ }
445
+ /**
446
+ * whatsapp-web.js drives a browser session rather than inbound HTTP, so this
447
+ * always answers 501. Call {@link WWebJSAdapter.connect} to receive messages.
448
+ */
449
+ async handleWebhook(_request, _options) {
450
+ return new Response(
451
+ JSON.stringify({
452
+ error: "The wwebjs adapter does not use HTTP webhooks. Call adapter.connect() to open the WhatsApp session."
453
+ }),
454
+ { headers: { "Content-Type": "application/json" }, status: 501 }
455
+ );
456
+ }
457
+ parseMessage(raw) {
458
+ const bot = this._botUsers();
459
+ const text = this._named(
460
+ raw.body ?? "",
461
+ this._mentioned(raw).filter((user) => bot.has(user)),
462
+ () => this.userName
463
+ );
464
+ return new Message({
465
+ attachments: toAttachments(raw, this._config.maxMediaBytes),
466
+ author: this._author(raw),
467
+ formatted: this._converter.toAst(text),
468
+ id: serialize(raw.id),
469
+ isMention: this._mentionsBot(raw),
470
+ links: (raw.links ?? []).map(({ link }) => ({ url: link })),
471
+ metadata: {
472
+ dateSent: new Date(raw.timestamp * 1e3),
473
+ edited: raw.latestEditSenderTimestampMs != null,
474
+ editedAt: raw.latestEditSenderTimestampMs ? new Date(raw.latestEditSenderTimestampMs) : void 0
475
+ },
476
+ raw,
477
+ text,
478
+ threadId: this.encodeThreadId({ chatId: chatIdOf(raw) })
479
+ });
480
+ }
481
+ async postMessage(threadId, message) {
482
+ return this._send(threadId, message);
483
+ }
484
+ async postChannelMessage(channelId, message) {
485
+ return this._send(channelId, message);
486
+ }
487
+ async reply(threadId, messageId, message) {
488
+ return this._send(threadId, message, { quotedMessageId: messageId });
489
+ }
490
+ async editMessage(threadId, messageId, message) {
491
+ const { card, text: rendered } = this._render(message, threadId);
492
+ const { mentions, text } = extractMentions(rendered);
493
+ const target = await this._requireMessage(messageId);
494
+ const edit = () => target.edit(text, mentions.length > 0 ? { mentions } : void 0);
495
+ let edited = await edit();
496
+ const fresh = target.fromMe && Date.now() - target.timestamp * 1e3 < FRESH_MS;
497
+ for (let retry = 0; !edited && fresh && retry < EDIT_RETRIES; retry++) {
498
+ await new Promise((resolve) => setTimeout(resolve, EDIT_RETRY_MS));
499
+ edited = await edit();
500
+ }
501
+ if (!edited) {
502
+ throw new ValidationError2(
503
+ "wwebjs",
504
+ `Message ${messageId} could not be edited. WhatsApp only allows editing your own messages within 15 minutes.`
505
+ );
506
+ }
507
+ const raw = this._raw(edited, threadId);
508
+ await this._cardSent(card, raw.id, threadId);
509
+ return raw;
510
+ }
511
+ async deleteMessage(_threadId, messageId) {
512
+ await (await this._requireMessage(messageId)).delete(true);
513
+ }
514
+ async addReaction(_threadId, messageId, emoji) {
515
+ await (await this._requireMessage(messageId)).react(defaultEmojiResolver.toGChat(emoji));
516
+ }
517
+ async removeReaction(_threadId, messageId, _emoji) {
518
+ await (await this._requireMessage(messageId)).react("");
519
+ }
520
+ async fetchMessages(threadId, options) {
521
+ return this._page(await this._requireChat(threadId), options);
522
+ }
523
+ async fetchChannelMessages(channelId, options) {
524
+ return this.fetchMessages(channelId, options);
525
+ }
526
+ async fetchMessage(_threadId, messageId) {
527
+ const message = await this.client.getMessageById(messageId).catch(() => null);
528
+ return message ? this.parseMessage(message) : null;
529
+ }
530
+ async fetchThread(threadId) {
531
+ const { chatId } = this.decodeThreadId(threadId);
532
+ const chat = await this._findChat(chatId);
533
+ return {
534
+ channelId: threadId,
535
+ channelName: chat?.name,
536
+ channelVisibility: this.getChannelVisibility(threadId),
537
+ id: threadId,
538
+ isDM: this.isDM(threadId),
539
+ metadata: { chatId }
540
+ };
541
+ }
542
+ async fetchChannelInfo(channelId) {
543
+ const { chatId } = this.decodeThreadId(channelId);
544
+ const chat = await this._findChat(chatId);
545
+ return {
546
+ channelVisibility: this.getChannelVisibility(channelId),
547
+ id: channelId,
548
+ isDM: this.isDM(channelId),
549
+ memberCount: isGroupChat(chat) ? chat.participants.length : void 0,
550
+ metadata: { chatId },
551
+ name: chat?.name
552
+ };
553
+ }
554
+ /** WhatsApp conversations are flat, so a channel never contains sub-threads. */
555
+ async listThreads() {
556
+ return { threads: [] };
557
+ }
558
+ async getUser(userId) {
559
+ const contact = await this.client.getContactById(toChatId(userId)).catch(() => null);
560
+ if (!contact) return null;
561
+ const number = contact.number || toUser(contact.id._serialized);
562
+ return {
563
+ avatarUrl: await contact.getProfilePicUrl().catch(() => void 0),
564
+ fullName: contact.name ?? contact.pushname ?? number,
565
+ isBot: false,
566
+ userId: contact.id._serialized,
567
+ userName: contact.pushname || number
568
+ };
569
+ }
570
+ /** A number, or its `@c.us` id, resolves to the chat WhatsApp uses for it — often a LID — so a DM is one thread whoever opened it. */
571
+ async openDM(userId) {
572
+ if (userId.includes("@") && !userId.endsWith("@c.us")) {
573
+ return this.encodeThreadId({ chatId: userId });
574
+ }
575
+ const resolved = await this.client.getNumberId(toUser(userId)).catch(() => null);
576
+ return this.encodeThreadId({ chatId: resolved?._serialized ?? toChatId(userId) });
577
+ }
578
+ async markAsRead(threadId) {
579
+ await (await this._requireChat(threadId)).sendSeen();
580
+ }
581
+ async startTyping(threadId, status) {
582
+ await this._indicator(
583
+ threadId,
584
+ "startTyping",
585
+ (chat) => status === "recording" ? chat.sendStateRecording() : chat.sendStateTyping()
586
+ );
587
+ }
588
+ async endTyping(threadId) {
589
+ await this._indicator(threadId, "endTyping", (chat) => chat.clearState());
590
+ }
591
+ renderFormatted(content) {
592
+ return this._converter.fromAst(content);
593
+ }
594
+ rehydrateAttachment(attachment) {
595
+ const messageId = attachment.fetchMetadata?.messageId;
596
+ if (!messageId) return attachment;
597
+ return {
598
+ ...attachment,
599
+ fetchData: async () => download(await this._requireMessage(messageId), this._config.maxMediaBytes)
600
+ };
601
+ }
602
+ /** Send a map pin. */
603
+ async sendLocation(args) {
604
+ assertRange("latitude", args.latitude, 90);
605
+ assertRange("longitude", args.longitude, 180);
606
+ const location = new Location(args.latitude, args.longitude, {
607
+ address: args.address,
608
+ name: args.name,
609
+ url: args.url
610
+ });
611
+ return this._sendContent(args.threadId, location);
612
+ }
613
+ /** Send a native WhatsApp poll. Between 2 and 12 options. */
614
+ async sendPoll(args) {
615
+ if (args.options.length < MIN_POLL_OPTIONS || args.options.length > MAX_POLL_OPTIONS) {
616
+ throw new ValidationError2(
617
+ "wwebjs",
618
+ `sendPoll: WhatsApp polls need between ${MIN_POLL_OPTIONS} and ${MAX_POLL_OPTIONS} options. Received ${args.options.length}.`
619
+ );
620
+ }
621
+ const poll = new Poll(args.question, args.options, {
622
+ allowMultipleAnswers: args.allowMultipleAnswers,
623
+ messageSecret: void 0
624
+ });
625
+ return this._sendContent(args.threadId, poll);
626
+ }
627
+ /** Send a scheduled event card. */
628
+ async sendEvent(args) {
629
+ const event = new ScheduledEvent(args.name, args.startTime, {
630
+ callType: args.callType ?? "none",
631
+ description: args.description,
632
+ endTime: args.endTime,
633
+ location: args.location,
634
+ messageSecret: void 0
635
+ });
636
+ return this._sendContent(args.threadId, event);
637
+ }
638
+ /** Send an image as a sticker. */
639
+ async sendSticker(threadId, source) {
640
+ return this._sendContent(threadId, await toMedia(source, this._config.maxMediaBytes), {
641
+ sendMediaAsSticker: true
642
+ });
643
+ }
644
+ /** Forward an existing message into another thread. */
645
+ async forwardMessage(messageId, targetThreadId) {
646
+ const { chatId } = this.decodeThreadId(targetThreadId);
647
+ await (await this._requireMessage(messageId)).forward(chatId);
648
+ }
649
+ /** Pin a message for the given number of seconds. */
650
+ async pinMessage(messageId, seconds) {
651
+ return (await this._requireMessage(messageId)).pin(seconds);
652
+ }
653
+ /** Unpin a message. */
654
+ async unpinMessage(messageId) {
655
+ return (await this._requireMessage(messageId)).unpin();
656
+ }
657
+ /** Star a message. */
658
+ async starMessage(messageId) {
659
+ await (await this._requireMessage(messageId)).star();
660
+ }
661
+ /** Unstar a message. */
662
+ async unstarMessage(messageId) {
663
+ await (await this._requireMessage(messageId)).unstar();
664
+ }
665
+ /** Every pinned message in a thread. */
666
+ async fetchPinnedMessages(threadId) {
667
+ const { chatId } = this.decodeThreadId(threadId);
668
+ const pinned = await this.client.getPinnedMessages(chatId);
669
+ return pinned.map((message) => this.parseMessage(message));
670
+ }
671
+ /** Search messages across every chat, or within one thread. */
672
+ async searchMessages(query, options) {
673
+ const found = await this.client.searchMessages(query, {
674
+ chatId: options?.threadId ? this.decodeThreadId(options.threadId).chatId : void 0,
675
+ limit: options?.limit,
676
+ page: options?.page
677
+ });
678
+ return found.map((message) => this.parseMessage(message));
679
+ }
680
+ /** Participants of a group thread, with their admin status. */
681
+ async fetchGroupParticipants(threadId) {
682
+ const chat = await this._requireChat(threadId);
683
+ if (!isGroupChat(chat)) {
684
+ throw new ValidationError2("wwebjs", "fetchGroupParticipants: thread is not a group.");
685
+ }
686
+ return chat.participants.map((participant) => ({
687
+ isAdmin: participant.isAdmin || participant.isSuperAdmin,
688
+ isSuperAdmin: participant.isSuperAdmin,
689
+ userId: participant.id._serialized
690
+ }));
691
+ }
692
+ /** The profile picture of a contact or group, when privacy settings allow it. */
693
+ async getProfilePicUrl(userId) {
694
+ return this.client.getProfilePicUrl(toChatId(userId)).catch(() => void 0);
695
+ }
696
+ /** Show the bot as online or offline. */
697
+ async setPresence(presence) {
698
+ await (presence === "available" ? this.client.sendPresenceAvailable() : this.client.sendPresenceUnavailable());
699
+ }
700
+ /** Mark a thread unread. */
701
+ async markAsUnread(threadId) {
702
+ await (await this._requireChat(threadId)).markUnread();
703
+ }
704
+ /** Mute a thread until the given date, or forever when omitted. */
705
+ async muteThread(threadId, until) {
706
+ await (await this._requireChat(threadId)).mute(until);
707
+ }
708
+ /** Unmute a thread. */
709
+ async unmuteThread(threadId) {
710
+ await (await this._requireChat(threadId)).unmute();
711
+ }
712
+ /** Archive a thread. */
713
+ async archiveThread(threadId) {
714
+ await (await this._requireChat(threadId)).archive();
715
+ }
716
+ /** Move a thread out of the archive. */
717
+ async unarchiveThread(threadId) {
718
+ await (await this._requireChat(threadId)).unarchive();
719
+ }
720
+ /** Pin a thread to the top of the chat list. */
721
+ async pinThread(threadId) {
722
+ return (await this._requireChat(threadId)).pin();
723
+ }
724
+ /** Unpin a thread. */
725
+ async unpinThread(threadId) {
726
+ return (await this._requireChat(threadId)).unpin();
727
+ }
728
+ onPollVote(first, second) {
729
+ if (typeof first === "function") {
730
+ this._pollVoteHandlers.push({ handler: first });
731
+ return;
732
+ }
733
+ if (!second) {
734
+ throw new ValidationError2(
735
+ "wwebjs",
736
+ "onPollVote: a handler is required when filtering by poll message ID."
737
+ );
738
+ }
739
+ this._pollVoteHandlers.push({
740
+ filter: new Set(Array.isArray(first) ? first : [first]),
741
+ handler: second
742
+ });
743
+ }
744
+ /** Subscribe to incoming calls. Use `call.reject()` to decline. */
745
+ onCall(handler) {
746
+ this._callHandlers.push(handler);
747
+ }
748
+ /** Subscribe to delivery-state changes for messages this account sent. */
749
+ onAck(handler) {
750
+ this._ackHandlers.push(handler);
751
+ }
752
+ /** Subscribe to group membership and metadata changes. */
753
+ onGroupEvent(handler) {
754
+ this._groupHandlers.push(handler);
755
+ }
756
+ _clientOptions() {
757
+ const options = { ...this._config.clientOptions };
758
+ const puppeteer = options.puppeteer ?? {};
759
+ options.puppeteer = {
760
+ // Puppeteer's handlers close the browser on a signal and keep the process alive; closeOnSignal does both.
761
+ ...this._config.handleSignals === false ? {} : { handleSIGHUP: false, handleSIGINT: false, handleSIGTERM: false },
762
+ ...puppeteer,
763
+ args: [
764
+ ...this._config.recommendedArgs === false ? [] : RECOMMENDED_CHROMIUM_ARGS,
765
+ ...puppeteer.args ?? []
766
+ ]
767
+ };
768
+ if (this._config.phoneNumber) {
769
+ options.pairWithPhoneNumber = {
770
+ phoneNumber: this._config.phoneNumber,
771
+ ...options.pairWithPhoneNumber
772
+ };
773
+ }
774
+ return options;
775
+ }
776
+ async _connect() {
777
+ const timeoutMs = this._config.connectTimeoutMs ?? CONNECT_TIMEOUT_MS;
778
+ let timer;
779
+ const timedOut = new Promise((_resolve, reject) => {
780
+ timer = setTimeout(
781
+ () => reject(new ValidationError2("wwebjs", `WhatsApp was not ready within ${timeoutMs}ms.`)),
782
+ timeoutMs
783
+ );
784
+ timer.unref?.();
785
+ });
786
+ const waiting = () => clearTimeout(timer);
787
+ this.client.once("qr", waiting);
788
+ this.client.once("code", waiting);
789
+ try {
790
+ await Promise.race([this._open(), timedOut]);
791
+ } catch (error) {
792
+ await this.client.destroy().catch(() => void 0);
793
+ throw error;
794
+ } finally {
795
+ clearTimeout(timer);
796
+ this.client.off("qr", waiting);
797
+ this.client.off("code", waiting);
798
+ }
799
+ }
800
+ async _open() {
801
+ this._state = this._initialized ? "reconnecting" : "connecting";
802
+ const ready = new Promise((resolve, reject) => {
803
+ const onReady = () => settle(resolve);
804
+ const onFailure = (message) => settle(
805
+ () => reject(new ValidationError2("wwebjs", `WhatsApp authentication failed: ${message}`))
806
+ );
807
+ const settle = (finish) => {
808
+ this.client.off("ready", onReady);
809
+ this.client.off("auth_failure", onFailure);
810
+ finish();
811
+ };
812
+ this.client.on("ready", onReady);
813
+ this.client.on("auth_failure", onFailure);
814
+ });
815
+ if (this._initialized) await this.client.destroy().catch(() => void 0);
816
+ this._initialized = true;
817
+ await this.client.initialize();
818
+ if (this._closed) {
819
+ await this.client.destroy();
820
+ return;
821
+ }
822
+ this.client.pupBrowser?.once("disconnected", () => this._onDisconnected("BROWSER_CLOSED"));
823
+ await ready;
824
+ }
825
+ _listen() {
826
+ const { onPairingCode, onQR } = this._config;
827
+ if (onQR) this.client.on("qr", (qr) => void onQR(qr));
828
+ if (onPairingCode) this.client.on("code", (code) => void onPairingCode(code));
829
+ this.client.on("ready", () => {
830
+ this._state = "connected";
831
+ this._strikes = 0;
832
+ if (!this._config.userName && this.client.info?.pushname) {
833
+ this.userName = this.client.info.pushname;
834
+ }
835
+ this._logger.info("WhatsApp session ready", { userId: this.botUserId });
836
+ void this._learnLid();
837
+ this._guard("catch-up", this._catchUp());
838
+ });
839
+ this.client.on("disconnected", (reason) => this._onDisconnected(String(reason)));
840
+ this.client.on("message_create", (message) => this._guard("message", this._onMessage(message)));
841
+ this.client.on(
842
+ "message_edit",
843
+ (message, _new, previous) => this._onEdit(message, String(previous))
844
+ );
845
+ this.client.on(
846
+ "message_revoke_everyone",
847
+ (message, revoked) => this._onRevoke(message, revoked)
848
+ );
849
+ this.client.on("message_reaction", (reaction) => this._onReaction(reaction));
850
+ this.client.on("message_ack", (message, ack) => this._onAck(message, ack));
851
+ this.client.on("vote_update", (vote) => this._guard("poll vote", this._onVote(vote)));
852
+ this.client.on("call", (call) => void this._dispatch(this._callHandlers, call, "onCall"));
853
+ for (const [event, type] of Object.entries(GROUP_EVENTS)) {
854
+ this.client.on(event, (notification) => this._onGroup(type, notification));
855
+ }
856
+ }
857
+ async _onMessage(raw) {
858
+ if (!this._chat || this._isOwn(raw.fromMe)) return;
859
+ const chatId = chatIdOf(raw);
860
+ if (raw.isStatus || isBroadcastId(chatId) || SYSTEM_TYPES.has(raw.type)) return;
861
+ const threadId = this.encodeThreadId({ chatId });
862
+ if (this._config.markSeen && !raw.fromMe) {
863
+ await this.markAsRead(threadId).catch(
864
+ (error) => this._logger.warn("Failed to send a read receipt", { error, threadId })
865
+ );
866
+ }
867
+ const parsed = this._addons("onMessage").length > 0 ? await this._parse(raw) : void 0;
868
+ if (!parsed || !await this._claimed(parsed, threadId)) {
869
+ await this._chat.processMessage(this, threadId, parsed ?? (() => this._parse(raw)));
870
+ }
871
+ await this._remember(raw);
872
+ }
873
+ async _claimed(message, threadId) {
874
+ for (const addon of this._addons("onMessage")) {
875
+ if (await addon.onMessage(message, this._context(threadId))) return true;
876
+ }
877
+ return false;
878
+ }
879
+ _addons(hook) {
880
+ return (this._config.addons ?? []).filter((addon) => addon[hook]);
881
+ }
882
+ _context(threadId) {
883
+ return { adapter: this, chat: this._chat, threadId };
884
+ }
885
+ _seenKey() {
886
+ return `wwebjs:${this.name}:seen`;
887
+ }
888
+ /** Writes run in turn, so an older position never lands after a newer one. */
889
+ _save() {
890
+ const state = this._chat?.getState();
891
+ if (!state) return Promise.resolve();
892
+ this._saving = this._saving.then(() => state.set(this._seenKey(), this._seen)).catch(
893
+ (error) => this._logger.warn("Could not record the last message delivered", { error })
894
+ );
895
+ return this._saving;
896
+ }
897
+ async _remember(raw) {
898
+ if (this._config.catchUpMs === false || !this._seen) return;
899
+ const id = serialize(raw.id);
900
+ const { at, ids } = this._seen;
901
+ if (raw.timestamp < at || raw.timestamp === at && ids.includes(id)) return;
902
+ this._seen = { at: raw.timestamp, ids: raw.timestamp === at ? [...ids, id] : [id] };
903
+ await this._save();
904
+ }
905
+ /** WhatsApp Web loads what arrived while the session was down without announcing every message. */
906
+ async _catchUp() {
907
+ const windowMs = this._config.catchUpMs ?? CATCH_UP_MS;
908
+ const state = this._chat?.getState();
909
+ if (windowMs === false || !state) return;
910
+ this._seen ??= await state.get(this._seenKey());
911
+ const seen = this._seen;
912
+ if (!seen) {
913
+ this._seen = { at: Math.floor(Date.now() / 1e3), ids: [] };
914
+ await this._save();
915
+ return;
916
+ }
917
+ const oldest = Math.max(seen.at, Math.floor((Date.now() - windowMs) / 1e3));
918
+ const unseen = (message) => message.timestamp > oldest || message.timestamp === seen.at && !seen.ids.includes(serialize(message.id));
919
+ const chats = (await this.client.getChats()).filter((chat) => chat.timestamp >= oldest).slice(0, MAX_CATCH_UP_CHATS);
920
+ for (const chat of chats) {
921
+ const missed = (await chat.fetchMessages({ limit: MAX_CATCH_UP_MESSAGES })).filter(unseen);
922
+ for (const message of missed) await this._onMessage(message);
923
+ }
924
+ }
925
+ _onEdit(raw, previousBody) {
926
+ if (this._isOwn(raw.fromMe)) return;
927
+ this._chat?.processMessageUpdated({
928
+ adapter: this,
929
+ message: () => this._parse(raw),
930
+ previousMessage: async () => {
931
+ const previous = this.parseMessage(raw);
932
+ previous.text = previousBody;
933
+ previous.formatted = this._converter.toAst(previousBody);
934
+ return previous;
935
+ },
936
+ threadId: this.encodeThreadId({ chatId: chatIdOf(raw) })
937
+ });
938
+ }
939
+ _onRevoke(raw, revoked) {
940
+ if (this._isOwn(raw.fromMe)) return;
941
+ const threadId = this.encodeThreadId({ chatId: chatIdOf(raw) });
942
+ this._chat?.processMessageDeleted({
943
+ adapter: this,
944
+ channelId: threadId,
945
+ deletedAt: new Date(raw.timestamp * 1e3),
946
+ messageId: serialize(revoked?.id) || serialize(raw.protocolMessageKey) || raw.id._serialized,
947
+ previousMessage: revoked ? this.parseMessage(revoked) : void 0,
948
+ raw,
949
+ threadId
950
+ });
951
+ }
952
+ _onReaction(reaction) {
953
+ if (this._isOwn(reaction.id.fromMe)) return;
954
+ this._chat?.processReaction({
955
+ adapter: this,
956
+ added: reaction.reaction.length > 0,
957
+ emoji: defaultEmojiResolver.fromGChat(reaction.reaction),
958
+ messageId: serialize(reaction.msgId),
959
+ raw: reaction,
960
+ rawEmoji: reaction.reaction,
961
+ threadId: this.encodeThreadId({ chatId: serialize(reaction.id.remote) }),
962
+ user: participantAuthor(serialize(reaction.senderId), reaction.id.fromMe)
963
+ });
964
+ }
965
+ _onAck(raw, ack) {
966
+ void this._dispatch(
967
+ this._ackHandlers,
968
+ {
969
+ messageId: raw.id._serialized,
970
+ raw,
971
+ status: ACK_STATUSES[ack] ?? "pending",
972
+ threadId: this.encodeThreadId({ chatId: chatIdOf(raw) })
973
+ },
974
+ "onAck"
975
+ );
976
+ }
977
+ _onGroup(type, notification) {
978
+ const threadId = this.encodeThreadId({ chatId: notification.chatId });
979
+ void this._dispatch(
980
+ this._groupHandlers,
981
+ {
982
+ authorId: notification.author,
983
+ raw: notification,
984
+ threadId,
985
+ type,
986
+ userIds: notification.recipientIds.map(serialize)
987
+ },
988
+ "onGroupEvent"
989
+ );
990
+ if (type !== "join" || !this._chat) return;
991
+ for (const userId of notification.recipientIds.map(serialize)) {
992
+ this._chat.processMemberJoinedChannel({
993
+ adapter: this,
994
+ channelId: threadId,
995
+ inviterId: notification.author,
996
+ userId
997
+ });
998
+ }
999
+ }
1000
+ async _onVote(vote) {
1001
+ const parent = vote.parentMessage;
1002
+ if (!parent?.id || !parent.fromMe) return;
1003
+ const pollMessageId = parent.id._serialized;
1004
+ const payload = {
1005
+ options: parent.pollOptions ?? [],
1006
+ pollMessageId,
1007
+ question: parent.pollName,
1008
+ raw: vote,
1009
+ selectedOptions: vote.selectedOptions.map((option) => option.name),
1010
+ threadId: this.encodeThreadId({ chatId: chatIdOf(parent) }),
1011
+ voter: participantAuthor(serialize(vote.voter), false)
1012
+ };
1013
+ await this._dispatch(
1014
+ this._pollVoteHandlers.filter(({ filter }) => !filter || filter.has(pollMessageId)).map(({ handler }) => handler),
1015
+ payload,
1016
+ "onPollVote"
1017
+ );
1018
+ }
1019
+ async _dispatch(handlers, value, label) {
1020
+ for (const handler of handlers) {
1021
+ try {
1022
+ await handler(value);
1023
+ } catch (error) {
1024
+ this._logger.error(`${label} handler threw`, error);
1025
+ }
1026
+ }
1027
+ }
1028
+ async _parse(raw) {
1029
+ const parsed = this.parseMessage(raw);
1030
+ const bot = this._botUsers();
1031
+ const others = [
1032
+ ...new Set((raw.mentionedIds ?? []).map(serialize).filter((id) => !bot.has(toUser(id))))
1033
+ ].slice(0, MAX_MENTION_LOOKUPS);
1034
+ if (others.length > 0) {
1035
+ const names = /* @__PURE__ */ new Map();
1036
+ for (const id of others) {
1037
+ const contact = await within(this.client.getContactById(id));
1038
+ const name = contact?.pushname || contact?.name;
1039
+ if (name) names.set(toUser(id), name);
1040
+ }
1041
+ parsed.text = this._named(parsed.text, [...names.keys()], (user) => names.get(user));
1042
+ parsed.formatted = this._converter.toAst(parsed.text);
1043
+ }
1044
+ if (raw.hasQuotedMsg) {
1045
+ const quoted = await within(raw.getQuotedMessage());
1046
+ if (quoted) parsed.replyTo = this.parseMessage(quoted);
1047
+ if (quoted?.fromMe) parsed.isMention = true;
1048
+ }
1049
+ return parsed;
1050
+ }
1051
+ _author(raw) {
1052
+ const chatId = chatIdOf(raw);
1053
+ const userId = raw.fromMe ? this.botUserId ?? chatId : isGroupId(chatId) ? raw.author ?? chatId : chatId;
1054
+ const pushName = raw.rawData?.notifyName;
1055
+ return {
1056
+ fullName: pushName ?? "",
1057
+ isBot: raw.fromMe,
1058
+ isMe: raw.fromMe,
1059
+ userId,
1060
+ userName: pushName || toUser(userId)
1061
+ };
1062
+ }
1063
+ async _indicator(threadId, label, send) {
1064
+ try {
1065
+ await send(await this._requireChat(threadId));
1066
+ } catch (error) {
1067
+ this._logger.warn(`${label} failed`, { error, threadId });
1068
+ }
1069
+ }
1070
+ /** Groups address the bot by its LID or its phone number, whichever they know it by. */
1071
+ _mentionsBot(raw) {
1072
+ const bot = this._botUsers();
1073
+ return this._mentioned(raw).some((user) => bot.has(user));
1074
+ }
1075
+ _botUsers() {
1076
+ return new Set([this.botUserId, this._botLid].filter(Boolean).map((id) => toUser(id)));
1077
+ }
1078
+ _mentioned(raw) {
1079
+ return (raw.mentionedIds ?? []).map((id) => toUser(serialize(id)));
1080
+ }
1081
+ /** WhatsApp writes a mention as `@` and the number or LID; readers expect the name. */
1082
+ _named(text, users, name) {
1083
+ return text.replace(
1084
+ /@(\d+)(?!\d)/g,
1085
+ (mention, user) => users.includes(user) ? `@${name(user)}` : mention
1086
+ );
1087
+ }
1088
+ async _learnLid() {
1089
+ const botUserId = this.botUserId;
1090
+ if (!botUserId) return;
1091
+ try {
1092
+ const [ids] = await this.client.getContactLidAndPhone([botUserId]);
1093
+ this._botLid = ids?.lid;
1094
+ } catch (error) {
1095
+ this._logger.warn("Could not learn the bot's LID; mentions by LID will be missed", { error });
1096
+ }
1097
+ }
1098
+ /** Listeners run unawaited, so a rejection here would end the process. */
1099
+ _guard(label, work) {
1100
+ work.catch(
1101
+ (error) => this._logger.warn(`Inbound ${label} was not handled`, { error })
1102
+ );
1103
+ }
1104
+ _isOwn(fromMe) {
1105
+ return fromMe && !this._config.receiveOwnMessages;
1106
+ }
1107
+ _onDisconnected(reason) {
1108
+ if (this._closed) return;
1109
+ this._connection = null;
1110
+ this._state = this._config.reconnect === false ? "disconnected" : "reconnecting";
1111
+ if (reason === "LOGOUT") {
1112
+ this._state = "logged_out";
1113
+ this._logger.error("WhatsApp logged this session out; pair it again to reconnect", {
1114
+ reason
1115
+ });
1116
+ return;
1117
+ }
1118
+ this._logger.warn("WhatsApp disconnected", { reason });
1119
+ this._reconnect(RECONNECT_MIN_MS);
1120
+ }
1121
+ _reconnect(delayMs) {
1122
+ if (this._closed || this._config.reconnect === false) return;
1123
+ clearTimeout(this._retry);
1124
+ this._state = "reconnecting";
1125
+ this._retry = setTimeout(() => {
1126
+ this._retry = void 0;
1127
+ this.connect().catch((error) => {
1128
+ this._logger.warn("Reconnecting to WhatsApp failed", { error, delayMs });
1129
+ this._reconnect(Math.min(delayMs * 2, RECONNECT_MAX_MS));
1130
+ });
1131
+ }, delayMs);
1132
+ this._retry.unref?.();
1133
+ }
1134
+ _watch() {
1135
+ const everyMs = this._config.watchdogIntervalMs ?? WATCHDOG_INTERVAL_MS;
1136
+ if (this._watchdog || everyMs === false) return;
1137
+ this._watchdog = setInterval(() => this._guard("watchdog check", this._check()), everyMs);
1138
+ this._watchdog.unref?.();
1139
+ }
1140
+ /** Revives a session that died without an event, or a first connection that failed. */
1141
+ async _check() {
1142
+ if (this._closed) return;
1143
+ if (this._state === "disconnected" && !this._retry) {
1144
+ this._reconnect(RECONNECT_MIN_MS);
1145
+ return;
1146
+ }
1147
+ if (this._state !== "connected") return;
1148
+ const state = await within(this.client.getState());
1149
+ if (state === "CONNECTED") {
1150
+ this._strikes = 0;
1151
+ return;
1152
+ }
1153
+ if (++this._strikes < 2) return;
1154
+ this._strikes = 0;
1155
+ this._onDisconnected(`UNRESPONSIVE (${state ?? "no answer"})`);
1156
+ }
1157
+ _render(message, threadId) {
1158
+ const card = extractCard(message);
1159
+ if (!card) return { text: this._converter.renderPostable(message) };
1160
+ for (const addon of this._addons("renderCard")) {
1161
+ const text = addon.renderCard(card, this._context(threadId));
1162
+ if (text !== void 0) return { card, text };
1163
+ }
1164
+ return { card, text: cardToFallbackText(card, { boldFormat: "*" }) };
1165
+ }
1166
+ /** The card is already on WhatsApp, so an addon failing here must not fail the send. */
1167
+ async _cardSent(card, messageId, threadId) {
1168
+ if (!card) return;
1169
+ for (const addon of this._addons("cardSent")) {
1170
+ try {
1171
+ await addon.cardSent(card, messageId, this._context(threadId));
1172
+ } catch (error) {
1173
+ this._logger.warn("An addon failed after a card was sent", { error, threadId });
1174
+ }
1175
+ }
1176
+ }
1177
+ async _send(threadId, message, options = {}) {
1178
+ const { chatId } = this.decodeThreadId(threadId);
1179
+ const { card, text: rendered } = this._render(message, threadId);
1180
+ const { mentions, text } = extractMentions(rendered);
1181
+ const media = await toMediaList(message, this._config.maxMediaBytes);
1182
+ const send = {
1183
+ ...options,
1184
+ ...mentions.length > 0 ? { mentions } : {}
1185
+ };
1186
+ const voice = this._config.voiceNotes !== false;
1187
+ const captionIndex = text ? media.findIndex(isCaptionable) : -1;
1188
+ const payloads = [];
1189
+ if (media.length === 0 || text && captionIndex === -1) payloads.push([text, send]);
1190
+ media.forEach((item, index) => {
1191
+ const itemOptions = index === captionIndex ? { ...send, caption: text } : send;
1192
+ payloads.push([
1193
+ item,
1194
+ voice && isAudio(item) ? { ...itemOptions, sendAudioAsVoice: true } : itemOptions
1195
+ ]);
1196
+ });
1197
+ let first;
1198
+ for (const [content, sendOptions] of payloads) {
1199
+ const sent = await this.client.sendMessage(
1200
+ chatId,
1201
+ content,
1202
+ first ? { ...sendOptions, quotedMessageId: void 0 } : sendOptions
1203
+ );
1204
+ first ??= sent;
1205
+ }
1206
+ const raw = this._raw(first, threadId);
1207
+ await this._cardSent(card, raw.id, threadId);
1208
+ return raw;
1209
+ }
1210
+ async _sendContent(threadId, content, options) {
1211
+ const { chatId } = this.decodeThreadId(threadId);
1212
+ return this._raw(await this.client.sendMessage(chatId, content, options), threadId);
1213
+ }
1214
+ _raw(sent, threadId) {
1215
+ if (!sent) {
1216
+ throw new ValidationError2(
1217
+ "wwebjs",
1218
+ "WhatsApp did not return the sent message. whatsapp-web.js 1.34.7 and older cannot read current WhatsApp Web; install github:pedroslopez/whatsapp-web.js#064a3d5."
1219
+ );
1220
+ }
1221
+ return { id: sent.id._serialized, raw: sent, threadId };
1222
+ }
1223
+ async _page(chat, options) {
1224
+ const limit = Math.min(MAX_HISTORY, Math.max(1, options?.limit ?? DEFAULT_LIMIT));
1225
+ const [count, before] = (options?.cursor ?? "").split("|");
1226
+ const offset = Math.min(MAX_HISTORY, Math.max(0, Number(count) || 0));
1227
+ const forward = options?.direction === "forward";
1228
+ const anchorIn = (messages) => before ? messages.findIndex((message) => serialize(message.id) === before) : -1;
1229
+ let size = forward ? MAX_HISTORY : Math.min(MAX_HISTORY, offset + limit);
1230
+ let window = await chat.fetchMessages({ limit: size });
1231
+ let anchor = anchorIn(window);
1232
+ while (before && !forward && anchor < limit && window.length === size && size < MAX_HISTORY) {
1233
+ size = Math.min(MAX_HISTORY, size + limit);
1234
+ window = await chat.fetchMessages({ limit: size });
1235
+ anchor = anchorIn(window);
1236
+ }
1237
+ const end = forward ? Math.min(window.length, offset + limit) : anchor >= 0 ? anchor : window.length - offset;
1238
+ const start = forward ? offset : Math.max(0, end - limit);
1239
+ const page = end > start ? window.slice(start, end) : [];
1240
+ const exhausted = forward ? end >= window.length : start === 0 && window.length < size;
1241
+ return {
1242
+ messages: page.map((message) => this.parseMessage(message)),
1243
+ nextCursor: exhausted || page.length === 0 ? void 0 : forward ? String(end) : `${window.length - start}|${serialize(page[0].id)}`
1244
+ };
1245
+ }
1246
+ async _findChat(chatId) {
1247
+ return this.client.getChatById(chatId).catch(() => null);
1248
+ }
1249
+ async _requireChat(threadId) {
1250
+ const { chatId } = this.decodeThreadId(threadId);
1251
+ const chat = await this._findChat(chatId);
1252
+ if (!chat) {
1253
+ throw new ResourceNotFoundError("wwebjs", "chat", chatId);
1254
+ }
1255
+ return chat;
1256
+ }
1257
+ async _requireMessage(messageId) {
1258
+ const message = await this.client.getMessageById(messageId).catch(() => null);
1259
+ if (!message) {
1260
+ throw new ResourceNotFoundError("wwebjs", "message", messageId);
1261
+ }
1262
+ return message;
1263
+ }
1264
+ };
1265
+ function createWWebJSAdapter(config = {}) {
1266
+ return new WWebJSAdapter(config);
1267
+ }
1268
+ function chatIdOf(message) {
1269
+ return message.id?.remote || (message.fromMe ? message.to : message.from);
1270
+ }
1271
+ function within(lookup) {
1272
+ return Promise.race([
1273
+ lookup.catch(() => null),
1274
+ new Promise((resolve) => setTimeout(resolve, LOOKUP_TIMEOUT_MS, null).unref?.())
1275
+ ]);
1276
+ }
1277
+ function isGroupChat(chat) {
1278
+ return chat?.isGroup === true;
1279
+ }
1280
+ function participantAuthor(userId, isMe) {
1281
+ return { fullName: "", isBot: isMe, isMe, userId, userName: toUser(userId) };
1282
+ }
1283
+ function assertRange(label, value, bound) {
1284
+ if (!Number.isFinite(value) || value < -bound || value > bound) {
1285
+ throw new ValidationError2(
1286
+ "wwebjs",
1287
+ `sendLocation: ${label} must be between -${bound} and ${bound}. Received ${value}.`
1288
+ );
1289
+ }
1290
+ }
1291
+
1292
+ // src/guards.ts
1293
+ import { ValidationError as ValidationError3 } from "@chat-adapter/shared";
1294
+ function isWWebJSAdapter(value) {
1295
+ return value instanceof WWebJSAdapter;
1296
+ }
1297
+ function requireWWebJSAdapter(value) {
1298
+ const adapter = value && typeof value === "object" && "adapter" in value ? value.adapter : value;
1299
+ if (isWWebJSAdapter(adapter)) return adapter;
1300
+ throw new ValidationError3("wwebjs", "This context does not belong to a wwebjs adapter.");
1301
+ }
1302
+
1303
+ // src/numbered-actions.ts
1304
+ import { cardToFallbackText as cardToFallbackText2 } from "@chat-adapter/shared";
1305
+ var TTL_MS = 864e5;
1306
+ function actionsOf(children) {
1307
+ return children.flatMap(
1308
+ (child) => child.type === "actions" ? [child] : child.type === "section" ? actionsOf(child.children) : []
1309
+ );
1310
+ }
1311
+ function layout(card) {
1312
+ const choices = [];
1313
+ const lines = [];
1314
+ const offer = (choice) => {
1315
+ choices.push(choice);
1316
+ lines.push(`${choices.length}. ${choice.label}`);
1317
+ };
1318
+ for (const { children } of actionsOf(card.children)) {
1319
+ for (const action of children) {
1320
+ if (action.type === "link-button") lines.push(`${action.label}: ${action.url}`);
1321
+ else if (action.type === "button") {
1322
+ if (!action.disabled && action.actionType !== "modal") {
1323
+ offer({ actionId: action.id, label: action.label, value: action.value });
1324
+ }
1325
+ } else {
1326
+ lines.push(`*${action.label}*`);
1327
+ for (const option of action.options) {
1328
+ offer({ actionId: action.id, label: option.label, value: option.value });
1329
+ }
1330
+ }
1331
+ }
1332
+ }
1333
+ return { choices, lines };
1334
+ }
1335
+ function keyOf({ adapter, threadId }) {
1336
+ return `wwebjs:${adapter.name}:offer:${threadId}`;
1337
+ }
1338
+ function numberedActions(options = {}) {
1339
+ return {
1340
+ renderCard(card) {
1341
+ const { lines } = layout(card);
1342
+ if (lines.length === 0) return void 0;
1343
+ return [cardToFallbackText2(card, { boldFormat: "*" }), lines.join("\n")].filter(Boolean).join("\n\n");
1344
+ },
1345
+ async cardSent(card, messageId, context) {
1346
+ const { choices } = layout(card);
1347
+ if (choices.length === 0 || !context.chat) return;
1348
+ await context.chat.getState().set(keyOf(context), { choices, messageId }, options.ttlMs ?? TTL_MS);
1349
+ },
1350
+ async onMessage(message, context) {
1351
+ const offer = await context.chat?.getState().get(keyOf(context));
1352
+ if (!offer || !context.chat) return false;
1353
+ const reply = message.text.trim();
1354
+ const choice = /^\d+$/.test(reply) ? offer.choices[Number(reply) - 1] : offer.choices.find(({ label }) => label.toLowerCase() === reply.toLowerCase());
1355
+ if (!choice) return false;
1356
+ await context.chat.processAction(
1357
+ {
1358
+ actionId: choice.actionId,
1359
+ adapter: context.adapter,
1360
+ messageId: offer.messageId,
1361
+ raw: message.raw,
1362
+ threadId: context.threadId,
1363
+ user: message.author,
1364
+ value: choice.value
1365
+ },
1366
+ void 0
1367
+ );
1368
+ return !options.keepMessage;
1369
+ }
1370
+ };
1371
+ }
1372
+ export {
1373
+ RECOMMENDED_CHROMIUM_ARGS,
1374
+ WWebJSAdapter,
1375
+ WWebJSFormatConverter,
1376
+ createWWebJSAdapter,
1377
+ download,
1378
+ extractMentions,
1379
+ isAudio,
1380
+ isCaptionable,
1381
+ isGroupId,
1382
+ isNewsletterId,
1383
+ isUserId,
1384
+ isWWebJSAdapter,
1385
+ numberedActions,
1386
+ requireWWebJSAdapter,
1387
+ toAttachments,
1388
+ toChatId,
1389
+ toMedia,
1390
+ toMediaList,
1391
+ toUser
1392
+ };