@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,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The slice of Baileys (`baileys` / `@whiskeysockets/baileys`, v7) this layer
|
|
3
|
+
* uses, typed STRUCTURALLY. The package never imports Baileys: the host passes
|
|
4
|
+
* the module it installed (`import * as baileys from "baileys"`), so a host on
|
|
5
|
+
* the official Cloud adapter never installs it, and the suites drive a fake.
|
|
6
|
+
*
|
|
7
|
+
* Every shape here is what Baileys 7.0.0 declares, narrowed to the fields read.
|
|
8
|
+
* Anything wider is left `unknown` and read defensively.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** A protobuf `Long`, as Baileys hands timestamps: a number, or `{ low, high }`. */
|
|
12
|
+
export type LongLike = number | string | { low: number; high: number; unsigned?: boolean } | null | undefined;
|
|
13
|
+
|
|
14
|
+
/** `WAMessageKey`: Baileys' `proto.IMessageKey` plus the v7 LID alternates. */
|
|
15
|
+
export interface BaileysMessageKey {
|
|
16
|
+
remoteJid?: string | null;
|
|
17
|
+
/** The same chat's other address: the phone-number JID when `remoteJid` is a LID, and back. */
|
|
18
|
+
remoteJidAlt?: string | null;
|
|
19
|
+
fromMe?: boolean | null;
|
|
20
|
+
id?: string | null;
|
|
21
|
+
participant?: string | null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** `WAMessage` (`proto.IWebMessageInfo`), the fields read. `message` is the raw `proto.IMessage`. */
|
|
25
|
+
export interface BaileysMessage {
|
|
26
|
+
key: BaileysMessageKey;
|
|
27
|
+
message?: object | null;
|
|
28
|
+
messageTimestamp?: number | { low: number; high: number } | null;
|
|
29
|
+
pushName?: string | null;
|
|
30
|
+
/** `proto.WebMessageInfo.Status`: 0 ERROR, 1 PENDING, 2 SERVER_ACK, 3 DELIVERY_ACK, 4 READ, 5 PLAYED. */
|
|
31
|
+
status?: number | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** One `messages.update` entry. */
|
|
35
|
+
export interface BaileysMessageUpdate {
|
|
36
|
+
key: BaileysMessageKey;
|
|
37
|
+
update: { status?: number | null } & Record<string, unknown>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The close reason Baileys reports: a Boom, whose `output.statusCode` is the `DisconnectReason`. */
|
|
41
|
+
export interface BaileysDisconnect {
|
|
42
|
+
error?: { output?: { statusCode?: number }; message?: string } | Error | null | undefined;
|
|
43
|
+
date?: Date;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface BaileysConnectionUpdate {
|
|
47
|
+
connection?: "open" | "connecting" | "close";
|
|
48
|
+
lastDisconnect?: BaileysDisconnect;
|
|
49
|
+
qr?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** `messaging-history.set`: a history sync. `syncType` is `proto.HistorySync.HistorySyncType` (6 is ON_DEMAND), a number or its name. */
|
|
53
|
+
export interface BaileysHistorySet<Msg extends BaileysMessage = BaileysMessage> {
|
|
54
|
+
messages: Msg[];
|
|
55
|
+
syncType?: number | string | null;
|
|
56
|
+
/** The id `fetchMessageHistory` returned, on the answer to that request. */
|
|
57
|
+
peerDataRequestSessionId?: string | null;
|
|
58
|
+
isLatest?: boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** `WAPresence` values this layer sends. */
|
|
62
|
+
export type BaileysPresence = "composing" | "paused";
|
|
63
|
+
|
|
64
|
+
/** The events this layer listens to, by Baileys' own names. */
|
|
65
|
+
export interface BaileysEventMap<Msg extends BaileysMessage = BaileysMessage> {
|
|
66
|
+
"connection.update": BaileysConnectionUpdate;
|
|
67
|
+
"creds.update": Record<string, unknown>;
|
|
68
|
+
"messages.upsert": { messages: Msg[]; type: "notify" | "append" | string };
|
|
69
|
+
"messages.update": BaileysMessageUpdate[];
|
|
70
|
+
"messaging-history.set": BaileysHistorySet<Msg>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** `SignalKeyStore`: keyed by category, then id. A null value deletes. */
|
|
74
|
+
export interface BaileysKeyStore {
|
|
75
|
+
get(type: string, ids: string[]): Promise<Record<string, unknown>>;
|
|
76
|
+
set(data: Record<string, Record<string, unknown>>): Promise<void>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** `AuthenticationState`, as this layer builds it. `creds` and every key are Baileys' own values, opaque here. */
|
|
80
|
+
export interface BaileysAuthState {
|
|
81
|
+
creds: object;
|
|
82
|
+
keys: BaileysKeyStore;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The socket `makeWASocket` returns, the members used. */
|
|
86
|
+
/** `Msg` is Baileys' own `WAMessage`, inferred from the module: messages go back to Baileys as they came. */
|
|
87
|
+
export interface BaileysSocket<Msg extends BaileysMessage = BaileysMessage> {
|
|
88
|
+
ev: {
|
|
89
|
+
on<E extends keyof BaileysEventMap>(event: E, listener: (data: BaileysEventMap<Msg>[E]) => void): void;
|
|
90
|
+
};
|
|
91
|
+
/** The linked account, once open: `id` is `5511999999999:12@s.whatsapp.net`. */
|
|
92
|
+
user?: { id?: string | null | undefined } | null | undefined;
|
|
93
|
+
sendMessage(jid: string, content: { text: string }): Promise<Msg | undefined>;
|
|
94
|
+
/** `sendPresenceUpdate(type, toJid?)`: "digitando…" (`composing`) or its end (`paused`) in one chat. */
|
|
95
|
+
sendPresenceUpdate(type: BaileysPresence, toJid?: string): Promise<void>;
|
|
96
|
+
/** `readMessages(keys)`: marks those messages read (blue ticks). */
|
|
97
|
+
readMessages(keys: BaileysMessageKey[]): Promise<void>;
|
|
98
|
+
/**
|
|
99
|
+
* `fetchMessageHistory(count, oldestMsgKey, oldestMsgTimestamp)`: asks the phone for up to `count` messages
|
|
100
|
+
* before that one. Returns the request id; the answer arrives on `messaging-history.set`.
|
|
101
|
+
*/
|
|
102
|
+
fetchMessageHistory(count: number, oldestMsgKey: BaileysMessageKey, oldestMsgTimestamp: number): Promise<string>;
|
|
103
|
+
requestPairingCode(phoneNumber: string): Promise<string>;
|
|
104
|
+
logout(msg?: string): Promise<void>;
|
|
105
|
+
end(error: Error | undefined): Promise<void> | void;
|
|
106
|
+
/** Asks the phone to re-upload expired media; passed to `downloadMediaMessage`. */
|
|
107
|
+
updateMediaMessage?(message: Msg): Promise<Msg>;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Baileys' `ILogger`: pino satisfies it. */
|
|
111
|
+
export interface BaileysLogger {
|
|
112
|
+
level: string;
|
|
113
|
+
child(obj: Record<string, unknown>): BaileysLogger;
|
|
114
|
+
trace(obj: unknown, msg?: string): void;
|
|
115
|
+
debug(obj: unknown, msg?: string): void;
|
|
116
|
+
info(obj: unknown, msg?: string): void;
|
|
117
|
+
warn(obj: unknown, msg?: string): void;
|
|
118
|
+
error(obj: unknown, msg?: string): void;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The members of the Baileys MODULE this layer calls. `import * as baileys from "baileys"` satisfies it. */
|
|
122
|
+
/**
|
|
123
|
+
* `Auth` is Baileys' own `AuthenticationState` and `Msg` its `WAMessage`, inferred from the module the
|
|
124
|
+
* host passes. The layer builds it from the host's store, where the values are
|
|
125
|
+
* Baileys' own, serialized by its `BufferJSON`.
|
|
126
|
+
*/
|
|
127
|
+
export interface BaileysModule<Auth = BaileysAuthState, Msg extends BaileysMessage = BaileysMessage> {
|
|
128
|
+
makeWASocket(config: {
|
|
129
|
+
auth: Auth;
|
|
130
|
+
logger?: BaileysLogger;
|
|
131
|
+
browser?: [string, string, string];
|
|
132
|
+
markOnlineOnConnect?: boolean;
|
|
133
|
+
syncFullHistory?: boolean;
|
|
134
|
+
}): BaileysSocket<Msg>;
|
|
135
|
+
initAuthCreds(): object;
|
|
136
|
+
BufferJSON: {
|
|
137
|
+
replacer(key: string, value: unknown): unknown;
|
|
138
|
+
reviver(key: string, value: unknown): unknown;
|
|
139
|
+
};
|
|
140
|
+
downloadMediaMessage(
|
|
141
|
+
message: Msg,
|
|
142
|
+
type: "buffer",
|
|
143
|
+
options: Record<string, unknown>,
|
|
144
|
+
ctx?: { logger?: BaileysLogger; reuploadRequest?: (message: Msg) => Promise<Msg> },
|
|
145
|
+
): Promise<Uint8Array>;
|
|
146
|
+
/** Optional: rebuilds an app-state sync key read back from storage (Baileys' own file store does). */
|
|
147
|
+
proto?: { Message?: { AppStateSyncKeyData?: { fromObject(value: unknown): unknown } } };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Baileys' `DisconnectReason` values this layer acts on. */
|
|
151
|
+
export const DISCONNECT = {
|
|
152
|
+
/** The phone unlinked this device, or the session was logged out: never reconnect. */
|
|
153
|
+
loggedOut: 401,
|
|
154
|
+
/** Another client took the session over. Reconnecting would fight it: stop. */
|
|
155
|
+
connectionReplaced: 440,
|
|
156
|
+
/** The account is banned or the session is unusable: stop. */
|
|
157
|
+
forbidden: 403,
|
|
158
|
+
/** Baileys asks for a fresh socket right after pairing: reconnect at once. */
|
|
159
|
+
restartRequired: 515,
|
|
160
|
+
} as const;
|
|
161
|
+
|
|
162
|
+
/** The close's `DisconnectReason`, or null when Baileys gave none. */
|
|
163
|
+
export function disconnectCode(disconnect: BaileysDisconnect | undefined): number | null {
|
|
164
|
+
const error = disconnect?.error;
|
|
165
|
+
if (!error || typeof error !== "object" || !("output" in error)) return null;
|
|
166
|
+
const code = error.output?.statusCode;
|
|
167
|
+
return typeof code === "number" ? code : null;
|
|
168
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { InboundContent, NormalizedEvent, OutboundContent } from "../core/types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The choices a personal account offered, remembered so the contact's typed
|
|
5
|
+
* answer reads as the tap it stands for.
|
|
6
|
+
*
|
|
7
|
+
* A personal account cannot send reply buttons or lists: `renderOutboundText`
|
|
8
|
+
* sends them as numbered lines, and the contact answers with text. An agent
|
|
9
|
+
* built for the Cloud adapter expects `INTERACTIVE { replyId, title }`. This
|
|
10
|
+
* module keeps the last choices offered to each contact (in memory, bounded,
|
|
11
|
+
* expiring) and turns an answer that is EXACTLY a listed number or EXACTLY a
|
|
12
|
+
* choice's title into that `INTERACTIVE`. Anything else stays `TEXT`.
|
|
13
|
+
*
|
|
14
|
+
* An offer maps only the first reply after it: any later message to that
|
|
15
|
+
* contact, from this session (plain text included) or from the owner's phone
|
|
16
|
+
* (`sent_elsewhere`), clears it, because the "1" that follows answers that.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** One offered choice: the id the agent gave it and the title the contact sees. */
|
|
20
|
+
export interface OfferedChoice {
|
|
21
|
+
replyId: string;
|
|
22
|
+
title: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The choices an outbound message offers, in the order {@link renderOutboundText} numbers them. Empty for plain text. */
|
|
26
|
+
export function choicesOf(content: OutboundContent): OfferedChoice[] {
|
|
27
|
+
if (content.kind === "TEXT") return [];
|
|
28
|
+
if (content.kind === "BUTTONS") return content.buttons.map((button) => ({ replyId: button.id, title: button.title }));
|
|
29
|
+
return content.sections.flatMap((section) => section.rows.map((row) => ({ replyId: row.id, title: row.title })));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Case, accents and spacing out of the way: `" Sim, Por Favor "` and `"sim, por favor"` are one title. */
|
|
33
|
+
export function foldTitle(value: string): string {
|
|
34
|
+
return value.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/\s+/g, " ").trim();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `"1"`, `"1."`, `" 2 "`, `"3)"` → the number; anything else (`"1 pizza"`, `"2x"`) → null. */
|
|
38
|
+
export function listedNumber(value: string): number | null {
|
|
39
|
+
// Trimmed and bounded first, so the pattern has one whitespace run and stays linear on any input.
|
|
40
|
+
const text = value.trim();
|
|
41
|
+
if (text.length > 8) return null;
|
|
42
|
+
const match = /^(\d{1,3})(?:\s*[.)])?$/.exec(text);
|
|
43
|
+
return match ? Number(match[1]) : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface Offer {
|
|
47
|
+
choices: readonly OfferedChoice[];
|
|
48
|
+
folded: readonly string[];
|
|
49
|
+
at: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ChoiceMemoryOptions {
|
|
53
|
+
/** How many contacts are remembered; the least recently offered goes first. Default 500. */
|
|
54
|
+
maxContacts?: number;
|
|
55
|
+
/** How long an offer stays answerable. Default 2 hours. */
|
|
56
|
+
ttlMs?: number;
|
|
57
|
+
now?(): Date;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export class ChoiceMemory {
|
|
61
|
+
private readonly offers = new Map<string, Offer>();
|
|
62
|
+
private readonly maxContacts: number;
|
|
63
|
+
private readonly ttlMs: number;
|
|
64
|
+
private readonly now: () => Date;
|
|
65
|
+
|
|
66
|
+
constructor(options: ChoiceMemoryOptions = {}) {
|
|
67
|
+
this.maxContacts = options.maxContacts ?? 500;
|
|
68
|
+
this.ttlMs = options.ttlMs ?? 2 * 60 * 60 * 1000;
|
|
69
|
+
this.now = options.now ?? (() => new Date());
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Remember what was just sent to a contact: its choices replace the earlier offer, and plain text clears it. */
|
|
73
|
+
offer(contactId: string, content: OutboundContent): void {
|
|
74
|
+
const choices = choicesOf(content);
|
|
75
|
+
this.offers.delete(contactId);
|
|
76
|
+
if (choices.length === 0) return;
|
|
77
|
+
this.offers.set(contactId, { choices, folded: choices.map((choice) => foldTitle(choice.title)), at: this.now().getTime() });
|
|
78
|
+
for (const oldest of this.offers.keys()) {
|
|
79
|
+
if (this.offers.size <= this.maxContacts) break;
|
|
80
|
+
this.offers.delete(oldest);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The choice a typed answer stands for, or null. A listed number wins over a
|
|
86
|
+
* title. A match uses the offer up (the answer was given); a miss, an
|
|
87
|
+
* expired offer or a contact never offered anything clears nothing.
|
|
88
|
+
*/
|
|
89
|
+
resolve(contactId: string, answer: string): OfferedChoice | null {
|
|
90
|
+
const offer = this.offers.get(contactId);
|
|
91
|
+
if (!offer) return null;
|
|
92
|
+
if (this.now().getTime() - offer.at > this.ttlMs) {
|
|
93
|
+
this.offers.delete(contactId);
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const number = listedNumber(answer);
|
|
97
|
+
const index = number === null ? offer.folded.indexOf(foldTitle(answer)) : number - 1;
|
|
98
|
+
const choice = offer.choices[index];
|
|
99
|
+
if (!choice || index < 0) return null;
|
|
100
|
+
this.offers.delete(contactId);
|
|
101
|
+
return choice;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Something else was said to the contact since: the offer no longer maps their reply. */
|
|
105
|
+
forget(contactId: string): void {
|
|
106
|
+
this.offers.delete(contactId);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
get size(): number {
|
|
110
|
+
return this.offers.size;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The events, in socket order, with each TEXT answer that picks an offered choice read as `INTERACTIVE`. A
|
|
116
|
+
* `sent_elsewhere` clears its contact's offer. Every other event is returned as it came.
|
|
117
|
+
*/
|
|
118
|
+
export function applyChoices(memory: ChoiceMemory, events: readonly NormalizedEvent[]): NormalizedEvent[] {
|
|
119
|
+
return events.map((event) => {
|
|
120
|
+
if (event.type === "sent_elsewhere") memory.forget(event.contactId);
|
|
121
|
+
if (event.type !== "message" || event.content.kind !== "TEXT") return event;
|
|
122
|
+
const choice = memory.resolve(event.contactId, event.content.text);
|
|
123
|
+
const content: InboundContent | null = choice ? { kind: "INTERACTIVE", replyId: choice.replyId, title: choice.title } : null;
|
|
124
|
+
return content ? { ...event, content } : event;
|
|
125
|
+
});
|
|
126
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { InboundContent, NormalizedEvent, ReceiptStatus } from "../core/types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The raw body a session hands the engine's inbox.
|
|
5
|
+
*
|
|
6
|
+
* The inbox stores every delivery raw before processing it, and re-parses it
|
|
7
|
+
* on a retry. A socket has no HTTP body, so the session writes one: its
|
|
8
|
+
* already-normalized events, as JSON. Never Baileys' own message objects —
|
|
9
|
+
* they carry media keys and the full protobuf, and the inbox keeps what it
|
|
10
|
+
* is given.
|
|
11
|
+
*
|
|
12
|
+
* `{ "format": "whatsapp-web/1", "events": [...] }`, dates as ISO strings.
|
|
13
|
+
*/
|
|
14
|
+
export const ENVELOPE_FORMAT = "whatsapp-web/1";
|
|
15
|
+
|
|
16
|
+
export function encodeEnvelope(events: readonly NormalizedEvent[]): string {
|
|
17
|
+
return JSON.stringify({ format: ENVELOPE_FORMAT, events });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type Json = Record<string, unknown>;
|
|
21
|
+
const isObject = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
22
|
+
const str = (value: unknown): string | null => (typeof value === "string" && value.length > 0 ? value : null);
|
|
23
|
+
const strOrNull = (value: unknown): string | null => (typeof value === "string" ? value : null);
|
|
24
|
+
const date = (value: unknown): Date | null => {
|
|
25
|
+
const parsed = typeof value === "string" ? new Date(value) : null;
|
|
26
|
+
return parsed && Number.isFinite(parsed.getTime()) ? parsed : null;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const RECEIPTS: readonly ReceiptStatus[] = ["SENT", "DELIVERED", "READ", "FAILED"];
|
|
30
|
+
|
|
31
|
+
const CONTENT: Readonly<Record<string, (value: Json) => InboundContent | null>> = {
|
|
32
|
+
TEXT: (value) => (typeof value.text === "string" ? { kind: "TEXT", text: value.text } : null),
|
|
33
|
+
INTERACTIVE: (value) => (str(value.replyId) ? { kind: "INTERACTIVE", replyId: value.replyId as string, title: strOrNull(value.title) ?? "" } : null),
|
|
34
|
+
AUDIO: (value) => (str(value.mediaId) ? { kind: "AUDIO", mediaId: value.mediaId as string, mimeType: strOrNull(value.mimeType) } : null),
|
|
35
|
+
OTHER: (value) => (str(value.channelType) ? { kind: "OTHER", channelType: value.channelType as string } : null),
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
function content(value: unknown): InboundContent | null {
|
|
39
|
+
if (!isObject(value) || typeof value.kind !== "string") return null;
|
|
40
|
+
return CONTENT[value.kind]?.(value) ?? null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function messageEvent(value: Json, accountId: string): NormalizedEvent | null {
|
|
44
|
+
const contactId = str(value.contactId);
|
|
45
|
+
const externalId = str(value.externalId);
|
|
46
|
+
const sentAt = date(value.sentAt);
|
|
47
|
+
const body = content(value.content);
|
|
48
|
+
if (!contactId || !externalId || !sentAt || !body) return null;
|
|
49
|
+
return { type: "message", accountId, contactId, contactName: strOrNull(value.contactName), externalId, sentAt, content: body, optOut: value.optOut === true };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function statusEvent(value: Json, accountId: string): NormalizedEvent | null {
|
|
53
|
+
const externalId = str(value.externalId);
|
|
54
|
+
const at = date(value.at);
|
|
55
|
+
const status = RECEIPTS.find((receipt) => receipt === value.status);
|
|
56
|
+
if (!externalId || !at || !status) return null;
|
|
57
|
+
const optional = { contactId: strOrNull(value.contactId), error: strOrNull(value.error), callbackData: strOrNull(value.callbackData) };
|
|
58
|
+
return { type: "status", accountId, externalId, status, at, ...optional };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function optOutEvent(value: Json, accountId: string): NormalizedEvent | null {
|
|
62
|
+
const contactId = str(value.contactId);
|
|
63
|
+
const at = date(value.at);
|
|
64
|
+
return contactId && at ? { type: "opt_out", accountId, contactId, at } : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function sentElsewhereEvent(value: Json, accountId: string): NormalizedEvent | null {
|
|
68
|
+
const contactId = str(value.contactId);
|
|
69
|
+
const externalId = str(value.externalId);
|
|
70
|
+
const sentAt = date(value.sentAt);
|
|
71
|
+
const body = content(value.content);
|
|
72
|
+
if (!contactId || !externalId || !sentAt || !body) return null;
|
|
73
|
+
return { type: "sent_elsewhere", accountId, contactId, externalId, sentAt, content: body };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const EVENTS: Readonly<Record<string, (value: Json, accountId: string) => NormalizedEvent | null>> = {
|
|
77
|
+
message: messageEvent,
|
|
78
|
+
status: statusEvent,
|
|
79
|
+
opt_out: optOutEvent,
|
|
80
|
+
sent_elsewhere: sentElsewhereEvent,
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
function event(value: unknown): NormalizedEvent | null {
|
|
84
|
+
if (!isObject(value) || typeof value.type !== "string") return null;
|
|
85
|
+
const accountId = str(value.accountId);
|
|
86
|
+
return accountId ? (EVENTS[value.type]?.(value, accountId) ?? null) : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* An envelope's events, in order. Another format, or an event of an unknown
|
|
91
|
+
* shape, yields nothing for it; only bytes that are not JSON throw.
|
|
92
|
+
*/
|
|
93
|
+
export function parseEnvelope(rawBody: string): NormalizedEvent[] {
|
|
94
|
+
const payload = JSON.parse(rawBody) as unknown;
|
|
95
|
+
if (!isObject(payload) || payload.format !== ENVELOPE_FORMAT || !Array.isArray(payload.events)) return [];
|
|
96
|
+
return payload.events.map(event).filter((parsed): parsed is NormalizedEvent => parsed !== null);
|
|
97
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import type { InboundContent } from "../core/types";
|
|
2
|
+
import type { BaileysHistorySet, BaileysMessage } from "./baileys-port";
|
|
3
|
+
import { addressJid, contactAddress, contentOf, longNumber } from "./normalize";
|
|
4
|
+
import { systemTimers, type WhatsAppWebTimers } from "./timers";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* On-demand history: the messages of ONE chat, read from the phone and handed
|
|
8
|
+
* back to the caller, never to the inbox or the engine.
|
|
9
|
+
*
|
|
10
|
+
* `fetchMessageHistory` asks the phone for messages before an anchor and
|
|
11
|
+
* returns only a request id; the answer arrives later on `messaging-history.set`
|
|
12
|
+
* (which can even come BEFORE the call resolves). This module holds the
|
|
13
|
+
* pending requests, matches an answer to the chat it is for, and reduces each
|
|
14
|
+
* message to what a model may read: text, or a placeholder kind for media.
|
|
15
|
+
* Nothing here keeps a message after its request settles.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** The message a history read starts before: the inbound message that began the turn. */
|
|
19
|
+
export interface HistoryAnchor {
|
|
20
|
+
externalId: string;
|
|
21
|
+
sentAt: Date;
|
|
22
|
+
fromMe: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* One message of a chat's history. `kind` is `text`, `interactive`, `audio`, or the channel's own type for
|
|
27
|
+
* anything else (`image`, `sticker`, `video`): text is carried only for `text` and `interactive`.
|
|
28
|
+
*/
|
|
29
|
+
export interface WhatsAppWebHistoryMessage {
|
|
30
|
+
externalId: string;
|
|
31
|
+
fromMe: boolean;
|
|
32
|
+
sentAt: Date;
|
|
33
|
+
text: string | null;
|
|
34
|
+
kind: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `proto.HistorySync.HistorySyncType.ON_DEMAND`. */
|
|
38
|
+
const ON_DEMAND = 6;
|
|
39
|
+
|
|
40
|
+
const isOnDemand = (syncType: unknown): boolean => syncType === ON_DEMAND || syncType === "ON_DEMAND";
|
|
41
|
+
|
|
42
|
+
/** What a content keeps: its text (or none) and the placeholder `kind`. Media keeps neither bytes nor keys. */
|
|
43
|
+
function kept(content: InboundContent): { text: string | null; kind: string } {
|
|
44
|
+
switch (content.kind) {
|
|
45
|
+
case "TEXT":
|
|
46
|
+
return { text: content.text, kind: "text" };
|
|
47
|
+
case "INTERACTIVE":
|
|
48
|
+
return { text: content.title || null, kind: "interactive" };
|
|
49
|
+
case "AUDIO":
|
|
50
|
+
return { text: null, kind: "audio" };
|
|
51
|
+
default:
|
|
52
|
+
return { text: null, kind: content.channelType.toLowerCase() };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** One raw message → its text-only form, or null for a protocol message, a malformed one or one with no id or time. */
|
|
57
|
+
export function historyMessage(message: BaileysMessage): WhatsAppWebHistoryMessage | null {
|
|
58
|
+
const id = message?.key?.id;
|
|
59
|
+
const seconds = longNumber(message?.messageTimestamp);
|
|
60
|
+
const content = contentOf(message?.message);
|
|
61
|
+
if (typeof id !== "string" || id === "" || seconds === null || !content) return null;
|
|
62
|
+
return { externalId: id, fromMe: message.key.fromMe === true, sentAt: new Date(seconds * 1000), ...kept(content) };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Whether a message key belongs to the contact's chat, by either of the chat's addresses (a LID or its phone number). */
|
|
66
|
+
const inChat = (contactId: string, key: BaileysMessage["key"]): boolean =>
|
|
67
|
+
contactAddress(key) === contactId || [key.remoteJid, key.remoteJidAlt].includes(addressJid(contactId));
|
|
68
|
+
|
|
69
|
+
/** The messages of one contact's chat out of a history batch: oldest first, each id once, the newest `count`. */
|
|
70
|
+
export function chatHistory(contactId: string, messages: readonly BaileysMessage[], count: number): WhatsAppWebHistoryMessage[] {
|
|
71
|
+
const seen = new Set<string>();
|
|
72
|
+
const found: WhatsAppWebHistoryMessage[] = [];
|
|
73
|
+
for (const raw of messages) {
|
|
74
|
+
if (!raw?.key || !inChat(contactId, raw.key)) continue;
|
|
75
|
+
const message = historyMessage(raw);
|
|
76
|
+
if (!message || seen.has(message.externalId)) continue;
|
|
77
|
+
seen.add(message.externalId);
|
|
78
|
+
found.push(message);
|
|
79
|
+
}
|
|
80
|
+
found.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());
|
|
81
|
+
return count > 0 ? found.slice(-count) : [];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
interface Pending {
|
|
85
|
+
contactId: string;
|
|
86
|
+
count: number;
|
|
87
|
+
requestId: string | null;
|
|
88
|
+
settle(messages: WhatsAppWebHistoryMessage[]): void;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A request waiting for its answer. */
|
|
92
|
+
export interface HistoryWait {
|
|
93
|
+
/** The messages, or `[]` on a timeout, an abandoned request or a closed socket. Never rejects. */
|
|
94
|
+
result: Promise<WhatsAppWebHistoryMessage[]>;
|
|
95
|
+
/** The id `fetchMessageHistory` returned: from then on an answer naming another id is not this one's. */
|
|
96
|
+
setRequestId(id: string): void;
|
|
97
|
+
/** Settle with nothing: the call that was to fetch it failed. */
|
|
98
|
+
abandon(): void;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export class HistoryRequests {
|
|
102
|
+
/** Oldest first: an answer that names no request goes to the oldest one for its chat. */
|
|
103
|
+
private readonly pending = new Set<Pending>();
|
|
104
|
+
|
|
105
|
+
constructor(private readonly timers: WhatsAppWebTimers = systemTimers) {}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Ask, and wait for the answer without waiting on the call: `call` (which returns the request id) may never
|
|
109
|
+
* settle, and the deadline still ends the wait. A rejected call abandons the request and goes to `onError`.
|
|
110
|
+
*/
|
|
111
|
+
fetch(contactId: string, count: number, timeoutMs: number, call: () => Promise<string>, onError: (error: unknown) => void): Promise<WhatsAppWebHistoryMessage[]> {
|
|
112
|
+
// Registered BEFORE the call: the phone's answer can beat the call's own return.
|
|
113
|
+
const wait = this.wait(contactId, count, timeoutMs);
|
|
114
|
+
Promise.resolve()
|
|
115
|
+
.then(call)
|
|
116
|
+
.then(wait.setRequestId, (error: unknown) => {
|
|
117
|
+
wait.abandon();
|
|
118
|
+
// A throwing host callback must not become an unhandled rejection of this detached chain.
|
|
119
|
+
try {
|
|
120
|
+
onError(error);
|
|
121
|
+
} catch {
|
|
122
|
+
/* the host's own error */
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
return wait.result;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Register a request BEFORE the call is made: the answer may beat the call's own return. The deadline is cleared once it settles. */
|
|
129
|
+
wait(contactId: string, count: number, timeoutMs: number): HistoryWait {
|
|
130
|
+
let entry!: Pending;
|
|
131
|
+
let timer: unknown = null;
|
|
132
|
+
const result = new Promise<WhatsAppWebHistoryMessage[]>((resolve) => {
|
|
133
|
+
entry = {
|
|
134
|
+
contactId,
|
|
135
|
+
count,
|
|
136
|
+
requestId: null,
|
|
137
|
+
settle: (messages) => {
|
|
138
|
+
if (!this.pending.delete(entry)) return;
|
|
139
|
+
this.timers.clearTimeout(timer);
|
|
140
|
+
resolve(messages);
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
});
|
|
144
|
+
this.pending.add(entry);
|
|
145
|
+
timer = this.timers.setTimeout(() => entry.settle([]), timeoutMs);
|
|
146
|
+
return { result, setRequestId: (id) => void (entry.requestId = id), abandon: () => entry.settle([]) };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* A `messaging-history.set`. An answer naming a request id settles THAT request; one naming an id nobody holds
|
|
151
|
+
* yet, or none, settles the oldest request for its chat whose id it cannot contradict. A late answer is dropped.
|
|
152
|
+
*/
|
|
153
|
+
answer(set: BaileysHistorySet): void {
|
|
154
|
+
if (!isOnDemand(set.syncType) || !Array.isArray(set.messages)) return;
|
|
155
|
+
const named = typeof set.peerDataRequestSessionId === "string" ? set.peerDataRequestSessionId : null;
|
|
156
|
+
const entries = [...this.pending];
|
|
157
|
+
const exact = named ? entries.find((entry) => entry.requestId === named) : undefined;
|
|
158
|
+
const candidates = exact ? [exact] : entries.filter((entry) => !named || entry.requestId === null);
|
|
159
|
+
for (const entry of candidates) {
|
|
160
|
+
const messages = chatHistory(entry.contactId, set.messages, entry.count);
|
|
161
|
+
if (messages.length === 0) continue;
|
|
162
|
+
entry.settle(messages);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The socket closed: nothing more will come. */
|
|
168
|
+
flush(): void {
|
|
169
|
+
for (const entry of [...this.pending]) entry.settle([]);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/messaging/whatsapp-web` — WhatsApp over the WhatsApp Web protocol
|
|
3
|
+
* (a linked device, through Baileys), as an alternative transport to the
|
|
4
|
+
* official Cloud API adapter at `@12-apps/messaging/whatsapp`.
|
|
5
|
+
*
|
|
6
|
+
* UNOFFICIAL. WhatsApp's terms forbid unofficial clients and the number used
|
|
7
|
+
* may be banned. A linked session's keys give full access to the account:
|
|
8
|
+
* where they live is the host's decision (`AuthStateStore`), and the package
|
|
9
|
+
* never logs them. See the README's "WhatsApp Web (unofficial)" section.
|
|
10
|
+
*
|
|
11
|
+
* Baileys is NOT a dependency: the host installs `baileys` and passes the
|
|
12
|
+
* module in. Nothing here loads it.
|
|
13
|
+
*/
|
|
14
|
+
export { createWhatsAppWebAdapter, type WhatsAppWebAdapterConfig } from "./adapter";
|
|
15
|
+
export {
|
|
16
|
+
createWhatsAppWebSession,
|
|
17
|
+
renderOutboundText,
|
|
18
|
+
type WhatsAppWebSession,
|
|
19
|
+
type WhatsAppWebSessionConfig,
|
|
20
|
+
type WhatsAppWebStatus,
|
|
21
|
+
} from "./session";
|
|
22
|
+
export { clearAuthState, createMemoryAuthStateStore, loadAuthState, type AuthStateStore } from "./auth-state";
|
|
23
|
+
export { ENVELOPE_FORMAT, encodeEnvelope, parseEnvelope } from "./envelope";
|
|
24
|
+
export {
|
|
25
|
+
addressJid,
|
|
26
|
+
contactAddress,
|
|
27
|
+
contentOf,
|
|
28
|
+
normalizeSentElsewhere,
|
|
29
|
+
normalizeUpdates,
|
|
30
|
+
normalizeUpsert,
|
|
31
|
+
receiptOf,
|
|
32
|
+
type NormalizeOptions,
|
|
33
|
+
} from "./normalize";
|
|
34
|
+
export { ChoiceMemory, type ChoiceMemoryOptions, type OfferedChoice } from "./choices";
|
|
35
|
+
export type { HistoryAnchor, WhatsAppWebHistoryMessage } from "./history";
|
|
36
|
+
export type { WhatsAppWebTimers } from "./timers";
|
|
37
|
+
export {
|
|
38
|
+
DISCONNECT,
|
|
39
|
+
disconnectCode,
|
|
40
|
+
type BaileysAuthState,
|
|
41
|
+
type BaileysConnectionUpdate,
|
|
42
|
+
type BaileysHistorySet,
|
|
43
|
+
type BaileysPresence,
|
|
44
|
+
type BaileysLogger,
|
|
45
|
+
type BaileysMessage,
|
|
46
|
+
type BaileysMessageKey,
|
|
47
|
+
type BaileysMessageUpdate,
|
|
48
|
+
type BaileysModule,
|
|
49
|
+
type BaileysSocket,
|
|
50
|
+
} from "./baileys-port";
|