@12-apps/messaging 1.3.0 → 1.5.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 +155 -0
- package/dist/chunk-RXJNLPY4.js +560 -0
- package/dist/chunk-RXJNLPY4.js.map +1 -0
- package/dist/inbound-guard/index.d.ts +254 -0
- package/dist/inbound-guard/index.js +913 -0
- package/dist/inbound-guard/index.js.map +1 -0
- package/dist/whatsapp/index.js +22 -536
- package/dist/whatsapp/index.js.map +1 -1
- package/dist/whatsapp-web/index.d.ts +369 -0
- package/dist/whatsapp-web/index.js +588 -0
- package/dist/whatsapp-web/index.js.map +1 -0
- package/package.json +9 -1
- package/src/inbound-guard/classification.ts +143 -0
- package/src/inbound-guard/decode.ts +128 -0
- package/src/inbound-guard/index.ts +55 -0
- package/src/inbound-guard/normalize.ts +164 -0
- package/src/inbound-guard/rules-infra.ts +200 -0
- package/src/inbound-guard/rules-phrases.ts +167 -0
- package/src/inbound-guard/rules-types.ts +61 -0
- package/src/inbound-guard/rules.ts +89 -0
- package/src/inbound-guard/screen.ts +165 -0
- package/src/inbound-guard/wrap.ts +163 -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 +146 -0
- package/src/whatsapp-web/envelope.ts +87 -0
- package/src/whatsapp-web/index.ts +36 -0
- package/src/whatsapp-web/media.ts +78 -0
- package/src/whatsapp-web/normalize.ts +183 -0
- package/src/whatsapp-web/session.ts +306 -0
|
@@ -0,0 +1,588 @@
|
|
|
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
|
+
var EVENTS = {
|
|
66
|
+
message: messageEvent,
|
|
67
|
+
status: statusEvent,
|
|
68
|
+
opt_out: optOutEvent
|
|
69
|
+
};
|
|
70
|
+
function event(value) {
|
|
71
|
+
if (!isObject(value) || typeof value.type !== "string") return null;
|
|
72
|
+
const accountId = str(value.accountId);
|
|
73
|
+
return accountId ? EVENTS[value.type]?.(value, accountId) ?? null : null;
|
|
74
|
+
}
|
|
75
|
+
__name(event, "event");
|
|
76
|
+
function parseEnvelope(rawBody) {
|
|
77
|
+
const payload = JSON.parse(rawBody);
|
|
78
|
+
if (!isObject(payload) || payload.format !== ENVELOPE_FORMAT || !Array.isArray(payload.events)) return [];
|
|
79
|
+
return payload.events.map(event).filter((parsed) => parsed !== null);
|
|
80
|
+
}
|
|
81
|
+
__name(parseEnvelope, "parseEnvelope");
|
|
82
|
+
|
|
83
|
+
// src/whatsapp-web/adapter.ts
|
|
84
|
+
function createWhatsAppWebAdapter(config) {
|
|
85
|
+
const sessionFor = /* @__PURE__ */ __name((accountId) => {
|
|
86
|
+
if (typeof config.sessions === "function") return config.sessions(accountId);
|
|
87
|
+
return config.sessions.accountId() === accountId ? config.sessions : void 0;
|
|
88
|
+
}, "sessionFor");
|
|
89
|
+
return {
|
|
90
|
+
kind: config.kind ?? WHATSAPP_CHANNEL,
|
|
91
|
+
handshake: /* @__PURE__ */ __name(() => null, "handshake"),
|
|
92
|
+
verify: /* @__PURE__ */ __name(() => false, "verify"),
|
|
93
|
+
parse: parseEnvelope,
|
|
94
|
+
send: /* @__PURE__ */ __name(async ({ accountId, to, content: content2 }) => {
|
|
95
|
+
const session = sessionFor(accountId);
|
|
96
|
+
if (!session) throw new ChannelSendFailure("NOT_CONNECTED", "no open WhatsApp Web session for this account");
|
|
97
|
+
return session.send(to, content2);
|
|
98
|
+
}, "send"),
|
|
99
|
+
fetchMedia: /* @__PURE__ */ __name(async ({ accountId, mediaId, maxBytes, timeoutMs }) => {
|
|
100
|
+
const session = sessionFor(accountId);
|
|
101
|
+
if (!session) throw new ChannelMediaFailure("NOT_CONNECTED", "no open WhatsApp Web session for this account");
|
|
102
|
+
return session.downloadMedia(mediaId, { maxBytes, ...timeoutMs !== void 0 ? { timeoutMs } : {} });
|
|
103
|
+
}, "fetchMedia"),
|
|
104
|
+
policy: config.policy ?? OPEN_SEND_POLICY
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
__name(createWhatsAppWebAdapter, "createWhatsAppWebAdapter");
|
|
108
|
+
|
|
109
|
+
// src/whatsapp-web/auth-state.ts
|
|
110
|
+
function createMemoryAuthStateStore() {
|
|
111
|
+
const values = /* @__PURE__ */ new Map();
|
|
112
|
+
return {
|
|
113
|
+
read: /* @__PURE__ */ __name(async (key) => values.get(key) ?? null, "read"),
|
|
114
|
+
write: /* @__PURE__ */ __name(async (key, value) => {
|
|
115
|
+
values.set(key, value);
|
|
116
|
+
}, "write"),
|
|
117
|
+
remove: /* @__PURE__ */ __name(async (key) => {
|
|
118
|
+
values.delete(key);
|
|
119
|
+
}, "remove"),
|
|
120
|
+
keys: /* @__PURE__ */ __name(() => [...values.keys()], "keys"),
|
|
121
|
+
clear: /* @__PURE__ */ __name(async () => {
|
|
122
|
+
values.clear();
|
|
123
|
+
}, "clear")
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
__name(createMemoryAuthStateStore, "createMemoryAuthStateStore");
|
|
127
|
+
var CREDS_KEY = "creds";
|
|
128
|
+
var APP_STATE_SYNC_KEY = "app-state-sync-key";
|
|
129
|
+
async function loadAuthState(baileys, store) {
|
|
130
|
+
const encode = /* @__PURE__ */ __name((value) => JSON.stringify(value, baileys.BufferJSON.replacer), "encode");
|
|
131
|
+
const decode = /* @__PURE__ */ __name((text2) => text2 === null ? null : JSON.parse(text2, baileys.BufferJSON.reviver), "decode");
|
|
132
|
+
const stored = decode(await store.read(CREDS_KEY));
|
|
133
|
+
const isNew = stored === null || typeof stored !== "object";
|
|
134
|
+
const creds = isNew ? baileys.initAuthCreds() : stored;
|
|
135
|
+
const appStateKey = baileys.proto?.Message?.AppStateSyncKeyData;
|
|
136
|
+
const state = {
|
|
137
|
+
creds,
|
|
138
|
+
keys: {
|
|
139
|
+
get: /* @__PURE__ */ __name(async (type, ids) => {
|
|
140
|
+
const found = {};
|
|
141
|
+
await Promise.all(
|
|
142
|
+
ids.map(async (id) => {
|
|
143
|
+
let value = decode(await store.read(`${type}-${id}`));
|
|
144
|
+
if (type === APP_STATE_SYNC_KEY && value && appStateKey) value = appStateKey.fromObject(value);
|
|
145
|
+
found[id] = value ?? void 0;
|
|
146
|
+
})
|
|
147
|
+
);
|
|
148
|
+
return found;
|
|
149
|
+
}, "get"),
|
|
150
|
+
set: /* @__PURE__ */ __name(async (data) => {
|
|
151
|
+
const writes = Object.entries(data).flatMap(
|
|
152
|
+
([category, entries]) => Object.entries(entries).map(([id, value]) => value ? store.write(`${category}-${id}`, encode(value)) : store.remove(`${category}-${id}`))
|
|
153
|
+
);
|
|
154
|
+
await Promise.all(writes);
|
|
155
|
+
}, "set")
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
return { state, saveCreds: /* @__PURE__ */ __name(() => store.write(CREDS_KEY, encode(creds)), "saveCreds"), isNew };
|
|
159
|
+
}
|
|
160
|
+
__name(loadAuthState, "loadAuthState");
|
|
161
|
+
async function clearAuthState(store) {
|
|
162
|
+
if (store.clear) await store.clear();
|
|
163
|
+
else await store.remove(CREDS_KEY);
|
|
164
|
+
}
|
|
165
|
+
__name(clearAuthState, "clearAuthState");
|
|
166
|
+
|
|
167
|
+
// src/whatsapp-web/baileys-port.ts
|
|
168
|
+
var DISCONNECT = {
|
|
169
|
+
/** The phone unlinked this device, or the session was logged out: never reconnect. */
|
|
170
|
+
loggedOut: 401,
|
|
171
|
+
/** Another client took the session over. Reconnecting would fight it: stop. */
|
|
172
|
+
connectionReplaced: 440,
|
|
173
|
+
/** The account is banned or the session is unusable: stop. */
|
|
174
|
+
forbidden: 403,
|
|
175
|
+
/** Baileys asks for a fresh socket right after pairing: reconnect at once. */
|
|
176
|
+
restartRequired: 515
|
|
177
|
+
};
|
|
178
|
+
function disconnectCode(disconnect) {
|
|
179
|
+
const error = disconnect?.error;
|
|
180
|
+
if (!error || typeof error !== "object" || !("output" in error)) return null;
|
|
181
|
+
const code = error.output?.statusCode;
|
|
182
|
+
return typeof code === "number" ? code : null;
|
|
183
|
+
}
|
|
184
|
+
__name(disconnectCode, "disconnectCode");
|
|
185
|
+
|
|
186
|
+
// src/whatsapp-web/normalize.ts
|
|
187
|
+
var isObject2 = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isObject");
|
|
188
|
+
var text = /* @__PURE__ */ __name((value) => typeof value === "string" && value.length > 0 ? value : null, "text");
|
|
189
|
+
var PN_SUFFIX = "@s.whatsapp.net";
|
|
190
|
+
var LID_SUFFIX = "@lid";
|
|
191
|
+
function jidUser(jid) {
|
|
192
|
+
const user = jid.slice(0, jid.indexOf("@") >= 0 ? jid.indexOf("@") : jid.length);
|
|
193
|
+
const colon = user.indexOf(":");
|
|
194
|
+
return colon >= 0 ? user.slice(0, colon) : user;
|
|
195
|
+
}
|
|
196
|
+
__name(jidUser, "jidUser");
|
|
197
|
+
function contactAddress(key) {
|
|
198
|
+
const candidates = [key.remoteJid, key.remoteJidAlt].filter((jid) => typeof jid === "string");
|
|
199
|
+
const pn = candidates.find((jid) => jid.endsWith(PN_SUFFIX));
|
|
200
|
+
if (pn) return jidUser(pn) || null;
|
|
201
|
+
const lid = candidates.find((jid) => jid.endsWith(LID_SUFFIX));
|
|
202
|
+
return lid ? `${jidUser(lid)}${LID_SUFFIX}` : null;
|
|
203
|
+
}
|
|
204
|
+
__name(contactAddress, "contactAddress");
|
|
205
|
+
function addressJid(address) {
|
|
206
|
+
if (address.includes("@")) return address;
|
|
207
|
+
const digits = address.replace(/\D/g, "");
|
|
208
|
+
return `${digits}${PN_SUFFIX}`;
|
|
209
|
+
}
|
|
210
|
+
__name(addressJid, "addressJid");
|
|
211
|
+
function longNumber(value) {
|
|
212
|
+
if (typeof value === "number") return Number.isFinite(value) && value > 0 ? value : null;
|
|
213
|
+
if (typeof value === "string") return longNumber(Number(value));
|
|
214
|
+
if (isObject2(value) && typeof value.low === "number" && typeof value.high === "number") {
|
|
215
|
+
return longNumber(value.high * 2 ** 32 + (value.low >>> 0));
|
|
216
|
+
}
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
__name(longNumber, "longNumber");
|
|
220
|
+
var WRAPPERS = ["ephemeralMessage", "viewOnceMessage", "viewOnceMessageV2", "viewOnceMessageV2Extension", "documentWithCaptionMessage", "editedMessage"];
|
|
221
|
+
var NOT_CONTENT = /* @__PURE__ */ new Set(["messageContextInfo", "senderKeyDistributionMessage"]);
|
|
222
|
+
var SKIPPED = /* @__PURE__ */ new Set(["protocolMessage", "reactionMessage", "pollUpdateMessage", "keepInChatMessage"]);
|
|
223
|
+
function unwrapMessage(message) {
|
|
224
|
+
if (!isObject2(message)) return {};
|
|
225
|
+
for (const wrapper of WRAPPERS) {
|
|
226
|
+
const inner = message[wrapper];
|
|
227
|
+
if (isObject2(inner) && isObject2(inner.message)) return unwrapMessage(inner.message);
|
|
228
|
+
}
|
|
229
|
+
return message;
|
|
230
|
+
}
|
|
231
|
+
__name(unwrapMessage, "unwrapMessage");
|
|
232
|
+
var interactive = /* @__PURE__ */ __name((replyId, title) => text(replyId) ? { kind: "INTERACTIVE", replyId, title: text(title) ?? "" } : null, "interactive");
|
|
233
|
+
var READERS = {
|
|
234
|
+
conversation: /* @__PURE__ */ __name((body) => text(body) ? { kind: "TEXT", text: body } : null, "conversation"),
|
|
235
|
+
extendedTextMessage: /* @__PURE__ */ __name((body) => isObject2(body) && text(body.text) ? { kind: "TEXT", text: body.text } : null, "extendedTextMessage"),
|
|
236
|
+
buttonsResponseMessage: /* @__PURE__ */ __name((body) => isObject2(body) ? interactive(body.selectedButtonId, body.selectedDisplayText) : null, "buttonsResponseMessage"),
|
|
237
|
+
templateButtonReplyMessage: /* @__PURE__ */ __name((body) => isObject2(body) ? interactive(body.selectedId, body.selectedDisplayText) : null, "templateButtonReplyMessage"),
|
|
238
|
+
listResponseMessage: /* @__PURE__ */ __name((body) => isObject2(body) && isObject2(body.singleSelectReply) ? interactive(body.singleSelectReply.selectedRowId, body.title) : null, "listResponseMessage"),
|
|
239
|
+
// The media id is filled with the message id by the caller.
|
|
240
|
+
audioMessage: /* @__PURE__ */ __name((body) => isObject2(body) ? { kind: "AUDIO", mediaId: "", mimeType: text(body.mimetype) } : null, "audioMessage")
|
|
241
|
+
};
|
|
242
|
+
function contentOf(raw) {
|
|
243
|
+
const message = unwrapMessage(raw);
|
|
244
|
+
const type = Object.keys(message).find((key) => !NOT_CONTENT.has(key) && message[key] !== null && message[key] !== void 0);
|
|
245
|
+
if (!type || SKIPPED.has(type)) return null;
|
|
246
|
+
const reader = READERS[type];
|
|
247
|
+
return reader ? reader(message[type]) : { kind: "OTHER", channelType: type.replace(/Message$/, "") || type };
|
|
248
|
+
}
|
|
249
|
+
__name(contentOf, "contentOf");
|
|
250
|
+
function inboundEvent(accountId, message, keywords) {
|
|
251
|
+
if (!isObject2(message) || !isObject2(message.key) || message.key.fromMe) return null;
|
|
252
|
+
const id = text(message.key.id);
|
|
253
|
+
const contactId = contactAddress(message.key);
|
|
254
|
+
const seconds = longNumber(message.messageTimestamp);
|
|
255
|
+
const content2 = contentOf(message.message);
|
|
256
|
+
if (!id || !contactId || seconds === null || !content2) return null;
|
|
257
|
+
return {
|
|
258
|
+
type: "message",
|
|
259
|
+
accountId,
|
|
260
|
+
contactId,
|
|
261
|
+
contactName: text(message.pushName),
|
|
262
|
+
externalId: id,
|
|
263
|
+
sentAt: new Date(seconds * 1e3),
|
|
264
|
+
// An audio's media id is the message's own id: the session keeps the message to download it.
|
|
265
|
+
content: content2.kind === "AUDIO" ? { ...content2, mediaId: id } : content2,
|
|
266
|
+
optOut: content2.kind === "TEXT" && isOptOutText(content2.text, keywords)
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
__name(inboundEvent, "inboundEvent");
|
|
270
|
+
function normalizeUpsert(accountId, upsert, options = {}) {
|
|
271
|
+
if (upsert.type !== "notify") return [];
|
|
272
|
+
const keywords = options.optOutKeywords ?? DEFAULT_OPT_OUT_KEYWORDS;
|
|
273
|
+
return upsert.messages.map((message) => inboundEvent(accountId, message, keywords)).filter((event2) => event2 !== null);
|
|
274
|
+
}
|
|
275
|
+
__name(normalizeUpsert, "normalizeUpsert");
|
|
276
|
+
function receiptOf(status) {
|
|
277
|
+
switch (status) {
|
|
278
|
+
case 0:
|
|
279
|
+
return "FAILED";
|
|
280
|
+
case 2:
|
|
281
|
+
return "SENT";
|
|
282
|
+
case 3:
|
|
283
|
+
return "DELIVERED";
|
|
284
|
+
case 4:
|
|
285
|
+
case 5:
|
|
286
|
+
return "READ";
|
|
287
|
+
default:
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
__name(receiptOf, "receiptOf");
|
|
292
|
+
function normalizeUpdates(accountId, updates, at) {
|
|
293
|
+
const events = [];
|
|
294
|
+
for (const entry of updates) {
|
|
295
|
+
if (!isObject2(entry) || !isObject2(entry.key) || !entry.key.fromMe || !isObject2(entry.update)) continue;
|
|
296
|
+
const id = text(entry.key.id);
|
|
297
|
+
const status = receiptOf(entry.update.status);
|
|
298
|
+
if (!id || !status) continue;
|
|
299
|
+
events.push({
|
|
300
|
+
type: "status",
|
|
301
|
+
accountId,
|
|
302
|
+
externalId: id,
|
|
303
|
+
status,
|
|
304
|
+
at,
|
|
305
|
+
contactId: contactAddress(entry.key),
|
|
306
|
+
error: status === "FAILED" ? "ERROR" : null,
|
|
307
|
+
callbackData: null
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
return events;
|
|
311
|
+
}
|
|
312
|
+
__name(normalizeUpdates, "normalizeUpdates");
|
|
313
|
+
|
|
314
|
+
// src/whatsapp-web/media.ts
|
|
315
|
+
var AudioCache = class {
|
|
316
|
+
constructor(size) {
|
|
317
|
+
this.size = size;
|
|
318
|
+
}
|
|
319
|
+
size;
|
|
320
|
+
static {
|
|
321
|
+
__name(this, "AudioCache");
|
|
322
|
+
}
|
|
323
|
+
messages = /* @__PURE__ */ new Map();
|
|
324
|
+
/** Keep `message` if it is an audio. The oldest is dropped past the size. */
|
|
325
|
+
remember(message) {
|
|
326
|
+
const id = message.key?.id;
|
|
327
|
+
if (!id || !audioOf(message)) return;
|
|
328
|
+
this.messages.set(id, message);
|
|
329
|
+
while (this.messages.size > this.size) this.messages.delete(this.messages.keys().next().value);
|
|
330
|
+
}
|
|
331
|
+
get(id) {
|
|
332
|
+
return this.messages.get(id);
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
function audioOf(message) {
|
|
336
|
+
const audio = unwrapMessage(message.message).audioMessage;
|
|
337
|
+
return typeof audio === "object" && audio !== null ? audio : null;
|
|
338
|
+
}
|
|
339
|
+
__name(audioOf, "audioOf");
|
|
340
|
+
async function withDeadline(work, ms) {
|
|
341
|
+
let timer;
|
|
342
|
+
const deadline = new Promise((_, reject) => {
|
|
343
|
+
timer = setTimeout(() => reject(new ChannelMediaFailure("TIMEOUT", `media download passed its ${ms} ms deadline`)), ms);
|
|
344
|
+
});
|
|
345
|
+
try {
|
|
346
|
+
return await Promise.race([work, deadline]);
|
|
347
|
+
} finally {
|
|
348
|
+
clearTimeout(timer);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
__name(withDeadline, "withDeadline");
|
|
352
|
+
function refuseOverCap(size, maxBytes, what) {
|
|
353
|
+
if (size !== null && size > maxBytes) throw new ChannelMediaFailure("TOO_LARGE", `the media ${what} ${size} bytes, over ${maxBytes}`);
|
|
354
|
+
}
|
|
355
|
+
__name(refuseOverCap, "refuseOverCap");
|
|
356
|
+
async function downloadAudio(input) {
|
|
357
|
+
const audio = input.message ? audioOf(input.message) : null;
|
|
358
|
+
if (!input.message || !audio) throw new ChannelMediaFailure("NOT_FOUND", "no recent audio with this id in this session");
|
|
359
|
+
refuseOverCap(longNumber(audio.fileLength), input.maxBytes, "declares");
|
|
360
|
+
const ctx = {
|
|
361
|
+
...input.logger ? { logger: input.logger } : {},
|
|
362
|
+
...input.reupload ? { reuploadRequest: input.reupload } : {}
|
|
363
|
+
};
|
|
364
|
+
const bytes = await withDeadline(input.baileys.downloadMediaMessage(input.message, "buffer", {}, ctx), input.timeoutMs ?? DEFAULT_MEDIA_TIMEOUT_MS).catch(
|
|
365
|
+
(error) => {
|
|
366
|
+
throw error instanceof ChannelMediaFailure ? error : new ChannelMediaFailure("DOWNLOAD_FAILED", "the media could not be downloaded");
|
|
367
|
+
}
|
|
368
|
+
);
|
|
369
|
+
refuseOverCap(bytes.length, input.maxBytes, "is");
|
|
370
|
+
const mimeType = typeof audio.mimetype === "string" && audio.mimetype ? audio.mimetype : "application/octet-stream";
|
|
371
|
+
return { bytes: new Uint8Array(bytes), mimeType, size: bytes.length };
|
|
372
|
+
}
|
|
373
|
+
__name(downloadAudio, "downloadAudio");
|
|
374
|
+
|
|
375
|
+
// src/whatsapp-web/session.ts
|
|
376
|
+
function renderOutboundText(content2) {
|
|
377
|
+
if (content2.kind === "TEXT") return content2.text;
|
|
378
|
+
if (content2.kind === "BUTTONS") return [content2.text, "", ...content2.buttons.map((button, i) => `${i + 1}. ${button.title}`)].join("\n");
|
|
379
|
+
let n = 0;
|
|
380
|
+
const sections = content2.sections.map((section) => [
|
|
381
|
+
"",
|
|
382
|
+
...section.title ? [`*${section.title}*`] : [],
|
|
383
|
+
...section.rows.map((row) => `${++n}. ${row.title}${row.description ? ` \u2014 ${row.description}` : ""}`)
|
|
384
|
+
]);
|
|
385
|
+
return [content2.text, ...sections.flat()].join("\n");
|
|
386
|
+
}
|
|
387
|
+
__name(renderOutboundText, "renderOutboundText");
|
|
388
|
+
var defaultSleep = /* @__PURE__ */ __name((ms) => new Promise((resolve) => setTimeout(resolve, ms)), "defaultSleep");
|
|
389
|
+
var TERMINAL = {
|
|
390
|
+
[DISCONNECT.connectionReplaced]: "replaced",
|
|
391
|
+
[DISCONNECT.forbidden]: "forbidden"
|
|
392
|
+
};
|
|
393
|
+
var BaileysSession = class {
|
|
394
|
+
constructor(config) {
|
|
395
|
+
this.config = config;
|
|
396
|
+
this.audio = new AudioCache(config.mediaCacheSize ?? 200);
|
|
397
|
+
}
|
|
398
|
+
config;
|
|
399
|
+
static {
|
|
400
|
+
__name(this, "BaileysSession");
|
|
401
|
+
}
|
|
402
|
+
socket = null;
|
|
403
|
+
current = { state: "idle" };
|
|
404
|
+
account = null;
|
|
405
|
+
attempts = 0;
|
|
406
|
+
stopping = false;
|
|
407
|
+
pairingRequested = false;
|
|
408
|
+
deliveries = Promise.resolve();
|
|
409
|
+
audio;
|
|
410
|
+
status = /* @__PURE__ */ __name(() => this.current, "status");
|
|
411
|
+
accountId = /* @__PURE__ */ __name(() => this.account, "accountId");
|
|
412
|
+
async start() {
|
|
413
|
+
if (this.socket) return;
|
|
414
|
+
this.stopping = false;
|
|
415
|
+
this.attempts = 0;
|
|
416
|
+
this.pairingRequested = false;
|
|
417
|
+
try {
|
|
418
|
+
await this.open();
|
|
419
|
+
} catch (error) {
|
|
420
|
+
this.socket = null;
|
|
421
|
+
this.setStatus({ state: "failed", code: null, reason: "start-failed" });
|
|
422
|
+
throw error;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
async stop() {
|
|
426
|
+
const sock = this.detach();
|
|
427
|
+
if (sock) await sock.end(void 0);
|
|
428
|
+
this.setStatus({ state: "stopped" });
|
|
429
|
+
}
|
|
430
|
+
async logout() {
|
|
431
|
+
const sock = this.detach();
|
|
432
|
+
if (sock) await sock.logout();
|
|
433
|
+
await clearAuthState(this.config.authStore);
|
|
434
|
+
this.setStatus({ state: "logged-out", code: null });
|
|
435
|
+
}
|
|
436
|
+
async send(to, content2) {
|
|
437
|
+
const sock = this.socket;
|
|
438
|
+
if (!sock || this.current.state !== "open") throw new ChannelSendFailure("NOT_CONNECTED", "the WhatsApp Web session is not open");
|
|
439
|
+
const sent = await sock.sendMessage(addressJid(to), { text: renderOutboundText(content2) }).catch((error) => {
|
|
440
|
+
const code = disconnectCode({ error });
|
|
441
|
+
throw new ChannelSendFailure(code === null ? "SEND_FAILED" : String(code), "the WhatsApp Web socket refused the send");
|
|
442
|
+
});
|
|
443
|
+
const externalId = sent?.key?.id;
|
|
444
|
+
if (!externalId) throw new ChannelSendFailure("NO_MESSAGE_ID", "the WhatsApp Web socket returned no message id");
|
|
445
|
+
return { externalId };
|
|
446
|
+
}
|
|
447
|
+
downloadMedia(mediaId, options) {
|
|
448
|
+
const sock = this.socket;
|
|
449
|
+
return downloadAudio({
|
|
450
|
+
baileys: this.config.baileys,
|
|
451
|
+
message: this.audio.get(mediaId),
|
|
452
|
+
maxBytes: options.maxBytes,
|
|
453
|
+
timeoutMs: options.timeoutMs,
|
|
454
|
+
logger: this.config.logger,
|
|
455
|
+
reupload: sock?.updateMediaMessage ? (message) => sock.updateMediaMessage(message) : void 0
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
// ── The socket ──────────────────────────────────────────────────────────
|
|
459
|
+
detach() {
|
|
460
|
+
this.stopping = true;
|
|
461
|
+
const sock = this.socket;
|
|
462
|
+
this.socket = null;
|
|
463
|
+
this.account = null;
|
|
464
|
+
return sock;
|
|
465
|
+
}
|
|
466
|
+
setStatus(status) {
|
|
467
|
+
this.current = status;
|
|
468
|
+
this.config.onStatus?.(status);
|
|
469
|
+
}
|
|
470
|
+
async open() {
|
|
471
|
+
this.setStatus({ state: "connecting" });
|
|
472
|
+
const { state, saveCreds } = await loadAuthState(this.config.baileys, this.config.authStore);
|
|
473
|
+
const sock = this.config.baileys.makeWASocket({
|
|
474
|
+
// The ONE boundary cast: the store holds Baileys' own values, which its key store types per category.
|
|
475
|
+
auth: state,
|
|
476
|
+
markOnlineOnConnect: false,
|
|
477
|
+
syncFullHistory: false,
|
|
478
|
+
...this.config.logger ? { logger: this.config.logger } : {},
|
|
479
|
+
...this.config.browser ? { browser: this.config.browser } : {}
|
|
480
|
+
});
|
|
481
|
+
this.socket = sock;
|
|
482
|
+
sock.ev.on("creds.update", () => {
|
|
483
|
+
saveCreds().catch((error) => this.config.onError?.(error, "save-creds"));
|
|
484
|
+
});
|
|
485
|
+
sock.ev.on("connection.update", (update) => {
|
|
486
|
+
if (sock === this.socket) void this.onConnection(sock, update);
|
|
487
|
+
});
|
|
488
|
+
sock.ev.on("messages.upsert", (upsert) => {
|
|
489
|
+
const account = this.linked(sock);
|
|
490
|
+
if (!account) return;
|
|
491
|
+
if (upsert.type === "notify") upsert.messages.forEach((message) => this.audio.remember(message));
|
|
492
|
+
this.deliver(normalizeUpsert(account, upsert, this.config.optOutKeywords ? { optOutKeywords: this.config.optOutKeywords } : {}));
|
|
493
|
+
});
|
|
494
|
+
sock.ev.on("messages.update", (updates) => {
|
|
495
|
+
const account = this.linked(sock);
|
|
496
|
+
if (account) this.deliver(normalizeUpdates(account, updates, (this.config.now ?? (() => /* @__PURE__ */ new Date()))()));
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
/** The account a CURRENT socket is linked to: from the open event, or its own user while still opening. */
|
|
500
|
+
linked(sock) {
|
|
501
|
+
if (sock !== this.socket) return null;
|
|
502
|
+
return this.account ?? (sock.user?.id ? jidUser(sock.user.id) : null);
|
|
503
|
+
}
|
|
504
|
+
/** Hand one body to the host, after every earlier one: a socket's order is kept. */
|
|
505
|
+
deliver(events) {
|
|
506
|
+
if (events.length === 0) return;
|
|
507
|
+
const body = encodeEnvelope(events);
|
|
508
|
+
this.deliveries = this.deliveries.then(
|
|
509
|
+
() => this.config.deliver(body).then(
|
|
510
|
+
() => void 0,
|
|
511
|
+
(error) => this.config.onError?.(error, "deliver")
|
|
512
|
+
)
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
async onConnection(sock, update) {
|
|
516
|
+
if (update.qr) await this.onQr(sock, update.qr);
|
|
517
|
+
if (update.connection === "open") {
|
|
518
|
+
this.attempts = 0;
|
|
519
|
+
this.account = sock.user?.id ? jidUser(sock.user.id) : null;
|
|
520
|
+
this.setStatus(this.account ? { state: "open", accountId: this.account } : { state: "connecting" });
|
|
521
|
+
} else if (update.connection === "close") {
|
|
522
|
+
await this.onClose(disconnectCode(update.lastDisconnect));
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
async onQr(sock, qr) {
|
|
526
|
+
const phone = this.config.pairingPhoneNumber;
|
|
527
|
+
if (!phone) return this.setStatus({ state: "qr", qr });
|
|
528
|
+
if (this.pairingRequested) return;
|
|
529
|
+
this.pairingRequested = true;
|
|
530
|
+
try {
|
|
531
|
+
this.setStatus({ state: "pairing-code", code: await sock.requestPairingCode(phone.replace(/\D/g, "")) });
|
|
532
|
+
} catch (error) {
|
|
533
|
+
this.pairingRequested = false;
|
|
534
|
+
this.config.onError?.(error, "pairing-code");
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
async onClose(code) {
|
|
538
|
+
this.socket = null;
|
|
539
|
+
this.account = null;
|
|
540
|
+
if (this.stopping) return this.setStatus({ state: "stopped" });
|
|
541
|
+
if (code === DISCONNECT.loggedOut) {
|
|
542
|
+
await clearAuthState(this.config.authStore);
|
|
543
|
+
return this.setStatus({ state: "logged-out", code });
|
|
544
|
+
}
|
|
545
|
+
const terminal = code === null ? void 0 : TERMINAL[code];
|
|
546
|
+
if (terminal) return this.setStatus({ state: "failed", code, reason: terminal });
|
|
547
|
+
if (code !== DISCONNECT.restartRequired && !await this.backOff(code)) return;
|
|
548
|
+
await this.open();
|
|
549
|
+
}
|
|
550
|
+
/** Wait before a reconnect; false when the attempts ran out or the session was stopped meanwhile. */
|
|
551
|
+
async backOff(code) {
|
|
552
|
+
const maxAttempts = this.config.reconnect?.maxAttempts ?? 5;
|
|
553
|
+
this.attempts += 1;
|
|
554
|
+
if (this.attempts > maxAttempts) {
|
|
555
|
+
this.setStatus({ state: "failed", code, reason: "reconnects-exhausted" });
|
|
556
|
+
return false;
|
|
557
|
+
}
|
|
558
|
+
this.setStatus({ state: "reconnecting", attempt: this.attempts, code });
|
|
559
|
+
await (this.config.sleep ?? defaultSleep)((this.config.reconnect?.delayMs ?? 2e3) * 2 ** (this.attempts - 1));
|
|
560
|
+
if (!this.stopping) return true;
|
|
561
|
+
this.setStatus({ state: "stopped" });
|
|
562
|
+
return false;
|
|
563
|
+
}
|
|
564
|
+
};
|
|
565
|
+
function createWhatsAppWebSession(config) {
|
|
566
|
+
return new BaileysSession(config);
|
|
567
|
+
}
|
|
568
|
+
__name(createWhatsAppWebSession, "createWhatsAppWebSession");
|
|
569
|
+
export {
|
|
570
|
+
DISCONNECT,
|
|
571
|
+
ENVELOPE_FORMAT,
|
|
572
|
+
addressJid,
|
|
573
|
+
clearAuthState,
|
|
574
|
+
contactAddress,
|
|
575
|
+
contentOf,
|
|
576
|
+
createMemoryAuthStateStore,
|
|
577
|
+
createWhatsAppWebAdapter,
|
|
578
|
+
createWhatsAppWebSession,
|
|
579
|
+
disconnectCode,
|
|
580
|
+
encodeEnvelope,
|
|
581
|
+
loadAuthState,
|
|
582
|
+
normalizeUpdates,
|
|
583
|
+
normalizeUpsert,
|
|
584
|
+
parseEnvelope,
|
|
585
|
+
receiptOf,
|
|
586
|
+
renderOutboundText
|
|
587
|
+
};
|
|
588
|
+
//# sourceMappingURL=index.js.map
|