npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

wasp-protocol

v0.3.2

Published

Production-ready WhatsApp Session Protocol - Unified session management, multi-tenant support, and intelligent anti-ban queueing for WhatsApp applications

Readme

WaSP - WhatsApp Session Protocol

██╗    ██╗ █████╗ ███████╗██████╗
██║    ██║██╔══██╗██╔════╝██╔══██╗
██║ █╗ ██║███████║███████╗██████╔╝
██║███╗██║██╔══██║╚════██║██╔═══╝
╚███╔███╔╝██║  ██║███████║██║
 ╚══╝╚══╝ ╚═╝  ╚═╝╚══════╝╚═╝

npm version npm downloads CI License: MIT TypeScript Discord

Production-ready infrastructure layer for WhatsApp integrations

Quick StartFeaturesDocumentationExamplesDocker


Used in Production

WaSP powers real-world WhatsApp integrations:

  • WhatsHub - Multi-tenant WhatsApp messaging platform
  • WhatsAuction (whatsauction.co.za) - Live auction bidding via WhatsApp
  • FlashVault VPN (flashvault.co.za) - Customer support automation

Why WaSP?

Building WhatsApp integrations is painful. Every project requires re-implementing:

  • Session management and persistence
  • Multi-tenant isolation
  • Anti-ban queueing with human-like delays
  • Reconnection logic and error handling
  • Provider-specific quirks

WaSP solves this. One unified API across Baileys, Whatsmeow, and Cloud API with batteries included.

Features

  • Unified API - One interface across all WhatsApp providers
  • 🏢 Multi-tenant - Isolated sessions per org/user
  • 🛡️ Anti-ban queue - Human-like delays, priority lanes
  • 💾 Pluggable storage - Memory, Redis, Postgres
  • 🔧 Middleware system - Logging, reconnection, rate limiting
  • 📘 TypeScript-first - Full type safety
  • 🚀 Production-ready - Auto-reconnect, error recovery
  • 📡 Event-driven - Normalized events across providers
  • 🐳 Docker support - Ready-to-deploy containers

Quick Start

Installation

npm install wasp-protocol @whiskeysockets/baileys

# Optional: For persistence
npm install ioredis  # Redis store
npm install pg       # Postgres store

Basic Usage

import { WaSP } from 'wasp-protocol';

const wasp = new WaSP({
  queue: {
    minDelay: 2000,  // Min 2s between messages
    maxDelay: 5000,  // Max 5s between messages
  },
});

// Create session (QR code authentication)
const session = await wasp.createSession('user-123', 'BAILEYS');

// Listen for QR code
wasp.on('SESSION_QR', (event) => {
  console.log('Scan this:', event.data.qr);
});

// Listen for connection
wasp.on('SESSION_CONNECTED', (event) => {
  console.log('Connected as:', event.data.phone);
});

// Handle incoming messages
wasp.on('MESSAGE_RECEIVED', async (event) => {
  const msg = event.data;
  console.log(`From ${msg.from}: ${msg.content}`);

  // Auto-reply
  if (msg.content === 'hello') {
    await wasp.sendMessage(event.sessionId, msg.from, 'Hi there!');
  }
});

// Send message (auto-queued with anti-ban delay)
await wasp.sendMessage('user-123', '[email protected]', 'Hello!');

Architecture

┌─────────────────────────────────────────┐
│         Your Application                │
│  (SaaS, Bot, Notifications, etc.)       │
└─────────────────────────────────────────┘
                  │
                  │ WaSP Unified API
                  ▼
┌─────────────────────────────────────────┐
│            WaSP Core                    │
│  • Session Manager (multi-tenant)       │
│  • Anti-Ban Queue (priority lanes)      │
│  • Middleware Pipeline                  │
│  • Store (Memory/Redis/Postgres)        │
└─────────────────────────────────────────┘
                  │
       ┌──────────┼──────────┐
       ▼          ▼          ▼
   Baileys  Whatsmeow  Cloud API
       │          │          │
       └──────────┴──────────┘
                  │
           WhatsApp Servers

Core Concepts

Sessions

Multi-tenant session isolation. Each user/org gets their own WhatsApp connection.

// Create session with metadata
await wasp.createSession('org-acme', 'BAILEYS', {
  orgId: 'org-acme',
  metadata: { plan: 'enterprise' },
});

// List sessions by org
const sessions = await wasp.listSessions({ orgId: 'org-acme' });

// Destroy session
await wasp.destroySession('org-acme');

Anti-Ban Queue

Prevents WhatsApp bans with human-like delays and priority lanes.

// Regular message (2-5s delay)
await wasp.sendMessage('session-1', recipient, 'Hello');

// Priority message (1-2.5s delay)
await wasp.sendMessage('session-1', recipient, 'Urgent!', { priority: 10 });

// Immediate (skip queue - use sparingly!)
await wasp.sendMessage('session-1', recipient, 'Alert!', { immediate: true });

Storage

Choose persistence layer based on your needs.

import { WaSP, RedisStore, PostgresStore } from 'wasp-protocol';

// Redis (multi-instance, fast)
const wasp = new WaSP({
  store: new RedisStore({
    host: 'localhost',
    port: 6379,
    keyPrefix: 'wasp:',
  }),
});

// Postgres (queryable, analytics)
const wasp = new WaSP({
  store: new PostgresStore({
    connectionString: 'postgresql://user:pass@localhost/db',
    autoCreate: true,
  }),
});

Middleware

Compose cross-cutting concerns without polluting core logic.

import { logger, autoReconnect, errorHandler } from 'wasp-protocol';

wasp.use(logger());  // Log all events
wasp.use(autoReconnect({ maxAttempts: 5 }));  // Auto-reconnect on disconnect
wasp.use(errorHandler((error) => console.error(error)));

// Custom middleware
wasp.use(async (event, next) => {
  console.log('Before:', event.type);
  await next();
  console.log('After:', event.type);
});

Events

WaSP emits normalized events across all providers:

| Event | Description | |-------|-------------| | SESSION_CONNECTED | Session authenticated | | SESSION_DISCONNECTED | Connection lost | | SESSION_QR | QR code for scanning | | SESSION_ERROR | Error occurred | | MESSAGE_RECEIVED | Incoming message | | MESSAGE_SENT | Outgoing message sent | | MESSAGE_DELIVERED | Message delivered | | MESSAGE_READ | Message read by recipient | | GROUP_JOIN | Bot joined group | | GROUP_LEAVE | Bot left group | | PRESENCE_UPDATE | User online/typing |

wasp.on('MESSAGE_RECEIVED', (event) => {
  console.log(event.data);  // Normalized Message object
});

wasp.on('*', (event) => {
  console.log('Any event:', event.type);
});

Examples

See examples/ directory:

Run examples:

npx tsx examples/echo-bot.ts

Docker

Quick Start

# Build and run with Redis
docker-compose up

# Development mode (hot reload)
docker-compose -f docker-compose.yml -f docker-compose.dev.yml up

Dockerfile

Pre-configured production Dockerfile included. Supports:

  • Node.js 20 slim base
  • Multi-stage builds
  • Auth state persistence
  • Environment configuration

See Dockerfile and docker-compose.yml.

CLI Usage

WaSP provides a CLI for testing and development:

# Start interactive session
npx wasp-protocol connect

# Send message
npx wasp-protocol send --to 27821234567 --message "Hello"

# List sessions
npx wasp-protocol list

API Reference

Core Methods

// Session management
createSession(id, provider, options?): Promise<Session>
destroySession(id): Promise<void>
getSession(id): Promise<Session | null>
listSessions(filter?): Promise<Session[]>

// Messaging
sendMessage(sessionId, to, content, options?): Promise<Message>

// Events
on(event, handler): this
off(event, handler): this
once(event, handler): this

// Middleware
use(middleware): this

// Stats
getQueueStats(): QueueStats
getSessionCount(): number

Types

interface Session {
  id: string;
  phone?: string;
  status: SessionStatus;
  provider: ProviderType;
  orgId?: string;
  connectedAt?: Date;
  createdAt: Date;
  lastActivityAt?: Date;
  metadata?: Record<string, unknown>;
}

interface Message {
  id: string;
  from: string;
  to: string;
  type: MessageType;
  content: string;
  timestamp: Date;
  isGroup: boolean;
  groupId?: string;
  mediaUrl?: string;
  mediaMimeType?: string;
}

Full API docs: See TypeScript definitions in src/types.ts.

Comparison

| Feature | WaSP | Raw Baileys | Cloud API | RetentionStack | |---------|------|-------------|-----------|----------------| | Multi-tenant | ✅ Built-in | ❌ DIY | ❌ DIY | ✅ Built-in | | Anti-ban queue | ✅ Built-in | ❌ DIY | ✅ Official | ✅ Paid | | Reconnection | ✅ Auto | ❌ DIY | ✅ Auto | ✅ Auto | | Storage | ✅ Pluggable | ❌ DIY | ☁️ Cloud | ☁️ Hosted | | Middleware | ✅ Built-in | ❌ None | ❌ None | ⚠️ Limited | | TypeScript | ✅ Full | ⚠️ Partial | ✅ Full | ✅ Full | | Cost | 🆓 Free | 🆓 Free | 💰 $0.005-0.09/msg | 💰 $99+/mo | | Self-hosted | ✅ Yes | ✅ Yes | ❌ No | ❌ No | | Provider swap | ✅ Easy | ❌ Rewrite | ❌ Locked | ❌ Locked |

Roadmap

  • [x] Baileys provider (v7.0+)
  • [x] Memory/Redis/Postgres stores
  • [x] Anti-ban queue
  • [x] Middleware system
  • [x] Docker support
  • [x] CLI tool
  • [ ] Whatsmeow provider
  • [ ] Cloud API provider
  • [ ] Webhook system
  • [ ] Message templates
  • [ ] Admin dashboard UI

Contributing

Contributions welcome! See CONTRIBUTING.md.

git clone https://github.com/kobie3717/wasp.git
cd wasp
npm install
npm test
npm run build

License

MIT © Kobus Wentzel

Support

Security

For security issues, email [email protected] instead of using the issue tracker.

Changelog

See CHANGELOG.md for release history.


Built with ❤️ in South Africa

npmGitHubIssues