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

auxwall-promotions

v2.0.9

Published

email and message promitions for our applications

Downloads

935

Readme

AuxWall Promotions

A comprehensive Node.js module for sending promotional messages via WhatsApp Web, WhatsApp Cloud API, and Email channels. This module provides a unified API for multi-channel promotional campaigns with robust error handling, session management, and delivery tracking.

Features

Multi-Channel Support

  • WhatsApp Web (via whatsapp-web.js)
  • WhatsApp Cloud API (Meta Official API)
  • Email (via SMTP with nodemailer)

Media & Attachments

  • Local file attachments for all channels
  • Complete media support: Image, video, audio, and document types
  • Auto-detection of file types (no need to specify messageType)
  • Automatic media upload for WhatsApp API
  • Optional attachments - works with or without files
  • Cross-platform compatibility (WhatsApp Web treats audio as documents)
  • Auto-cleanup - Attachments deleted after successful sending ✨ NEW!

Campaign Management

  • Real-time progress notifications with WebSocket-style updates ✨ NEW!
  • Campaign control - Stop, pause, resume campaigns mid-execution ✨ NEW!
  • Initiation status - Know immediately if setup succeeded ✨ NEW!
  • Enhanced error handling with detailed progress tracking ✨ NEW!

Personalization & Contact Management

  • Contact objects with name, phone, and email support ✨ NEW!
  • Name replacement - Use [name] placeholders in title and content ✨ NEW!
  • Flexible contact format - Support for WhatsApp (phone) and Email (email) ✨ NEW!
  • Case-insensitive replacement - Works with [name], [Name], [NAME] ✨ NEW!

Company-Based Isolation

  • Separate sessions and configurations per company
  • Secure storage management
  • Independent client instances

Robust Error Handling

  • Retry mechanisms with exponential backoff
  • Graceful fallback between channels
  • Comprehensive logging and status callbacks

Production Ready

  • TypeScript support
  • Concurrent message sending with throttling
  • Auto-reconnection and session recovery
  • Clean modular architecture with organized file structure
  • Auto-detection of media types from file extensions
  • Automatic folder structure creation and management ✨ NEW!
  • Campaign control system with stop/pause/resume ✨ NEW!

Installation

npm install auxwall-promotions

Quick Start

1. Module Configuration (Optional)

import { configureModule, sendPromotion } from 'auxwall-promotions';

// Configure module with custom paths (optional)
await configureModule({
  basePaths: {
    storage: './custom-storage',
    logs: './custom-logs',
    sessions: './custom-sessions',
    temp: './custom-temp',
    config: './custom-config'
  },
  defaultConcurrency: 10,
  defaultDelayMs: 500,
  logLevel: 'info',
  enableAutoCleanup: true
});

2. Check WhatsApp Connection Status

import { checkWhatsAppWebConnectionStatus } from 'auxwall-promotions';

// Check if WhatsApp is ready to send messages
const status = await checkWhatsAppWebConnectionStatus('company-id');

if (status.isReady) {
  console.log('✅ WhatsApp is ready to send messages!');
  // You can now safely send messages
} else if (status.isConnected) {
  console.log('⏳ WhatsApp is connecting, please wait...');
} else if (status.status === 'not_initialized') {
  console.log('❌ WhatsApp is not initialized. Call loginWhatsappWeb first.');
} else {
  console.log('❌ WhatsApp is disconnected');
}

console.log('Detailed status:', status);

3. Send Messages with Contact Objects and Name Replacement

// Email with contact objects and name replacement
const result = await sendPromotion({
  channel: 'email',
  contacts: [
    { name: 'John Doe', email: '[email protected]' },
    { name: 'Jane Smith', email: '[email protected]' }
  ],
  title: 'Hello [name], Product Catalog',
  content: 'Hi [name]! Please find our catalog attached.',
  companyId: 'company-id',
  attachment: './catalog.pdf', // Auto-detects as document
  concurrency: 10,
  delayMs: 500,
  notifications: (update) => {
    console.log(`Email ${update.status}: ${update.uid}`, update.progress);
  }
});

// WhatsApp Web with contact objects and name replacement
const whatsappResult = await sendPromotion({
  channel: 'whatsappWeb',
  contacts: [
    { name: 'Alice Johnson', phone: '+1234567890' },
    { name: 'Bob Wilson', phone: '+1234567891' }
  ],
  title: 'Hi [name], Product Images',
  content: 'Hello [name]! Check out these amazing products!',
  companyId: 'company-id',
  attachment: './product-image.jpg', // Auto-detects as image
  delayMs: 2000,
  notifications: (update) => {
    console.log(`WhatsApp ${update.status}: ${update.uid}`, update.progress);
  }
});

