New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@darkcriminal/baileys

Package Overview
Dependencies
Maintainers
0
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@darkcriminal/baileys - npm Package Compare versions

Comparing version 1.0.0 to 2.0.0

lib/Socket/Client/types.d.ts

2

lib/Defaults/baileys-version.json
{
"version": [2, 3000, 1015901307]
"version": [2, 3000, 1017531287]
}
/// <reference types="node" />
/// <reference types="node" />
import { proto } from '../../WAProto';
import type { MediaType, SocketConfig } from '../Types';
export declare const UNAUTHORIZED_CODES: number[];
export declare const PHONENUMBER_MCC: {
"93": number;
"355": number;
"213": number;
"1-684": number;
"376": number;
"244": number;
"1-264": number;
"1-268": number;
"54": number;
"374": number;
"297": number;
"61": number;
"43": number;
"994": number;
"1-242": number;
"973": number;
"880": number;
"1-246": number;
"375": number;
"32": number;
"501": number;
"229": number;
"1-441": number;
"975": number;
"591": number;
"387": number;
"267": number;
"55": number;
"1-284": number;
"673": number;
"359": number;
"226": number;
"257": number;
"855": number;
"237": number;
"238": number;
"1-345": number;
"236": number;
"235": number;
"56": number;
"86": number;
"57": number;
"269": number;
"682": number;
"506": number;
"385": number;
"53": number;
"357": number;
"420": number;
"243": number;
"45": number;
"253": number;
"1-767": number;
"1-809": number;
"1-849": number;
"1-829": number;
"593": number;
"20": number;
"503": number;
"240": number;
"291": number;
"372": number;
"251": number;
"500": number;
"298": number;
"679": number;
"358": number;
"33": number;
"689": number;
"241": number;
"220": number;
"995": number;
"49": number;
"233": number;
"350": number;
"30": number;
"299": number;
"1-473": number;
"1-671": number;
"502": number;
"224": number;
"592": number;
"509": number;
"504": number;
"852": number;
"36": number;
"354": number;
"91": number;
"62": number;
"98": number;
"964": number;
"353": number;
"972": number;
"39": number;
"225": number;
"1-876": number;
"81": number;
"962": number;
"254": number;
"686": number;
"383": number;
"965": number;
"371": number;
"961": number;
"266": number;
"231": number;
"218": number;
"423": number;
"370": number;
"352": number;
"389": number;
"261": number;
"265": number;
"60": number;
"960": number;
"223": number;
"356": number;
"692": number;
"222": number;
"230": number;
"52": number;
"691": number;
"373": number;
"377": number;
"976": number;
"382": number;
"1-664": number;
"212": number;
"258": number;
"95": number;
"264": number;
"674": number;
"977": number;
"31": number;
"687": number;
"64": number;
"505": number;
"227": number;
"234": number;
"683": number;
"1-670": number;
"47": number;
"968": number;
"92": number;
"680": number;
"970": number;
"507": number;
"675": number;
"595": number;
"51": number;
"63": number;
"48": number;
"351": number;
"1-787, 1-939": number;
"974": number;
"242": number;
"40": number;
"7": number;
"250": number;
"290": number;
"1-869": number;
"1-758": number;
"508": number;
"1-784": number;
"685": number;
"378": number;
"239": number;
"966": number;
"221": number;
"381": number;
"248": number;
"232": number;
"65": number;
"386": number;
"677": number;
"27": number;
"211": number;
"34": number;
"94": number;
"249": number;
"597": number;
"268": number;
"46": number;
"41": number;
"963": number;
"886": number;
"992": number;
"255": number;
"66": number;
"228": number;
"690": number;
"676": number;
"1-868": number;
"216": number;
"90": number;
"993": number;
"1-649": number;
"688": number;
"1-340": number;
"256": number;
"380": number;
"971": number;
"44": number;
"1": number;
"598": number;
"998": number;
"678": number;
"379": number;
"58": number;
"681": number;
"967": number;
"260": number;
"263": number;
"670": number;
"245": number;
"856": number;
"599": number;
"850": number;
"262": number;
"82": number;
"84": number;
};
export declare const DEFAULT_ORIGIN = "https://web.whatsapp.com";
export declare const MOBILE_ENDPOINT = "g.whatsapp.net";
export declare const MOBILE_PORT = 443;
export declare const DEF_CALLBACK_PREFIX = "CB:";

@@ -235,6 +11,2 @@ export declare const DEF_TAG_PREFIX = "TAG:";

export declare const WA_DEFAULT_EPHEMERAL: number;
export declare const MOBILE_TOKEN: Buffer;
export declare const MOBILE_REGISTRATION_ENDPOINT = "https://v.whatsapp.net/v2";
export declare const MOBILE_USERAGENT: string;
export declare const REGISTRATION_PUBLIC_KEY: Buffer;
export declare const NOISE_MODE = "Noise_XX_25519_AESGCM_SHA256\0\0\0\0";

@@ -244,4 +16,2 @@ export declare const DICT_VERSION = 2;

export declare const NOISE_WA_HEADER: Buffer;
export declare const PROTOCOL_VERSION: number[];
export declare const MOBILE_NOISE_HEADER: Buffer;
/** from: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url */

@@ -248,0 +18,0 @@ export declare const URL_REGEX: RegExp;

@@ -6,4 +6,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_CACHE_TTLS = exports.INITIAL_PREKEY_COUNT = exports.MIN_PREKEY_COUNT = exports.MEDIA_KEYS = exports.MEDIA_HKDF_KEY_MAPPING = exports.MEDIA_PATH_MAP = exports.DEFAULT_CONNECTION_CONFIG = exports.PROCESSABLE_HISTORY_TYPES = exports.WA_CERT_DETAILS = exports.URL_REGEX = exports.MOBILE_NOISE_HEADER = exports.PROTOCOL_VERSION = exports.NOISE_WA_HEADER = exports.KEY_BUNDLE_TYPE = exports.DICT_VERSION = exports.NOISE_MODE = exports.REGISTRATION_PUBLIC_KEY = exports.MOBILE_USERAGENT = exports.MOBILE_REGISTRATION_ENDPOINT = exports.MOBILE_TOKEN = exports.WA_DEFAULT_EPHEMERAL = exports.PHONE_CONNECTION_CB = exports.DEF_TAG_PREFIX = exports.DEF_CALLBACK_PREFIX = exports.MOBILE_PORT = exports.MOBILE_ENDPOINT = exports.DEFAULT_ORIGIN = exports.PHONENUMBER_MCC = exports.UNAUTHORIZED_CODES = void 0;
const crypto_1 = require("crypto");
exports.DEFAULT_CACHE_TTLS = exports.INITIAL_PREKEY_COUNT = exports.MIN_PREKEY_COUNT = exports.MEDIA_KEYS = exports.MEDIA_HKDF_KEY_MAPPING = exports.MEDIA_PATH_MAP = exports.DEFAULT_CONNECTION_CONFIG = exports.PROCESSABLE_HISTORY_TYPES = exports.WA_CERT_DETAILS = exports.URL_REGEX = exports.NOISE_WA_HEADER = exports.KEY_BUNDLE_TYPE = exports.DICT_VERSION = exports.NOISE_MODE = exports.WA_DEFAULT_EPHEMERAL = exports.PHONE_CONNECTION_CB = exports.DEF_TAG_PREFIX = exports.DEF_CALLBACK_PREFIX = exports.DEFAULT_ORIGIN = exports.UNAUTHORIZED_CODES = void 0;
const WAProto_1 = require("../../WAProto");

@@ -14,8 +13,4 @@ const libsignal_1 = require("../Signal/libsignal");

const baileys_version_json_1 = require("./baileys-version.json");
const phonenumber_mcc_json_1 = __importDefault(require("./phonenumber-mcc.json"));
exports.UNAUTHORIZED_CODES = [401, 403, 419];
exports.PHONENUMBER_MCC = phonenumber_mcc_json_1.default;
exports.DEFAULT_ORIGIN = 'https://web.whatsapp.com';
exports.MOBILE_ENDPOINT = 'g.whatsapp.net';
exports.MOBILE_PORT = 443;
exports.DEF_CALLBACK_PREFIX = 'CB:';

@@ -25,11 +20,2 @@ exports.DEF_TAG_PREFIX = 'TAG:';

