@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,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,223 @@
|
|
|
1
|
+
import type { InboundContent, NormalizedEvent, ReceiptStatus, SentElsewhereEvent, 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`) are NOT inbound: `normalizeUpsert`
|
|
15
|
+
* drops them, and `normalizeSentElsewhere` reads them as a separate event (the
|
|
16
|
+
* session drops the echo of its own sends before it hands them on);
|
|
17
|
+
* - history sync (`messages.upsert` of type `append`, `messaging-history.set`):
|
|
18
|
+
* only live messages reach the inbox; on-demand history never leaves the session;
|
|
19
|
+
* - protocol messages (a deletion, an edit, a key distribution).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
type Json = Record<string, unknown>;
|
|
23
|
+
const isObject = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24
|
+
const text = (value: unknown): string | null => (typeof value === "string" && value.length > 0 ? value : null);
|
|
25
|
+
|
|
26
|
+
const PN_SUFFIX = "@s.whatsapp.net";
|
|
27
|
+
const LID_SUFFIX = "@lid";
|
|
28
|
+
|
|
29
|
+
/** A JID's user part, without the device (`5511…:12@s.whatsapp.net` → `5511…`). */
|
|
30
|
+
export function jidUser(jid: string): string {
|
|
31
|
+
const user = jid.slice(0, jid.indexOf("@") >= 0 ? jid.indexOf("@") : jid.length);
|
|
32
|
+
const colon = user.indexOf(":");
|
|
33
|
+
return colon >= 0 ? user.slice(0, colon) : user;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The contact's address, as the engine stores it. A phone-number JID becomes
|
|
38
|
+
* its digits (`5511987654321`), the same address the Cloud API's `wa_id` is.
|
|
39
|
+
* A contact WhatsApp only names by a LID keeps the whole LID JID
|
|
40
|
+
* (`123456@lid`): the send path routes it back as is. Null for anything that
|
|
41
|
+
* is not one person.
|
|
42
|
+
*/
|
|
43
|
+
export function contactAddress(key: BaileysMessageKey): string | null {
|
|
44
|
+
const candidates = [key.remoteJid, key.remoteJidAlt].filter((jid): jid is string => typeof jid === "string");
|
|
45
|
+
const pn = candidates.find((jid) => jid.endsWith(PN_SUFFIX));
|
|
46
|
+
if (pn) return jidUser(pn) || null;
|
|
47
|
+
const lid = candidates.find((jid) => jid.endsWith(LID_SUFFIX));
|
|
48
|
+
return lid ? `${jidUser(lid)}${LID_SUFFIX}` : null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The JID a send goes to, for an address `contactAddress` produced (or plain digits). */
|
|
52
|
+
export function addressJid(address: string): string {
|
|
53
|
+
if (address.includes("@")) return address;
|
|
54
|
+
const digits = address.replace(/\D/g, "");
|
|
55
|
+
return `${digits}${PN_SUFFIX}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The address a contact's reply to a send will carry, keyed as {@link contactAddress} keys an inbound message:
|
|
60
|
+
* `+55 11 98765-4321`, `5511987654321` and `5511987654321:12@s.whatsapp.net` are all `5511987654321`, and a LID
|
|
61
|
+
* the socket reports beside its phone-number JID (`sentKey.remoteJidAlt`) is that number. Null when it is not one person.
|
|
62
|
+
*/
|
|
63
|
+
export function replyAddress(to: string, sentKey?: BaileysMessageKey | null): string | null {
|
|
64
|
+
return contactAddress({ remoteJid: addressJid(to), remoteJidAlt: sentKey?.remoteJidAlt ?? null });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A protobuf Long (a timestamp in seconds, a byte length) as a positive number, or null. */
|
|
68
|
+
export function longNumber(value: LongLike): number | null {
|
|
69
|
+
if (typeof value === "number") return Number.isFinite(value) && value > 0 ? value : null;
|
|
70
|
+
if (typeof value === "string") return longNumber(Number(value));
|
|
71
|
+
if (isObject(value) && typeof value.low === "number" && typeof value.high === "number") {
|
|
72
|
+
return longNumber(value.high * 2 ** 32 + (value.low >>> 0));
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Wrappers whose inner `message` is the real content. */
|
|
78
|
+
const WRAPPERS = ["ephemeralMessage", "viewOnceMessage", "viewOnceMessageV2", "viewOnceMessageV2Extension", "documentWithCaptionMessage", "editedMessage"];
|
|
79
|
+
/** Fields of a message that are never its content. */
|
|
80
|
+
const NOT_CONTENT = new Set(["messageContextInfo", "senderKeyDistributionMessage"]);
|
|
81
|
+
/** Content that is not a message a person reads: skipped whole. */
|
|
82
|
+
const SKIPPED = new Set(["protocolMessage", "reactionMessage", "pollUpdateMessage", "keepInChatMessage"]);
|
|
83
|
+
|
|
84
|
+
/** A message's real content, out of its ephemeral, view-once or edit wrappers. `{}` for anything else. */
|
|
85
|
+
export function unwrapMessage(message: unknown): Json {
|
|
86
|
+
if (!isObject(message)) return {};
|
|
87
|
+
for (const wrapper of WRAPPERS) {
|
|
88
|
+
const inner = message[wrapper];
|
|
89
|
+
if (isObject(inner) && isObject(inner.message)) return unwrapMessage(inner.message);
|
|
90
|
+
}
|
|
91
|
+
return message;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
type Reader = (body: unknown) => InboundContent | null;
|
|
95
|
+
|
|
96
|
+
const interactive = (replyId: unknown, title: unknown): InboundContent | null =>
|
|
97
|
+
text(replyId) ? { kind: "INTERACTIVE", replyId: replyId as string, title: text(title) ?? "" } : null;
|
|
98
|
+
|
|
99
|
+
/** How each content type a person reads is read. A type not listed is OTHER. */
|
|
100
|
+
const READERS: Readonly<Record<string, Reader>> = {
|
|
101
|
+
conversation: (body) => (text(body) ? { kind: "TEXT", text: body as string } : null),
|
|
102
|
+
extendedTextMessage: (body) => (isObject(body) && text(body.text) ? { kind: "TEXT", text: body.text as string } : null),
|
|
103
|
+
buttonsResponseMessage: (body) => (isObject(body) ? interactive(body.selectedButtonId, body.selectedDisplayText) : null),
|
|
104
|
+
templateButtonReplyMessage: (body) => (isObject(body) ? interactive(body.selectedId, body.selectedDisplayText) : null),
|
|
105
|
+
listResponseMessage: (body) =>
|
|
106
|
+
isObject(body) && isObject(body.singleSelectReply) ? interactive(body.singleSelectReply.selectedRowId, body.title) : null,
|
|
107
|
+
// The media id is filled with the message id by the caller.
|
|
108
|
+
audioMessage: (body) => (isObject(body) ? { kind: "AUDIO", mediaId: "", mimeType: text(body.mimetype) } : null),
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
/** The message's content, or null to skip it. */
|
|
112
|
+
export function contentOf(raw: unknown): InboundContent | null {
|
|
113
|
+
const message = unwrapMessage(raw);
|
|
114
|
+
const type = Object.keys(message).find((key) => !NOT_CONTENT.has(key) && message[key] !== null && message[key] !== undefined);
|
|
115
|
+
if (!type || SKIPPED.has(type)) return null;
|
|
116
|
+
const reader = READERS[type];
|
|
117
|
+
return reader ? reader(message[type]) : { kind: "OTHER", channelType: type.replace(/Message$/, "") || type };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface NormalizeOptions {
|
|
121
|
+
/** The whole-message words that opt a contact out. Default: the Cloud adapter's. */
|
|
122
|
+
optOutKeywords?: readonly string[];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** One message → its inbound event, or null when it is not one a contact sent to this account. */
|
|
126
|
+
function inboundEvent(accountId: string, message: BaileysMessage, keywords: readonly string[]): NormalizedEvent | null {
|
|
127
|
+
if (!isObject(message) || !isObject(message.key) || message.key.fromMe) return null;
|
|
128
|
+
const id = text(message.key.id);
|
|
129
|
+
const contactId = contactAddress(message.key);
|
|
130
|
+
const seconds = longNumber(message.messageTimestamp);
|
|
131
|
+
const content = contentOf(message.message);
|
|
132
|
+
if (!id || !contactId || seconds === null || !content) return null;
|
|
133
|
+
return {
|
|
134
|
+
type: "message",
|
|
135
|
+
accountId,
|
|
136
|
+
contactId,
|
|
137
|
+
contactName: text(message.pushName),
|
|
138
|
+
externalId: id,
|
|
139
|
+
sentAt: new Date(seconds * 1000),
|
|
140
|
+
// An audio's media id is the message's own id: the session keeps the message to download it.
|
|
141
|
+
content: content.kind === "AUDIO" ? { ...content, mediaId: id } : content,
|
|
142
|
+
optOut: content.kind === "TEXT" && isOptOutText(content.text, keywords),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** One live `messages.upsert` → inbound message events. `accountId` is the linked account's digits. */
|
|
147
|
+
export function normalizeUpsert(
|
|
148
|
+
accountId: string,
|
|
149
|
+
upsert: { messages: readonly BaileysMessage[]; type: string },
|
|
150
|
+
options: NormalizeOptions = {},
|
|
151
|
+
): NormalizedEvent[] {
|
|
152
|
+
if (upsert.type !== "notify") return [];
|
|
153
|
+
const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;
|
|
154
|
+
return upsert.messages.map((message) => inboundEvent(accountId, message, keywords)).filter((event): event is NormalizedEvent => event !== null);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** What a message the account sent from another device carried: its text, or `OTHER` for anything else (never media keys). */
|
|
158
|
+
function sentContent(raw: unknown): InboundContent | null {
|
|
159
|
+
const content = contentOf(raw);
|
|
160
|
+
if (!content) return null;
|
|
161
|
+
if (content.kind === "AUDIO") return { kind: "OTHER", channelType: "audio" };
|
|
162
|
+
return content.kind === "INTERACTIVE" ? { kind: "TEXT", text: content.title } : content;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** One message → the event for a message the account sent itself, or null when it is not one a person sent to one contact. */
|
|
166
|
+
function sentElsewhereEvent(accountId: string, message: BaileysMessage): SentElsewhereEvent | null {
|
|
167
|
+
if (!isObject(message) || !isObject(message.key) || !message.key.fromMe) return null;
|
|
168
|
+
const id = text(message.key.id);
|
|
169
|
+
const contactId = contactAddress(message.key);
|
|
170
|
+
const seconds = longNumber(message.messageTimestamp);
|
|
171
|
+
const content = sentContent(message.message);
|
|
172
|
+
if (!id || !contactId || seconds === null || !content) return null;
|
|
173
|
+
return { type: "sent_elsewhere", accountId, contactId, externalId: id, sentAt: new Date(seconds * 1000), content };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* One live `messages.upsert` → events for the messages the account sent itself
|
|
178
|
+
* (from another device, or the echo of one of this session's own sends: the
|
|
179
|
+
* CALLER tells them apart by id). `accountId` is the linked account's digits.
|
|
180
|
+
*/
|
|
181
|
+
export function normalizeSentElsewhere(accountId: string, upsert: { messages: readonly BaileysMessage[]; type: string }): SentElsewhereEvent[] {
|
|
182
|
+
if (upsert.type !== "notify") return [];
|
|
183
|
+
return upsert.messages.map((message) => sentElsewhereEvent(accountId, message)).filter((event): event is SentElsewhereEvent => event !== null);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** `proto.WebMessageInfo.Status` → a receipt. PENDING (1) and unknown values are not receipts. */
|
|
187
|
+
export function receiptOf(status: unknown): ReceiptStatus | null {
|
|
188
|
+
switch (status) {
|
|
189
|
+
case 0:
|
|
190
|
+
return "FAILED";
|
|
191
|
+
case 2:
|
|
192
|
+
return "SENT";
|
|
193
|
+
case 3:
|
|
194
|
+
return "DELIVERED";
|
|
195
|
+
case 4:
|
|
196
|
+
case 5:
|
|
197
|
+
return "READ";
|
|
198
|
+
default:
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** One `messages.update` → receipts for the messages this account sent. `at` is when the socket saw it. */
|
|
204
|
+
export function normalizeUpdates(accountId: string, updates: readonly BaileysMessageUpdate[], at: Date): StatusEvent[] {
|
|
205
|
+
const events: StatusEvent[] = [];
|
|
206
|
+
for (const entry of updates) {
|
|
207
|
+
if (!isObject(entry) || !isObject(entry.key) || !entry.key.fromMe || !isObject(entry.update)) continue;
|
|
208
|
+
const id = text(entry.key.id);
|
|
209
|
+
const status = receiptOf(entry.update.status);
|
|
210
|
+
if (!id || !status) continue;
|
|
211
|
+
events.push({
|
|
212
|
+
type: "status",
|
|
213
|
+
accountId,
|
|
214
|
+
externalId: id,
|
|
215
|
+
status,
|
|
216
|
+
at,
|
|
217
|
+
contactId: contactAddress(entry.key),
|
|
218
|
+
error: status === "FAILED" ? "ERROR" : null,
|
|
219
|
+
callbackData: null,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
return events;
|
|
223
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { SentElsewhereEvent } from "../core/types";
|
|
2
|
+
import { systemTimers, type WhatsAppWebTimers } from "./timers";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Tells a message the account sent from ANOTHER device from the echo of a
|
|
6
|
+
* send this session made.
|
|
7
|
+
*
|
|
8
|
+
* A linked device sees every message of the account on `messages.upsert`,
|
|
9
|
+
* its own sends included, and the echo can arrive BEFORE `sendMessage`
|
|
10
|
+
* resolves with the id. So: the ids of finished sends are remembered (bounded),
|
|
11
|
+
* and a `fromMe` event that arrives while sends are in flight is HELD, stamped
|
|
12
|
+
* with THOSE sends, and judged against the ids once they settle (a send that
|
|
13
|
+
* starts later never holds it). The engine already recorded its own sends; an
|
|
14
|
+
* echo reaching the host as "the owner replied from the phone" would pause the
|
|
15
|
+
* agent on its own reply.
|
|
16
|
+
*
|
|
17
|
+
* Bounded: an event is held at most `maxHoldMs` (a send that never settles
|
|
18
|
+
* cannot pin it), at most `maxHeld` events are held (the oldest is judged and
|
|
19
|
+
* released first), and `reset` (the socket closed) releases everything. A
|
|
20
|
+
* released event is judged against the ids known then. Released events reach
|
|
21
|
+
* the host later than events that arrived after them.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export interface OwnSendsOptions {
|
|
25
|
+
timers?: WhatsAppWebTimers;
|
|
26
|
+
/** The longest an event waits for its sends. Default 30 s. */
|
|
27
|
+
maxHoldMs?: number;
|
|
28
|
+
/** How many events may be held at once. Default 200. */
|
|
29
|
+
maxHeld?: number;
|
|
30
|
+
/** How many sent ids are remembered. Default 1000. */
|
|
31
|
+
remembered?: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface Held {
|
|
35
|
+
event: SentElsewhereEvent;
|
|
36
|
+
/** The sends in flight when it arrived that have not settled yet. */
|
|
37
|
+
waitingOn: Set<number>;
|
|
38
|
+
timer: unknown;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export class OwnSends {
|
|
42
|
+
private readonly ids = new Set<string>();
|
|
43
|
+
private readonly inFlight = new Set<number>();
|
|
44
|
+
private sequence = 0;
|
|
45
|
+
private held: Held[] = [];
|
|
46
|
+
private readonly timers: WhatsAppWebTimers;
|
|
47
|
+
private readonly maxHoldMs: number;
|
|
48
|
+
private readonly maxHeld: number;
|
|
49
|
+
private readonly remembered: number;
|
|
50
|
+
|
|
51
|
+
/** `release` gets the held events that turned out to be from another device, when they are judged. */
|
|
52
|
+
constructor(
|
|
53
|
+
private readonly release: (events: SentElsewhereEvent[]) => void,
|
|
54
|
+
options: OwnSendsOptions = {},
|
|
55
|
+
) {
|
|
56
|
+
this.timers = options.timers ?? systemTimers;
|
|
57
|
+
this.maxHoldMs = options.maxHoldMs ?? 30_000;
|
|
58
|
+
this.maxHeld = options.maxHeld ?? 200;
|
|
59
|
+
this.remembered = options.remembered ?? 1000;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Run one send. Its id is remembered whether the caller or the echo gets there first. */
|
|
63
|
+
async track<T extends { externalId: string }>(run: () => Promise<T>): Promise<T> {
|
|
64
|
+
this.sequence += 1;
|
|
65
|
+
const send = this.sequence;
|
|
66
|
+
this.inFlight.add(send);
|
|
67
|
+
let id: string | null = null;
|
|
68
|
+
try {
|
|
69
|
+
const result = await run();
|
|
70
|
+
id = result.externalId;
|
|
71
|
+
return result;
|
|
72
|
+
} finally {
|
|
73
|
+
this.inFlight.delete(send);
|
|
74
|
+
if (id) this.remember(id);
|
|
75
|
+
for (const entry of this.held) entry.waitingOn.delete(send);
|
|
76
|
+
this.releaseWhere((entry) => entry.waitingOn.size === 0);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The events to hand on NOW: not our own, and none while a send is in flight (those are held). */
|
|
81
|
+
accept(events: readonly SentElsewhereEvent[]): SentElsewhereEvent[] {
|
|
82
|
+
if (this.inFlight.size === 0) return this.judge(events);
|
|
83
|
+
for (const event of events) this.hold(event);
|
|
84
|
+
const excess = new Set(this.held.slice(0, Math.max(0, this.held.length - this.maxHeld)));
|
|
85
|
+
this.releaseWhere((entry) => excess.has(entry));
|
|
86
|
+
return [];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The socket closed: release everything held, and hold nothing for the sends that were in flight. */
|
|
90
|
+
reset(): void {
|
|
91
|
+
this.inFlight.clear();
|
|
92
|
+
this.releaseWhere(() => true);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
private hold(event: SentElsewhereEvent): void {
|
|
96
|
+
const entry: Held = { event, waitingOn: new Set(this.inFlight), timer: null };
|
|
97
|
+
entry.timer = this.timers.setTimeout(() => this.releaseWhere((held) => held === entry), this.maxHoldMs);
|
|
98
|
+
this.held.push(entry);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Release the held entries `done` picks, in the order they arrived, judged against the ids known now. */
|
|
102
|
+
private releaseWhere(done: (entry: Held) => boolean): void {
|
|
103
|
+
const out: Held[] = [];
|
|
104
|
+
const kept: Held[] = [];
|
|
105
|
+
for (const entry of this.held) (done(entry) ? out : kept).push(entry);
|
|
106
|
+
if (out.length === 0) return;
|
|
107
|
+
this.held = kept;
|
|
108
|
+
for (const entry of out) this.timers.clearTimeout(entry.timer);
|
|
109
|
+
const events = this.judge(out.map((entry) => entry.event));
|
|
110
|
+
if (events.length > 0) this.release(events);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private judge(events: readonly SentElsewhereEvent[]): SentElsewhereEvent[] {
|
|
114
|
+
return events.filter((event) => !this.ids.has(event.externalId));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
private remember(id: string): void {
|
|
118
|
+
this.ids.add(id);
|
|
119
|
+
for (const oldest of this.ids) {
|
|
120
|
+
if (this.ids.size <= this.remembered) break;
|
|
121
|
+
this.ids.delete(oldest);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|