Socket
Socket
Sign inDemoInstall

@jhonatant98/baileys

Package Overview
Dependencies
234
Maintainers
1
Versions
29
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 4.2.1 to 4.2.2

1

lib/Defaults/index.js

@@ -36,3 +36,2 @@ "use strict";

customUploadHosts: [],
treatCiphertextMessagesAsReal: false,
retryRequestDelayMs: 250

@@ -39,0 +38,0 @@ };

2

lib/LegacySocket/business.d.ts

@@ -36,3 +36,3 @@ /// <reference types="node" />

messageInfo: (jid: string, messageID: string) => Promise<import("../Types").WAProto.IUserReceipt[]>;
downloadMediaMessage: (message: import("../Types").WAProto.IWebMessageInfo, type?: "buffer" | "stream", options?: import("..").MediaDownloadOptions) => Promise<Buffer | import("stream").Transform>;
downloadMediaMessage: (message: import("../Types").WAProto.IWebMessageInfo, type?: "stream" | "buffer", options?: import("..").MediaDownloadOptions) => Promise<Buffer | import("stream").Transform>;
updateMediaMessage: (message: import("../Types").WAProto.IWebMessageInfo) => Promise<import("../Types").WAProto.IWebMessageInfo>;

@@ -39,0 +39,0 @@ fetchMessagesFromWA: (jid: string, count: number, cursor?: import("../Types").WAMessageCursor) => Promise<import("../Types").WAProto.WebMessageInfo[]>;

@@ -51,3 +51,3 @@ /// <reference types="node" />

messageInfo: (jid: string, messageID: string) => Promise<import("../Types").WAProto.IUserReceipt[]>;
downloadMediaMessage: (message: import("../Types").WAProto.IWebMessageInfo, type?: "buffer" | "stream", options?: import("..").MediaDownloadOptions) => Promise<Buffer | import("stream").Transform>;
downloadMediaMessage: (message: import("../Types").WAProto.IWebMessageInfo, type?: "stream" | "buffer", options?: import("..").MediaDownloadOptions) => Promise<Buffer | import("stream").Transform>;
updateMediaMessage: (message: import("../Types").WAProto.IWebMessageInfo) => Promise<import("../Types").WAProto.IWebMessageInfo>;

@@ -54,0 +54,0 @@ fetchMessagesFromWA: (jid: string, count: number, cursor?: import("../Types").WAMessageCursor) => Promise<import("../Types").WAProto.WebMessageInfo[]>;

@@ -35,3 +35,3 @@ /// <reference types="node" />

messageInfo: (jid: string, messageID: string) => Promise<import("../Types").WAProto.IUserReceipt[]>;
downloadMediaMessage: (message: import("../Types").WAProto.IWebMessageInfo, type?: "buffer" | "stream", options?: import("..").MediaDownloadOptions) => Promise<Buffer | import("stream").Transform>;
downloadMediaMessage: (message: import("../Types").WAProto.IWebMessageInfo, type?: "stream" | "buffer", options?: import("..").MediaDownloadOptions) => Promise<Buffer | import("stream").Transform>;
updateMediaMessage: (message: import("../Types").WAProto.IWebMessageInfo) => Promise<import("../Types").WAProto.IWebMessageInfo>;

@@ -38,0 +38,0 @@ fetchMessagesFromWA: (jid: string, count: number, cursor?: import("../Types").WAMessageCursor) => Promise<import("../Types").WAProto.WebMessageInfo[]>;

@@ -18,3 +18,3 @@ "use strict";