// WhatsApp API with contact objects and name replacement
const apiResult = await sendPromotion({
  channel: 'whatsappApi',
  contacts: [
    { name: 'Charlie Brown', phone: '+1234567890' },
    { name: 'Diana Prince', phone: '+1234567891' }
  ],
  title: 'Hey [name], Product Video',
  content: 'Hi [name]! Watch this product demonstration!',
  companyId: 'company-id',
  attachment: './demo-video.mp4', // Auto-detects as video
  delayMs: 1000,
  notifications: (update) => {
    console.log(`WhatsApp API ${update.status}: ${update.uid}`, update.progress);
  }
});

// Send promotional messages const result = await sendPromotion({ channel: 'whatsappWeb', uid: ['+1234567890', '+1234567891'], title: 'Special Offer', content: 'Get 50% off today only!', companyId, delayMs: 2000, // 2 second delay between messages channelUpdates: (update) => { console.log(Message to ${update.uid}: ${update.status}); } });


### 2. WhatsApp API Setup

```typescript
import { configureWhatsAppApi, sendPromotion } from 'auxwall-promotions';

const companyId = 'your-company-id';

// Configure WhatsApp API credentials
await configureWhatsAppApi(companyId, {
  accessToken: 'your-access-token',
  phoneNumberId: 'your-phone-number-id',
  businessAccountId: 'your-business-account-id'
}, 'write');

// Send promotional messages via API
const result = await sendPromotion({
  channel: 'whatsappApi',
  uid: ['+1234567890', '+1234567891'],
  title: 'Flash Sale',
  content: '30% discount for 24 hours!',
  companyId,
  channelUpdates: (update) => {
    console.log(`API Message to ${update.uid}: ${update.status}`);
  }
});

3. Email Setup

import { emailConfig, sendPromotion } from 'auxwall-promotions';

const companyId = 'your-company-id';

// Configure email settings
await emailConfig(companyId, 'write', {
  host: 'smtp.gmail.com',
  port: '587',
  secure: false,
  user: '[email protected]',
  pass: 'your-app-password'
});

// Send promotional emails
const result = await sendPromotion({
  channel: 'email',
  uid: ['[email protected]', '[email protected]'],
  title: 'Weekly Newsletter',
  content: '<h1>Special Offers</h1><p>Check out our latest deals!</p>',
  companyId,
  channelUpdates: (update) => {
    console.log(`Email to ${update.uid}: ${update.status}`);
  }
});

API Reference

Core Functions

loginWhatsappWeb(companyId, onQrCallback, onStatusCallback)

Initialize WhatsApp Web client for a company.

Parameters:

  • companyId (string): Unique company identifier
  • onQrCallback (function): QR code callback function
  • onStatusCallback (function): Status update callback

Returns: Promise<{ success: boolean, client?: Client, error?: string }>

logoutWhatsappWeb(companyId)

Logout and destroy WhatsApp Web session for a company.

Parameters:

  • companyId (string): Company identifier

Returns: Promise<{ success: boolean, error?: string }>

checkWhatsAppWebConnectionStatus(companyId) ✨ NEW!

Check current WhatsApp Web connection status for a company.

Parameters:

  • companyId (string): Company identifier

Returns: Promise<{ isConnected: boolean, isReady: boolean, status: 'connected' | 'disconnected' | 'not_initialized', state?: string }>

Example:

import { checkWhatsAppWebConnectionStatus } from 'auxwall-promotions';

const status = await checkWhatsAppWebConnectionStatus('company-123');
// Returns: { isConnected: true, isReady: true, status: 'connected', state: 'CONNECTED' }

if (status.isReady) {
  console.log('✅ WhatsApp is ready to send messages!');
} else if (status.isConnected) {
  console.log('⏳ WhatsApp is connecting...');
} else {
  console.log('❌ WhatsApp is not connected');
}

emailConfig(companyId, mode, data?)

Configure email settings for a company.

Parameters:

  • companyId (string): Company identifier
  • mode ('read' | 'write'): Operation mode
  • data (EmailConfig): Email configuration (for write mode)

Returns: Promise<{ success: boolean, config?: EmailConfig, error?: string }>

sendPromotion(options)

Main function to send promotional messages across all channels.

Parameters:

  • options (PromotionOptions): Configuration object

Returns: Promise

Channel-Specific Functions

WhatsApp Web

import {
  loginWhatsappWeb,
  logoutWhatsappWeb,
  sendWhatsAppWebMessage,
  sendBulkWhatsAppWebMessages,
  checkWhatsAppWebConnectionStatus,
  checkWhatsAppWebSessionStatus
} from 'auxwall-promotions/whatsapp/whatsappWeb';

WhatsApp API

import {
  configureWhatsAppApi,
  sendWhatsAppApiMessage,
  sendBulkWhatsAppApiMessages
} from 'auxwall-promotions/whatsapp/whatsappApi';

Email

import {
  emailConfig,
  sendEmail,
  sendBulkEmails
} from 'auxwall-promotions/email';

File Organization

The module is organized into logical modules for better maintainability:

src/
├── promotion/              # Main promotion orchestrator
│   ├── index.ts           # Main exports
│   ├── orchestrator.ts    # Main sendPromotion and fallback logic
│   ├── whatsapp.ts        # WhatsApp-specific promotion functions
│   └── email.ts           # Email-specific promotion functions
├── email/                  # Email functionality
│   ├── index.ts           # Email client management
│   └── client.ts          # SMTP email implementation
├── whatsapp/               # WhatsApp functionality
│   ├── whatsappWeb/       # WhatsApp Web implementation
│   ├── whatsappApi/       # WhatsApp Cloud API implementation
│   ├── baileys/           # Alternative WhatsApp implementation
│   ├── getFileType.ts     # File type auto-detection utility
│   └── formatMobileNumber.ts
└── utils/                  # Shared utilities
    ├── index.ts
    ├── logger.ts
    ├── storage.ts
    └── delay.ts

Configuration

Storage Structure

storage/
├── whatsapp/
│   └── {companyId}-session/
├── email/
│   └── {companyId}-email.json
└── whatsapp-api/
    └── {companyId}-api.json

Email Configuration

interface EmailConfig {
  host: string;
  port: string | number;
  secure: boolean;
  user: string;
  pass: string;
}

WhatsApp API Configuration

interface WhatsAppApiConfig {
  accessToken: string;
  phoneNumberId: string;
  businessAccountId: string;
}

Promotion Options (Enhanced with Contact Objects)

interface Contact {
  name: string; // Name to replace [name] placeholders (case insensitive)
  phone?: string; // For WhatsApp channels (+country code format)
  email?: string; // For Email channels (any valid email format)
}

interface PromotionOptions {
  channel: 'whatsappWeb' | 'whatsappApi' | 'email';
  contacts: Contact[]; // Array of contact objects with name, phone, and/or email ✨ NEW!
  title: string; // Subject for email, title for WhatsApp (supports [name] replacement) ✨ NEW!
  content: string; // Message content (supports [name] replacement) ✨ NEW!
  companyId: string;
  attachment?: string; // Local file path (auto-detected)
  concurrency?: number; // Send N messages concurrently (default: 5)
  delayMs?: number; // Delay between batches (default: 1000ms)
  notifications?: (update: CampaignUpdate) => void; // Real-time progress
}

interface CampaignUpdate {
  uid: string;
  status: 'sent' | 'failed' | 'stopped' | 'paused';
  timestamp: number;
  error?: string;
  progress?: {
    current: number;
    total: number;
    percentage: number;
  };
}

interface PromotionResult {
  success: boolean;
  initiationStatus: 'success' | 'failed'; // ✨ NEW!
  totalSent: number;
  totalFailed: number;
  errors: string[];
  channel: string;
  campaignId?: string; // ✨ NEW!
  firstResult?: CampaignUpdate; // ✨ NEW!
}

Advanced Usage

Module Configuration

import { configureModule, getModuleConfig, getBasePath } from 'auxwall-promotions';

// Configure module paths and settings
await configureModule({
  basePaths: {
    storage: './my-storage',
    logs: './my-logs',
    sessions: './my-sessions',
    temp: './my-temp',
    config: './my-config'
  },
  defaultConcurrency: 10,
  defaultDelayMs: 500,
  logLevel: 'info',
  enableAutoCleanup: true,
  maxRetries: 3,
  retryDelayMs: 1000,
  timeoutMs: 30000
});

// Get current configuration
const config = getModuleConfig();
console.log('Base storage path:', getBasePath('storage'));

Campaign Control

import { sendPromotion, createCampaign, stopCampaign } from 'auxwall-promotions';

const result = await sendPromotion({
  channel: 'email',
  uid: emailList,
  title: 'Newsletter',
  content: 'Weekly updates...',
  companyId: 'company-id',
  attachment: './newsletter.pdf'
});

// Get campaign control
const campaign = createCampaign(result.campaignId!);

// Stop campaign mid-execution
campaign.stop();

// Check status
console.log('Is stopped:', campaign.getIsStopped());
console.log('Is paused:', campaign.getIsPaused());

Fallback Support

import { sendPromotionWithFallback } from 'auxwall-promotions';

// Try WhatsApp API first, fallback to WhatsApp Web if needed
const result = await sendPromotionWithFallback({
  channel: 'whatsappApi',
  uid: ['+1234567890'],
  title: 'Important Message',
  content: 'This message is important!',
  companyId: 'company-id'
});

Custom Concurrency and Throttling

const result = await sendPromotion({
  channel: 'email',
  uid: emailList,
  title: 'Newsletter',
  content: 'Weekly updates...',
  companyId: 'company-id',
  concurrency: 10,    // Send 10 emails concurrently
  delayMs: 500        // 500ms delay between batches
});

Attachments Support

// Email with attachment (auto-detects as document)
const emailResult = await sendPromotion({
  channel: 'email',
  uid: ['[email protected]'],
  title: 'Product Catalog',
  content: 'Please find our product catalog attached.',
  companyId: 'company-id',
  attachmentPath: './catalog.pdf' // Auto-detects file type - no need to specify messageType
});

// WhatsApp Web with media attachment (auto-detects as image)
const whatsappResult = await sendPromotion({
  channel: 'whatsappWeb',
  uid: ['+1234567890'],
  title: 'Product Images',
  content: 'Check out these amazing products!',
  companyId: 'company-id',
  attachmentPath: './product-image.jpg' // Auto-detects as image - no need to specify messageType
});

// WhatsApp API with media attachment (auto-detects as video)
const apiResult = await sendPromotion({
  channel: 'whatsappApi',
  uid: ['+1234567890'],
  title: 'Product Demo',
  content: 'Watch this product demonstration!',
  companyId: 'company-id',
  attachmentPath: './demo-video.mp4' // Auto-detects as video - no need to specify messageType
});

// Supported file types auto-detection:
// Images: .jpg, .jpeg, .png, .gif, .webp, .bmp, .svg
// Videos: .mp4, .avi, .mov, .mkv, .webm, .flv, .wmv, .3gp
// Audio: .mp3, .ogg, .wav, .m4a, .aac, .flac (WhatsApp API supported, WhatsApp Web as document)
// Documents: .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .txt, .zip, .rar, .csv, .json, .xml

Error Handling and Retries

// The module includes built-in retry mechanisms with exponential backoff
// All functions return detailed error information for debugging

const result = await sendPromotion({
  channel: 'whatsappWeb',
  uid: ['+1234567890'],
  title: 'Test',
  content: 'Test message',
  companyId: 'company-id',
  channelUpdates: (update) => {
    if (update.status === 'failed') {
      console.log(`Failed to send to ${update.uid}: ${update.error}`);
      // Handle failure (retry, log, etc.)
    }
  }
});

Examples

See the examples directory for comprehensive usage examples:

  • WhatsApp Web setup and messaging
  • WhatsApp API configuration and usage
  • Email campaign management
  • Multi-channel promotion campaigns
  • Storage management utilities

Error Handling

The module provides comprehensive error handling:

  • Network failures: Automatic retries with exponential backoff
  • Invalid configurations: Clear validation errors
  • Session issues: Auto-reconnection and session recovery
  • Rate limiting: Built-in throttling to avoid bans
  • Detailed logging: Comprehensive logs for debugging

TypeScript Support

Full TypeScript support with detailed type definitions:

import type {
  PromotionOptions,
  PromotionResult,
  EmailConfig,
  WhatsAppApiConfig
} from 'auxwall-promotions';

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure TypeScript compilation passes
  5. Submit a pull request

License

ISC License

Support

For support and questions, please create an issue in the repository or contact the development team.


Note: This module is designed for legitimate promotional messaging only. Please ensure compliance with platform terms of service and local regulations regarding promotional messaging.