@gqb333/based 2.7.71
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/LICENSE +58 -0
- package/README.MD +611 -0
- package/WAProto/GenerateStatics.sh +4 -0
- package/WAProto/WAProto.proto +5604 -0
- package/WAProto/index.d.ts +63156 -0
- package/WAProto/index.js +195638 -0
- package/WAProto/p.html +1 -0
- package/engine-requirements.js +10 -0
- package/lib/Defaults/baileys-version.json +3 -0
- package/lib/Defaults/index.d.ts +53 -0
- package/lib/Defaults/index.js +108 -0
- package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
- package/lib/Signal/Group/ciphertext-message.js +15 -0
- package/lib/Signal/Group/group-session-builder.d.ts +14 -0
- package/lib/Signal/Group/group-session-builder.js +64 -0
- package/lib/Signal/Group/group_cipher.d.ts +17 -0
- package/lib/Signal/Group/group_cipher.js +96 -0
- package/lib/Signal/Group/index.d.ts +11 -0
- package/lib/Signal/Group/index.js +57 -0
- package/lib/Signal/Group/keyhelper.d.ts +10 -0
- package/lib/Signal/Group/keyhelper.js +55 -0
- package/lib/Signal/Group/queue-job.d.ts +1 -0
- package/lib/Signal/Group/queue-job.js +57 -0
- package/lib/Signal/Group/sender-chain-key.d.ts +13 -0
- package/lib/Signal/Group/sender-chain-key.js +34 -0
- package/lib/Signal/Group/sender-key-distribution-message.d.ts +16 -0
- package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
- package/lib/Signal/Group/sender-key-message.d.ts +18 -0
- package/lib/Signal/Group/sender-key-message.js +69 -0
- package/lib/Signal/Group/sender-key-name.d.ts +17 -0
- package/lib/Signal/Group/sender-key-name.js +51 -0
- package/lib/Signal/Group/sender-key-record.d.ts +30 -0
- package/lib/Signal/Group/sender-key-record.js +53 -0
- package/lib/Signal/Group/sender-key-state.d.ts +38 -0
- package/lib/Signal/Group/sender-key-state.js +99 -0
- package/lib/Signal/Group/sender-message-key.d.ts +11 -0
- package/lib/Signal/Group/sender-message-key.js +29 -0
- package/lib/Signal/libsignal.d.ts +3 -0
- package/lib/Signal/libsignal.js +174 -0
- package/lib/Socket/Client/index.d.ts +2 -0
- package/lib/Socket/Client/index.js +18 -0
- package/lib/Socket/Client/types.d.ts +16 -0
- package/lib/Socket/Client/types.js +13 -0
- package/lib/Socket/Client/websocket.d.ts +13 -0
- package/lib/Socket/Client/websocket.js +111 -0
- package/lib/Socket/business.d.ts +172 -0
- package/lib/Socket/business.js +260 -0
- package/lib/Socket/chats.d.ts +85 -0
- package/lib/Socket/chats.js +1094 -0
- package/lib/Socket/groups.d.ts +124 -0
- package/lib/Socket/groups.js +423 -0
- package/lib/Socket/index.d.ts +172 -0
- package/lib/Socket/index.js +32 -0
- package/lib/Socket/messages-interactive.js +259 -0
- package/lib/Socket/messages-recv.d.ts +161 -0
- package/lib/Socket/messages-recv.js +1474 -0
- package/lib/Socket/messages-send.d.ts +151 -0
- package/lib/Socket/messages-send.js +1085 -0
- package/lib/Socket/newsletter.d.ts +136 -0
- package/lib/Socket/newsletter.js +250 -0
- package/lib/Socket/socket.d.ts +43 -0
- package/lib/Socket/socket.js +1241 -0
- package/lib/Socket/usync.d.ts +36 -0
- package/lib/Socket/usync.js +123 -0
- package/lib/Store/index.d.ts +2 -0
- package/lib/Store/index.js +8 -0
- package/lib/Store/make-in-memory-store.d.ts +118 -0
- package/lib/Store/make-in-memory-store.js +452 -0
- package/lib/Store/make-ordered-dictionary.d.ts +13 -0
- package/lib/Store/make-ordered-dictionary.js +81 -0
- package/lib/Store/object-repository.d.ts +10 -0
- package/lib/Store/object-repository.js +27 -0
- package/lib/Types/Auth.d.ts +114 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Call.d.ts +13 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.d.ts +109 -0
- package/lib/Types/Chat.js +4 -0
- package/lib/Types/Contact.d.ts +29 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.d.ts +199 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.d.ts +64 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.d.ts +35 -0
- package/lib/Types/Label.js +27 -0
- package/lib/Types/LabelAssociation.d.ts +29 -0
- package/lib/Types/LabelAssociation.js +9 -0
- package/lib/Types/Message.d.ts +740 -0
- package/lib/Types/Message.js +7 -0
- package/lib/Types/Newsletter.d.ts +22 -0
- package/lib/Types/Newsletter.js +18 -0
- package/lib/Types/Product.d.ts +78 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.d.ts +63 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.d.ts +134 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.d.ts +27 -0
- package/lib/Types/State.js +2 -0
- package/lib/Types/USync.d.ts +25 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.d.ts +65 -0
- package/lib/Types/index.js +43 -0
- package/lib/Utils/auth-utils.d.ts +18 -0
- package/lib/Utils/auth-utils.js +209 -0
- package/lib/Utils/baileys-event-stream.d.ts +16 -0
- package/lib/Utils/baileys-event-stream.js +63 -0
- package/lib/Utils/business.d.ts +22 -0
- package/lib/Utils/business.js +234 -0
- package/lib/Utils/cache-manager.d.ts +16 -0
- package/lib/Utils/cache-manager.js +114 -0
- package/lib/Utils/chat-utils.d.ts +70 -0
- package/lib/Utils/chat-utils.js +734 -0
- package/lib/Utils/crypto.d.ts +40 -0
- package/lib/Utils/crypto.js +193 -0
- package/lib/Utils/decode-wa-message.d.ts +35 -0
- package/lib/Utils/decode-wa-message.js +207 -0
- package/lib/Utils/event-buffer.d.ts +35 -0
- package/lib/Utils/event-buffer.js +619 -0
- package/lib/Utils/generics.d.ts +89 -0
- package/lib/Utils/generics.js +440 -0
- package/lib/Utils/history.d.ts +19 -0
- package/lib/Utils/history.js +94 -0
- package/lib/Utils/index.d.ts +22 -0
- package/lib/Utils/index.js +38 -0
- package/lib/Utils/jid-validation.d.ts +2 -0
- package/lib/Utils/jid-validation.js +186 -0
- package/lib/Utils/link-preview.d.ts +21 -0
- package/lib/Utils/link-preview.js +152 -0
- package/lib/Utils/logger.d.ts +11 -0
- package/lib/Utils/logger.js +59 -0
- package/lib/Utils/lt-hash.d.ts +12 -0
- package/lib/Utils/lt-hash.js +51 -0
- package/lib/Utils/make-mutex.d.ts +7 -0
- package/lib/Utils/make-mutex.js +43 -0
- package/lib/Utils/messages-media.d.ts +120 -0
- package/lib/Utils/messages-media.js +848 -0
- package/lib/Utils/messages.d.ts +131 -0
- package/lib/Utils/messages.js +1793 -0
- package/lib/Utils/newsletter-utils.d.ts +2 -0
- package/lib/Utils/newsletter-utils.js +48 -0
- package/lib/Utils/noise-handler.d.ts +19 -0
- package/lib/Utils/noise-handler.js +150 -0
- package/lib/Utils/performance-config.d.ts +70 -0
- package/lib/Utils/performance-config.js +183 -0
- package/lib/Utils/process-message.d.ts +42 -0
- package/lib/Utils/process-message.js +498 -0
- package/lib/Utils/rate-limiter.js +90 -0
- package/lib/Utils/retry.js +66 -0
- package/lib/Utils/signal.d.ts +33 -0
- package/lib/Utils/signal.js +153 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
- package/lib/Utils/use-multi-file-auth-state.js +129 -0
- package/lib/Utils/validate-connection.d.ts +10 -0
- package/lib/Utils/validate-connection.js +233 -0
- package/lib/WABinary/constants.d.ts +27 -0
- package/lib/WABinary/constants.js +1303 -0
- package/lib/WABinary/decode.d.ts +6 -0
- package/lib/WABinary/decode.js +279 -0
- package/lib/WABinary/encode.d.ts +2 -0
- package/lib/WABinary/encode.js +264 -0
- package/lib/WABinary/generic-utils.d.ts +14 -0
- package/lib/WABinary/generic-utils.js +114 -0
- package/lib/WABinary/index.d.ts +5 -0
- package/lib/WABinary/index.js +21 -0
- package/lib/WABinary/jid-utils.d.ts +38 -0
- package/lib/WABinary/jid-utils.js +485 -0
- package/lib/WABinary/types.d.ts +18 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.d.ts +8 -0
- package/lib/WAM/BinaryInfo.js +13 -0
- package/lib/WAM/constants.d.ts +38 -0
- package/lib/WAM/constants.js +15350 -0
- package/lib/WAM/encode.d.ts +2 -0
- package/lib/WAM/encode.js +155 -0
- package/lib/WAM/index.d.ts +3 -0
- package/lib/WAM/index.js +19 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +102 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +110 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +25 -0
- package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +8 -0
- package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
- package/lib/WAUSync/Protocols/index.d.ts +4 -0
- package/lib/WAUSync/Protocols/index.js +20 -0
- package/lib/WAUSync/USyncQuery.d.ts +28 -0
- package/lib/WAUSync/USyncQuery.js +147 -0
- package/lib/WAUSync/USyncUser.d.ts +12 -0
- package/lib/WAUSync/USyncUser.js +26 -0
- package/lib/WAUSync/index.d.ts +3 -0
- package/lib/WAUSync/index.js +19 -0
- package/lib/index.d.ts +17 -0
- package/lib/index.js +53 -0
- package/package.json +104 -0
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getChatId = exports.shouldIncrementChatUnread = exports.isRealMessage = exports.cleanMessage = void 0;
|
|
4
|
+
exports.decryptPollVote = decryptPollVote;
|
|
5
|
+
const WAProto_1 = require("../../WAProto");
|
|
6
|
+
const Types_1 = require("../Types");
|
|
7
|
+
const messages_1 = require("../Utils/messages");
|
|
8
|
+
const WABinary_1 = require("../WABinary");
|
|
9
|
+
const crypto_1 = require("./crypto");
|
|
10
|
+
const generics_1 = require("./generics");
|
|
11
|
+
const history_1 = require("./history");
|
|
12
|
+
const REAL_MSG_STUB_TYPES = new Set([
|
|
13
|
+
Types_1.WAMessageStubType.CALL_MISSED_GROUP_VIDEO,
|
|
14
|
+
Types_1.WAMessageStubType.CALL_MISSED_GROUP_VOICE,
|
|
15
|
+
Types_1.WAMessageStubType.CALL_MISSED_VIDEO,
|
|
16
|
+
Types_1.WAMessageStubType.CALL_MISSED_VOICE
|
|
17
|
+
]);
|
|
18
|
+
const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
|
|
19
|
+
Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
/** Helper function to normalize JID */
|
|
23
|
+
const normalizeToJid = (jid) => {
|
|
24
|
+
if (!jid || typeof jid !== 'string') {
|
|
25
|
+
return jid;
|
|
26
|
+
}
|
|
27
|
+
if ((0, WABinary_1.isLid)(jid)) {
|
|
28
|
+
const decoded = (0, WABinary_1.lidToJid)(jid);
|
|
29
|
+
return decoded || jid;
|
|
30
|
+
}
|
|
31
|
+
return jid;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** Cleans a received message to further processing */
|
|
35
|
+
const cleanMessage = (message, meId) => {
|
|
36
|
+
// ensure remoteJid and participant doesn't have device or agent in it
|
|
37
|
+
// normalize JIDs but catch errors to avoid throwing on invalid LIDs/JIDs
|
|
38
|
+
try {
|
|
39
|
+
const r0 = message.key.remoteJid;
|
|
40
|
+
if (r0) {
|
|
41
|
+
const rd = (0, WABinary_1.jidDecode)(r0);
|
|
42
|
+
if (rd === null || rd === void 0 ? void 0 : rd.user) {
|
|
43
|
+
message.key.remoteLid = message.key.remoteLid || ((0, WABinary_1.isLid)(r0) ? r0 : (0, WABinary_1.jidEncode)(rd.user, 'lid'));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
message.key.remoteJid = normalizeToJid(message.key.remoteJid);
|
|
47
|
+
}
|
|
48
|
+
catch (_e) {
|
|
49
|
+
// if normalization fails, retain original remoteJid
|
|
50
|
+
}
|
|
51
|
+
if (message.key.participant) {
|
|
52
|
+
try {
|
|
53
|
+
const p0 = message.key.participant;
|
|
54
|
+
if (p0) {
|
|
55
|
+
const pd = (0, WABinary_1.jidDecode)(p0);
|
|
56
|
+
if (pd === null || pd === void 0 ? void 0 : pd.user) {
|
|
57
|
+
message.key.participantLid = message.key.participantLid || ((0, WABinary_1.isLid)(p0) ? p0 : (0, WABinary_1.jidEncode)(pd.user, 'lid'));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
message.key.participant = normalizeToJid(message.key.participant);
|
|
61
|
+
}
|
|
62
|
+
catch (_e) {
|
|
63
|
+
// ignore if can't normalize participant
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
message.key.remoteJidNormalized = message.key.remoteJid;
|
|
67
|
+
const content = (0, messages_1.normalizeMessageContent)(message.message);
|
|
68
|
+
// if the message has a reaction, ensure fromMe & remoteJid are from our perspective
|
|
69
|
+
if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
|
|
70
|
+
normaliseKey(content.reactionMessage.key);
|
|
71
|
+
}
|
|
72
|
+
if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
|
|
73
|
+
normaliseKey(content.pollUpdateMessage.pollCreationMessageKey);
|
|
74
|
+
}
|
|
75
|
+
function normaliseKey(msgKey) {
|
|
76
|
+
// if the reaction is from another user
|
|
77
|
+
// we've to correctly map the key to this user's perspective
|
|
78
|
+
if (!message.key.fromMe) {
|
|
79
|
+
// if the sender believed the message being reacted to is not from them
|
|
80
|
+
// we've to correct the key to be from them, or some other participant
|
|
81
|
+
msgKey.fromMe = !msgKey.fromMe
|
|
82
|
+
? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId)
|
|
83
|
+
// if the message being reacted to, was from them
|
|
84
|
+
// fromMe automatically becomes false
|
|
85
|
+
: false;
|
|
86
|
+
// set the remoteJid to being the same as the chat the message came from
|
|
87
|
+
msgKey.remoteJid = message.key.remoteJid;
|
|
88
|
+
// set participant of the message
|
|
89
|
+
msgKey.participant = msgKey.participant || message.key.participant;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
exports.cleanMessage = cleanMessage;
|
|
94
|
+
const isRealMessage = (message, meId) => {
|
|
95
|
+
var _a;
|
|
96
|
+
const normalizedContent = (0, messages_1.normalizeMessageContent)(message.message);
|
|
97
|
+
const hasSomeContent = !!(0, messages_1.getContentType)(normalizedContent);
|
|
98
|
+
return (!!normalizedContent
|
|
99
|
+
|| REAL_MSG_STUB_TYPES.has(message.messageStubType)
|
|
100
|
+
|| (REAL_MSG_REQ_ME_STUB_TYPES.has(message.messageStubType)
|
|
101
|
+
&& ((_a = message.messageStubParameters) === null || _a === void 0 ? void 0 : _a.some(p => (0, WABinary_1.areJidsSameUser)(meId, p)))))
|
|
102
|
+
&& hasSomeContent
|
|
103
|
+
&& !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage)
|
|
104
|
+
&& !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.reactionMessage)
|
|
105
|
+
&& !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.pollUpdateMessage);
|
|
106
|
+
};
|
|
107
|
+
exports.isRealMessage = isRealMessage;
|
|
108
|
+
const shouldIncrementChatUnread = (message) => (!message.key.fromMe && !message.messageStubType);
|
|
109
|
+
exports.shouldIncrementChatUnread = shouldIncrementChatUnread;
|
|
110
|
+
/**
|
|
111
|
+
* Get the ID of the chat from the given key.
|
|
112
|
+
* Typically -- that'll be the remoteJid, but for broadcasts, it'll be the participant
|
|
113
|
+
*/
|
|
114
|
+
const getChatId = ({ remoteJid, participant, fromMe }) => {
|
|
115
|
+
if ((0, WABinary_1.isJidBroadcast)(remoteJid)
|
|
116
|
+
&& !(0, WABinary_1.isJidStatusBroadcast)(remoteJid)
|
|
117
|
+
&& !fromMe) {
|
|
118
|
+
return participant;
|
|
119
|
+
}
|
|
120
|
+
return remoteJid;
|
|
121
|
+
};
|
|
122
|
+
exports.getChatId = getChatId;
|
|
123
|
+
/**
|
|
124
|
+
* Decrypt a poll vote
|
|
125
|
+
* @param vote encrypted vote
|
|
126
|
+
* @param ctx additional info about the poll required for decryption
|
|
127
|
+
* @returns list of SHA256 options
|
|
128
|
+
*/
|
|
129
|
+
function decryptPollVote({ encPayload, encIv }, { pollCreatorJid, pollMsgId, pollEncKey, voterJid, }) {
|
|
130
|
+
const sign = Buffer.concat([
|
|
131
|
+
toBinary(pollMsgId),
|
|
132
|
+
toBinary(pollCreatorJid),
|
|
133
|
+
toBinary(voterJid),
|
|
134
|
+
toBinary('Poll Vote'),
|
|
135
|
+
new Uint8Array([1])
|
|
136
|
+
]);
|
|
137
|
+
const key0 = (0, crypto_1.hmacSign)(pollEncKey, new Uint8Array(32), 'sha256');
|
|
138
|
+
const decKey = (0, crypto_1.hmacSign)(sign, key0, 'sha256');
|
|
139
|
+
const aad = toBinary(`${pollMsgId}\u0000${voterJid}`);
|
|
140
|
+
const decrypted = (0, crypto_1.aesDecryptGCM)(encPayload, decKey, encIv, aad);
|
|
141
|
+
return WAProto_1.proto.Message.PollVoteMessage.decode(decrypted);
|
|
142
|
+
function toBinary(txt) {
|
|
143
|
+
return Buffer.from(txt);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const processMessage = async (message, { shouldProcessHistoryMsg, placeholderResendCache, ev, creds, keyStore, logger, options, getMessage }) => {
|
|
147
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
|
|
148
|
+
const meId = creds.me.id;
|
|
149
|
+
const { accountSettings } = creds;
|
|
150
|
+
const chat = { id: (0, WABinary_1.jidNormalizedUser)((0, exports.getChatId)(message.key)) };
|
|
151
|
+
const isRealMsg = (0, exports.isRealMessage)(message, meId);
|
|
152
|
+
if (isRealMsg) {
|
|
153
|
+
chat.messages = [{ message }];
|
|
154
|
+
chat.conversationTimestamp = (0, generics_1.toNumber)(message.messageTimestamp);
|
|
155
|
+
// only increment unread count if not CIPHERTEXT and from another person
|
|
156
|
+
if ((0, exports.shouldIncrementChatUnread)(message)) {
|
|
157
|
+
chat.unreadCount = (chat.unreadCount || 0) + 1;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const content = (0, messages_1.normalizeMessageContent)(message.message);
|
|
161
|
+
|
|
162
|
+
// unarchive chat if it's a real message, or someone reacted to our message
|
|
163
|
+
// and we've the unarchive chats setting on
|
|
164
|
+
if ((isRealMsg || ((_b = (_a = content === null || content === void 0 ? void 0 : content.reactionMessage) === null || _a === void 0 ? void 0 : _a.key) === null || _b === void 0 ? void 0 : _b.fromMe))
|
|
165
|
+
&& (accountSettings === null || accountSettings === void 0 ? void 0 : accountSettings.unarchiveChats)) {
|
|
166
|
+
chat.archived = false;
|
|
167
|
+
chat.readOnly = false;
|
|
168
|
+
}
|
|
169
|
+
const protocolMsg = content === null || content === void 0 ? void 0 : content.protocolMessage;
|
|
170
|
+
if (protocolMsg) {
|
|
171
|
+
switch (protocolMsg.type) {
|
|
172
|
+
case WAProto_1.proto.Message.ProtocolMessage.Type.HISTORY_SYNC_NOTIFICATION:
|
|
173
|
+
const histNotification = protocolMsg.historySyncNotification;
|
|
174
|
+
const process = shouldProcessHistoryMsg;
|
|
175
|
+
const isLatest = !((_c = creds.processedHistoryMessages) === null || _c === void 0 ? void 0 : _c.length);
|
|
176
|
+
logger === null || logger === void 0 ? void 0 : logger.info({
|
|
177
|
+
histNotification,
|
|
178
|
+
process,
|
|
179
|
+
id: message.key.id,
|
|
180
|
+
isLatest,
|
|
181
|
+
}, 'got history notification');
|
|
182
|
+
if (process) {
|
|
183
|
+
if (histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
|
|
184
|
+
ev.emit('creds.update', {
|
|
185
|
+
processedHistoryMessages: [
|
|
186
|
+
...(creds.processedHistoryMessages || []),
|
|
187
|
+
{ key: message.key, messageTimestamp: message.messageTimestamp }
|
|
188
|
+
]
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
const data = await (0, history_1.downloadAndProcessHistorySyncNotification)(histNotification, options);
|
|
192
|
+
ev.emit('messaging-history.set', {
|
|
193
|
+
...data,
|
|
194
|
+
isLatest: histNotification.syncType !== WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND
|
|
195
|
+
? isLatest
|
|
196
|
+
: undefined,
|
|
197
|
+
peerDataRequestSessionId: histNotification.peerDataRequestSessionId
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
break;
|
|
201
|
+
case WAProto_1.proto.Message.ProtocolMessage.Type.APP_STATE_SYNC_KEY_SHARE:
|
|
202
|
+
const keys = protocolMsg.appStateSyncKeyShare.keys;
|
|
203
|
+
if (keys === null || keys === void 0 ? void 0 : keys.length) {
|
|
204
|
+
let newAppStateSyncKeyId = '';
|
|
205
|
+
await keyStore.transaction(async () => {
|
|
206
|
+
const newKeys = [];
|
|
207
|
+
for (const { keyData, keyId } of keys) {
|
|
208
|
+
const strKeyId = Buffer.from(keyId.keyId).toString('base64');
|
|
209
|
+
newKeys.push(strKeyId);
|
|
210
|
+
await keyStore.set({ 'app-state-sync-key': { [strKeyId]: keyData } });
|
|
211
|
+
newAppStateSyncKeyId = strKeyId;
|
|
212
|
+
}
|
|
213
|
+
logger === null || logger === void 0 ? void 0 : logger.info({ newAppStateSyncKeyId, newKeys }, 'injecting new app state sync keys');
|
|
214
|
+
});
|
|
215
|
+
ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
logger === null || logger === void 0 ? void 0 : logger.info({ protocolMsg }, 'recv app state sync with 0 keys');
|
|
219
|
+
}
|
|
220
|
+
break;
|
|
221
|
+
case WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE:
|
|
222
|
+
ev.emit('messages.update', [
|
|
223
|
+
{
|
|
224
|
+
key: {
|
|
225
|
+
...message.key,
|
|
226
|
+
id: protocolMsg.key.id
|
|
227
|
+
},
|
|
228
|
+
update: { message: null, messageStubType: Types_1.WAMessageStubType.REVOKE, key: message.key }
|
|
229
|
+
}
|
|
230
|
+
]);
|
|
231
|
+
break;
|
|
232
|
+
case WAProto_1.proto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING:
|
|
233
|
+
Object.assign(chat, {
|
|
234
|
+
ephemeralSettingTimestamp: (0, generics_1.toNumber)(message.messageTimestamp),
|
|
235
|
+
ephemeralExpiration: protocolMsg.ephemeralExpiration || null
|
|
236
|
+
});
|
|
237
|
+
break;
|
|
238
|
+
case WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE:
|
|
239
|
+
const response = protocolMsg.peerDataOperationRequestResponseMessage;
|
|
240
|
+
if (response) {
|
|
241
|
+
placeholderResendCache === null || placeholderResendCache === void 0 ? void 0 : placeholderResendCache.del(response.stanzaId);
|
|
242
|
+
// Handle peer data operation results including sticker uploads, media uploads, link previews, and history sync
|
|
243
|
+
const { peerDataOperationResult } = response;
|
|
244
|
+
for (const result of peerDataOperationResult) {
|
|
245
|
+
// Handle placeholder message resend responses
|
|
246
|
+
const { placeholderMessageResendResponse: retryResponse } = result;
|
|
247
|
+
if (retryResponse) {
|
|
248
|
+
const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);
|
|
249
|
+
// wait till another upsert event is available, don't want it to be part of the PDO response message
|
|
250
|
+
setTimeout(() => {
|
|
251
|
+
ev.emit('messages.upsert', {
|
|
252
|
+
messages: [webMessageInfo],
|
|
253
|
+
type: 'notify',
|
|
254
|
+
requestId: response.stanzaId
|
|
255
|
+
});
|
|
256
|
+
}, 500);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Handle sticker message results
|
|
260
|
+
if (result.stickerMessage) {
|
|
261
|
+
ev.emit('sticker.upload-result', {
|
|
262
|
+
stickerMessage: result.stickerMessage,
|
|
263
|
+
requestId: response.stanzaId
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Handle media upload results
|
|
268
|
+
if (result.mediaUploadResult !== undefined) {
|
|
269
|
+
ev.emit('media.upload-result', {
|
|
270
|
+
result: result.mediaUploadResult,
|
|
271
|
+
requestId: response.stanzaId
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Handle link preview responses
|
|
276
|
+
if (result.linkPreviewResponse) {
|
|
277
|
+
ev.emit('link-preview.response', {
|
|
278
|
+
response: result.linkPreviewResponse,
|
|
279
|
+
requestId: response.stanzaId
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Handle history sync chunk retry responses
|
|
284
|
+
if (result.historySyncChunkRetryResponse) {
|
|
285
|
+
const historySyncResponse = result.historySyncChunkRetryResponse;
|
|
286
|
+
ev.emit('history-sync.chunk-retry', {
|
|
287
|
+
syncType: historySyncResponse.syncType,
|
|
288
|
+
chunkOrder: historySyncResponse.chunkOrder,
|
|
289
|
+
requestId: historySyncResponse.requestId,
|
|
290
|
+
responseCode: historySyncResponse.responseCode,
|
|
291
|
+
canRecover: historySyncResponse.canRecover,
|
|
292
|
+
stanzaId: response.stanzaId
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Handle full history sync on-demand responses
|
|
297
|
+
if (result.fullHistorySyncOnDemandRequestResponse) {
|
|
298
|
+
ev.emit('history-sync.on-demand-response', {
|
|
299
|
+
response: result.fullHistorySyncOnDemandRequestResponse,
|
|
300
|
+
requestId: response.stanzaId
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
case WAProto_1.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT:
|
|
306
|
+
ev.emit('messages.update', [
|
|
307
|
+
{
|
|
308
|
+
// flip the sender / fromMe properties because they're in the perspective of the sender
|
|
309
|
+
key: { ...message.key, id: (_d = protocolMsg.key) === null || _d === void 0 ? void 0 : _d.id },
|
|
310
|
+
update: {
|
|
311
|
+
message: {
|
|
312
|
+
editedMessage: {
|
|
313
|
+
message: protocolMsg.editedMessage
|
|
314
|
+
}
|
|
315
|
+
},
|
|
316
|
+
messageTimestamp: protocolMsg.timestampMs
|
|
317
|
+
? Math.floor((0, generics_1.toNumber)(protocolMsg.timestampMs) / 1000)
|
|
318
|
+
: message.messageTimestamp
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
]);
|
|
322
|
+
break;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
else if (content === null || content === void 0 ? void 0 : content.reactionMessage) {
|
|
326
|
+
const reaction = {
|
|
327
|
+
...content.reactionMessage,
|
|
328
|
+
key: message.key,
|
|
329
|
+
};
|
|
330
|
+
ev.emit('messages.reaction', [{
|
|
331
|
+
reaction,
|
|
332
|
+
key: (_e = content.reactionMessage) === null || _e === void 0 ? void 0 : _e.key,
|
|
333
|
+
}]);
|
|
334
|
+
}
|
|
335
|
+
else if (message.messageStubType) {
|
|
336
|
+
const jid = (_f = message.key) === null || _f === void 0 ? void 0 : _f.remoteJid;
|
|
337
|
+
//let actor = whatsappID (message.participant)
|
|
338
|
+
let participants;
|
|
339
|
+
const author = normalizeToJid(message.participant);
|
|
340
|
+
const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, author, participants, action }));
|
|
341
|
+
const emitGroupUpdate = (update) => {
|
|
342
|
+
var _a;
|
|
343
|
+
ev.emit('groups.update', [{ id: jid, ...update, author: (_a = author) !== null && _a !== void 0 ? _a : undefined }]);
|
|
344
|
+
};
|
|
345
|
+
const emitGroupRequestJoin = (participant, action, method) => {
|
|
346
|
+
ev.emit('group.join-request', { id: jid, author, participant: normalizeToJid(participant), action, method: method });
|
|
347
|
+
};
|
|
348
|
+
const participantsIncludesMe = () => participants.find(jid => (0, WABinary_1.areJidsSameUser)(meId, jid));
|
|
349
|
+
switch (message.messageStubType) {
|
|
350
|
+
case Types_1.WAMessageStubType.GROUP_PARTICIPANT_CHANGE_NUMBER:
|
|
351
|
+
participants = (message.messageStubParameters || []).map(normalizeToJid);
|
|
352
|
+
participants = participants.map(p => {
|
|
353
|
+
if (typeof p === 'string') {
|
|
354
|
+
const cleanedJid = (0, WABinary_1.validateAndCleanJid)(p);
|
|
355
|
+
return cleanedJid;
|
|
356
|
+
}
|
|
357
|
+
return p;
|
|
358
|
+
});
|
|
359
|
+
emitParticipantsUpdate('modify');
|
|
360
|
+
break;
|
|
361
|
+
case Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE:
|
|
362
|
+
case Types_1.WAMessageStubType.GROUP_PARTICIPANT_REMOVE:
|
|
363
|
+
participants = (message.messageStubParameters || []).map(normalizeToJid);
|
|
364
|
+
participants = participants.map(p => {
|
|
365
|
+
if (typeof p === 'string') {
|
|
366
|
+
const cleanedJid = (0, WABinary_1.validateAndCleanJid)(p);
|
|
367
|
+
return cleanedJid;
|
|
368
|
+
}
|
|
369
|
+
return p;
|
|
370
|
+
});
|
|
371
|
+
emitParticipantsUpdate('remove');
|
|
372
|
+
if (participantsIncludesMe()) {
|
|
373
|
+
chat.readOnly = true;
|
|
374
|
+
}
|
|
375
|
+
break;
|
|
376
|
+
case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD:
|
|
377
|
+
case Types_1.WAMessageStubType.GROUP_PARTICIPANT_INVITE:
|
|
378
|
+
case Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD_REQUEST_JOIN:
|
|
379
|
+
participants = (message.messageStubParameters || []).map(normalizeToJid);
|
|
380
|
+
// Additional safety check: ensure all participants are proper JIDs
|
|
381
|
+
participants = participants.map(p => {
|
|
382
|
+
if (typeof p === 'string') {
|
|
383
|
+
const cleanedJid = (0, WABinary_1.validateAndCleanJid)(p);
|
|
384
|
+
return cleanedJid;
|
|
385
|
+
}
|
|
386
|
+
return p;
|
|
387
|
+
});
|
|
388
|
+
if (participantsIncludesMe()) {
|
|
389
|
+
chat.readOnly = false;
|
|
390
|
+
}
|
|
391
|
+
emitParticipantsUpdate('add');
|
|
392
|
+
break;
|
|
393
|
+
case Types_1.WAMessageStubType.GROUP_PARTICIPANT_DEMOTE:
|
|
394
|
+
participants = (message.messageStubParameters || []).map(normalizeToJid);
|
|
395
|
+
// Additional safety check: ensure all participants are proper JIDs
|
|
396
|
+
participants = participants.map(p => {
|
|
397
|
+
if (typeof p === 'string') {
|
|
398
|
+
const cleanedJid = (0, WABinary_1.validateAndCleanJid)(p);
|
|
399
|
+
return cleanedJid;
|
|
400
|
+
}
|
|
401
|
+
return p;
|
|
402
|
+
});
|
|
403
|
+
emitParticipantsUpdate('demote');
|
|
404
|
+
break;
|
|
405
|
+
case Types_1.WAMessageStubType.GROUP_PARTICIPANT_PROMOTE:
|
|
406
|
+
participants = (message.messageStubParameters || []).map(normalizeToJid);
|
|
407
|
+
// Additional safety check: ensure all participants are proper JIDs
|
|
408
|
+
participants = participants.map(p => {
|
|
409
|
+
if (typeof p === 'string') {
|
|
410
|
+
const cleanedJid = (0, WABinary_1.validateAndCleanJid)(p);
|
|
411
|
+
return cleanedJid;
|
|
412
|
+
}
|
|
413
|
+
return p;
|
|
414
|
+
});
|
|
415
|
+
emitParticipantsUpdate('promote');
|
|
416
|
+
break;
|
|
417
|
+
case Types_1.WAMessageStubType.GROUP_CHANGE_ANNOUNCE:
|
|
418
|
+
const announceValue = (_g = message.messageStubParameters) === null || _g === void 0 ? void 0 : _g[0];
|
|
419
|
+
emitGroupUpdate({ announce: announceValue === 'true' || announceValue === 'on' });
|
|
420
|
+
break;
|
|
421
|
+
case Types_1.WAMessageStubType.GROUP_CHANGE_RESTRICT:
|
|
422
|
+
const restrictValue = (_h = message.messageStubParameters) === null || _h === void 0 ? void 0 : _h[0];
|
|
423
|
+
emitGroupUpdate({ restrict: restrictValue === 'true' || restrictValue === 'on' });
|
|
424
|
+
break;
|
|
425
|
+
case Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT:
|
|
426
|
+
const name = (_j = message.messageStubParameters) === null || _j === void 0 ? void 0 : _j[0];
|
|
427
|
+
chat.name = name;
|
|
428
|
+
emitGroupUpdate({ subject: name });
|
|
429
|
+
break;
|
|
430
|
+
case Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION:
|
|
431
|
+
const description = (_k = message.messageStubParameters) === null || _k === void 0 ? void 0 : _k[0];
|
|
432
|
+
chat.description = description;
|
|
433
|
+
emitGroupUpdate({ desc: description });
|
|
434
|
+
break;
|
|
435
|
+
case Types_1.WAMessageStubType.GROUP_CHANGE_INVITE_LINK:
|
|
436
|
+
const code = (_l = message.messageStubParameters) === null || _l === void 0 ? void 0 : _l[0];
|
|
437
|
+
emitGroupUpdate({ inviteCode: code });
|
|
438
|
+
break;
|
|
439
|
+
case Types_1.WAMessageStubType.GROUP_MEMBER_ADD_MODE:
|
|
440
|
+
const memberAddValue = (_m = message.messageStubParameters) === null || _m === void 0 ? void 0 : _m[0];
|
|
441
|
+
emitGroupUpdate({ memberAddMode: memberAddValue === 'all_member_add' });
|
|
442
|
+
break;
|
|
443
|
+
case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE:
|
|
444
|
+
const approvalMode = (_o = message.messageStubParameters) === null || _o === void 0 ? void 0 : _o[0];
|
|
445
|
+
emitGroupUpdate({ joinApprovalMode: approvalMode === 'on' });
|
|
446
|
+
break;
|
|
447
|
+
case Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD:
|
|
448
|
+
const participant = (_p = message.messageStubParameters) === null || _p === void 0 ? void 0 : _p[0];
|
|
449
|
+
const action = (_q = message.messageStubParameters) === null || _q === void 0 ? void 0 : _q[1];
|
|
450
|
+
const method = (_r = message.messageStubParameters) === null || _r === void 0 ? void 0 : _r[2];
|
|
451
|
+
emitGroupRequestJoin(participant, action, method);
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
else if (content === null || content === void 0 ? void 0 : content.pollUpdateMessage) {
|
|
456
|
+
const creationMsgKey = content.pollUpdateMessage.pollCreationMessageKey;
|
|
457
|
+
// we need to fetch the poll creation message to get the poll enc key
|
|
458
|
+
const pollMsg = await getMessage(creationMsgKey);
|
|
459
|
+
if (pollMsg) {
|
|
460
|
+
const meIdNormalised = (0, WABinary_1.jidNormalizedUser)(meId);
|
|
461
|
+
const pollCreatorJid = (0, generics_1.getKeyAuthor)(creationMsgKey, meIdNormalised);
|
|
462
|
+
const voterJid = (0, generics_1.getKeyAuthor)(message.key, meIdNormalised);
|
|
463
|
+
const pollEncKey = (_s = pollMsg.messageContextInfo) === null || _s === void 0 ? void 0 : _s.messageSecret;
|
|
464
|
+
try {
|
|
465
|
+
const voteMsg = decryptPollVote(content.pollUpdateMessage.vote, {
|
|
466
|
+
pollEncKey,
|
|
467
|
+
pollCreatorJid,
|
|
468
|
+
pollMsgId: creationMsgKey.id,
|
|
469
|
+
voterJid,
|
|
470
|
+
});
|
|
471
|
+
ev.emit('messages.update', [
|
|
472
|
+
{
|
|
473
|
+
key: creationMsgKey,
|
|
474
|
+
update: {
|
|
475
|
+
pollUpdates: [
|
|
476
|
+
{
|
|
477
|
+
pollUpdateMessageKey: message.key,
|
|
478
|
+
vote: voteMsg,
|
|
479
|
+
senderTimestampMs: content.pollUpdateMessage.senderTimestampMs.toNumber(),
|
|
480
|
+
}
|
|
481
|
+
]
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
]);
|
|
485
|
+
}
|
|
486
|
+
catch (err) {
|
|
487
|
+
logger === null || logger === void 0 ? void 0 : logger.warn({ err, creationMsgKey }, 'failed to decrypt poll vote');
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
else {
|
|
491
|
+
logger === null || logger === void 0 ? void 0 : logger.warn({ creationMsgKey }, 'poll creation message not found, cannot decrypt update');
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
if (Object.keys(chat).length > 1) {
|
|
495
|
+
ev.emit('chats.update', [chat]);
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
exports.default = processMessage;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
class RateLimiter {
|
|
4
|
+
/**
|
|
5
|
+
* @param {object} [options] - Configuration options
|
|
6
|
+
* @param {number} [options.limitPerSecond=1] - Number of tasks to process per second
|
|
7
|
+
* @param {number} [options.maxRandomDelayMs=500] - Maximum random delay to add after each task in milliseconds
|
|
8
|
+
*/
|
|
9
|
+
constructor(options = {}) {
|
|
10
|
+
const { limitPerSecond = 1, maxRandomDelayMs = 500 } = options;
|
|
11
|
+
|
|
12
|
+
this.limitPerSecond = limitPerSecond;
|
|
13
|
+
this.interval = 1000 / this.limitPerSecond;
|
|
14
|
+
this.maxRandomDelayMs = maxRandomDelayMs;
|
|
15
|
+
|
|
16
|
+
this.queue = [];
|
|
17
|
+
this.processing = false;
|
|
18
|
+
this.lastSendTime = 0;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Add a task to the rate limiting queue
|
|
23
|
+
* @param {Function} task - Async function to execute
|
|
24
|
+
* @returns {Promise} - Promise that resolves when task is complete
|
|
25
|
+
*/
|
|
26
|
+
async add(task) {
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
this.queue.push({ task, resolve, reject });
|
|
29
|
+
if (!this.processing) {
|
|
30
|
+
this.process();
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
async process() {
|
|
35
|
+
if (this.processing || this.queue.length === 0) {
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
this.processing = true;
|
|
40
|
+
|
|
41
|
+
while (this.queue.length > 0) {
|
|
42
|
+
const { task, resolve, reject } = this.queue.shift();
|
|
43
|
+
const now = Date.now();
|
|
44
|
+
const timeSinceLastSend = now - this.lastSendTime;
|
|
45
|
+
if (timeSinceLastSend < this.interval) {
|
|
46
|
+
const waitTime = this.interval - timeSinceLastSend;
|
|
47
|
+
await new Promise(r => setTimeout(r, waitTime));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
try {
|
|
51
|
+
const result = await task();
|
|
52
|
+
this.lastSendTime = Date.now();
|
|
53
|
+
resolve(result);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
reject(error);
|
|
56
|
+
}
|
|
57
|
+
if (this.maxRandomDelayMs > 0) {
|
|
58
|
+
const randomDelay = Math.random() * this.maxRandomDelayMs;
|
|
59
|
+
await new Promise(r => setTimeout(r, randomDelay));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
this.processing = false;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Update the rate limit
|
|
68
|
+
* @param {number} newLimit - New messages per second limit
|
|
69
|
+
*/
|
|
70
|
+
setLimit(newLimit) {
|
|
71
|
+
this.limitPerSecond = newLimit;
|
|
72
|
+
this.interval = 1000 / newLimit;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Get current queue length
|
|
77
|
+
* @returns {number} - Number of pending tasks
|
|
78
|
+
*/
|
|
79
|
+
getQueueLength() {
|
|
80
|
+
return this.queue.length;
|
|
81
|
+
}
|
|
82
|
+
clear() {
|
|
83
|
+
this.queue.forEach(({ reject }) => {
|
|
84
|
+
reject(new Error('Rate limiter cleared'));
|
|
85
|
+
});
|
|
86
|
+
this.queue = [];
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
module.exports = RateLimiter;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.retryWithBackoff = void 0;
|
|
4
|
+
|
|
5
|
+
async function sleep(ms, signal) {
|
|
6
|
+
return new Promise((resolve, reject) => {
|
|
7
|
+
const t = setTimeout(resolve, ms);
|
|
8
|
+
if (signal) {
|
|
9
|
+
const onAbort = () => {
|
|
10
|
+
clearTimeout(t);
|
|
11
|
+
reject(Object.assign(new Error('aborted'), { code: 'ABORT_ERR' }));
|
|
12
|
+
};
|
|
13
|
+
if (signal.aborted) {
|
|
14
|
+
onAbort();
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function computeDelay(attempt, baseMs, maxMs, jitter) {
|
|
23
|
+
const exp = Math.min(maxMs, baseMs * Math.pow(2, attempt));
|
|
24
|
+
if (!jitter) return exp;
|
|
25
|
+
// full jitter strategy: random between 0 and exp
|
|
26
|
+
const rand = Math.random() * exp;
|
|
27
|
+
return Math.min(maxMs, rand);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function retryWithBackoff(fn, opts = {}) {
|
|
31
|
+
const {
|
|
32
|
+
retries = 3,
|
|
33
|
+
baseMs = 300,
|
|
34
|
+
maxMs = 5000,
|
|
35
|
+
jitter = true,
|
|
36
|
+
timeoutPerAttemptMs,
|
|
37
|
+
signal,
|
|
38
|
+
onRetry,
|
|
39
|
+
shouldRetry
|
|
40
|
+
} = opts;
|
|
41
|
+
let lastErr;
|
|
42
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
43
|
+
try {
|
|
44
|
+
if (timeoutPerAttemptMs && timeoutPerAttemptMs > 0) {
|
|
45
|
+
const ctrl = new AbortController();
|
|
46
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutPerAttemptMs);
|
|
47
|
+
try {
|
|
48
|
+
return await fn({ signal: ctrl.signal });
|
|
49
|
+
} finally {
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return await fn({ signal });
|
|
54
|
+
} catch (err) {
|
|
55
|
+
lastErr = err;
|
|
56
|
+
if (attempt === retries) break;
|
|
57
|
+
if (shouldRetry && !shouldRetry(err)) break;
|
|
58
|
+
if (onRetry) {
|
|
59
|
+
try { onRetry(err, attempt + 1); } catch {}
|
|
60
|
+
}
|
|
61
|
+
await sleep(computeDelay(attempt, baseMs, maxMs, jitter), signal);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
throw lastErr;
|
|
65
|
+
}
|
|
66
|
+
exports.retryWithBackoff = retryWithBackoff;
|