@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,956 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_OPT_OUT_KEYWORDS,
|
|
3
|
+
WHATSAPP_CHANNEL,
|
|
4
|
+
isOptOutText
|
|
5
|
+
} from "../chunk-RXJNLPY4.js";
|
|
6
|
+
import {
|
|
7
|
+
ChannelMediaFailure,
|
|
8
|
+
ChannelSendFailure,
|
|
9
|
+
DEFAULT_MEDIA_TIMEOUT_MS,
|
|
10
|
+
OPEN_SEND_POLICY
|
|
11
|
+
} from "../chunk-NKH5TCSO.js";
|
|
12
|
+
import {
|
|
13
|
+
__name
|
|
14
|
+
} from "../chunk-7QVYU63E.js";
|
|
15
|
+
|
|
16
|
+
// src/whatsapp-web/envelope.ts
|
|
17
|
+
var ENVELOPE_FORMAT = "whatsapp-web/1";
|
|
18
|
+
function encodeEnvelope(events) {
|
|
19
|
+
return JSON.stringify({ format: ENVELOPE_FORMAT, events });
|
|
20
|
+
}
|
|
21
|
+
__name(encodeEnvelope, "encodeEnvelope");
|
|
22
|
+
var isObject = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isObject");
|
|
23
|
+
var str = /* @__PURE__ */ __name((value) => typeof value === "string" && value.length > 0 ? value : null, "str");
|
|
24
|
+
var strOrNull = /* @__PURE__ */ __name((value) => typeof value === "string" ? value : null, "strOrNull");
|
|
25
|
+
var date = /* @__PURE__ */ __name((value) => {
|
|
26
|
+
const parsed = typeof value === "string" ? new Date(value) : null;
|
|
27
|
+
return parsed && Number.isFinite(parsed.getTime()) ? parsed : null;
|
|
28
|
+
}, "date");
|
|
29
|
+
var RECEIPTS = ["SENT", "DELIVERED", "READ", "FAILED"];
|
|
30
|
+
var CONTENT = {
|
|
31
|
+
TEXT: /* @__PURE__ */ __name((value) => typeof value.text === "string" ? { kind: "TEXT", text: value.text } : null, "TEXT"),
|
|
32
|
+
INTERACTIVE: /* @__PURE__ */ __name((value) => str(value.replyId) ? { kind: "INTERACTIVE", replyId: value.replyId, title: strOrNull(value.title) ?? "" } : null, "INTERACTIVE"),
|
|
33
|
+
AUDIO: /* @__PURE__ */ __name((value) => str(value.mediaId) ? { kind: "AUDIO", mediaId: value.mediaId, mimeType: strOrNull(value.mimeType) } : null, "AUDIO"),
|
|
34
|
+
OTHER: /* @__PURE__ */ __name((value) => str(value.channelType) ? { kind: "OTHER", channelType: value.channelType } : null, "OTHER")
|
|
35
|
+
};
|
|
36
|
+
function content(value) {
|
|
37
|
+
if (!isObject(value) || typeof value.kind !== "string") return null;
|
|
38
|
+
return CONTENT[value.kind]?.(value) ?? null;
|
|
39
|
+
}
|
|
40
|
+
__name(content, "content");
|
|
41
|
+
function messageEvent(value, accountId) {
|
|
42
|
+
const contactId = str(value.contactId);
|
|
43
|
+
const externalId = str(value.externalId);
|
|
44
|
+
const sentAt = date(value.sentAt);
|
|
45
|
+
const body = content(value.content);
|
|
46
|
+
if (!contactId || !externalId || !sentAt || !body) return null;
|
|
47
|
+
return { type: "message", accountId, contactId, contactName: strOrNull(value.contactName), externalId, sentAt, content: body, optOut: value.optOut === true };
|
|
48
|
+
}
|
|
49
|
+
__name(messageEvent, "messageEvent");
|
|
50
|
+
function statusEvent(value, accountId) {
|
|
51
|
+
const externalId = str(value.externalId);
|
|
52
|
+
const at = date(value.at);
|
|
53
|
+
const status = RECEIPTS.find((receipt) => receipt === value.status);
|
|
54
|
+
if (!externalId || !at || !status) return null;
|
|
55
|
+
const optional = { contactId: strOrNull(value.contactId), error: strOrNull(value.error), callbackData: strOrNull(value.callbackData) };
|
|
56
|
+
return { type: "status", accountId, externalId, status, at, ...optional };
|
|
57
|
+
}
|
|
58
|
+
__name(statusEvent, "statusEvent");
|
|
59
|
+
function optOutEvent(value, accountId) {
|
|
60
|
+
const contactId = str(value.contactId);
|
|
61
|
+
const at = date(value.at);
|
|
62
|
+
return contactId && at ? { type: "opt_out", accountId, contactId, at } : null;
|
|
63
|
+
}
|
|
64
|
+
__name(optOutEvent, "optOutEvent");
|
|
65
|
+
function sentElsewhereEvent(value, accountId) {
|
|
66
|
+
const contactId = str(value.contactId);
|
|
67
|
+
const externalId = str(value.externalId);
|
|
68
|
+
const sentAt = date(value.sentAt);
|
|
69
|
+
const body = content(value.content);
|
|
70
|
+
if (!contactId || !externalId || !sentAt || !body) return null;
|
|
71
|
+
return { type: "sent_elsewhere", accountId, contactId, externalId, sentAt, content: body };
|
|
72
|
+
}
|
|
73
|
+
__name(sentElsewhereEvent, "sentElsewhereEvent");
|
|
74
|
+
var EVENTS = {
|
|
75
|
+
message: messageEvent,
|
|
76
|
+
status: statusEvent,
|
|
77
|
+
opt_out: optOutEvent,
|
|
78
|
+
sent_elsewhere: sentElsewhereEvent
|
|
79
|
+
};
|
|
80
|
+
function event(value) {
|
|
81
|
+
if (!isObject(value) || typeof value.type !== "string") return null;
|
|
82
|
+
const accountId = str(value.accountId);
|
|
83
|
+
return accountId ? EVENTS[value.type]?.(value, accountId) ?? null : null;
|
|
84
|
+
}
|
|
85
|
+
__name(event, "event");
|
|
86
|
+
function parseEnvelope(rawBody) {
|
|
87
|
+
const payload = JSON.parse(rawBody);
|
|
88
|
+
if (!isObject(payload) || payload.format !== ENVELOPE_FORMAT || !Array.isArray(payload.events)) return [];
|
|
89
|
+
return payload.events.map(event).filter((parsed) => parsed !== null);
|
|
90
|
+
}
|
|
91
|
+
__name(parseEnvelope, "parseEnvelope");
|
|
92
|
+
|
|
93
|
+
// src/whatsapp-web/adapter.ts
|
|
94
|
+
function createWhatsAppWebAdapter(config) {
|
|
95
|
+
const sessionFor = /* @__PURE__ */ __name((accountId) => {
|
|
96
|
+
if (typeof config.sessions === "function") return config.sessions(accountId);
|
|
97
|
+
return config.sessions.accountId() === accountId ? config.sessions : void 0;
|
|
98
|
+
}, "sessionFor");
|
|
99
|
+
return {
|
|
100
|
+
kind: config.kind ?? WHATSAPP_CHANNEL,
|
|
101
|
+
handshake: /* @__PURE__ */ __name(() => null, "handshake"),
|
|
102
|
+
verify: /* @__PURE__ */ __name(() => false, "verify"),
|
|
103
|
+
parse: parseEnvelope,
|
|
104
|
+
send: /* @__PURE__ */ __name(async ({ accountId, to, content: content2 }) => {
|
|
105
|
+
const session = sessionFor(accountId);
|
|
106
|
+
if (!session) throw new ChannelSendFailure("NOT_CONNECTED", "no open WhatsApp Web session for this account");
|
|
107
|
+
return session.send(to, content2);
|
|
108
|
+
}, "send"),
|
|
109
|
+
fetchMedia: /* @__PURE__ */ __name(async ({ accountId, mediaId, maxBytes, timeoutMs }) => {
|
|
110
|
+
const session = sessionFor(accountId);
|
|
111
|
+
if (!session) throw new ChannelMediaFailure("NOT_CONNECTED", "no open WhatsApp Web session for this account");
|
|
112
|
+
return session.downloadMedia(mediaId, { maxBytes, ...timeoutMs !== void 0 ? { timeoutMs } : {} });
|
|
113
|
+
}, "fetchMedia"),
|
|
114
|
+
policy: config.policy ?? OPEN_SEND_POLICY
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
__name(createWhatsAppWebAdapter, "createWhatsAppWebAdapter");
|
|
118
|
+
|
|
119
|
+
// src/whatsapp-web/auth-state.ts
|
|
120
|
+
function createMemoryAuthStateStore() {
|
|
121
|
+
const values = /* @__PURE__ */ new Map();
|
|
122
|
+
return {
|
|
123
|
+
read: /* @__PURE__ */ __name(async (key) => values.get(key) ?? null, "read"),
|
|
124
|
+
write: /* @__PURE__ */ __name(async (key, value) => {
|
|
125
|
+
values.set(key, value);
|
|
126
|
+
}, "write"),
|
|
127
|
+
remove: /* @__PURE__ */ __name(async (key) => {
|
|
128
|
+
values.delete(key);
|
|
129
|
+
}, "remove"),
|
|
130
|
+
keys: /* @__PURE__ */ __name(() => [...values.keys()], "keys"),
|
|
131
|
+
clear: /* @__PURE__ */ __name(async () => {
|
|
132
|
+
values.clear();
|
|
133
|
+
}, "clear")
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
__name(createMemoryAuthStateStore, "createMemoryAuthStateStore");
|
|
137
|
+
var CREDS_KEY = "creds";
|
|
138
|
+
var APP_STATE_SYNC_KEY = "app-state-sync-key";
|
|
139
|
+
async function loadAuthState(baileys, store) {
|
|
140
|
+
const encode = /* @__PURE__ */ __name((value) => JSON.stringify(value, baileys.BufferJSON.replacer), "encode");
|
|
141
|
+
const decode = /* @__PURE__ */ __name((text2) => text2 === null ? null : JSON.parse(text2, baileys.BufferJSON.reviver), "decode");
|
|
142
|
+
const stored = decode(await store.read(CREDS_KEY));
|
|
143
|
+
const isNew = stored === null || typeof stored !== "object";
|
|
144
|
+
const creds = isNew ? baileys.initAuthCreds() : stored;
|
|
145
|
+
const appStateKey = baileys.proto?.Message?.AppStateSyncKeyData;
|
|
146
|
+
const state = {
|
|
147
|
+
creds,
|
|
148
|
+
keys: {
|
|
149
|
+
get: /* @__PURE__ */ __name(async (type, ids) => {
|
|
150
|
+
const found = {};
|
|
151
|
+
await Promise.all(
|
|
152
|
+
ids.map(async (id) => {
|
|
153
|
+
let value = decode(await store.read(`${type}-${id}`));
|
|
154
|
+
if (type === APP_STATE_SYNC_KEY && value && appStateKey) value = appStateKey.fromObject(value);
|
|
155
|
+
found[id] = value ?? void 0;
|
|
156
|
+
})
|
|
157
|
+
);
|
|
158
|
+
return found;
|
|
159
|
+
}, "get"),
|
|
160
|
+
set: /* @__PURE__ */ __name(async (data) => {
|
|
161
|
+
const writes = Object.entries(data).flatMap(
|
|
162
|
+
([category, entries]) => Object.entries(entries).map(([id, value]) => value ? store.write(`${category}-${id}`, encode(value)) : store.remove(`${category}-${id}`))
|
|
163
|
+
);
|
|
164
|
+
await Promise.all(writes);
|
|
165
|
+
}, "set")
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
return { state, saveCreds: /* @__PURE__ */ __name(() => store.write(CREDS_KEY, encode(creds)), "saveCreds"), isNew };
|
|
169
|
+
}
|
|
170
|
+
__name(loadAuthState, "loadAuthState");
|
|
171
|
+
async function clearAuthState(store) {
|
|
172
|
+
if (store.clear) await store.clear();
|
|
173
|
+
else await store.remove(CREDS_KEY);
|
|
174
|
+
}
|
|
175
|
+
__name(clearAuthState, "clearAuthState");
|
|
176
|
+
|
|
177
|
+
// src/whatsapp-web/baileys-port.ts
|
|
178
|
+
var DISCONNECT = {
|
|
179
|
+
/** The phone unlinked this device, or the session was logged out: never reconnect. */
|
|
180
|
+
loggedOut: 401,
|
|
181
|
+
/** Another client took the session over. Reconnecting would fight it: stop. */
|
|
182
|
+
connectionReplaced: 440,
|
|
183
|
+
/** The account is banned or the session is unusable: stop. */
|
|
184
|
+
forbidden: 403,
|
|
185
|
+
/** Baileys asks for a fresh socket right after pairing: reconnect at once. */
|
|
186
|
+
restartRequired: 515
|
|
187
|
+
};
|
|
188
|
+
function disconnectCode(disconnect) {
|
|
189
|
+
const error = disconnect?.error;
|
|
190
|
+
if (!error || typeof error !== "object" || !("output" in error)) return null;
|
|
191
|
+
const code = error.output?.statusCode;
|
|
192
|
+
return typeof code === "number" ? code : null;
|
|
193
|
+
}
|
|
194
|
+
__name(disconnectCode, "disconnectCode");
|
|
195
|
+
|
|
196
|
+
// src/whatsapp-web/choices.ts
|
|
197
|
+
function choicesOf(content2) {
|
|
198
|
+
if (content2.kind === "TEXT") return [];
|
|
199
|
+
if (content2.kind === "BUTTONS") return content2.buttons.map((button) => ({ replyId: button.id, title: button.title }));
|
|
200
|
+
return content2.sections.flatMap((section) => section.rows.map((row) => ({ replyId: row.id, title: row.title })));
|
|
201
|
+
}
|
|
202
|
+
__name(choicesOf, "choicesOf");
|
|
203
|
+
function foldTitle(value) {
|
|
204
|
+
return value.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/\s+/g, " ").trim();
|
|
205
|
+
}
|
|
206
|
+
__name(foldTitle, "foldTitle");
|
|
207
|
+
function listedNumber(value) {
|
|
208
|
+
const text2 = value.trim();
|
|
209
|
+
if (text2.length > 8) return null;
|
|
210
|
+
const match = /^(\d{1,3})(?:\s*[.)])?$/.exec(text2);
|
|
211
|
+
return match ? Number(match[1]) : null;
|
|
212
|
+
}
|
|
213
|
+
__name(listedNumber, "listedNumber");
|
|
214
|
+
var ChoiceMemory = class {
|
|
215
|
+
static {
|
|
216
|
+
__name(this, "ChoiceMemory");
|
|
217
|
+
}
|
|
218
|
+
offers = /* @__PURE__ */ new Map();
|
|
219
|
+
maxContacts;
|
|
220
|
+
ttlMs;
|
|
221
|
+
now;
|
|
222
|
+
constructor(options = {}) {
|
|
223
|
+
this.maxContacts = options.maxContacts ?? 500;
|
|
224
|
+
this.ttlMs = options.ttlMs ?? 2 * 60 * 60 * 1e3;
|
|
225
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
226
|
+
}
|
|
227
|
+
/** Remember what was just sent to a contact: its choices replace the earlier offer, and plain text clears it. */
|
|
228
|
+
offer(contactId, content2) {
|
|
229
|
+
const choices = choicesOf(content2);
|
|
230
|
+
this.offers.delete(contactId);
|
|
231
|
+
if (choices.length === 0) return;
|
|
232
|
+
this.offers.set(contactId, { choices, folded: choices.map((choice) => foldTitle(choice.title)), at: this.now().getTime() });
|
|
233
|
+
for (const oldest of this.offers.keys()) {
|
|
234
|
+
if (this.offers.size <= this.maxContacts) break;
|
|
235
|
+
this.offers.delete(oldest);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* The choice a typed answer stands for, or null. A listed number wins over a
|
|
240
|
+
* title. A match uses the offer up (the answer was given); a miss, an
|
|
241
|
+
* expired offer or a contact never offered anything clears nothing.
|
|
242
|
+
*/
|
|
243
|
+
resolve(contactId, answer) {
|
|
244
|
+
const offer = this.offers.get(contactId);
|
|
245
|
+
if (!offer) return null;
|
|
246
|
+
if (this.now().getTime() - offer.at > this.ttlMs) {
|
|
247
|
+
this.offers.delete(contactId);
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
const number = listedNumber(answer);
|
|
251
|
+
const index = number === null ? offer.folded.indexOf(foldTitle(answer)) : number - 1;
|
|
252
|
+
const choice = offer.choices[index];
|
|
253
|
+
if (!choice || index < 0) return null;
|
|
254
|
+
this.offers.delete(contactId);
|
|
255
|
+
return choice;
|
|
256
|
+
}
|
|
257
|
+
/** Something else was said to the contact since: the offer no longer maps their reply. */
|
|
258
|
+
forget(contactId) {
|
|
259
|
+
this.offers.delete(contactId);
|
|
260
|
+
}
|
|
261
|
+
get size() {
|
|
262
|
+
return this.offers.size;
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
function applyChoices(memory, events) {
|
|
266
|
+
return events.map((event2) => {
|
|
267
|
+
if (event2.type === "sent_elsewhere") memory.forget(event2.contactId);
|
|
268
|
+
if (event2.type !== "message" || event2.content.kind !== "TEXT") return event2;
|
|
269
|
+
const choice = memory.resolve(event2.contactId, event2.content.text);
|
|
270
|
+
const content2 = choice ? { kind: "INTERACTIVE", replyId: choice.replyId, title: choice.title } : null;
|
|
271
|
+
return content2 ? { ...event2, content: content2 } : event2;
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
__name(applyChoices, "applyChoices");
|
|
275
|
+
|
|
276
|
+
// src/whatsapp-web/normalize.ts
|
|
277
|
+
var isObject2 = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isObject");
|
|
278
|
+
var text = /* @__PURE__ */ __name((value) => typeof value === "string" && value.length > 0 ? value : null, "text");
|
|
279
|
+
var PN_SUFFIX = "@s.whatsapp.net";
|
|
280
|
+
var LID_SUFFIX = "@lid";
|
|
281
|
+
function jidUser(jid) {
|
|
282
|
+
const user = jid.slice(0, jid.indexOf("@") >= 0 ? jid.indexOf("@") : jid.length);
|
|
283
|
+
const colon = user.indexOf(":");
|
|
284
|
+
return colon >= 0 ? user.slice(0, colon) : user;
|
|
285
|
+
}
|
|
286
|
+
__name(jidUser, "jidUser");
|
|
287
|
+
function contactAddress(key) {
|
|
288
|
+
const candidates = [key.remoteJid, key.remoteJidAlt].filter((jid) => typeof jid === "string");
|
|
289
|
+
const pn = candidates.find((jid) => jid.endsWith(PN_SUFFIX));
|
|
290
|
+
if (pn) return jidUser(pn) || null;
|
|
291
|
+
const lid = candidates.find((jid) => jid.endsWith(LID_SUFFIX));
|
|
292
|
+
return lid ? `${jidUser(lid)}${LID_SUFFIX}` : null;
|
|
293
|
+
}
|
|
294
|
+
__name(contactAddress, "contactAddress");
|
|
295
|
+
function addressJid(address) {
|
|
296
|
+
if (address.includes("@")) return address;
|
|
297
|
+
const digits = address.replace(/\D/g, "");
|
|
298
|
+
return `${digits}${PN_SUFFIX}`;
|
|
299
|
+
}
|
|
300
|
+
__name(addressJid, "addressJid");
|
|
301
|
+
function replyAddress(to, sentKey) {
|
|
302
|
+
return contactAddress({ remoteJid: addressJid(to), remoteJidAlt: sentKey?.remoteJidAlt ?? null });
|
|
303
|
+
}
|
|
304
|
+
__name(replyAddress, "replyAddress");
|
|
305
|
+
function longNumber(value) {
|
|
306
|
+
if (typeof value === "number") return Number.isFinite(value) && value > 0 ? value : null;
|
|
307
|
+
if (typeof value === "string") return longNumber(Number(value));
|
|
308
|
+
if (isObject2(value) && typeof value.low === "number" && typeof value.high === "number") {
|
|
309
|
+
return longNumber(value.high * 2 ** 32 + (value.low >>> 0));
|
|
310
|
+
}
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
__name(longNumber, "longNumber");
|
|
314
|
+
var WRAPPERS = ["ephemeralMessage", "viewOnceMessage", "viewOnceMessageV2", "viewOnceMessageV2Extension", "documentWithCaptionMessage", "editedMessage"];
|
|
315
|
+
var NOT_CONTENT = /* @__PURE__ */ new Set(["messageContextInfo", "senderKeyDistributionMessage"]);
|
|
316
|
+
var SKIPPED = /* @__PURE__ */ new Set(["protocolMessage", "reactionMessage", "pollUpdateMessage", "keepInChatMessage"]);
|
|
317
|
+
function unwrapMessage(message) {
|
|
318
|
+
if (!isObject2(message)) return {};
|
|
319
|
+
for (const wrapper of WRAPPERS) {
|
|
320
|
+
const inner = message[wrapper];
|
|
321
|
+
if (isObject2(inner) && isObject2(inner.message)) return unwrapMessage(inner.message);
|
|
322
|
+
}
|
|
323
|
+
return message;
|
|
324
|
+
}
|
|
325
|
+
__name(unwrapMessage, "unwrapMessage");
|
|
326
|
+
var interactive = /* @__PURE__ */ __name((replyId, title) => text(replyId) ? { kind: "INTERACTIVE", replyId, title: text(title) ?? "" } : null, "interactive");
|
|
327
|
+
var READERS = {
|
|
328
|
+
conversation: /* @__PURE__ */ __name((body) => text(body) ? { kind: "TEXT", text: body } : null, "conversation"),
|
|
329
|
+
extendedTextMessage: /* @__PURE__ */ __name((body) => isObject2(body) && text(body.text) ? { kind: "TEXT", text: body.text } : null, "extendedTextMessage"),
|
|
330
|
+
buttonsResponseMessage: /* @__PURE__ */ __name((body) => isObject2(body) ? interactive(body.selectedButtonId, body.selectedDisplayText) : null, "buttonsResponseMessage"),
|
|
331
|
+
templateButtonReplyMessage: /* @__PURE__ */ __name((body) => isObject2(body) ? interactive(body.selectedId, body.selectedDisplayText) : null, "templateButtonReplyMessage"),
|
|
332
|
+
listResponseMessage: /* @__PURE__ */ __name((body) => isObject2(body) && isObject2(body.singleSelectReply) ? interactive(body.singleSelectReply.selectedRowId, body.title) : null, "listResponseMessage"),
|
|
333
|
+
// The media id is filled with the message id by the caller.
|
|
334
|
+
audioMessage: /* @__PURE__ */ __name((body) => isObject2(body) ? { kind: "AUDIO", mediaId: "", mimeType: text(body.mimetype) } : null, "audioMessage")
|
|
335
|
+
};
|
|
336
|
+
function contentOf(raw) {
|
|
337
|
+
const message = unwrapMessage(raw);
|
|
338
|
+
const type = Object.keys(message).find((key) => !NOT_CONTENT.has(key) && message[key] !== null && message[key] !== void 0);
|
|
339
|
+
if (!type || SKIPPED.has(type)) return null;
|
|
340
|
+
const reader = READERS[type];
|
|
341
|
+
return reader ? reader(message[type]) : { kind: "OTHER", channelType: type.replace(/Message$/, "") || type };
|
|
342
|
+
}
|
|
343
|
+
__name(contentOf, "contentOf");
|
|
344
|
+
function inboundEvent(accountId, message, keywords) {
|
|
345
|
+
if (!isObject2(message) || !isObject2(message.key) || message.key.fromMe) return null;
|
|
346
|
+
const id = text(message.key.id);
|
|
347
|
+
const contactId = contactAddress(message.key);
|
|
348
|
+
const seconds = longNumber(message.messageTimestamp);
|
|
349
|
+
const content2 = contentOf(message.message);
|
|
350
|
+
if (!id || !contactId || seconds === null || !content2) return null;
|
|
351
|
+
return {
|
|
352
|
+
type: "message",
|
|
353
|
+
accountId,
|
|
354
|
+
contactId,
|
|
355
|
+
contactName: text(message.pushName),
|
|
356
|
+
externalId: id,
|
|
357
|
+
sentAt: new Date(seconds * 1e3),
|
|
358
|
+
// An audio's media id is the message's own id: the session keeps the message to download it.
|
|
359
|
+
content: content2.kind === "AUDIO" ? { ...content2, mediaId: id } : content2,
|
|
360
|
+
optOut: content2.kind === "TEXT" && isOptOutText(content2.text, keywords)
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
__name(inboundEvent, "inboundEvent");
|
|
364
|
+
function normalizeUpsert(accountId, upsert, options = {}) {
|
|
365
|
+
if (upsert.type !== "notify") return [];
|
|
366
|
+
const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;
|
|
367
|
+
return upsert.messages.map((message) => inboundEvent(accountId, message, keywords)).filter((event2) => event2 !== null);
|
|
368
|
+
}
|
|
369
|
+
__name(normalizeUpsert, "normalizeUpsert");
|
|
370
|
+
function sentContent(raw) {
|
|
371
|
+
const content2 = contentOf(raw);
|
|
372
|
+
if (!content2) return null;
|
|
373
|
+
if (content2.kind === "AUDIO") return { kind: "OTHER", channelType: "audio" };
|
|
374
|
+
return content2.kind === "INTERACTIVE" ? { kind: "TEXT", text: content2.title } : content2;
|
|
375
|
+
}
|
|
376
|
+
__name(sentContent, "sentContent");
|
|
377
|
+
function sentElsewhereEvent2(accountId, message) {
|
|
378
|
+
if (!isObject2(message) || !isObject2(message.key) || !message.key.fromMe) return null;
|
|
379
|
+
const id = text(message.key.id);
|
|
380
|
+
const contactId = contactAddress(message.key);
|
|
381
|
+
const seconds = longNumber(message.messageTimestamp);
|
|
382
|
+
const content2 = sentContent(message.message);
|
|
383
|
+
if (!id || !contactId || seconds === null || !content2) return null;
|
|
384
|
+
return { type: "sent_elsewhere", accountId, contactId, externalId: id, sentAt: new Date(seconds * 1e3), content: content2 };
|
|
385
|
+
}
|
|
386
|
+
__name(sentElsewhereEvent2, "sentElsewhereEvent");
|
|
387
|
+
function normalizeSentElsewhere(accountId, upsert) {
|
|
388
|
+
if (upsert.type !== "notify") return [];
|
|
389
|
+
return upsert.messages.map((message) => sentElsewhereEvent2(accountId, message)).filter((event2) => event2 !== null);
|
|
390
|
+
}
|
|
391
|
+
__name(normalizeSentElsewhere, "normalizeSentElsewhere");
|
|
392
|
+
function receiptOf(status) {
|
|
393
|
+
switch (status) {
|
|
394
|
+
case 0:
|
|
395
|
+
return "FAILED";
|
|
396
|
+
case 2:
|
|
397
|
+
return "SENT";
|
|
398
|
+
case 3:
|
|
399
|
+
return "DELIVERED";
|
|
400
|
+
case 4:
|
|
401
|
+
case 5:
|
|
402
|
+
return "READ";
|
|
403
|
+
default:
|
|
404
|
+
return null;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
__name(receiptOf, "receiptOf");
|
|
408
|
+
function normalizeUpdates(accountId, updates, at) {
|
|
409
|
+
const events = [];
|
|
410
|
+
for (const entry of updates) {
|
|
411
|
+
if (!isObject2(entry) || !isObject2(entry.key) || !entry.key.fromMe || !isObject2(entry.update)) continue;
|
|
412
|
+
const id = text(entry.key.id);
|
|
413
|
+
const status = receiptOf(entry.update.status);
|
|
414
|
+
if (!id || !status) continue;
|
|
415
|
+
events.push({
|
|
416
|
+
type: "status",
|
|
417
|
+
accountId,
|
|
418
|
+
externalId: id,
|
|
419
|
+
status,
|
|
420
|
+
at,
|
|
421
|
+
contactId: contactAddress(entry.key),
|
|
422
|
+
error: status === "FAILED" ? "ERROR" : null,
|
|
423
|
+
callbackData: null
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
return events;
|
|
427
|
+
}
|
|
428
|
+
__name(normalizeUpdates, "normalizeUpdates");
|
|
429
|
+
|
|
430
|
+
// src/whatsapp-web/timers.ts
|
|
431
|
+
var systemTimers = {
|
|
432
|
+
setTimeout: /* @__PURE__ */ __name((run, ms) => {
|
|
433
|
+
const handle = setTimeout(run, ms);
|
|
434
|
+
handle.unref?.();
|
|
435
|
+
return handle;
|
|
436
|
+
}, "setTimeout"),
|
|
437
|
+
clearTimeout: /* @__PURE__ */ __name((handle) => clearTimeout(handle), "clearTimeout")
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
// src/whatsapp-web/history.ts
|
|
441
|
+
var ON_DEMAND = 6;
|
|
442
|
+
var isOnDemand = /* @__PURE__ */ __name((syncType) => syncType === ON_DEMAND || syncType === "ON_DEMAND", "isOnDemand");
|
|
443
|
+
function kept(content2) {
|
|
444
|
+
switch (content2.kind) {
|
|
445
|
+
case "TEXT":
|
|
446
|
+
return { text: content2.text, kind: "text" };
|
|
447
|
+
case "INTERACTIVE":
|
|
448
|
+
return { text: content2.title || null, kind: "interactive" };
|
|
449
|
+
case "AUDIO":
|
|
450
|
+
return { text: null, kind: "audio" };
|
|
451
|
+
default:
|
|
452
|
+
return { text: null, kind: content2.channelType.toLowerCase() };
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
__name(kept, "kept");
|
|
456
|
+
function historyMessage(message) {
|
|
457
|
+
const id = message?.key?.id;
|
|
458
|
+
const seconds = longNumber(message?.messageTimestamp);
|
|
459
|
+
const content2 = contentOf(message?.message);
|
|
460
|
+
if (typeof id !== "string" || id === "" || seconds === null || !content2) return null;
|
|
461
|
+
return { externalId: id, fromMe: message.key.fromMe === true, sentAt: new Date(seconds * 1e3), ...kept(content2) };
|
|
462
|
+
}
|
|
463
|
+
__name(historyMessage, "historyMessage");
|
|
464
|
+
var inChat = /* @__PURE__ */ __name((contactId, key) => contactAddress(key) === contactId || [key.remoteJid, key.remoteJidAlt].includes(addressJid(contactId)), "inChat");
|
|
465
|
+
function chatHistory(contactId, messages, count) {
|
|
466
|
+
const seen = /* @__PURE__ */ new Set();
|
|
467
|
+
const found = [];
|
|
468
|
+
for (const raw of messages) {
|
|
469
|
+
if (!raw?.key || !inChat(contactId, raw.key)) continue;
|
|
470
|
+
const message = historyMessage(raw);
|
|
471
|
+
if (!message || seen.has(message.externalId)) continue;
|
|
472
|
+
seen.add(message.externalId);
|
|
473
|
+
found.push(message);
|
|
474
|
+
}
|
|
475
|
+
found.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());
|
|
476
|
+
return count > 0 ? found.slice(-count) : [];
|
|
477
|
+
}
|
|
478
|
+
__name(chatHistory, "chatHistory");
|
|
479
|
+
var HistoryRequests = class {
|
|
480
|
+
constructor(timers = systemTimers) {
|
|
481
|
+
this.timers = timers;
|
|
482
|
+
}
|
|
483
|
+
timers;
|
|
484
|
+
static {
|
|
485
|
+
__name(this, "HistoryRequests");
|
|
486
|
+
}
|
|
487
|
+
/** Oldest first: an answer that names no request goes to the oldest one for its chat. */
|
|
488
|
+
pending = /* @__PURE__ */ new Set();
|
|
489
|
+
/**
|
|
490
|
+
* Ask, and wait for the answer without waiting on the call: `call` (which returns the request id) may never
|
|
491
|
+
* settle, and the deadline still ends the wait. A rejected call abandons the request and goes to `onError`.
|
|
492
|
+
*/
|
|
493
|
+
fetch(contactId, count, timeoutMs, call, onError) {
|
|
494
|
+
const wait = this.wait(contactId, count, timeoutMs);
|
|
495
|
+
Promise.resolve().then(call).then(wait.setRequestId, (error) => {
|
|
496
|
+
wait.abandon();
|
|
497
|
+
try {
|
|
498
|
+
onError(error);
|
|
499
|
+
} catch {
|
|
500
|
+
}
|
|
501
|
+
});
|
|
502
|
+
return wait.result;
|
|
503
|
+
}
|
|
504
|
+
/** Register a request BEFORE the call is made: the answer may beat the call's own return. The deadline is cleared once it settles. */
|
|
505
|
+
wait(contactId, count, timeoutMs) {
|
|
506
|
+
let entry;
|
|
507
|
+
let timer = null;
|
|
508
|
+
const result = new Promise((resolve) => {
|
|
509
|
+
entry = {
|
|
510
|
+
contactId,
|
|
511
|
+
count,
|
|
512
|
+
requestId: null,
|
|
513
|
+
settle: /* @__PURE__ */ __name((messages) => {
|
|
514
|
+
if (!this.pending.delete(entry)) return;
|
|
515
|
+
this.timers.clearTimeout(timer);
|
|
516
|
+
resolve(messages);
|
|
517
|
+
}, "settle")
|
|
518
|
+
};
|
|
519
|
+
});
|
|
520
|
+
this.pending.add(entry);
|
|
521
|
+
timer = this.timers.setTimeout(() => entry.settle([]), timeoutMs);
|
|
522
|
+
return { result, setRequestId: /* @__PURE__ */ __name((id) => void (entry.requestId = id), "setRequestId"), abandon: /* @__PURE__ */ __name(() => entry.settle([]), "abandon") };
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* A `messaging-history.set`. An answer naming a request id settles THAT request; one naming an id nobody holds
|
|
526
|
+
* yet, or none, settles the oldest request for its chat whose id it cannot contradict. A late answer is dropped.
|
|
527
|
+
*/
|
|
528
|
+
answer(set) {
|
|
529
|
+
if (!isOnDemand(set.syncType) || !Array.isArray(set.messages)) return;
|
|
530
|
+
const named = typeof set.peerDataRequestSessionId === "string" ? set.peerDataRequestSessionId : null;
|
|
531
|
+
const entries = [...this.pending];
|
|
532
|
+
const exact = named ? entries.find((entry) => entry.requestId === named) : void 0;
|
|
533
|
+
const candidates = exact ? [exact] : entries.filter((entry) => !named || entry.requestId === null);
|
|
534
|
+
for (const entry of candidates) {
|
|
535
|
+
const messages = chatHistory(entry.contactId, set.messages, entry.count);
|
|
536
|
+
if (messages.length === 0) continue;
|
|
537
|
+
entry.settle(messages);
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
/** The socket closed: nothing more will come. */
|
|
542
|
+
flush() {
|
|
543
|
+
for (const entry of [...this.pending]) entry.settle([]);
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
// src/whatsapp-web/own-sends.ts
|
|
548
|
+
var OwnSends = class {
|
|
549
|
+
/** `release` gets the held events that turned out to be from another device, when they are judged. */
|
|
550
|
+
constructor(release, options = {}) {
|
|
551
|
+
this.release = release;
|
|
552
|
+
this.timers = options.timers ?? systemTimers;
|
|
553
|
+
this.maxHoldMs = options.maxHoldMs ?? 3e4;
|
|
554
|
+
this.maxHeld = options.maxHeld ?? 200;
|
|
555
|
+
this.remembered = options.remembered ?? 1e3;
|
|
556
|
+
}
|
|
557
|
+
release;
|
|
558
|
+
static {
|
|
559
|
+
__name(this, "OwnSends");
|
|
560
|
+
}
|
|
561
|
+
ids = /* @__PURE__ */ new Set();
|
|
562
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
563
|
+
sequence = 0;
|
|
564
|
+
held = [];
|
|
565
|
+
timers;
|
|
566
|
+
maxHoldMs;
|
|
567
|
+
maxHeld;
|
|
568
|
+
remembered;
|
|
569
|
+
/** Run one send. Its id is remembered whether the caller or the echo gets there first. */
|
|
570
|
+
async track(run) {
|
|
571
|
+
this.sequence += 1;
|
|
572
|
+
const send = this.sequence;
|
|
573
|
+
this.inFlight.add(send);
|
|
574
|
+
let id = null;
|
|
575
|
+
try {
|
|
576
|
+
const result = await run();
|
|
577
|
+
id = result.externalId;
|
|
578
|
+
return result;
|
|
579
|
+
} finally {
|
|
580
|
+
this.inFlight.delete(send);
|
|
581
|
+
if (id) this.remember(id);
|
|
582
|
+
for (const entry of this.held) entry.waitingOn.delete(send);
|
|
583
|
+
this.releaseWhere((entry) => entry.waitingOn.size === 0);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
/** The events to hand on NOW: not our own, and none while a send is in flight (those are held). */
|
|
587
|
+
accept(events) {
|
|
588
|
+
if (this.inFlight.size === 0) return this.judge(events);
|
|
589
|
+
for (const event2 of events) this.hold(event2);
|
|
590
|
+
const excess = new Set(this.held.slice(0, Math.max(0, this.held.length - this.maxHeld)));
|
|
591
|
+
this.releaseWhere((entry) => excess.has(entry));
|
|
592
|
+
return [];
|
|
593
|
+
}
|
|
594
|
+
/** The socket closed: release everything held, and hold nothing for the sends that were in flight. */
|
|
595
|
+
reset() {
|
|
596
|
+
this.inFlight.clear();
|
|
597
|
+
this.releaseWhere(() => true);
|
|
598
|
+
}
|
|
599
|
+
hold(event2) {
|
|
600
|
+
const entry = { event: event2, waitingOn: new Set(this.inFlight), timer: null };
|
|
601
|
+
entry.timer = this.timers.setTimeout(() => this.releaseWhere((held) => held === entry), this.maxHoldMs);
|
|
602
|
+
this.held.push(entry);
|
|
603
|
+
}
|
|
604
|
+
/** Release the held entries `done` picks, in the order they arrived, judged against the ids known now. */
|
|
605
|
+
releaseWhere(done) {
|
|
606
|
+
const out = [];
|
|
607
|
+
const kept2 = [];
|
|
608
|
+
for (const entry of this.held) (done(entry) ? out : kept2).push(entry);
|
|
609
|
+
if (out.length === 0) return;
|
|
610
|
+
this.held = kept2;
|
|
611
|
+
for (const entry of out) this.timers.clearTimeout(entry.timer);
|
|
612
|
+
const events = this.judge(out.map((entry) => entry.event));
|
|
613
|
+
if (events.length > 0) this.release(events);
|
|
614
|
+
}
|
|
615
|
+
judge(events) {
|
|
616
|
+
return events.filter((event2) => !this.ids.has(event2.externalId));
|
|
617
|
+
}
|
|
618
|
+
remember(id) {
|
|
619
|
+
this.ids.add(id);
|
|
620
|
+
for (const oldest of this.ids) {
|
|
621
|
+
if (this.ids.size <= this.remembered) break;
|
|
622
|
+
this.ids.delete(oldest);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
|
|
627
|
+
// src/whatsapp-web/media.ts
|
|
628
|
+
var AudioCache = class {
|
|
629
|
+
constructor(size) {
|
|
630
|
+
this.size = size;
|
|
631
|
+
}
|
|
632
|
+
size;
|
|
633
|
+
static {
|
|
634
|
+
__name(this, "AudioCache");
|
|
635
|
+
}
|
|
636
|
+
messages = /* @__PURE__ */ new Map();
|
|
637
|
+
/** Keep `message` if it is an audio. The oldest is dropped past the size. */
|
|
638
|
+
remember(message) {
|
|
639
|
+
const id = message.key?.id;
|
|
640
|
+
if (!id || !audioOf(message)) return;
|
|
641
|
+
this.messages.set(id, message);
|
|
642
|
+
while (this.messages.size > this.size) this.messages.delete(this.messages.keys().next().value);
|
|
643
|
+
}
|
|
644
|
+
get(id) {
|
|
645
|
+
return this.messages.get(id);
|
|
646
|
+
}
|
|
647
|
+
};
|
|
648
|
+
function audioOf(message) {
|
|
649
|
+
const audio = unwrapMessage(message.message).audioMessage;
|
|
650
|
+
return typeof audio === "object" && audio !== null ? audio : null;
|
|
651
|
+
}
|
|
652
|
+
__name(audioOf, "audioOf");
|
|
653
|
+
async function withDeadline(work, ms) {
|
|
654
|
+
let timer;
|
|
655
|
+
const deadline = new Promise((_, reject) => {
|
|
656
|
+
timer = setTimeout(() => reject(new ChannelMediaFailure("TIMEOUT", `media download passed its ${ms} ms deadline`)), ms);
|
|
657
|
+
});
|
|
658
|
+
try {
|
|
659
|
+
return await Promise.race([work, deadline]);
|
|
660
|
+
} finally {
|
|
661
|
+
clearTimeout(timer);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
__name(withDeadline, "withDeadline");
|
|
665
|
+
function refuseOverCap(size, maxBytes, what) {
|
|
666
|
+
if (size !== null && size > maxBytes) throw new ChannelMediaFailure("TOO_LARGE", `the media ${what} ${size} bytes, over ${maxBytes}`);
|
|
667
|
+
}
|
|
668
|
+
__name(refuseOverCap, "refuseOverCap");
|
|
669
|
+
async function downloadAudio(input) {
|
|
670
|
+
const audio = input.message ? audioOf(input.message) : null;
|
|
671
|
+
if (!input.message || !audio) throw new ChannelMediaFailure("NOT_FOUND", "no recent audio with this id in this session");
|
|
672
|
+
refuseOverCap(longNumber(audio.fileLength), input.maxBytes, "declares");
|
|
673
|
+
const ctx = {
|
|
674
|
+
...input.logger ? { logger: input.logger } : {},
|
|
675
|
+
...input.reupload ? { reuploadRequest: input.reupload } : {}
|
|
676
|
+
};
|
|
677
|
+
const bytes = await withDeadline(input.baileys.downloadMediaMessage(input.message, "buffer", {}, ctx), input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS).catch(
|
|
678
|
+
(error) => {
|
|
679
|
+
throw error instanceof ChannelMediaFailure ? error : new ChannelMediaFailure("DOWNLOAD_FAILED", "the media could not be downloaded");
|
|
680
|
+
}
|
|
681
|
+
);
|
|
682
|
+
refuseOverCap(bytes.length, input.maxBytes, "is");
|
|
683
|
+
const mimeType = typeof audio.mimetype === "string" && audio.mimetype ? audio.mimetype : "application/octet-stream";
|
|
684
|
+
return { bytes: new Uint8Array(bytes), mimeType, size: bytes.length };
|
|
685
|
+
}
|
|
686
|
+
__name(downloadAudio, "downloadAudio");
|
|
687
|
+
|
|
688
|
+
// src/whatsapp-web/session.ts
|
|
689
|
+
function renderOutboundText(content2) {
|
|
690
|
+
if (content2.kind === "TEXT") return content2.text;
|
|
691
|
+
if (content2.kind === "BUTTONS") return [content2.text, "", ...content2.buttons.map((button, i) => `${i + 1}. ${button.title}`)].join("\n");
|
|
692
|
+
let n = 0;
|
|
693
|
+
const sections = content2.sections.map((section) => [
|
|
694
|
+
"",
|
|
695
|
+
...section.title ? [`*${section.title}*`] : [],
|
|
696
|
+
...section.rows.map((row) => `${++n}. ${row.title}${row.description ? ` \u2014 ${row.description}` : ""}`)
|
|
697
|
+
]);
|
|
698
|
+
return [content2.text, ...sections.flat()].join("\n");
|
|
699
|
+
}
|
|
700
|
+
__name(renderOutboundText, "renderOutboundText");
|
|
701
|
+
var defaultSleep = /* @__PURE__ */ __name((ms) => new Promise((resolve) => setTimeout(resolve, ms)), "defaultSleep");
|
|
702
|
+
var TERMINAL = {
|
|
703
|
+
[DISCONNECT.connectionReplaced]: "replaced",
|
|
704
|
+
[DISCONNECT.forbidden]: "forbidden"
|
|
705
|
+
};
|
|
706
|
+
var BaileysSession = class {
|
|
707
|
+
constructor(config) {
|
|
708
|
+
this.config = config;
|
|
709
|
+
this.history = new HistoryRequests(config.timers);
|
|
710
|
+
this.ownSends = new OwnSends((events) => this.deliver(applyChoices(this.choices, events)), config.timers ? { timers: config.timers } : {});
|
|
711
|
+
this.audio = new AudioCache(config.mediaCacheSize ?? 200);
|
|
712
|
+
this.choices = new ChoiceMemory({
|
|
713
|
+
...config.choiceMemorySize !== void 0 ? { maxContacts: config.choiceMemorySize } : {},
|
|
714
|
+
...config.choiceTtlMs !== void 0 ? { ttlMs: config.choiceTtlMs } : {},
|
|
715
|
+
now: /* @__PURE__ */ __name(() => (config.now ?? (() => /* @__PURE__ */ new Date()))(), "now")
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
config;
|
|
719
|
+
static {
|
|
720
|
+
__name(this, "BaileysSession");
|
|
721
|
+
}
|
|
722
|
+
socket = null;
|
|
723
|
+
current = { state: "idle" };
|
|
724
|
+
account = null;
|
|
725
|
+
attempts = 0;
|
|
726
|
+
stopping = false;
|
|
727
|
+
pairingRequested = false;
|
|
728
|
+
deliveries = Promise.resolve();
|
|
729
|
+
audio;
|
|
730
|
+
choices;
|
|
731
|
+
history;
|
|
732
|
+
ownSends;
|
|
733
|
+
status = /* @__PURE__ */ __name(() => this.current, "status");
|
|
734
|
+
accountId = /* @__PURE__ */ __name(() => this.account, "accountId");
|
|
735
|
+
async start() {
|
|
736
|
+
if (this.socket) return;
|
|
737
|
+
this.stopping = false;
|
|
738
|
+
this.attempts = 0;
|
|
739
|
+
this.pairingRequested = false;
|
|
740
|
+
try {
|
|
741
|
+
await this.open();
|
|
742
|
+
} catch (error) {
|
|
743
|
+
this.socket = null;
|
|
744
|
+
this.setStatus({ state: "failed", code: null, reason: "start-failed" });
|
|
745
|
+
throw error;
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
async stop() {
|
|
749
|
+
const sock = this.detach();
|
|
750
|
+
if (sock) await sock.end(void 0);
|
|
751
|
+
this.setStatus({ state: "stopped" });
|
|
752
|
+
}
|
|
753
|
+
async logout() {
|
|
754
|
+
const sock = this.detach();
|
|
755
|
+
if (sock) await sock.logout();
|
|
756
|
+
await clearAuthState(this.config.authStore);
|
|
757
|
+
this.setStatus({ state: "logged-out", code: null });
|
|
758
|
+
}
|
|
759
|
+
async send(to, content2) {
|
|
760
|
+
const sock = this.socket;
|
|
761
|
+
if (!sock || this.current.state !== "open") throw new ChannelSendFailure("NOT_CONNECTED", "the WhatsApp Web session is not open");
|
|
762
|
+
const { externalId, key } = await this.ownSends.track(() => this.dispatch(sock, to, content2));
|
|
763
|
+
const contact = replyAddress(to, key);
|
|
764
|
+
if (contact) this.choices.offer(contact, content2);
|
|
765
|
+
return { externalId };
|
|
766
|
+
}
|
|
767
|
+
async dispatch(sock, to, content2) {
|
|
768
|
+
const sent = await sock.sendMessage(addressJid(to), { text: renderOutboundText(content2) }).catch((error) => {
|
|
769
|
+
const code = disconnectCode({ error });
|
|
770
|
+
throw new ChannelSendFailure(code === null ? "SEND_FAILED" : String(code), "the WhatsApp Web socket refused the send");
|
|
771
|
+
});
|
|
772
|
+
const externalId = sent?.key?.id;
|
|
773
|
+
if (!externalId) throw new ChannelSendFailure("NO_MESSAGE_ID", "the WhatsApp Web socket returned no message id");
|
|
774
|
+
return { externalId, key: sent?.key ?? {} };
|
|
775
|
+
}
|
|
776
|
+
sendPresence(contactId, state) {
|
|
777
|
+
return this.fireAndForget("presence", (sock) => sock.sendPresenceUpdate(state, addressJid(contactId)));
|
|
778
|
+
}
|
|
779
|
+
markRead(contactId, externalIds) {
|
|
780
|
+
if (externalIds.length === 0) return Promise.resolve();
|
|
781
|
+
const remoteJid = addressJid(contactId);
|
|
782
|
+
return this.fireAndForget("mark-read", (sock) => sock.readMessages(externalIds.map((id) => ({ remoteJid, id, fromMe: false }))));
|
|
783
|
+
}
|
|
784
|
+
/** One call on the open socket whose failure is reported, never thrown. */
|
|
785
|
+
async fireAndForget(where, call) {
|
|
786
|
+
const sock = this.socket;
|
|
787
|
+
try {
|
|
788
|
+
if (!sock || this.current.state !== "open") throw new ChannelSendFailure("NOT_CONNECTED", "the WhatsApp Web session is not open");
|
|
789
|
+
await call(sock);
|
|
790
|
+
} catch (error) {
|
|
791
|
+
this.config.onError?.(error, where);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
async fetchHistory(contactId, anchor, count, timeoutMs) {
|
|
795
|
+
const sock = this.socket;
|
|
796
|
+
if (!sock || this.current.state !== "open" || count <= 0) return [];
|
|
797
|
+
const key = { remoteJid: addressJid(contactId), id: anchor.externalId, fromMe: anchor.fromMe };
|
|
798
|
+
const call = /* @__PURE__ */ __name(() => sock.fetchMessageHistory(count, key, Math.floor(anchor.sentAt.getTime() / 1e3)), "call");
|
|
799
|
+
return this.history.fetch(contactId, count, timeoutMs, call, (error) => this.config.onError?.(error, "history"));
|
|
800
|
+
}
|
|
801
|
+
downloadMedia(mediaId, options) {
|
|
802
|
+
const sock = this.socket;
|
|
803
|
+
return downloadAudio({
|
|
804
|
+
baileys: this.config.baileys,
|
|
805
|
+
message: this.audio.get(mediaId),
|
|
806
|
+
maxBytes: options.maxBytes,
|
|
807
|
+
timeoutMs: options.timeoutMs,
|
|
808
|
+
logger: this.config.logger,
|
|
809
|
+
reupload: sock?.updateMediaMessage ? (message) => sock.updateMediaMessage(message) : void 0
|
|
810
|
+
});
|
|
811
|
+
}
|
|
812
|
+
// ── The socket ──────────────────────────────────────────────────────────
|
|
813
|
+
detach() {
|
|
814
|
+
this.stopping = true;
|
|
815
|
+
const sock = this.socket;
|
|
816
|
+
this.socket = null;
|
|
817
|
+
this.account = null;
|
|
818
|
+
this.history.flush();
|
|
819
|
+
this.ownSends.reset();
|
|
820
|
+
return sock;
|
|
821
|
+
}
|
|
822
|
+
setStatus(status) {
|
|
823
|
+
this.current = status;
|
|
824
|
+
this.config.onStatus?.(status);
|
|
825
|
+
}
|
|
826
|
+
async open() {
|
|
827
|
+
this.setStatus({ state: "connecting" });
|
|
828
|
+
const { state, saveCreds } = await loadAuthState(this.config.baileys, this.config.authStore);
|
|
829
|
+
const sock = this.config.baileys.makeWASocket({
|
|
830
|
+
// The ONE boundary cast: the store holds Baileys' own values, which its key store types per category.
|
|
831
|
+
auth: state,
|
|
832
|
+
markOnlineOnConnect: false,
|
|
833
|
+
syncFullHistory: false,
|
|
834
|
+
...this.config.logger ? { logger: this.config.logger } : {},
|
|
835
|
+
...this.config.browser ? { browser: this.config.browser } : {}
|
|
836
|
+
});
|
|
837
|
+
this.socket = sock;
|
|
838
|
+
sock.ev.on("creds.update", () => {
|
|
839
|
+
saveCreds().catch((error) => this.config.onError?.(error, "save-creds"));
|
|
840
|
+
});
|
|
841
|
+
sock.ev.on("connection.update", (update) => {
|
|
842
|
+
if (sock === this.socket) void this.onConnection(sock, update);
|
|
843
|
+
});
|
|
844
|
+
sock.ev.on("messages.upsert", (upsert) => {
|
|
845
|
+
const account = this.linked(sock);
|
|
846
|
+
if (!account) return;
|
|
847
|
+
if (upsert.type === "notify") upsert.messages.forEach((message) => this.audio.remember(message));
|
|
848
|
+
const options = this.config.optOutKeywords ? { optOutKeywords: this.config.optOutKeywords } : {};
|
|
849
|
+
const events = upsert.messages.flatMap((message) => {
|
|
850
|
+
const one = { type: upsert.type, messages: [message] };
|
|
851
|
+
return [...normalizeUpsert(account, one, options), ...this.ownSends.accept(normalizeSentElsewhere(account, one))];
|
|
852
|
+
});
|
|
853
|
+
this.deliver(applyChoices(this.choices, events));
|
|
854
|
+
});
|
|
855
|
+
sock.ev.on("messaging-history.set", (set) => {
|
|
856
|
+
if (sock === this.socket) this.history.answer(set);
|
|
857
|
+
});
|
|
858
|
+
sock.ev.on("messages.update", (updates) => {
|
|
859
|
+
const account = this.linked(sock);
|
|
860
|
+
if (account) this.deliver(normalizeUpdates(account, updates, (this.config.now ?? (() => /* @__PURE__ */ new Date()))()));
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
/** The account a CURRENT socket is linked to: from the open event, or its own user while still opening. */
|
|
864
|
+
linked(sock) {
|
|
865
|
+
if (sock !== this.socket) return null;
|
|
866
|
+
return this.account ?? (sock.user?.id ? jidUser(sock.user.id) : null);
|
|
867
|
+
}
|
|
868
|
+
/** Hand one body to the host, after every earlier one: a socket's order is kept. */
|
|
869
|
+
deliver(events) {
|
|
870
|
+
if (events.length === 0) return;
|
|
871
|
+
const body = encodeEnvelope(events);
|
|
872
|
+
this.deliveries = this.deliveries.then(
|
|
873
|
+
() => this.config.deliver(body).then(
|
|
874
|
+
() => void 0,
|
|
875
|
+
(error) => this.config.onError?.(error, "deliver")
|
|
876
|
+
)
|
|
877
|
+
);
|
|
878
|
+
}
|
|
879
|
+
async onConnection(sock, update) {
|
|
880
|
+
if (update.qr) await this.onQr(sock, update.qr);
|
|
881
|
+
if (update.connection === "open") {
|
|
882
|
+
this.attempts = 0;
|
|
883
|
+
this.account = sock.user?.id ? jidUser(sock.user.id) : null;
|
|
884
|
+
this.setStatus(this.account ? { state: "open", accountId: this.account } : { state: "connecting" });
|
|
885
|
+
} else if (update.connection === "close") {
|
|
886
|
+
await this.onClose(disconnectCode(update.lastDisconnect));
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
async onQr(sock, qr) {
|
|
890
|
+
const phone = this.config.pairingPhoneNumber;
|
|
891
|
+
if (!phone) return this.setStatus({ state: "qr", qr });
|
|
892
|
+
if (this.pairingRequested) return;
|
|
893
|
+
this.pairingRequested = true;
|
|
894
|
+
try {
|
|
895
|
+
this.setStatus({ state: "pairing-code", code: await sock.requestPairingCode(phone.replace(/\D/g, "")) });
|
|
896
|
+
} catch (error) {
|
|
897
|
+
this.pairingRequested = false;
|
|
898
|
+
this.config.onError?.(error, "pairing-code");
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
async onClose(code) {
|
|
902
|
+
this.socket = null;
|
|
903
|
+
this.account = null;
|
|
904
|
+
this.history.flush();
|
|
905
|
+
this.ownSends.reset();
|
|
906
|
+
if (this.stopping) return this.setStatus({ state: "stopped" });
|
|
907
|
+
if (code === DISCONNECT.loggedOut) {
|
|
908
|
+
await clearAuthState(this.config.authStore);
|
|
909
|
+
return this.setStatus({ state: "logged-out", code });
|
|
910
|
+
}
|
|
911
|
+
const terminal = code === null ? void 0 : TERMINAL[code];
|
|
912
|
+
if (terminal) return this.setStatus({ state: "failed", code, reason: terminal });
|
|
913
|
+
if (code !== DISCONNECT.restartRequired && !await this.backOff(code)) return;
|
|
914
|
+
await this.open();
|
|
915
|
+
}
|
|
916
|
+
/** Wait before a reconnect; false when the attempts ran out or the session was stopped meanwhile. */
|
|
917
|
+
async backOff(code) {
|
|
918
|
+
const maxAttempts = this.config.reconnect?.maxAttempts ?? 5;
|
|
919
|
+
this.attempts += 1;
|
|
920
|
+
if (this.attempts > maxAttempts) {
|
|
921
|
+
this.setStatus({ state: "failed", code, reason: "reconnects-exhausted" });
|
|
922
|
+
return false;
|
|
923
|
+
}
|
|
924
|
+
this.setStatus({ state: "reconnecting", attempt: this.attempts, code });
|
|
925
|
+
await (this.config.sleep ?? defaultSleep)((this.config.reconnect?.delayMs ?? 2e3) * 2 ** (this.attempts - 1));
|
|
926
|
+
if (!this.stopping) return true;
|
|
927
|
+
this.setStatus({ state: "stopped" });
|
|
928
|
+
return false;
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
function createWhatsAppWebSession(config) {
|
|
932
|
+
return new BaileysSession(config);
|
|
933
|
+
}
|
|
934
|
+
__name(createWhatsAppWebSession, "createWhatsAppWebSession");
|
|
935
|
+
export {
|
|
936
|
+
ChoiceMemory,
|
|
937
|
+
DISCONNECT,
|
|
938
|
+
ENVELOPE_FORMAT,
|
|
939
|
+
addressJid,
|
|
940
|
+
clearAuthState,
|
|
941
|
+
contactAddress,
|
|
942
|
+
contentOf,
|
|
943
|
+
createMemoryAuthStateStore,
|
|
944
|
+
createWhatsAppWebAdapter,
|
|
945
|
+
createWhatsAppWebSession,
|
|
946
|
+
disconnectCode,
|
|
947
|
+
encodeEnvelope,
|
|
948
|
+
loadAuthState,
|
|
949
|
+
normalizeSentElsewhere,
|
|
950
|
+
normalizeUpdates,
|
|
951
|
+
normalizeUpsert,
|
|
952
|
+
parseEnvelope,
|
|
953
|
+
receiptOf,
|
|
954
|
+
renderOutboundText
|
|
955
|
+
};
|
|
956
|
+
//# sourceMappingURL=index.js.map
|