exports.WA_DEFAULT_EPHEMERAL = 7 * 24 * 60 * 60;
const WA_VERSION = '2.24.6.77';
const WA_VERSION_HASH = (0, crypto_1.createHash)('md5').update(WA_VERSION).digest('hex');
exports.MOBILE_TOKEN = Buffer.from('0a1mLfGUIBVrMKF1RdvLI5lkRBvof6vn0fD2QRSM' + WA_VERSION_HASH);
exports.MOBILE_REGISTRATION_ENDPOINT = 'https://v.whatsapp.net/v2';
exports.MOBILE_USERAGENT = `WhatsApp/${WA_VERSION} iOS/15.3.1 Device/Apple-iPhone_7`;
exports.REGISTRATION_PUBLIC_KEY = Buffer.from([
5, 142, 140, 15, 116, 195, 235, 197, 215, 166, 134, 92, 108, 60, 132, 56, 86, 176, 97, 33, 204, 232, 234, 119, 77,
34, 251, 111, 18, 37, 18, 48, 45,
]);
exports.NOISE_MODE = 'Noise_XX_25519_AESGCM_SHA256\0\0\0\0';

@@ -39,4 +25,2 @@ exports.DICT_VERSION = 2;

exports.NOISE_WA_HEADER = Buffer.from([87, 65, 6, exports.DICT_VERSION]); // last is "DICT_VERSION"
exports.PROTOCOL_VERSION = [5, 2];
exports.MOBILE_NOISE_HEADER = Buffer.concat([Buffer.from('WA'), Buffer.from(exports.PROTOCOL_VERSION)]);
/** from: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url */

@@ -43,0 +27,0 @@ exports.URL_REGEX = /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/;

/// <reference types="long" />
/// <reference types="node" />
/// <reference types="node" />
import { GetCatalogOptions, ProductCreate, ProductUpdate, SocketConfig } from '../Types';

@@ -110,2 +111,3 @@ import { BinaryNode } from '../WABinary';

cleanDirtyBits: (type: "account_sync" | "groups", fromTimestamp?: string | number | undefined) => Promise<void>;
addLabel: (jid: string, labels: import("../Types/Label").LabelActionBody) => Promise<void>;
addChatLabel: (jid: string, labelId: string) => Promise<void>;

@@ -120,3 +122,3 @@ removeChatLabel: (jid: string, labelId: string) => Promise<void>;

type: "md";
ws: any;
ws: import("./Client").WebSocketClient;
ev: import("../Types").BaileysEventEmitter & {

@@ -123,0 +125,0 @@ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;

/// <reference types="node" />
/// <reference types="node" />
import { Boom } from '@hapi/boom';
import { proto } from '../../WAProto';
import { ChatModification, MessageUpsertType, SocketConfig, WABusinessProfile, WAMediaUpload, WAPatchCreate, WAPresence, WAPrivacyCallValue, WAPrivacyGroupAddValue, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '../Types';
import { LabelActionBody } from '../Types/Label';
import { BinaryNode } from '../WABinary';

@@ -44,2 +46,3 @@ export declare const makeChatsSocket: (config: SocketConfig) => {

cleanDirtyBits: (type: 'account_sync' | 'groups', fromTimestamp?: number | string) => Promise<void>;
addLabel: (jid: string, labels: LabelActionBody) => Promise<void>;
addChatLabel: (jid: string, labelId: string) => Promise<void>;

@@ -54,3 +57,3 @@ removeChatLabel: (jid: string, labelId: string) => Promise<void>;

type: "md";
ws: any;
ws: import("./Client").WebSocketClient;
ev: import("../Types").BaileysEventEmitter & {

@@ -57,0 +60,0 @@ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;

@@ -186,2 +186,9 @@ "use strict";

const updateProfilePicture = async (jid, content) => {
let targetJid;
if (!jid) {
throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
}
if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
}
const { img } = await (0, Utils_1.generateProfilePicture)(content);

@@ -191,3 +198,4 @@ await query({

attrs: {
to: (0, WABinary_1.jidNormalizedUser)(jid),
target: targetJid,
to: WABinary_1.S_WHATSAPP_NET,
type: 'set',

@@ -207,6 +215,14 @@ xmlns: 'w:profile:picture'

const removeProfilePicture = async (jid) => {
let targetJid;
if (!jid) {
throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update');
}
if ((0, WABinary_1.jidNormalizedUser)(jid) !== (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id)) {
targetJid = (0, WABinary_1.jidNormalizedUser)(jid); // in case it is someone other than us
}
await query({
tag: 'iq',
attrs: {
to: (0, WABinary_1.jidNormalizedUser)(jid),
target: targetJid,
to: WABinary_1.S_WHATSAPP_NET,
type: 'set',

@@ -617,3 +633,3 @@ xmlns: 'w:profile:picture'

const fetchProps = async () => {
var _a, _b;
var _a, _b, _c;
const resultNode = await query({

@@ -636,4 +652,6 @@ tag: 'iq',

if (propsNode) {
authState.creds.lastPropHash = (_b = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash;
ev.emit('creds.update', authState.creds);
if ((_b = propsNode.attrs) === null || _b === void 0 ? void 0 : _b.hash) { // on some clients, the hash is returning as undefined
authState.creds.lastPropHash = (_c = propsNode === null || propsNode === void 0 ? void 0 : propsNode.attrs) === null || _c === void 0 ? void 0 : _c.hash;
ev.emit('creds.update', authState.creds);
}
props = (0, WABinary_1.reduceBinaryNodeToDictionary)(propsNode, 'prop');

@@ -665,2 +683,12 @@ }

/**
* Adds label
*/
const addLabel = (jid, labels) => {
return chatModify({
addLabel: {
...labels
}
}, jid);
};
/**
* Adds label for the chats

@@ -812,10 +840,9 @@ */

}
if (receivedPendingNotifications) {
// if we don't have the app state key
if (receivedPendingNotifications && // if we don't have the app state key
// we keep buffering events until we finally have
// the key and can sync the messages
if (!((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId) && !config.mobile) {
ev.buffer();
needToFlushWithAppStateSync = true;
}
// todo scrutinize
!((_a = authState.creds) === null || _a === void 0 ? void 0 : _a.myAppStateKeyId)) {
ev.buffer();
needToFlushWithAppStateSync = true;
}

@@ -852,2 +879,3 @@ });

cleanDirtyBits,
addLabel,
addChatLabel,

@@ -854,0 +882,0 @@ removeChatLabel,

@@ -1,3 +0,2 @@

export * from './abstract-socket-client';
export * from './mobile-socket-client';
export * from './web-socket-client';
export * from './types';
export * from './websocket';

@@ -17,4 +17,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./abstract-socket-client"), exports);
__exportStar(require("./mobile-socket-client"), exports);
__exportStar(require("./web-socket-client"), exports);
__exportStar(require("./types"), exports);
__exportStar(require("./websocket"), exports);
/// <reference types="node" />
/// <reference types="node" />
import { proto } from '../../WAProto';

@@ -84,2 +85,3 @@ import { GroupMetadata, ParticipantAction, SocketConfig } from '../Types';

cleanDirtyBits: (type: "account_sync" | "groups", fromTimestamp?: string | number | undefined) => Promise<void>;
addLabel: (jid: string, labels: import("../Types/Label").LabelActionBody) => Promise<void>;
addChatLabel: (jid: string, labelId: string) => Promise<void>;

@@ -94,3 +96,3 @@ removeChatLabel: (jid: string, labelId: string) => Promise<void>;

type: "md";
ws: any;
ws: import("./Client").WebSocketClient;
ev: import("../Types").BaileysEventEmitter & {

@@ -97,0 +99,0 @@ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;

/// <reference types="long" />
/// <reference types="node" />
/// <reference types="node" />
import { UserFacingSocketConfig } from '../Types';
declare const makeWASocket: (config: UserFacingSocketConfig) => {
register: (code: string) => Promise<import("./registration").ExistsResponse>;
requestRegistrationCode: (registrationOptions?: import("./registration").RegistrationOptions | undefined) => Promise<import("./registration").ExistsResponse>;
logger: import("pino").Logger<import("pino").LoggerOptions>;

@@ -21,8 +20,8 @@ getOrderDetails: (orderId: string, tokenBase64: string) => Promise<import("../Types").OrderDetails>;

productUpdate: (productId: string, update: import("../Types").ProductUpdate) => Promise<import("../Types").Product>;
sendMessageAck: ({ tag, attrs, content }: import("../index").BinaryNode) => Promise<void>;
sendRetryRequest: (node: import("../index").BinaryNode, forceIncludeKeys?: boolean) => Promise<void>;
sendMessageAck: ({ tag, attrs, content }: import("..").BinaryNode) => Promise<void>;
sendRetryRequest: (node: import("..").BinaryNode, forceIncludeKeys?: boolean) => Promise<void>;
rejectCall: (callId: string, callFrom: string) => Promise<void>;
fetchMessageHistory: (count: number, oldestMsgKey: import("../Types").WAProto.IMessageKey, oldestMsgTimestamp: number | import("long").Long) => Promise<string>;
requestPlaceholderResend: (messageKey: import("../Types").WAProto.IMessageKey) => Promise<string | undefined>;
getPrivacyTokens: (jids: string[]) => Promise<import("../index").BinaryNode>;
getPrivacyTokens: (jids: string[]) => Promise<import("..").BinaryNode>;
assertSessions: (jids: string[], force: boolean) => Promise<boolean>;

@@ -42,6 +41,6 @@ relayMessage: (jid: string, message: import("../Types").WAProto.IMessage, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList }: import("../Types").MessageRelayOptions) => Promise<string>;

} | undefined) => Promise<{
nodes: import("../index").BinaryNode[];
nodes: import("..").BinaryNode[];
shouldIncludeDeviceIdentity: boolean;
}>;
getUSyncDevices: (jids: string[], useCache: boolean, ignoreZeroDevices: boolean) => Promise<import("../index").JidWithDevice[]>;
getUSyncDevices: (jids: string[], useCache: boolean, ignoreZeroDevices: boolean) => Promise<import("..").JidWithDevice[]>;
updateMediaMessage: (message: import("../Types").WAProto.IWebMessageInfo) => Promise<import("../Types").WAProto.IWebMessageInfo>;

@@ -63,3 +62,3 @@ sendMessage: (jid: string, content: import("../Types").AnyMessageContent, options?: import("../Types").MiscMessageGenerationOptions) => Promise<import("../Types").WAProto.WebMessageInfo | undefined>;

jid: string;
content: import("../index").BinaryNode;
content: import("..").BinaryNode;
}[]>;

@@ -114,2 +113,3 @@ groupUpdateDescription: (jid: string, description?: string | undefined) => Promise<void>;

cleanDirtyBits: (type: "account_sync" | "groups", fromTimestamp?: string | number | undefined) => Promise<void>;
addLabel: (jid: string, labels: import("../Types/Label").LabelActionBody) => Promise<void>;
addChatLabel: (jid: string, labelId: string) => Promise<void>;

@@ -124,3 +124,3 @@ removeChatLabel: (jid: string, labelId: string) => Promise<void>;

type: "md";
ws: any;
ws: import("./Client").WebSocketClient;
ev: import("../Types").BaileysEventEmitter & {

@@ -140,7 +140,7 @@ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;

generateMessageTag: () => string;
query: (node: import("../index").BinaryNode, timeoutMs?: number | undefined) => Promise<import("../index").BinaryNode>;
query: (node: import("..").BinaryNode, timeoutMs?: number | undefined) => Promise<import("..").BinaryNode>;
waitForMessage: <T_2>(msgId: string, timeoutMs?: number | undefined) => Promise<T_2>;
waitForSocketOpen: () => Promise<void>;
sendRawMessage: (data: Uint8Array | Buffer) => Promise<void>;
sendNode: (frame: import("../index").BinaryNode) => Promise<void>;
sendNode: (frame: import("..").BinaryNode) => Promise<void>;
logout: (msg?: string | undefined) => Promise<void>;

@@ -153,4 +153,4 @@ end: (error: Error | undefined) => void;

waitForConnectionUpdate: (check: (u: Partial<import("../Types").ConnectionState>) => boolean | undefined, timeoutMs?: number | undefined) => Promise<void>;
sendWAMBuffer: (wamBuffer: Buffer) => Promise<import("../index").BinaryNode>;
sendWAMBuffer: (wamBuffer: Buffer) => Promise<import("..").BinaryNode>;
};
export default makeWASocket;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Defaults_1 = require("../Defaults");
const registration_1 = require("./registration");
const business_1 = require("./business");
// export the last socket layer
const makeWASocket = (config) => ((0, registration_1.makeRegistrationSocket)({
const makeWASocket = (config) => ((0, business_1.makeBusinessSocket)({
...Defaults_1.DEFAULT_CONNECTION_CONFIG,

@@ -8,0 +8,0 @@ ...config

/// <reference types="node" />
/// <reference types="node" />
import { Boom } from '@hapi/boom';

@@ -11,3 +12,3 @@ import { proto } from '../../WAProto';

fetchMessageHistory: (count: number, oldestMsgKey: WAMessageKey, oldestMsgTimestamp: number | Long) => Promise<string>;
requestPlaceholderResend: (messageKey: WAMessageKey) => Promise<'RESOLVED' | string | undefined>;
requestPlaceholderResend: (messageKey: WAMessageKey) => Promise<string | undefined>;
getPrivacyTokens: (jids: string[]) => Promise<BinaryNode>;

@@ -98,2 +99,3 @@ assertSessions: (jids: string[], force: boolean) => Promise<boolean>;

cleanDirtyBits: (type: "account_sync" | "groups", fromTimestamp?: string | number | undefined) => Promise<void>;
addLabel: (jid: string, labels: import("../Types/Label").LabelActionBody) => Promise<void>;
addChatLabel: (jid: string, labelId: string) => Promise<void>;

@@ -108,3 +110,3 @@ removeChatLabel: (jid: string, labelId: string) => Promise<void>;

type: "md";
ws: any;
ws: import("./Client").WebSocketClient;
ev: import("../Types").BaileysEventEmitter & {

@@ -111,0 +113,0 @@ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;

@@ -463,4 +463,3 @@ "use strict";

logger.debug({ participant, sendToAll }, 'forced new session for retry recp');
for (let i = 0; i < msgs.length; i++) {
const msg = msgs[i];
for (const [i, msg] of msgs.entries()) {
if (msg) {

@@ -508,55 +507,59 @@ updateSendMessageAgainCount(ids[i], participant);

}
await Promise.all([
processingMutex.mutex(async () => {
const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
if (typeof status !== 'undefined' &&
(
// basically, we only want to know when a message from us has been delivered to/read by the other person
// or another device of ours has read some messages
status > WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ||
!isNodeFromMe)) {
if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
if (attrs.participant) {
const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
ev.emit('message-receipt.update', ids.map(id => ({
try {
await Promise.all([
processingMutex.mutex(async () => {
const status = (0, Utils_1.getStatusFromReceiptType)(attrs.type);
if (typeof status !== 'undefined' &&
(
// basically, we only want to know when a message from us has been delivered to/read by the other person
// or another device of ours has read some messages
status > WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ||
!isNodeFromMe)) {
if ((0, WABinary_1.isJidGroup)(remoteJid) || (0, WABinary_1.isJidStatusBroadcast)(remoteJid)) {
if (attrs.participant) {
const updateKey = status === WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK ? 'receiptTimestamp' : 'readTimestamp';
ev.emit('message-receipt.update', ids.map(id => ({
key: { ...key, id },
receipt: {
userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
[updateKey]: +attrs.t
}
})));
}
}
else {
ev.emit('messages.update', ids.map(id => ({
key: { ...key, id },
receipt: {
userJid: (0, WABinary_1.jidNormalizedUser)(attrs.participant),
[updateKey]: +attrs.t
}
update: { status }
})));
}
}
else {
ev.emit('messages.update', ids.map(id => ({
key: { ...key, id },
update: { status }
})));
}
}
if (attrs.type === 'retry') {
// correctly set who is asking for the retry
key.participant = key.participant || attrs.from;
const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
if (willSendMessageAgain(ids[0], key.participant)) {
if (key.fromMe) {
try {
logger.debug({ attrs, key }, 'recv retry request');
await sendMessagesAgain(key, ids, retryNode);
if (attrs.type === 'retry') {
// correctly set who is asking for the retry
key.participant = key.participant || attrs.from;
const retryNode = (0, WABinary_1.getBinaryNodeChild)(node, 'retry');
if (willSendMessageAgain(ids[0], key.participant)) {
if (key.fromMe) {
try {
logger.debug({ attrs, key }, 'recv retry request');
await sendMessagesAgain(key, ids, retryNode);
}
catch (error) {
logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
}
}
catch (error) {
logger.error({ key, ids, trace: error.stack }, 'error in sending message again');
else {
logger.info({ attrs, key }, 'recv retry for not fromMe message');
}
}
else {
logger.info({ attrs, key }, 'recv retry for not fromMe message');
logger.info({ attrs, key }, 'will not send message again, as sent too many times');
}
}
else {
logger.info({ attrs, key }, 'will not send message again, as sent too many times');
}
}
}),
sendMessageAck(node)
]);
})
]);
}
finally {
await sendMessageAck(node);
}
};

@@ -570,23 +573,27 @@ const handleNotification = async (node) => {

}
await Promise.all([
processingMutex.mutex(async () => {
var _a;
const msg = await processNotification(node);
if (msg) {
const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
msg.key = {
remoteJid,
fromMe,
participant: node.attrs.participant,
id: node.attrs.id,
...(msg.key || {})
};
(_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
msg.messageTimestamp = +node.attrs.t;
const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
await upsertMessage(fullMsg, 'append');
}
}),
sendMessageAck(node)
]);
try {
await Promise.all([
processingMutex.mutex(async () => {
var _a;
const msg = await processNotification(node);
if (msg) {
const fromMe = (0, WABinary_1.areJidsSameUser)(node.attrs.participant || remoteJid, authState.creds.me.id);
msg.key = {
remoteJid,
fromMe,
participant: node.attrs.participant,
id: node.attrs.id,
...(msg.key || {})
};
(_a = msg.participant) !== null && _a !== void 0 ? _a : (msg.participant = node.attrs.participant);
msg.messageTimestamp = +node.attrs.t;
const fullMsg = WAProto_1.proto.WebMessageInfo.fromObject(msg);
await upsertMessage(fullMsg, 'append');
}
})
]);
}
finally {
await sendMessageAck(node);
}
};

@@ -619,58 +626,60 @@ const handleMessage = async (node) => {

}
if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.type) === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER) {
if (node.attrs.sender_pn) {
ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
}
if (((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.protocolMessage) === null || _c === void 0 ? void 0 : _c.type) === WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER && node.attrs.sender_pn) {
ev.emit('chats.phoneNumberShare', { lid: node.attrs.from, jid: node.attrs.sender_pn });
}
await Promise.all([
processingMutex.mutex(async () => {
await decrypt();
// message failed to decrypt
if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
retryMutex.mutex(async () => {
if (ws.isOpen) {
if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')) {
return;
try {
await Promise.all([
processingMutex.mutex(async () => {
await decrypt();
// message failed to decrypt
if (msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT) {
retryMutex.mutex(async () => {
if (ws.isOpen) {
if ((0, WABinary_1.getBinaryNodeChild)(node, 'unavailable')) {
return;
}
const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
await sendRetryRequest(node, !encNode);
if (retryRequestDelayMs) {
await (0, Utils_1.delay)(retryRequestDelayMs);
}
}
const encNode = (0, WABinary_1.getBinaryNodeChild)(node, 'enc');
await sendRetryRequest(node, !encNode);
if (retryRequestDelayMs) {
await (0, Utils_1.delay)(retryRequestDelayMs);
else {
logger.debug({ node }, 'connection closed, ignoring retry req');
}
});
}
else {
// no type in the receipt => message delivered
let type = undefined;
let participant = msg.key.participant;
if (category === 'peer') { // special peer message
type = 'peer_msg';
}
else {
logger.debug({ node }, 'connection closed, ignoring retry req');
else if (msg.key.fromMe) { // message was sent by us from a different device
type = 'sender';
// need to specially handle this case
if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
participant = author;
}
}
});
}
else {
// no type in the receipt => message delivered
let type = undefined;
let participant = msg.key.participant;
if (category === 'peer') { // special peer message
type = 'peer_msg';
}
else if (msg.key.fromMe) { // message was sent by us from a different device
type = 'sender';
// need to specially handle this case
if ((0, WABinary_1.isJidUser)(msg.key.remoteJid)) {
participant = author;
else if (!sendActiveReceipts) {
type = 'inactive';
}
await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
// send ack for history message
const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
if (isAnyHistoryMsg) {
const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
}
}
else if (!sendActiveReceipts) {
type = 'inactive';
}
await sendReceipt(msg.key.remoteJid, participant, [msg.key.id], type);
// send ack for history message
const isAnyHistoryMsg = (0, Utils_1.getHistoryMsg)(msg.message);
if (isAnyHistoryMsg) {
const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
await sendReceipt(jid, undefined, [msg.key.id], 'hist_sync');
}
}
(0, Utils_2.cleanMessage)(msg, authState.creds.me.id);
await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
}),
sendMessageAck(node)
]);
(0, Utils_2.cleanMessage)(msg, authState.creds.me.id);
await upsertMessage(msg, node.attrs.offline ? 'append' : 'notify');
})
]);
}
finally {
await sendMessageAck(node);
}
};

@@ -752,3 +761,3 @@ const fetchMessageHistory = async (count, oldestMsgKey, oldestMsgTimestamp) => {

// delete data once call has ended
if (status === 'reject' || status === 'accept' || status === 'timeout') {
if (status === 'reject' || status === 'accept' || status === 'timeout' || status === 'terminate') {
callOfferCache.del(call.id);

@@ -755,0 +764,0 @@ }

/// <reference types="node" />
/// <reference types="node" />
import { Boom } from '@hapi/boom';

@@ -90,2 +91,3 @@ import { proto } from '../../WAProto';

cleanDirtyBits: (type: "account_sync" | "groups", fromTimestamp?: string | number | undefined) => Promise<void>;
addLabel: (jid: string, labels: import("../Types/Label").LabelActionBody) => Promise<void>;
addChatLabel: (jid: string, labelId: string) => Promise<void>;

@@ -100,3 +102,3 @@ removeChatLabel: (jid: string, labelId: string) => Promise<void>;

type: "md";
ws: any;
ws: import("./Client").WebSocketClient;
ev: import("../Types").BaileysEventEmitter & {

@@ -103,0 +105,0 @@ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;

@@ -383,10 +383,9 @@ "use strict";

else {
const { user: meUser, device: meDevice } = (0, WABinary_1.jidDecode)(meId);
const { user: meUser } = (0, WABinary_1.jidDecode)(meId);
if (!participant) {
devices.push({ user });
// do not send message to self if the device is 0 (mobile)
if (!((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer' && user === meUser)) {
if (meDevice !== undefined && meDevice !== 0) {
devices.push({ user: meUser });
}
if (user !== meUser) {
devices.push({ user: meUser });
}
if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) !== 'peer') {
const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);

@@ -438,3 +437,3 @@ devices.push(...additionalDevices);

id: msgId,
type: 'text',
type: getMessageType(message),
...(additionalAttributes || {})

@@ -479,2 +478,8 @@ },

};
const getMessageType = (message) => {
if (message.pollCreationMessage || message.pollCreationMessageV2 || message.pollCreationMessageV3) {
return 'poll';
}
return 'text';
};
const getMediaType = (message) => {

@@ -649,3 +654,5 @@ if (message.imageMessage) {

const isPinMsg = 'pin' in content && !!content.pin;
const isPollMessage = 'poll' in content && !!content.poll;
const additionalAttributes = {};
const additionalNodes = [];
// required for delete

@@ -667,6 +674,14 @@ if (isDeleteMsg) {

}
else if (isPollMessage) {
additionalNodes.push({
tag: 'meta',
attrs: {
polltype: 'creation'
},
});
}
if ('cachedGroupMetadata' in options) {
console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
}
await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList });
await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, additionalAttributes, statusJidList: options.statusJidList, additionalNodes });
if (config.emitOwnEvents) {

@@ -673,0 +688,0 @@ process.nextTick(() => {

/// <reference types="node" />
/// <reference types="node" />
import { Boom } from '@hapi/boom';
import { SocketConfig } from '../Types';
import { BinaryNode } from '../WABinary';
import { WebSocketClient } from './Client';
/**

@@ -13,3 +15,3 @@ * Connects to WA servers and performs:

type: "md";
ws: any;
ws: WebSocketClient;
ev: import("../Types").BaileysEventEmitter & {

@@ -16,0 +18,0 @@ process(handler: (events: Partial<import("../Types").BaileysEventMap>) => void | Promise<void>): () => void;

@@ -23,11 +23,10 @@ "use strict";

const { waWebSocketUrl, connectTimeoutMs, logger, keepAliveIntervalMs, browser, auth: authState, printQRInTerminal, defaultQueryTimeoutMs, transactionOpts, qrTimeout, makeSignalRepository, } = config;
let url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
config.mobile = config.mobile || url.protocol === 'tcp:';
if (config.mobile && url.protocol !== 'tcp:') {
url = new url_1.URL(`tcp://${Defaults_1.MOBILE_ENDPOINT}:${Defaults_1.MOBILE_PORT}`);
const url = typeof waWebSocketUrl === 'string' ? new url_1.URL(waWebSocketUrl) : waWebSocketUrl;
if (config.mobile || url.protocol === 'tcp:') {
throw new boom_1.Boom('Mobile API is not supported anymore', { statusCode: Types_1.DisconnectReason.loggedOut });
}
if (!config.mobile && url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
if (url.protocol === 'wss' && ((_a = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _a === void 0 ? void 0 : _a.routingInfo)) {
url.searchParams.append('ED', authState.creds.routingInfo.toString('base64url'));
}
const ws = config.socket ? config.socket : config.mobile ? new Client_1.MobileSocketClient(url, config) : new Client_1.WebSocketClient(url, config);
const ws = new Client_1.WebSocketClient(url, config);
ws.connect();

@@ -40,4 +39,3 @@ const ev = (0, Utils_1.makeEventBuffer)(logger);

keyPair: ephemeralKeyPair,
NOISE_HEADER: config.mobile ? Defaults_1.MOBILE_NOISE_HEADER : Defaults_1.NOISE_WA_HEADER,
mobile: config.mobile,
NOISE_HEADER: Defaults_1.NOISE_WA_HEADER,
logger,

@@ -164,6 +162,3 @@ routingInfo: (_b = authState === null || authState === void 0 ? void 0 : authState.creds) === null || _b === void 0 ? void 0 : _b.routingInfo

let node;
if (config.mobile) {
node = (0, Utils_1.generateMobileNode)(config);
}
else if (!creds.me) {
if (!creds.me) {
node = (0, Utils_1.generateRegistrationNode)(creds, config);

@@ -238,7 +233,7 @@ logger.info({ node }, 'not logged in, attempting registration...');

const l2 = Array.isArray(frame.content) ? (_a = frame.content[0]) === null || _a === void 0 ? void 0 : _a.tag : '';
Object.keys(l1).forEach(key => {
for (const key of Object.keys(l1)) {
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]},${l2}`, frame) || anyTriggered;
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}:${l1[key]}`, frame) || anyTriggered;
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},${key}`, frame) || anyTriggered;
});
}
anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0},,${l2}`, frame) || anyTriggered;

@@ -245,0 +240,0 @@ anyTriggered = ws.emit(`${Defaults_1.DEF_CALLBACK_PREFIX}${l0}`, frame) || anyTriggered;

@@ -0,3 +1,4 @@

import { Store } from 'cache-manager';
import { AuthenticationCreds } from '../Types';
declare const makeCacheManagerAuthState: (store: Storage, sessionKey: string) => Promise<{
declare const makeCacheManagerAuthState: (store: Store, sessionKey: string) => Promise<{
clearState: () => Promise<void>;

@@ -4,0 +5,0 @@ saveCreds: () => Promise<void>;

@@ -185,12 +185,10 @@ "use strict";

list.upsert(msg, 'append');
if (type === 'notify') {
if (!chats.get(jid)) {
ev.emit('chats.upsert', [
{
id: jid,
conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
unreadCount: 1
}
]);
}
if (type === 'notify' && !chats.get(jid)) {
ev.emit('chats.upsert', [
{
id: jid,
conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
unreadCount: 1
}
]);
}

@@ -197,0 +195,0 @@ }

@@ -59,5 +59,5 @@ "use strict";

array.splice(0, array.length);
Object.keys(dict).forEach(key => {
for (const key of Object.keys(dict)) {
delete dict[key];
});
}
},

@@ -64,0 +64,0 @@ filter: (contain) => {

/// <reference types="node" />
/// <reference types="node" />
import type { proto } from '../../WAProto';
import { RegistrationOptions } from '../Socket/registration';
import type { Contact } from './Contact';

@@ -60,8 +60,3 @@ import type { MinimalMessage } from './Message';

accountSettings: AccountSettings;
deviceId: string;
phoneId: string;
identityId: Buffer;
registered: boolean;
backupToken: Buffer;
registration: RegistrationOptions;
pairingCode: string | undefined;

@@ -68,0 +63,0 @@ lastPropHash: string | undefined;

@@ -1,2 +0,2 @@

export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept';
export type WACallUpdateType = 'offer' | 'ringing' | 'timeout' | 'reject' | 'accept' | 'terminate';
export type WACallEvent = {

@@ -3,0 +3,0 @@ chatId: string;

import type { proto } from '../../WAProto';
import type { AccountSettings } from './Auth';
import type { BufferedEventData } from './Events';
import type { LabelActionBody } from './Label';
import type { ChatLabelAssociationActionBody } from './LabelAssociation';
import type { MessageLabelAssociationActionBody } from './LabelAssociation';
import type { MinimalMessage } from './Message';
import type { MinimalMessage, WAMessageKey } from './Message';
/** privacy settings in WhatsApp Web */

@@ -64,8 +65,8 @@ export type WAPrivacyValue = 'all' | 'contacts' | 'contact_blacklist' | 'none';

} | {
clear: 'all' | {
messages: {
id: string;
fromMe?: boolean;
timestamp: number;
}[];
clear: boolean;
} | {
deleteForMe: {
deleteMedia: boolean;
key: WAMessageKey;
timestamp: number;
};

@@ -87,2 +88,4 @@ } | {

} | {
addLabel: LabelActionBody;
} | {
addChatLabel: ChatLabelAssociationActionBody;

@@ -89,0 +92,0 @@ } | {

@@ -17,4 +17,4 @@ export interface Contact {

*/
imgUrl?: string | null | 'changed';
imgUrl?: string | null;
status?: string;
}

@@ -25,2 +25,3 @@ import type { Boom } from '@hapi/boom';

syncType?: proto.HistorySync.HistorySyncType;
peerDataRequestSessionId?: string | null;
};

@@ -121,2 +122,5 @@ /** upsert chats */

isLatest: boolean;
progress?: number | null;
syncType?: proto.HistorySync.HistorySyncType;
peerDataRequestSessionId?: string;
};

@@ -123,0 +127,0 @@ chatUpserts: {

@@ -13,2 +13,13 @@ export interface Label {

}
export interface LabelActionBody {
id: string;
/** Label name */
name?: string;
/** Label color ID */
color?: number;
/** Is label has been deleted */
deleted?: boolean;
/** WhatsApp has 5 predefined labels (New customer, New order & etc) */
predefinedId?: number;
}
/** WhatsApp has 20 predefined colors */

@@ -15,0 +26,0 @@ export declare enum LabelColor {

/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import { AxiosRequestConfig } from 'axios';

@@ -25,7 +26,9 @@ import type { Logger } from 'pino';

export import WAMessageStatus = proto.WebMessageInfo.Status;
export type WAMediaUpload = Buffer | {
export type WAMediaPayloadURL = {
url: URL | string;
} | {
};
export type WAMediaPayloadStream = {
stream: Readable;
};
export type WAMediaUpload = Buffer | WAMediaPayloadStream | WAMediaPayloadURL;
/** Set of message types that are supported by the library */

@@ -32,0 +35,0 @@ export type MessageType = keyof proto.Message;

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

keepAliveIntervalMs: number;
/** should baileys use the mobile api instead of the multi device api */
/** should baileys use the mobile api instead of the multi device api
* @deprecated This feature has been removed
*/
mobile?: boolean;

@@ -115,4 +117,2 @@ /** proxy agent */

makeSignalRepository: (auth: SignalAuthState) => SignalRepository;
/** Socket passthrough */
socket?: any;
};

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

const node_cache_1 = __importDefault(require("node-cache"));
const uuid_1 = require("uuid");
const Defaults_1 = require("../Defaults");

@@ -147,2 +146,3 @@ const crypto_2 = require("./crypto");

tries -= 1;
//eslint-disable-next-line max-depth
try {

@@ -196,9 +196,3 @@ await state.set(mutations);

},
// mobile creds
deviceId: Buffer.from((0, uuid_1.v4)().replace(/-/g, ''), 'hex').toString('base64url'),
phoneId: (0, uuid_1.v4)(),
identityId: (0, crypto_1.randomBytes)(20),
registered: false,
backupToken: (0, crypto_1.randomBytes)(20),
registration: {},
pairingCode: undefined,

@@ -205,0 +199,0 @@ lastPropHash: undefined,

/// <reference types="node" />
/// <reference types="node" />
import { AxiosRequestConfig } from 'axios';

@@ -32,3 +33,3 @@ import type { Logger } from 'pino';

}>;
export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosRequestConfig<any>) => Promise<{
export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosRequestConfig<{}>) => Promise<{
critical_block: {

@@ -60,4 +61,4 @@ patches: proto.ISyncdPatch[];

}>;
export declare const downloadExternalBlob: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<any>) => Promise<Buffer>;
export declare const downloadExternalPatch: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<any>) => Promise<proto.SyncdMutations>;
export declare const downloadExternalBlob: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => Promise<Buffer>;
export declare const downloadExternalPatch: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => Promise<proto.SyncdMutations>;
export declare const decodeSyncdSnapshot: (name: WAPatchName, snapshot: proto.ISyncdSnapshot, getAppStateSyncKey: FetchAppStateSyncKey, minimumVersionNumber: number | undefined, validateMacs?: boolean) => Promise<{

@@ -67,3 +68,3 @@ state: LTHashState;

}>;
export declare const decodePatches: (name: WAPatchName, syncds: proto.ISyncdPatch[], initial: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, options: AxiosRequestConfig<any>, minimumVersionNumber?: number, logger?: Logger, validateMacs?: boolean) => Promise<{
export declare const decodePatches: (name: WAPatchName, syncds: proto.ISyncdPatch[], initial: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, options: AxiosRequestConfig<{}>, minimumVersionNumber?: number, logger?: Logger, validateMacs?: boolean) => Promise<{
state: LTHashState;

@@ -70,0 +71,0 @@ mutationMap: ChatMutationMap;

@@ -308,4 +308,3 @@ "use strict";

const mutationMap = {};
for (let i = 0; i < syncds.length; i++) {
const syncd = syncds[i];
for (const syncd of syncds) {
const { version, keyId, snapshotMac } = syncd;

@@ -422,21 +421,27 @@ if (syncd.externalMutations) {

}
else if ('deleteForMe' in mod) {
const { timestamp, key, deleteMedia } = mod.deleteForMe;
patch = {
syncAction: {
deleteMessageForMeAction: {
deleteMedia,
messageTimestamp: timestamp
}
},
index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
type: 'regular_high',
apiVersion: 3,
operation: OP.SET
};
}
else if ('clear' in mod) {
if (mod.clear === 'all') {
throw new boom_1.Boom('not supported');
}
else {
const key = mod.clear.messages[0];
patch = {
syncAction: {
deleteMessageForMeAction: {
deleteMedia: false,
messageTimestamp: key.timestamp
}
},
index: ['deleteMessageForMe', jid, key.id, key.fromMe ? '1' : '0', '0'],
type: 'regular_high',
apiVersion: 3,
operation: OP.SET
};
}
patch = {
syncAction: {
clearChatAction: {} // add message range later
},
index: ['clearChat', jid, '1' /*the option here is 0 when keep starred messages is enabled*/, '0'],
type: 'regular_high',
apiVersion: 6,
operation: OP.SET
};
}

@@ -496,2 +501,18 @@ else if ('pin' in mod) {

}
else if ('addLabel' in mod) {
patch = {
syncAction: {
labelEditAction: {
name: mod.addLabel.name,
color: mod.addLabel.color,
predefinedId: mod.addLabel.predefinedId,
deleted: mod.addLabel.deleted
}
},
index: ['label_edit', mod.addLabel.id],
type: 'regular',
apiVersion: 3,
operation: OP.SET,
};
}
else if ('addChatLabel' in mod) {

@@ -498,0 +519,0 @@ patch = {

/// <reference types="node" />
/// <reference types="node" />
import { KeyPair } from '../Types';

@@ -3,0 +4,0 @@ /** prefix version byte to the pub keys, required for some curve crypto functions */

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

if (msg.senderKeyDistributionMessage) {
//eslint-disable-next-line max-depth
try {

@@ -158,0 +159,0 @@ await repository.processSenderKeyDistributionMessage({

@@ -141,3 +141,5 @@ "use strict";

};
function append(data, historyCache, event, eventData, logger) {
function append(data, historyCache, event,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
eventData, logger) {
var _a, _b, _c;

@@ -180,2 +182,5 @@ switch (event) {

data.historySets.empty = false;
data.historySets.syncType = eventData.syncType;
data.historySets.progress = eventData.progress;
data.historySets.peerDataRequestSessionId = eventData.peerDataRequestSessionId;
data.historySets.isLatest = eventData.isLatest || data.historySets.isLatest;

@@ -447,3 +452,6 @@ break;

contacts: Object.values(data.historySets.contacts),
isLatest: data.historySets.isLatest
syncType: data.historySets.syncType,
progress: data.historySets.progress,
isLatest: data.historySets.isLatest,
peerDataRequestSessionId: data.historySets.peerDataRequestSessionId
};

@@ -502,8 +510,6 @@ }

function concatChats(a, b) {
if (b.unreadCount === null) {
// neutralize unread counter
if (a.unreadCount < 0) {
a.unreadCount = undefined;
b.unreadCount = undefined;
}
if (b.unreadCount === null && // neutralize unread counter
a.unreadCount < 0) {
a.unreadCount = undefined;
b.unreadCount = undefined;
}

@@ -510,0 +516,0 @@ if (typeof a.unreadCount === 'number' && typeof b.unreadCount === 'number') {

/// <reference types="node" />
/// <reference types="node" />
import { AxiosRequestConfig } from 'axios';
import { Logger } from 'pino';
import { proto } from '../../WAProto';
import { BaileysEventEmitter, BaileysEventMap, BrowsersMap, WACallUpdateType, WAVersion } from '../Types';
import { BaileysEventEmitter, BaileysEventMap, BrowsersMap, ConnectionState, WACallUpdateType, WAVersion } from '../Types';
import { BinaryNode } from '../WABinary';

@@ -38,3 +39,3 @@ export declare const Browsers: BrowsersMap;

export declare function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T): (check: (u: BaileysEventMap[T]) => boolean | undefined, timeoutMs?: number) => Promise<void>;
export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<import("../Types").ConnectionState>) => boolean | undefined, timeoutMs?: number) => Promise<void>;
export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<ConnectionState>) => boolean | undefined, timeoutMs?: number) => Promise<void>;
export declare const printQRIfNecessaryListener: (ev: BaileysEventEmitter, logger: Logger) => void;

@@ -45,3 +46,3 @@ /**

*/
export declare const fetchLatestBaileysVersion: (options?: AxiosRequestConfig<any>) => Promise<{
export declare const fetchLatestBaileysVersion: (options?: AxiosRequestConfig<{}>) => Promise<{
version: WAVersion;

@@ -59,3 +60,3 @@ isLatest: boolean;

*/
export declare const fetchLatestWaWebVersion: (options: AxiosRequestConfig<any>) => Promise<{
export declare const fetchLatestWaWebVersion: (options: AxiosRequestConfig<{}>) => Promise<{
version: WAVersion;

@@ -91,3 +92,7 @@ isLatest: boolean;

export declare const isWABusinessPlatform: (platform: string) => boolean;
export declare function trimUndefined(obj: any): any;
export declare function trimUndefined(obj: {
[_: string]: any;
}): {
[_: string]: any;
};
export declare function bytesToCrockford(buffer: Buffer): string;
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -38,2 +61,3 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.BufferJSON = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
replacer: (k, value) => {

@@ -45,2 +69,3 @@ if (Buffer.isBuffer(value) || value instanceof Uint8Array || (value === null || value === void 0 ? void 0 : value.type) === 'Buffer') {

},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
reviver: (_, value) => {

@@ -93,3 +118,3 @@ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {

exports.encodeBigEndian = encodeBigEndian;
const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t);
const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0);
exports.toNumber = toNumber;

@@ -213,4 +238,3 @@ /** unix timestamp of a date in seconds */

if (qr) {
const QR = await import('qrcode-terminal')
.then(m => m.default || m)
const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).then(m => m.default || m)
.catch(() => {

@@ -329,3 +353,4 @@ logger.error('QR code terminal not added as dependency');

else {
status = 'reject';
//fired when accepted/rejected/timeout/caller hangs up
status = 'terminate';
}

@@ -356,3 +381,5 @@ break;

}
else if (((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
else if (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
((_b = error === null || error === void 0 ? void 0 : error.code) === null || _b === void 0 ? void 0 : _b.startsWith('E'))
|| ((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('timed out'))) { // handle ETIMEOUT, ENOTFOUND etc

@@ -372,2 +399,3 @@ statusCode = 408;

exports.isWABusinessPlatform = isWABusinessPlatform;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function trimUndefined(obj) {

@@ -387,4 +415,4 @@ for (const key in obj) {

const crockford = [];
for (let i = 0; i < buffer.length; i++) {
value = (value << 8) | (buffer[i] & 0xff);
for (const element of buffer) {
value = (value << 8) | (element & 0xff);
bitCount += 8;

@@ -391,0 +419,0 @@ while (bitCount >= 5) {

import { AxiosRequestConfig } from 'axios';
import { proto } from '../../WAProto';
import { Chat, Contact } from '../Types';
export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<proto.HistorySync>;
export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<{}>) => Promise<proto.HistorySync>;
export declare const processHistoryMessage: (item: proto.IHistorySync) => {

@@ -12,3 +12,3 @@ chats: Chat[];

};
export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<any>) => Promise<{
export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<{}>) => Promise<{
chats: Chat[];

@@ -15,0 +15,0 @@ contacts: Contact[];

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

syncType: item.syncType,
progress: item.progress,
progress: item.progress
};

@@ -82,0 +82,0 @@ };

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -28,3 +51,3 @@ exports.getUrlInfo = void 0;

const maxRetry = 5;
const { getLinkPreview } = await import('link-preview-js');
const { getLinkPreview } = await Promise.resolve().then(() => __importStar(require('link-preview-js')));
let previewLink = text;

@@ -31,0 +54,0 @@ if (!text.startsWith('https://') && !text.startsWith('http://')) {

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

const makeMutex = () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let task = Promise.resolve();

@@ -7,0 +8,0 @@ let taskTimeout;

/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import { Boom } from '@hapi/boom';

@@ -79,3 +80,3 @@ import { AxiosRequestConfig } from 'axios';

endByte?: number;
options?: AxiosRequestConfig<any>;
options?: AxiosRequestConfig<{}>;
};

@@ -82,0 +83,0 @@ export declare const getUrlFromDirectPath: (directPath: string) => string;

@@ -48,9 +48,7 @@ "use strict";

(async () => {
const jimp = await (import('jimp')
.catch(() => { }));
const jimp = await (Promise.resolve().then(() => __importStar(require('jimp'))).catch(() => { }));
return jimp;
})(),
(async () => {
const sharp = await (import('sharp')
.catch(() => { }));
const sharp = await (Promise.resolve().then(() => __importStar(require('sharp'))).catch(() => { }));
return sharp;

@@ -196,3 +194,3 @@ })()

async function getAudioDuration(buffer) {
const musicMetadata = await import('music-metadata');
const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')));
let metadata;

@@ -222,3 +220,3 @@ if (Buffer.isBuffer(buffer)) {

try {
const audioDecode = (buffer) => import('audio-decode').then(({ default: audioDecode }) => audioDecode(buffer));
const audioDecode = (buffer) => Promise.resolve().then(() => __importStar(require('audio-decode'))).then(({ default: audioDecode }) => audioDecode(buffer));
let audioData;

@@ -337,3 +335,3 @@ if (Buffer.isBuffer(buffer)) {

if (type === 'file') {
bodyPath = media.url;
bodyPath = media.url.toString();
}

@@ -361,6 +359,4 @@ else if (saveOriginalFileIfRequired) {

sha256Plain = sha256Plain.update(data);
if (writeStream) {
if (!writeStream.write(data)) {
await (0, events_1.once)(writeStream, 'drain');
}
if (writeStream && !writeStream.write(data)) {
await (0, events_1.once)(writeStream, 'drain');
}

@@ -545,2 +541,3 @@ onChunk(aes.update(data));

const url = `https://${hostname}${Defaults_1.MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let result;

@@ -677,5 +674,1 @@ try {

};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function __importStar(arg0) {
throw new Error('Function not implemented.');
}
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import { Logger } from 'pino';

@@ -4,0 +5,0 @@ import { type Transform } from 'stream';

@@ -696,13 +696,9 @@ "use strict";

var _a;
if (ctx) {
if (axios_1.default.isAxiosError(error)) {
// check if the message requires a reupload
if (REUPLOAD_REQUIRED_STATUS.includes((_a = error.response) === null || _a === void 0 ? void 0 : _a.status)) {
ctx.logger.info({ key: message.key }, 'sending reupload media request...');
// request reupload
message = await ctx.reuploadRequest(message);
const result = await downloadMsg();
return result;
}
}
if (ctx && axios_1.default.isAxiosError(error) && // check if the message requires a reupload
REUPLOAD_REQUIRED_STATUS.includes((_a = error.response) === null || _a === void 0 ? void 0 : _a.status)) {
ctx.logger.info({ key: message.key }, 'sending reupload media request...');
// request reupload
message = await ctx.reuploadRequest(message);
const result = await downloadMsg();
return result;
}

@@ -709,0 +705,0 @@ throw error;

/// <reference types="node" />
/// <reference types="node" />
import { Logger } from 'pino';

@@ -6,6 +7,5 @@ import { proto } from '../../WAProto';

import { BinaryNode } from '../WABinary';
export declare const makeNoiseHandler: ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, routingInfo }: {
export declare const makeNoiseHandler: ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }: {
keyPair: KeyPair;
NOISE_HEADER: Uint8Array;
mobile: boolean;
logger: Logger;

@@ -12,0 +12,0 @@ routingInfo?: Buffer | undefined;

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

};
const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, mobile, logger, routingInfo }) => {
const makeNoiseHandler = ({ keyPair: { private: privateKey, public: publicKey }, NOISE_HEADER, logger, routingInfo }) => {
logger = logger.child({ class: 'ns' });

@@ -87,12 +87,7 @@ const authenticate = (data) => {

const certDecoded = decrypt(serverHello.payload);
if (mobile) {
WAProto_1.proto.CertChain.NoiseCertificate.decode(certDecoded);
const { intermediate: certIntermediate } = WAProto_1.proto.CertChain.decode(certDecoded);
const { issuerSerial } = WAProto_1.proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details);
if (issuerSerial !== Defaults_1.WA_CERT_DETAILS.SERIAL) {
throw new boom_1.Boom('certification match failed', { statusCode: 400 });
}
else {
const { intermediate: certIntermediate } = WAProto_1.proto.CertChain.decode(certDecoded);
const { issuerSerial } = WAProto_1.proto.CertChain.NoiseCertificate.Details.decode(certIntermediate.details);
if (issuerSerial !== Defaults_1.WA_CERT_DETAILS.SERIAL) {
throw new boom_1.Boom('certification match failed', { statusCode: 400 });
}
}
const keyEnc = encrypt(noiseKey.public);

@@ -99,0 +94,0 @@ mixIntoKey(crypto_1.Curve.sharedKey(noiseKey.private, serverHello.ephemeral));

@@ -153,3 +153,4 @@ "use strict";

? isLatest
: undefined
: undefined,
peerDataRequestSessionId: histNotification.peerDataRequestSessionId
});

@@ -203,2 +204,3 @@ }

const { placeholderMessageResendResponse: retryResponse } = result;
//eslint-disable-next-line max-depth
if (retryResponse) {

@@ -205,0 +207,0 @@ const webMessageInfo = WAProto_1.proto.WebMessageInfo.decode(retryResponse.webMessageInfoBytes);

@@ -109,4 +109,6 @@ "use strict";

if (Array.isArray(deviceListNode === null || deviceListNode === void 0 ? void 0 : deviceListNode.content)) {
//eslint-disable-next-line max-depth
for (const { tag, attrs } of deviceListNode.content) {
const device = +attrs.id;
//eslint-disable-next-line max-depth
if (tag === 'device' && // ensure the "device" tag

@@ -113,0 +115,0 @@ (!excludeZeroDevices || device !== 0) && // if zero devices are not-excluded, or device is non zero

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

const useMultiFileAuthState = async (folder) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const writeData = (data, file) => {

@@ -29,0 +30,0 @@ const filePath = (0, path_1.join)(folder, fixFileName(file));

import { proto } from '../../WAProto';
import type { AuthenticationCreds, SignalCreds, SocketConfig } from '../Types';
import { BinaryNode } from '../WABinary';
export declare const generateMobileNode: (config: SocketConfig) => proto.IClientPayload;
export declare const generateLoginNode: (userJid: string, config: SocketConfig) => proto.IClientPayload;

@@ -6,0 +5,0 @@ export declare const generateRegistrationNode: ({ registrationId, signedPreKey, signedIdentityKey }: SignalCreds, config: SocketConfig) => proto.ClientPayload;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeSignedDeviceIdentity = exports.configureSuccessfulPairing = exports.generateRegistrationNode = exports.generateLoginNode = exports.generateMobileNode = void 0;
exports.encodeSignedDeviceIdentity = exports.configureSuccessfulPairing = exports.generateRegistrationNode = exports.generateLoginNode = void 0;
const boom_1 = require("@hapi/boom");

@@ -13,26 +13,15 @@ const crypto_1 = require("crypto");

const getUserAgent = (config) => {
var _a, _b;
const osVersion = config.mobile ? '15.3.1' : '0.1';
const version = config.mobile ? [2, 24, 6] : config.version;
const device = config.mobile ? 'iPhone_7' : 'Desktop';
const manufacturer = config.mobile ? 'Apple' : '';
const platform = config.mobile ? WAProto_1.proto.ClientPayload.UserAgent.Platform.IOS : WAProto_1.proto.ClientPayload.UserAgent.Platform.WEB;
const phoneId = config.mobile ? { phoneId: config.auth.creds.phoneId } : {};
return {
appVersion: {
primary: version[0],
secondary: version[1],
tertiary: version[2],
primary: config.version[0],
secondary: config.version[1],
tertiary: config.version[2],
},
platform,
platform: WAProto_1.proto.ClientPayload.UserAgent.Platform.WEB,
releaseChannel: WAProto_1.proto.ClientPayload.UserAgent.ReleaseChannel.RELEASE,
mcc: ((_a = config.auth.creds.registration) === null || _a === void 0 ? void 0 : _a.phoneNumberMobileCountryCode) || '000',
mnc: ((_b = config.auth.creds.registration) === null || _b === void 0 ? void 0 : _b.phoneNumberMobileNetworkCode) || '000',
osVersion: osVersion,
manufacturer,
device,
osBuildNumber: osVersion,
osVersion: '0.1',
device: 'Desktop',
osBuildNumber: '0.1',
localeLanguageIso6391: 'en',
localeCountryIso31661Alpha2: 'US',
...phoneId
localeCountryIso31661Alpha2: 'US'
};

@@ -57,28 +46,5 @@ };

};
if (!config.mobile) {
payload.webInfo = getWebInfo(config);
}
payload.webInfo = getWebInfo(config);
return payload;
};
const generateMobileNode = (config) => {
if (!config.auth.creds) {
throw new boom_1.Boom('No registration data found', { data: config });
}
const payload = {
...getClientPayload(config),
sessionId: Math.floor(Math.random() * 999999999 + 1),
shortConnect: true,
connectAttemptCount: 0,
device: 0,
dnsSource: {
appCached: false,
dnsMethod: WAProto_1.proto.ClientPayload.DNSSource.DNSResolutionMethod.SYSTEM,
},
passive: false,
pushName: 'test',
username: Number(`${config.auth.creds.registration.phoneNumberCountryCode}${config.auth.creds.registration.phoneNumberNationalNumber}`),
};
return WAProto_1.proto.ClientPayload.fromObject(payload);
};
exports.generateMobileNode = generateMobileNode;
const generateLoginNode = (userJid, config) => {

@@ -85,0 +51,0 @@ const { user, device } = (0, WABinary_1.jidDecode)(userJid);

@@ -33,9 +33,9 @@ "use strict";

exports.TOKEN_MAP = {};
for (let i = 0; i < exports.SINGLE_BYTE_TOKENS.length; i++) {
exports.TOKEN_MAP[exports.SINGLE_BYTE_TOKENS[i]] = { index: i };
for (const [i, SINGLE_BYTE_TOKEN] of exports.SINGLE_BYTE_TOKENS.entries()) {
exports.TOKEN_MAP[SINGLE_BYTE_TOKEN] = { index: i };
}
for (let i = 0; i < exports.DOUBLE_BYTE_TOKENS.length; i++) {
for (let j = 0; j < exports.DOUBLE_BYTE_TOKENS[i].length; j++) {
exports.TOKEN_MAP[exports.DOUBLE_BYTE_TOKENS[i][j]] = { dict: i, index: j };
for (const [i, DOUBLE_BYTE_TOKEN] of exports.DOUBLE_BYTE_TOKENS.entries()) {
for (const [j, element] of DOUBLE_BYTE_TOKEN.entries()) {
exports.TOKEN_MAP[element] = { dict: i, index: j };
}
}
/// <reference types="node" />
/// <reference types="node" />
import type { BinaryNode, BinaryNodeCodingOptions } from './types';

@@ -3,0 +4,0 @@ export declare const decompressingIfRequired: (buffer: Buffer) => Promise<Buffer>;

/// <reference types="node" />
/// <reference types="node" />
import type { BinaryNode, BinaryNodeCodingOptions } from './types';
export declare const encodeBinaryNode: (node: BinaryNode, opts?: Pick<BinaryNodeCodingOptions, 'TAGS' | 'TOKEN_MAP'>, buffer?: number[]) => Buffer;

@@ -43,3 +43,7 @@ "use strict";

};
const pushBytes = (bytes) => (bytes.forEach(b => buffer.push(b)));
const pushBytes = (bytes) => {
for (const b of bytes) {
buffer.push(b);
}
};
const pushInt16 = (value) => {

@@ -146,4 +150,3 @@ pushBytes([(value >> 8) & 0xff, value & 0xff]);

}
for (let i = 0; i < str.length; i++) {
const char = str[i];
for (const char of str) {
const isInNibbleRange = char >= '0' && char <= '9';

@@ -160,4 +163,3 @@ if (!isInNibbleRange && char !== '-' && char !== '.') {

}
for (let i = 0; i < str.length; i++) {
const char = str[i];
for (const char of str) {
const isInNibbleRange = char >= '0' && char <= '9';

@@ -164,0 +166,0 @@ if (!isInNibbleRange && !(char >= 'A' && char <= 'F') && !(char >= 'a' && char <= 'f')) {

/// <reference types="node" />
/// <reference types="node" />
import { proto } from '../../WAProto';

@@ -3,0 +4,0 @@ import { BinaryNode } from './types';

@@ -6,3 +6,3 @@ export declare const S_WHATSAPP_NET = "@s.whatsapp.net";

export declare const STORIES_JID = "status@broadcast";
export type JidServer = 'c.us' | 'g.us' | 'broadcast' | 's.whatsapp.net' | 'call' | 'lid';
export type JidServer = 'c.us' | 'g.us' | 'broadcast' | 's.whatsapp.net' | 'call' | 'lid' | 'newsletter';
export type JidWithDevice = {

@@ -13,3 +13,3 @@ user: string;

export type FullJid = JidWithDevice & {
server: JidServer | string;
server: JidServer;
domainType?: number;

@@ -16,0 +16,0 @@ };

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

return {
server,
server: server,
user,

@@ -26,0 +26,0 @@ domainType: server === 'lid' ? 1 : 0,

/// <reference types="node" />
/// <reference types="node" />
export declare class BinaryInfo {

@@ -8,6 +9,6 @@ protocolVersion: number;

props: {
[x: string]: any;
[x: string]: import("./constants").Value;
};
globals: {
[x: string]: any;
[x: string]: import("./constants").Value;
};

@@ -14,0 +15,0 @@ };

@@ -31,9 +31,10 @@ export declare const WEB_EVENTS: Event[];

props: {
[k in keyof EventByName<key>['props']]: any;
[k in keyof EventByName<key>['props']]: Value;
};
globals: {
[x: string]: any;
[x: string]: Value;
};
};
} & {};
export type Value = number | null | string;
export {};
/// <reference types="node" />
/// <reference types="node" />
import { BinaryInfo } from './BinaryInfo';
export declare const encodeWAM: (binaryInfo: BinaryInfo) => Buffer;

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

let offset = 0;
binaryInfo.buffer.forEach((buffer_) => {
for (const buffer_ of binaryInfo.buffer) {
buffer_.copy(buffer, offset);
offset += buffer_.length;
});
}
return buffer;

@@ -22,0 +22,0 @@ };

{
"name": "@darkcriminal/baileys",
"version": "1.0.0",
"version": "2.0.0",
"description": "Unofficial WhatsApp API",

@@ -20,3 +20,3 @@ "keywords": [

"license": "MIT",
"author": "Nimesh Official",
"author": "Nimesh Piyumal",
"main": "lib/index.js",

@@ -37,6 +37,5 @@ "types": "lib/index.d.ts",

"example": "node --inspect -r ts-node/register Example/example.ts",
"example:mobile": "node --inspect -r ts-node/register Example/example.ts --mobile",
"gen:protobuf": "sh WAProto/GenerateStatics.sh",
"lint": "eslint src --ext .js,.ts,.jsx,.tsx",
"lint:fix": "eslint src --fix --ext .js,.ts,.jsx,.tsx",
"lint": "eslint src --ext .js,.ts",
"lint:fix": "yarn lint --fix",
"prepack": "tsc",

@@ -50,6 +49,7 @@ "prepare": "tsc",

"@hapi/boom": "^9.1.3",
"@whiskeysockets/eslint-config": "github:whiskeysockets/eslint-config",
"async-lock": "^1.4.1",
"audio-decode": "^2.1.3",
"axios": "^1.6.0",
"cache-manager": "4.0.1",
"cache-manager": "^5.7.6",
"futoin-hkdf": "^1.5.1",

@@ -67,3 +67,2 @@ "libphonenumber-js": "^1.10.20",

"devDependencies": {
"@adiwajshing/eslint-config": "github:adiwajshing/eslint-config",
"@types/got": "^9.6.11",

@@ -76,3 +75,3 @@ "@types/jest": "^27.5.1",

"eslint": "^8.0.0",
"jest": "^29.7.0",
"jest": "^27.0.6",
"jimp": "^0.16.1",

@@ -85,6 +84,6 @@ "json": "^11.0.0",

"sharp": "^0.32.6",
"ts-jest": "^29.2.5",
"ts-jest": "^27.0.3",
"ts-node": "^10.8.1",
"typedoc": "^0.24.7",
"typescript": "^4.9.5"
"typescript": "^4.6.4"
},

@@ -91,0 +90,0 @@ "peerDependencies": {

@@ -21,3 +21,3 @@ # Baileys - Typescript/Javascript WhatsApp Web API

This is the only official repository and is maintained by the community.
**Join the Discord [here](https://discord.gg/WeJM5FP9GGF)**
**Join the Discord [here](https://discord.gg/WeJM5FP9GG)**

@@ -93,12 +93,2 @@ ## Example

**Note:** install `qrcode-terminal` using `yarn add qrcode-terminal` to auto-print the QR to the terminal.
**Note:** the code to support the legacy version of WA Web (pre multi-device) has been removed in v5. Only the standard multi-device connection is now supported. This is done as WA seems to have completely dropped support for the legacy version.
## Connecting native mobile api
Baileys also supports the native mobile API, which allows users to authenticate as a standalone WhatsApp client using their phone number.
Run the [example](Example/example.ts) file with ``--mobile`` cli flag to use the native mobile API.
## Configuring the Connection

@@ -105,0 +95,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc