npm package: @kripikindomart/baileys-gateway
Description: Advanced WhatsApp Gateway with Multi-Session Support, Group Caching, Poll Decryption, and User Queries
Author: Kripik Indomart
Latest version: 1.0.0

# Baileys Gateway - Advanced WhatsApp Multi-Session Library

[![npm version](https://badge.fury.io/js/baileys-gateway.svg)](https://badge.fury.io/js/baileys-gateway)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A comprehensive WhatsApp gateway built on Baileys with multi-session support, group metadata caching, poll decryption, user queries, and much more.

## 🚀 Features

### ✅ Core Features
- **Multi-Session Support** - Manage multiple WhatsApp instances simultaneously
- **QR Code & Pairing Code Connection** - Flexible connection methods
- **Full History Sync** - Retrieve complete chat history
- **Message Store** - In-memory storage for improved retry system
- **Auto-Reconnection** - Automatic reconnection with backoff strategy
- **Health Monitoring** - Session health checks and statistics

### 📁 Advanced Features
- **Group Metadata Caching** - Cache group information for performance
- **Poll Votes Decryption** - Decrypt encrypted poll votes automatically
- **Send States in Chat** - Read receipts and presence updates
- **User Queries** - Profile pictures, status, business profiles
- **Privacy Settings** - Block/unblock users, privacy management
- **Profile Management** - Update profile name, status, picture
- **Event-Driven Architecture** - Comprehensive event system

### 🎯 Message Features
- **All Message Types** - Text, image, video, audio, document, location, contact
- **Media Messages** - Support for images, videos, audio, documents with thumbnails
- **Interactive Messages** - Buttons, lists, polls, reactions
- **Message Modification** - Edit, delete, pin messages
- **Forward Messages** - Message forwarding support
- **Mentions & Quotes** - Rich message formatting

## 📦 Installation

```bash
npm install baileys-gateway
```

## 🚀 Quick Start

### Basic Usage

```javascript
import { BaileysGateway, EVENTS } from 'baileys-gateway';

// Create gateway
const gateway = new BaileysGateway();

// Setup message listener
gateway.on(EVENTS.MESSAGE_RECEIVED, (data) => {
  console.log('New message:', data);
});

// Start a session
const sessionInfo = await gateway.startSession('my-session');

// Send message
await gateway.sendMessage('my-session', '628123456789@s.whatsapp.net', 'Hello World!');
```

### Quick Start Function

```javascript
import { quickStart } from 'baileys-gateway';

const { gateway, session } = await quickStart('default-session');
console.log('Gateway ready!');
```

## 📚 API Documentation

### Gateway Class

#### Constructor

```javascript
const gateway = new BaileysGateway(options);
```

**Options:**
- `sessionFolder` (string): Directory to store session files (default: './sessions')
- `autoLoad` (boolean): Auto-load existing sessions on startup (default: true)
- `maxSessions` (number): Maximum number of sessions (default: 100)

#### Session Management

```javascript
// Start new session
const sessionInfo = await gateway.startSession(sessionId, options);

// Stop session
const success = await gateway.stopSession(sessionId);

// Delete session
const success = await gateway.deleteSession(sessionId);

// Get session
const session = gateway.getSession(sessionId);

// Get all sessions
const sessions = gateway.getAllSessions();

// Get connected sessions
const connected = gateway.getConnectedSessions();
```

#### Messaging

```javascript
// Send text message
const result = await gateway.sendMessage(sessionId, jid, 'Hello World!');

// Send image
const result = await gateway.sendMessage(sessionId, jid, {
  type: 'image',
  image: './path/to/image.jpg',
  caption: 'Check this out!'
});

// Send buttons
const result = await gateway.sendMessage(sessionId, jid, {
  type: 'buttons',
  text: 'Choose an option:',
  buttons: [
    { buttonId: 'btn1', buttonText: { displayText: 'Option 1' } },
    { buttonId: 'btn2', buttonText: { displayText: 'Option 2' } }
  ]
});

// Send list
const result = await gateway.sendMessage(sessionId, jid, {
  type: 'list',
  text: 'Choose from list:',
  buttonText: 'View Options',
  sections: [{
    title: 'Options',
    rows: [
      { rowId: 'opt1', title: 'Option 1', description: 'Description 1' },
      { rowId: 'opt2', title: 'Option 2', description: 'Description 2' }
    ]
  }]
});
```

#### Events

```javascript
// Message received
gateway.on(EVENTS.MESSAGE_RECEIVED, (data) => {
  console.log('Message:', data);
});

// QR Code updated
gateway.on(EVENTS.QR_UPDATED, (data) => {
  console.log('QR Code:', data.qr);
});

// Connected
gateway.on(EVENTS.CONNECTED, (data) => {
  console.log('Connected:', data.sessionId);
});

// Disconnected
gateway.on(EVENTS.DISCONNECTED, (data) => {
  console.log('Disconnected:', data.sessionId);
});
```

### Utils Class

#### Phone Number Operations

```javascript
import { Utils } from 'baileys-gateway';

// Format phone number to JID
const jid = Utils.formatPhoneNumber('08123456789');
// Result: '628123456789@s.whatsapp.net'

// Extract phone number from JID
const number = Utils.extractPhoneNumber('628123456789@s.whatsapp.net');
// Result: '628123456789'

// Generate session ID
const sessionId = Utils.generateSessionId('device');
// Result: 'device_1234567890_abc123'
```

#### Message Operations

```javascript
// Get message type
const type = Utils.getMessageType(messageObject);

// Extract text from message
const text = Utils.extractText(messageObject);

// Extract media info
const mediaInfo = Utils.extractMediaInfo(messageObject);
```

## 🌐 Building Your API

This library is designed to be the foundation for your WhatsApp API. Here's a simple example:

```javascript
import express from 'express';
import { BaileysGateway, Utils } from 'baileys-gateway';

const app = express();
app.use(express.json());

const gateway = new BaileysGateway();

// Create session
app.post('/sessions', async (req, res) => {
  try {
    const { sessionId } = req.body;
    const sessionInfo = await gateway.startSession(sessionId);
    res.json({ success: true, data: sessionInfo });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// Send message
app.post('/send/:sessionId', async (req, res) => {
  try {
    const { sessionId } = req.params;
    const { number, message } = req.body;

    const jid = Utils.formatPhoneNumber(number);
    const result = await gateway.sendMessage(sessionId, jid, message);

    res.json({ success: true, data: result });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// Get QR code
app.get('/sessions/:sessionId/qr', (req, res) => {
  try {
    const { sessionId } = req.params;
    const qr = gateway.getQRCode(sessionId);

    if (!qr) {
      return res.status(404).json({ success: false, error: 'QR not available' });
    }

    res.json({ success: true, data: { qr } });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// Real-time messages via WebSocket (optional)
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });

gateway.on(EVENTS.MESSAGE_RECEIVED, (message) => {
  wss.clients.forEach(client => {
    if (client.readyState === client.OPEN) {
      client.send(JSON.stringify(message));
    }
  });
});

app.listen(3000, () => {
  console.log('WhatsApp API running on port 3000');
  console.log('WebSocket server running on port 8080');
});
```

## 📁 Project Structure

```
baileys-gateway/
├── src/
│   ├── index.js          # Main exports
│   ├── Gateway.js        # Main gateway class
│   ├── Session.js        # Individual session management
│   ├── Messenger.js      # Message sending functionality
│   ├── Utils.js          # Utility functions
│   └── Constants.js      # Configuration constants
├── examples/
│   ├── test.js           # Basic usage example
│   └── api-example.js    # REST API example
└── README.md
```

## 🔧 Configuration

### Session Options

```javascript
const sessionInfo = await gateway.startSession(sessionId, {
  printQR: true,           // Print QR to terminal
  sessionFolder: './sessions', // Custom session folder
  browser: ['My App', 'Chrome', '10.0'], // Custom browser
  connectTimeoutMs: 60000, // Connection timeout
  maxRetries: 10          // Maximum retry attempts
});
```

### Gateway Options

```javascript
const gateway = new BaileysGateway({
  sessionFolder: './my-sessions', // Custom session folder
  autoLoad: false,           // Don't auto-load sessions
  maxSessions: 50            // Maximum sessions
});
```

## 🎯 Events

The gateway emits the following events:

- `EVENTS.QR_UPDATED`: QR code is available
- `EVENTS.CONNECTING`: Session is connecting
- `EVENTS.CONNECTED`: Session is connected
- `EVENTS.DISCONNECTED`: Session is disconnected
- `EVENTS.MESSAGE_RECEIVED`: New message received
- `EVENTS.MESSAGE_UPDATED`: Message status updated
- `EVENTS.SESSION_READY`: Session is ready for use
- `EVENTS.ERROR`: Error occurred

## 🚨 Error Handling

The library provides comprehensive error handling:

```javascript
try {
  await gateway.startSession('new-session');
} catch (error) {
  if (error.message.includes('already exists')) {
    console.log('Session already exists');
  } else {
    console.error('Error:', error.message);
  }
}
```

## 🔄 Migration from wa-multi-session

If you're migrating from `wa-multi-session`, the API is similar but cleaner:

```javascript
// Old wa-multi-session
import { startSession, onMessageReceived } from 'wa-multi-session';

// New Baileys Gateway
import { BaileysGateway, EVENTS } from 'baileys-gateway';

const gateway = new BaileysGateway();
gateway.on(EVENTS.MESSAGE_RECEIVED, handler);
await gateway.startSession('session-id');
```

## 📄 License

MIT License

## 🙏 Acknowledgments

- Built on top of [@whiskeysockets/baileys](https://github.com/WhiskeySockets/Baileys)
- Inspired by [wa-multi-session](https://github.com/mimamch/wa-multi-session) architecture