const makeMessagesSocket = (config) => {
const { logger, treatCiphertextMessagesAsReal } = config;
const { logger } = config;
const sock = (0, chats_1.default)(config);

@@ -98,4 +98,3 @@ const { ev, ws: socketEvents, query, generateMessageTag, currentEpoch, setQuery, state } = sock;

const protocolMessage = normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage;
if ((!!normalizedContent ||
(message.messageStubType === Types_1.WAMessageStubType.CIPHERTEXT && treatCiphertextMessagesAsReal))
if (!!normalizedContent
&& !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage)

@@ -102,0 +101,0 @@ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.reactionMessage)) {

@@ -53,5 +53,2 @@ /// <reference types="ws" />

}>;
mutationMutex: {
mutex<T>(code: () => T | Promise<T>): Promise<T>;
};
processingMutex: {

@@ -75,2 +72,3 @@ mutex<T>(code: () => T | Promise<T>): Promise<T>;

updateProfilePicture: (jid: string, content: import("../Types").WAMediaUpload) => Promise<void>;
updateProfileStatus: (status: string) => Promise<void>;
updateBlockStatus: (jid: string, action: "block" | "unblock") => Promise<void>;

@@ -84,2 +82,3 @@ getBusinessProfile: (jid: string) => Promise<void | import("../Types").WABusinessProfile>;

ev: import("../Types").BaileysEventEmitter & {
process(handler: (events: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void | Promise<void>): () => void;
buffer(): boolean;

@@ -94,3 +93,2 @@ flush(): Promise<void>;

user: import("../Types").Contact;
emitEventsFromMap: (map: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void;
generateMessageTag: () => string;

@@ -100,3 +98,3 @@ query: (node: import("../WABinary").BinaryNode, timeoutMs?: number) => Promise<import("../WABinary").BinaryNode>;

waitForSocketOpen: () => Promise<void>;
sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
sendRawMessage: (data: Buffer | Uint8Array) => Promise<void>;
sendNode: (frame: import("../WABinary").BinaryNode) => Promise<void>;

@@ -103,0 +101,0 @@ logout: () => Promise<void>;

@@ -6,5 +6,2 @@ /// <reference types="ws" />

export declare const makeChatsSocket: (config: SocketConfig) => {
mutationMutex: {
mutex<T>(code: () => T | Promise<T>): Promise<T>;
};
processingMutex: {

@@ -31,2 +28,3 @@ mutex<T>(code: () => T | Promise<T>): Promise<T>;

updateProfilePicture: (jid: string, content: WAMediaUpload) => Promise<void>;
updateProfileStatus: (status: string) => Promise<void>;
updateBlockStatus: (jid: string, action: 'block' | 'unblock') => Promise<void>;

@@ -40,2 +38,3 @@ getBusinessProfile: (jid: string) => Promise<WABusinessProfile | void>;

ev: import("../Types").BaileysEventEmitter & {
process(handler: (events: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void | Promise<void>): () => void;
buffer(): boolean;

@@ -50,3 +49,2 @@ flush(): Promise<void>;

user: import("../Types").Contact;
emitEventsFromMap: (map: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void;
generateMessageTag: () => string;

@@ -56,3 +54,3 @@ query: (node: BinaryNode, timeoutMs?: number) => Promise<BinaryNode>;

waitForSocketOpen: () => Promise<void>;
sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
sendRawMessage: (data: Buffer | Uint8Array) => Promise<void>;
sendNode: (frame: BinaryNode) => Promise<void>;

@@ -59,0 +57,0 @@ logout: () => Promise<void>;

@@ -18,7 +18,6 @@ "use strict";

const makeChatsSocket = (config) => {
const { logger, markOnlineOnConnect, treatCiphertextMessagesAsReal, downloadHistory } = config;
const { logger, markOnlineOnConnect, downloadHistory } = config;
const sock = (0, socket_1.makeSocket)(config);
const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, emitEventsFromMap, } = sock;
const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, } = sock;
let privacySettings;
const mutationMutex = (0, make_mutex_1.makeMutex)();
/** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */

@@ -144,2 +143,20 @@ const processingMutex = (0, make_mutex_1.makeMutex)();

};
/** update the profile status for yourself */
const updateProfileStatus = async (status) => {
await query({
tag: 'iq',
attrs: {
to: WABinary_1.S_WHATSAPP_NET,
type: 'set',
xmlns: 'status'
},
content: [
{
tag: 'status',
attrs: {},
content: Buffer.from(status, 'utf-8')
}
]
});
};
const fetchBlocklist = async () => {

@@ -443,3 +460,3 @@ var _a, _b;

logger.debug('resyncing main app state');
await (mutationMutex.mutex(() => resyncAppState(Types_1.ALL_WA_PATCH_NAMES, ctx))
await (processingMutex.mutex(() => resyncAppState(Types_1.ALL_WA_PATCH_NAMES, ctx))
.catch(err => (onUnexpectedError(err, 'main app sync'))));

@@ -455,3 +472,3 @@ };

let encodeResult;
await mutationMutex.mutex(async () => {
await processingMutex.mutex(async () => {
await authState.keys.transaction(async () => {

@@ -568,6 +585,21 @@ logger.debug({ patch: patchCreate }, 'applying app patch');

};
const processMessageLocal = async (msg) => {
const upsertMessage = async (msg, type) => {
var _a;
const startedBuffer = ev.buffer();
ev.emit('messages.upsert', { messages: [msg], type });
if (!!msg.pushName) {
let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
jid = (0, WABinary_1.jidNormalizedUser)(jid);
if (!msg.key.fromMe) {
ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
}
// update our pushname too
if (msg.key.fromMe && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
}
}
// process message and emit events
const newEvents = await (0, process_message_1.default)(msg, {
await (0, process_message_1.default)(msg, {
downloadHistory,
ev,
historyCache,

@@ -578,3 +610,2 @@ recvChats,

logger,
treatCiphertextMessagesAsReal
});

@@ -588,20 +619,5 @@ const isAnyHistoryMsg = (0, Utils_1.isHistoryMsg)(msg.message);

}
return newEvents;
};
const upsertMessage = async (msg, type) => {
var _a;
ev.emit('messages.upsert', { messages: [msg], type });
if (!!msg.pushName) {
let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
jid = (0, WABinary_1.jidNormalizedUser)(jid);
if (!msg.key.fromMe) {
ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
}
// update our pushname too
if (msg.key.fromMe && ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.name) !== msg.pushName) {
ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
}
if (startedBuffer) {
await ev.flush();
}
const events = await processMessageLocal(msg);
emitEventsFromMap(events);
};

@@ -637,3 +653,2 @@ ws.on('CB:presence', handlePresenceUpdate);

...sock,
mutationMutex,
processingMutex,

@@ -650,2 +665,3 @@ fetchPrivacySettings,

updateProfilePicture,
updateProfileStatus,
updateBlockStatus,

@@ -652,0 +668,0 @@ getBusinessProfile,

@@ -31,5 +31,2 @@ /// <reference types="ws" />

}>;
mutationMutex: {
mutex<T>(code: () => T | Promise<T>): Promise<T>;
};
processingMutex: {

@@ -56,2 +53,3 @@ mutex<T>(code: () => T | Promise<T>): Promise<T>;

updateProfilePicture: (jid: string, content: import("../Types").WAMediaUpload) => Promise<void>;
updateProfileStatus: (status: string) => Promise<void>;
updateBlockStatus: (jid: string, action: "block" | "unblock") => Promise<void>;

@@ -65,2 +63,3 @@ getBusinessProfile: (jid: string) => Promise<void | import("../Types").WABusinessProfile>;

ev: import("../Types").BaileysEventEmitter & {
process(handler: (events: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void | Promise<void>): () => void;
buffer(): boolean;

@@ -75,3 +74,2 @@ flush(): Promise<void>;

user: import("../Types").Contact;
emitEventsFromMap: (map: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void;
generateMessageTag: () => string;

@@ -81,3 +79,3 @@ query: (node: BinaryNode, timeoutMs?: number) => Promise<BinaryNode>;

waitForSocketOpen: () => Promise<void>;
sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
sendRawMessage: (data: Buffer | Uint8Array) => Promise<void>;
sendNode: (frame: BinaryNode) => Promise<void>;

@@ -84,0 +82,0 @@ logout: () => Promise<void>;

@@ -127,2 +127,3 @@ "use strict";

}]);
const started = ev.buffer();
// if we have the full message key

@@ -161,2 +162,5 @@ // update the invite message to be expired

}, 'notify');
if (started) {
await ev.flush();
}
return results.attrs.from;

@@ -163,0 +167,0 @@ },

@@ -53,5 +53,2 @@ /// <reference types="ws" />

}>;
mutationMutex: {
mutex<T>(code: () => T | Promise<T>): Promise<T>;
};
processingMutex: {

@@ -75,2 +72,3 @@ mutex<T>(code: () => T | Promise<T>): Promise<T>;

updateProfilePicture: (jid: string, content: import("../Types").WAMediaUpload) => Promise<void>;
updateProfileStatus: (status: string) => Promise<void>;
updateBlockStatus: (jid: string, action: "block" | "unblock") => Promise<void>;

@@ -84,2 +82,3 @@ getBusinessProfile: (jid: string) => Promise<void | import("../Types").WABusinessProfile>;

ev: import("../Types").BaileysEventEmitter & {
process(handler: (events: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void | Promise<void>): () => void;
buffer(): boolean;

@@ -94,3 +93,2 @@ flush(): Promise<void>;

user: import("../Types").Contact;
emitEventsFromMap: (map: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void;
generateMessageTag: () => string;

@@ -100,3 +98,3 @@ query: (node: import("..").BinaryNode, timeoutMs?: number) => Promise<import("..").BinaryNode>;

waitForSocketOpen: () => Promise<void>;
sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
sendRawMessage: (data: Buffer | Uint8Array) => Promise<void>;
sendNode: (frame: import("..").BinaryNode) => Promise<void>;

@@ -103,0 +101,0 @@ logout: () => Promise<void>;

@@ -41,5 +41,2 @@ /// <reference types="ws" />

}>;
mutationMutex: {
mutex<T>(code: () => T | Promise<T>): Promise<T>;
};
processingMutex: {

@@ -63,2 +60,3 @@ mutex<T>(code: () => T | Promise<T>): Promise<T>;

updateProfilePicture: (jid: string, content: import("../Types").WAMediaUpload) => Promise<void>;
updateProfileStatus: (status: string) => Promise<void>;
updateBlockStatus: (jid: string, action: "block" | "unblock") => Promise<void>;

@@ -72,2 +70,3 @@ getBusinessProfile: (jid: string) => Promise<void | import("../Types").WABusinessProfile>;

ev: import("../Types").BaileysEventEmitter & {
process(handler: (events: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void | Promise<void>): () => void;
buffer(): boolean;

@@ -82,3 +81,2 @@ flush(): Promise<void>;

user: import("../Types").Contact;
emitEventsFromMap: (map: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void;
generateMessageTag: () => string;

@@ -88,3 +86,3 @@ query: (node: BinaryNode, timeoutMs?: number) => Promise<BinaryNode>;

waitForSocketOpen: () => Promise<void>;
sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
sendRawMessage: (data: Buffer | Uint8Array) => Promise<void>;
sendNode: (frame: BinaryNode) => Promise<void>;

@@ -91,0 +89,0 @@ logout: () => Promise<void>;

@@ -16,3 +16,3 @@ "use strict";

const sock = (0, messages_send_1.makeMessagesSocket)(config);
const { ev, authState, ws, mutationMutex, processingMutex, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, } = sock;
const { ev, authState, ws, processingMutex, upsertMessage, resyncAppState, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, } = sock;
/** this mutex ensures that each retryRequest will wait for the previous one to finish */

@@ -210,3 +210,3 @@ const retryMutex = (0, make_mutex_1.makeMutex)();

const name = update.attrs.name;
await mutationMutex.mutex(() => resyncAppState([name], undefined));
await resyncAppState([name], undefined);
}

@@ -456,8 +456,8 @@ }

// called when all offline notifs are handled
ws.on('CB:ib,,offline', (node) => {
ws.on('CB:ib,,offline', async (node) => {
const child = (0, WABinary_1.getBinaryNodeChild)(node, 'offline');
const offlineNotifs = +child.attrs.count;
logger.info(`handled ${offlineNotifs} offline messages/notifications`);
await ev.flush();
ev.emit('connection.update', { receivedPendingNotifications: true });
ev.flush();
});

@@ -504,3 +504,3 @@ // recv a message

const protoMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
ev.emit('messages.upsert', { messages: [protoMsg], type: call.offline ? 'append' : 'notify' });
upsertMessage(protoMsg, call.offline ? 'append' : 'notify');
}

@@ -507,0 +507,0 @@ });

@@ -39,5 +39,2 @@ /// <reference types="ws" />

}>;
mutationMutex: {
mutex<T>(code: () => T | Promise<T>): Promise<T>;
};
processingMutex: {

@@ -61,2 +58,3 @@ mutex<T>(code: () => T | Promise<T>): Promise<T>;

updateProfilePicture: (jid: string, content: import("../Types").WAMediaUpload) => Promise<void>;
updateProfileStatus: (status: string) => Promise<void>;
updateBlockStatus: (jid: string, action: "block" | "unblock") => Promise<void>;

@@ -70,2 +68,3 @@ getBusinessProfile: (jid: string) => Promise<void | import("../Types").WABusinessProfile>;

ev: import("../Types").BaileysEventEmitter & {
process(handler: (events: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void | Promise<void>): () => void;
buffer(): boolean;

@@ -80,3 +79,2 @@ flush(): Promise<void>;

user: import("../Types").Contact;
emitEventsFromMap: (map: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void;
generateMessageTag: () => string;

@@ -86,3 +84,3 @@ query: (node: BinaryNode, timeoutMs?: number) => Promise<BinaryNode>;

waitForSocketOpen: () => Promise<void>;
sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
sendRawMessage: (data: Buffer | Uint8Array) => Promise<void>;
sendNode: (frame: BinaryNode) => Promise<void>;

@@ -89,0 +87,0 @@ logout: () => Promise<void>;

@@ -458,3 +458,3 @@ "use strict";

const resultStr = WAProto_1.proto.MediaRetryNotification.MediaRetryNotificationResultType[media.result];
throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: MEDIA_RETRY_STATUS_MAP[media.result] || 404 });
throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
}

@@ -520,7 +520,1 @@ content.directPath = media.directPath;

exports.makeMessagesSocket = makeMessagesSocket;
const MEDIA_RETRY_STATUS_MAP = {
[WAProto_1.proto.MediaRetryNotification.MediaRetryNotificationResultType.SUCCESS]: 200,
[WAProto_1.proto.MediaRetryNotification.MediaRetryNotificationResultType.DECRYPTION_ERROR]: 412,
[WAProto_1.proto.MediaRetryNotification.MediaRetryNotificationResultType.NOT_FOUND]: 404,
[WAProto_1.proto.MediaRetryNotification.MediaRetryNotificationResultType.GENERAL_ERROR]: 418,
};
/// <reference types="node" />
import WebSocket from 'ws';
import { AuthenticationCreds, BaileysEventEmitter, BaileysEventMap, SocketConfig } from '../Types';
import { SocketConfig } from '../Types';
import { BinaryNode } from '../WABinary';

@@ -14,3 +14,4 @@ /**

ws: WebSocket;
ev: BaileysEventEmitter & {
ev: import("../Types").BaileysEventEmitter & {
process(handler: (events: Partial<import("../Types").BaileysEventMap<import("../Types").AuthenticationCreds>>) => void | Promise<void>): () => void;
buffer(): boolean;

@@ -21,7 +22,6 @@ flush(): Promise<void>;

authState: {
creds: AuthenticationCreds;
creds: import("../Types").AuthenticationCreds;
keys: import("../Types").SignalKeyStoreWithTransaction;
};
readonly user: import("../Types").Contact;
emitEventsFromMap: (map: Partial<BaileysEventMap<AuthenticationCreds>>) => void;
generateMessageTag: () => string;

@@ -28,0 +28,0 @@ query: (node: BinaryNode, timeoutMs?: number) => Promise<BinaryNode>;

@@ -8,3 +8,2 @@ "use strict";

const boom_1 = require("@hapi/boom");
const events_1 = __importDefault(require("events"));
const util_1 = require("util");

@@ -32,4 +31,3 @@ const ws_1 = __importDefault(require("ws"));

ws.setMaxListeners(0);
const _ev = new events_1.default();
const ev = (0, event_buffer_1.makeEventBuffer)(_ev, logger);
const ev = (0, event_buffer_1.makeEventBuffer)(logger);
/** ephemeral key pair used to encrypt/decrypt communication. Unique for each connection */

@@ -319,7 +317,2 @@ const ephemeralKeyPair = Utils_1.Curve.generateKeyPair();

}));
const emitEventsFromMap = (map) => {
for (const key in map) {
ev.emit(key, map[key]);
}
};
/** logout & invalidate connection */

@@ -461,3 +454,2 @@ const logout = async () => {

},
emitEventsFromMap,
generateMessageTag,

@@ -464,0 +456,0 @@ query,

@@ -39,6 +39,4 @@ /// <reference types="node" />

customUploadHosts: MediaConnInfo['hosts'];
/** fires a conversationTimestamp & read count update on CIPHERTEXT messages */
treatCiphertextMessagesAsReal: boolean;
/** time to wait between sending new retry requests */
retryRequestDelayMs: number;
};

@@ -16,3 +16,3 @@ /// <reference types="node" />

[indexMacBase64: string]: {
valueMac: Uint8Array | Buffer;
valueMac: Buffer | Uint8Array;
};

@@ -25,3 +25,3 @@ };

[indexMacBase64: string]: {
valueMac: Uint8Array | Buffer;
valueMac: Buffer | Uint8Array;
};

@@ -28,0 +28,0 @@ };

/// <reference types="node" />
import { KeyPair } from '../Types';
/** prefix version byte to the pub keys, required for some curve crypto functions */
export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Uint8Array | Buffer;
export declare const generateSignalPubKey: (pubKey: Uint8Array | Buffer) => Buffer | Uint8Array;
export declare const Curve: {

@@ -6,0 +6,0 @@ generateKeyPair: () => KeyPair;

import { Logger } from 'pino';
import { BaileysEventEmitter } from '../Types';
import { AuthenticationCreds, BaileysEventEmitter, BaileysEventMap } from '../Types';
/**
* A map that contains a list of all events that have been triggered
*
* Note, this can contain different type of events
* this can make processing events extremely efficient -- since everything
* can be done in a single transaction
*/
declare type BaileysEventData = Partial<BaileysEventMap<AuthenticationCreds>>;
declare type BaileysBufferableEventEmitter = BaileysEventEmitter & {
/** Use to process events in a batch */
process(handler: (events: BaileysEventData) => void | Promise<void>): (() => void);
/**

@@ -19,3 +29,3 @@ * starts buffering events, call flush() to release them

*/
export declare const makeEventBuffer: (ev: BaileysEventEmitter, logger: Logger) => BaileysBufferableEventEmitter;
export declare const makeEventBuffer: (logger: Logger) => BaileysBufferableEventEmitter;
export {};
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeEventBuffer = void 0;
const events_1 = __importDefault(require("events"));
const Types_1 = require("../Types");

@@ -26,7 +30,23 @@ const messages_1 = require("./messages");

*/
const makeEventBuffer = (ev, logger) => {
const makeEventBuffer = (logger) => {
const ev = new events_1.default();
let data = makeBufferData();
let isBuffering = false;
let preBufferTask = Promise.resolve();
// take the generic event and fire it as a baileys event
ev.on('event', (map) => {
for (const event in map) {
ev.emit(event, map[event]);
}
});
return {
process(handler) {
const listener = (map) => {
handler(map);
};
ev.on('event', listener);
return () => {
ev.off('event', listener);
};
},
emit(event, evData) {

@@ -37,3 +57,3 @@ if (isBuffering && BUFFERABLE_EVENT_SET.has(event)) {

}
return ev.emit(event, evData);
return ev.emit('event', { [event]: evData });
},

@@ -59,3 +79,3 @@ processInBuffer(task) {

isBuffering = false;
flush(data, ev);
ev.emit('event', consolidateEvents(data));
data = makeBufferData();

@@ -247,3 +267,3 @@ logger.trace('released buffered events');

const chat = data.chatUpdates[chatId] || data.chatUpserts[chatId];
if ((0, process_message_1.isRealMessage)(message, false)
if ((0, process_message_1.isRealMessage)(message)
&& (0, process_message_1.shouldIncrementChatUnread)(message)

@@ -260,38 +280,53 @@ && typeof chat.unreadCount !== 'undefined'

}
function flush(data, ev) {
function consolidateEvents(data) {
const map = {};
const chatUpsertList = Object.values(data.chatUpserts);
chatUpsertList.length && ev.emit('chats.upsert', chatUpsertList);
if (chatUpsertList.length) {
map['chats.upsert'] = chatUpsertList;
}
const chatUpdateList = Object.values(data.chatUpdates);
chatUpdateList.length && ev.emit('chats.update', chatUpdateList);
if (chatUpdateList.length) {
map['chats.update'] = chatUpdateList;
}
const chatDeleteList = Array.from(data.chatDeletes);
chatDeleteList.length && ev.emit('chats.delete', chatDeleteList);
if (chatDeleteList.length) {
map['chats.delete'] = chatDeleteList;
}
const messageUpsertList = Object.values(data.messageUpserts);
if (messageUpsertList.length) {
const appends = [];
const notifys = [];
for (const { message, type } of messageUpsertList) {
const arr = type === 'append' ? appends : notifys;
arr.push(message);
}
if (appends.length) {
ev.emit('messages.upsert', { type: 'append', messages: appends });
}
if (notifys.length) {
ev.emit('messages.upsert', { type: 'notify', messages: notifys });
}
const type = messageUpsertList[0].type;
map['messages.upsert'] = {
messages: messageUpsertList.map(m => m.message),
type
};
}
const messageUpdateList = Object.values(data.messageUpdates);
messageUpdateList.length && ev.emit('messages.update', messageUpdateList);
if (messageUpdateList.length) {
map['messages.update'] = messageUpdateList;
}
const messageDeleteList = Object.values(data.messageDeletes);
messageDeleteList.length && ev.emit('messages.delete', { keys: messageDeleteList });
if (messageDeleteList.length) {
map['messages.delete'] = { keys: messageDeleteList };
}
const messageReactionList = Object.values(data.messageReactions).flatMap(({ key, reactions }) => reactions.flatMap(reaction => ({ key, reaction })));
messageReactionList.length && ev.emit('messages.reaction', messageReactionList);
if (messageReactionList.length) {
map['messages.reaction'] = messageReactionList;
}
const messageReceiptList = Object.values(data.messageReceipts).flatMap(({ key, userReceipt }) => userReceipt.flatMap(receipt => ({ key, receipt })));
messageReceiptList.length && ev.emit('message-receipt.update', messageReceiptList);
if (messageReceiptList.length) {
map['message-receipt.update'] = messageReceiptList;
}
const contactUpsertList = Object.values(data.contactUpserts);
contactUpsertList.length && ev.emit('contacts.upsert', contactUpsertList);
if (contactUpsertList.length) {
map['contacts.upsert'] = contactUpsertList;
}
const contactUpdateList = Object.values(data.contactUpdates);
contactUpdateList.length && ev.emit('contacts.update', contactUpdateList);
if (contactUpdateList.length) {
map['contacts.update'] = contactUpdateList;
}
const groupUpdateList = Object.values(data.groupUpdates);
groupUpdateList.length && ev.emit('groups.update', groupUpdateList);
if (groupUpdateList.length) {
map['groups.update'] = groupUpdateList;
}
return map;
}

@@ -298,0 +333,0 @@ function concatChats(a, b) {

@@ -73,1 +73,2 @@ /// <reference types="node" />

}, mediaKey: Uint8Array, msgId: string) => proto.MediaRetryNotification;
export declare const getStatusCodeForMediaRetry: (code: number) => any;

@@ -26,3 +26,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.extensionForMediaMessage = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.encryptedStream = exports.getHttpStream = exports.generateThumbnail = exports.getStream = exports.toBuffer = exports.toReadable = exports.getAudioDuration = exports.mediaMessageSHA256B64 = exports.generateProfilePicture = exports.extractImageThumb = exports.getMediaKeys = exports.hkdfInfoKey = void 0;
exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.extensionForMediaMessage = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.encryptedStream = exports.getHttpStream = exports.generateThumbnail = exports.getStream = exports.toBuffer = exports.toReadable = exports.getAudioDuration = exports.mediaMessageSHA256B64 = exports.generateProfilePicture = exports.extractImageThumb = exports.getMediaKeys = exports.hkdfInfoKey = void 0;
const boom_1 = require("@hapi/boom");

@@ -549,3 +549,3 @@ const child_process_1 = require("child_process");

const errorCode = +errorNode.attrs.code;
event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, { data: errorNode.attrs });
event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, { data: errorNode.attrs, statusCode: (0, exports.getStatusCodeForMediaRetry)(errorCode) });
}

@@ -572,1 +572,9 @@ else {

exports.decryptMediaRetryData = decryptMediaRetryData;
const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
const MEDIA_RETRY_STATUS_MAP = {
[WAProto_1.proto.MediaRetryNotification.MediaRetryNotificationResultType.SUCCESS]: 200,
[WAProto_1.proto.MediaRetryNotification.MediaRetryNotificationResultType.DECRYPTION_ERROR]: 412,
[WAProto_1.proto.MediaRetryNotification.MediaRetryNotificationResultType.NOT_FOUND]: 404,
[WAProto_1.proto.MediaRetryNotification.MediaRetryNotificationResultType.GENERAL_ERROR]: 418,
};

@@ -56,3 +56,3 @@ /// <reference types="node" />

/** Checks whether the given message is a media message; if it is returns the inner content */
export declare const assertMediaContent: (content: proto.IMessage) => proto.IAudioMessage | proto.IDocumentMessage | proto.IImageMessage | proto.IVideoMessage | proto.IStickerMessage;
export declare const assertMediaContent: (content: proto.IMessage) => proto.IVideoMessage | proto.IImageMessage | proto.IAudioMessage | proto.IDocumentMessage | proto.IStickerMessage;
export {};

@@ -225,2 +225,5 @@ "use strict";

else if ('react' in message) {
if (!message.react.senderTimestampMs) {
message.react.senderTimestampMs = Date.now();
}
m.reactionMessage = Types_1.WAProto.ReactionMessage.fromObject(message.react);

@@ -227,0 +230,0 @@ }

import type { Logger } from 'pino';
import { proto } from '../../WAProto';
import { AuthenticationCreds, BaileysEventMap, InitialReceivedChatsState, SignalKeyStoreWithTransaction } from '../Types';
import { AuthenticationCreds, BaileysEventEmitter, InitialReceivedChatsState, SignalKeyStoreWithTransaction } from '../Types';
declare type ProcessMessageContext = {

@@ -10,10 +10,10 @@ historyCache: Set<string>;

keyStore: SignalKeyStoreWithTransaction;
ev: BaileysEventEmitter;
logger?: Logger;
treatCiphertextMessagesAsReal?: boolean;
};
/** Cleans a received message to further processing */
export declare const cleanMessage: (message: proto.IWebMessageInfo, meId: string) => void;
export declare const isRealMessage: (message: proto.IWebMessageInfo, treatCiphertextMessagesAsReal: boolean) => boolean;
export declare const isRealMessage: (message: proto.IWebMessageInfo) => boolean;
export declare const shouldIncrementChatUnread: (message: proto.IWebMessageInfo) => boolean;
declare const processMessage: (message: proto.IWebMessageInfo, { downloadHistory, historyCache, recvChats, creds, keyStore, logger, treatCiphertextMessagesAsReal }: ProcessMessageContext) => Promise<Partial<BaileysEventMap<any>>>;
declare const processMessage: (message: proto.IWebMessageInfo, { downloadHistory, ev, historyCache, recvChats, creds, keyStore, logger }: ProcessMessageContext) => Promise<void>;
export default processMessage;

@@ -31,7 +31,6 @@ "use strict";

exports.cleanMessage = cleanMessage;
const isRealMessage = (message, treatCiphertextMessagesAsReal) => {
const isRealMessage = (message) => {
const normalizedContent = (0, Utils_1.normalizeMessageContent)(message.message);
return (!!normalizedContent
|| MSG_MISSED_CALL_TYPES.has(message.messageStubType)
|| (message.messageStubType === Types_1.WAMessageStubType.CIPHERTEXT && treatCiphertextMessagesAsReal))
|| MSG_MISSED_CALL_TYPES.has(message.messageStubType))
&& !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.protocolMessage)

@@ -43,9 +42,8 @@ && !(normalizedContent === null || normalizedContent === void 0 ? void 0 : normalizedContent.reactionMessage);

exports.shouldIncrementChatUnread = shouldIncrementChatUnread;
const processMessage = async (message, { downloadHistory, historyCache, recvChats, creds, keyStore, logger, treatCiphertextMessagesAsReal }) => {
const processMessage = async (message, { downloadHistory, ev, historyCache, recvChats, creds, keyStore, logger }) => {
var _a;
const meId = creds.me.id;
const { accountSettings } = creds;
const map = {};
const chat = { id: (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid) };
if ((0, exports.isRealMessage)(message, treatCiphertextMessagesAsReal)) {
if ((0, exports.isRealMessage)(message)) {
chat.conversationTimestamp = (0, Utils_1.toNumber)(message.messageTimestamp);

@@ -72,18 +70,17 @@ // only increment unread count if not CIPHERTEXT and from another person

if (chats.length) {
map['chats.set'] = { chats, isLatest };
ev.emit('chats.set', { chats, isLatest });
}
if (messages.length) {
map['messages.set'] = { messages, isLatest };
ev.emit('messages.set', { messages, isLatest });
}
if (contacts.length) {
map['contacts.set'] = { contacts, isLatest };
ev.emit('contacts.set', { contacts, isLatest });
}
if (didProcess) {
map['creds.update'] = {
...(map['creds.update'] || {}),
ev.emit('creds.update', {
processedHistoryMessages: [
...(creds.processedHistoryMessages || []),
{ key: message.key, timestamp: message.messageTimestamp }
{ key: message.key, messageTimestamp: message.messageTimestamp }
]
};
});
}

@@ -104,3 +101,3 @@ }

});
map['creds.update'] = { myAppStateKeyId: newAppStateSyncKeyId };
ev.emit('creds.update', { myAppStateKeyId: newAppStateSyncKeyId });
}

@@ -112,3 +109,3 @@ else {

case WAProto_1.proto.ProtocolMessage.ProtocolMessageType.REVOKE:
map['messages.update'] = [
ev.emit('messages.update', [
{

@@ -121,3 +118,3 @@ key: {

}
];
]);
break;

@@ -137,6 +134,6 @@ case WAProto_1.proto.ProtocolMessage.ProtocolMessageType.EPHEMERAL_SETTING:

};
map['messages.reaction'] = [{
ev.emit('messages.reaction', [{
reaction,
key: content.reactionMessage.key,
}];
}]);
}

@@ -147,5 +144,5 @@ else if (message.messageStubType) {

let participants;
const emitParticipantsUpdate = (action) => (map['group-participants.update'] = { id: jid, participants, action });
const emitParticipantsUpdate = (action) => (ev.emit('group-participants.update', { id: jid, participants, action }));
const emitGroupUpdate = (update) => {
map['groups.update'] = [{ id: jid, ...update }];
ev.emit('groups.update', [{ id: jid, ...update }]);
};

@@ -196,6 +193,5 @@ const participantsIncludesMe = () => participants.find(jid => (0, WABinary_1.areJidsSameUser)(meId, jid));

if (Object.keys(chat).length > 1) {
map['chats.update'] = [chat];
ev.emit('chats.update', [chat]);
}
return map;
};
exports.default = processMessage;

@@ -38,3 +38,3 @@ /// <reference types="node" />

privKey: Buffer;
pubKey: Uint8Array | Buffer;
pubKey: Buffer | Uint8Array;
};

@@ -41,0 +41,0 @@ };

@@ -7,3 +7,3 @@ /// <reference types="node" />

export declare const getBinaryNodeChild: ({ content }: BinaryNode, childTag: string) => BinaryNode;
export declare const getBinaryNodeChildBuffer: (node: BinaryNode, childTag: string) => Uint8Array | Buffer;
export declare const getBinaryNodeChildBuffer: (node: BinaryNode, childTag: string) => Buffer | Uint8Array;
export declare const getBinaryNodeChildString: (node: BinaryNode, childTag: string) => string;

@@ -10,0 +10,0 @@ export declare const getBinaryNodeChildUInt: (node: BinaryNode, childTag: string, length: number) => number;

{
"name": "@jhonatant98/baileys",
"version": "4.2.1",
"version": "4.2.2",
"description": "WhatsApp API",

@@ -5,0 +5,0 @@ "homepage": "https://github.com/adiwajshing/Baileys",

@@ -127,4 +127,2 @@ # Baileys - Typescript/Javascript WhatsApp Web API

printQRInTerminal: boolean
/** fires a conversationTimestamp & read count update on CIPHERTEXT messages */
treatCiphertextMessagesAsReal: boolean
/**

@@ -415,3 +413,3 @@ * fetch a message from your store

react: {
text: "💖",
text: "💖", // use an empty string to remove the reaction
key: message.key

@@ -693,2 +691,7 @@ }

```
- To change your profile status
``` ts
const status = 'Hello World!'
await sock.updateProfileStatus(status)
```
- To get the display picture of some person/group

@@ -695,0 +698,0 @@ ``` ts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc