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

whatsapp-crm-common

v0.3.0

Published

Componentes compartidos para servicios de WhatsApp CRM - Common utilities and types for WhatsApp CRM system

Readme

whatsapp-crm-common

npm version License: MIT

Paquete compartido con tipos, utilidades e infraestructura común para los servicios WhatsApp CRM.

🚀 Características

  • Sistema Híbrido de Eventos: BullMQ para persistencia + Redis Pub/Sub para tiempo real
  • Colas Especializadas: 4 colas optimizadas (realtime, bulk, webhook, notifications)
  • Tipos TypeScript Completos: Interfaces para todas las entidades de dominio
  • Logging Estructurado: Sistema de logs con Pino y contexto automático
  • Gestión de Sesiones: Soporte multi-tenant con agentes múltiples
  • Utilidades WhatsApp: Formateo de números, extracción de contenido de mensajes

📦 Instalación

npm install whatsapp-crm-common

🔧 Configuración

Opción 1: Variables de entorno (Recomendado)

Crea un archivo .env en tu proyecto:

# Copia el archivo de ejemplo desde el paquete
cp node_modules/whatsapp-crm-common/.env.example .env

# O crea tu propio .env con estas variables:
# Redis Configuration
REDIS_URL=redis://localhost:6379
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0

# Database Configuration
DATABASE_URL=postgresql://user:password@localhost:5432/whatsapp_crm
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_NAME=whatsapp_crm
DATABASE_USER=postgres
DATABASE_PASSWORD=

# Logging
LOG_LEVEL=info
NODE_ENV=development

# Queue Configuration
ENABLE_MESSAGE_QUEUE=true
WORKER_ENABLED=true
QUEUE_CONCURRENCY=5
MAX_SESSIONS_PER_PROCESS=100

# WhatsApp Configuration
WEBHOOK_URL=http://localhost:3000/webhook
MAX_RECONNECT_ATTEMPTS=5
QR_TIMEOUT_MS=60000
SYNC_FULL_HISTORY=false

Opción 2: Configuración programática

import { configureWhatsAppCommon } from 'whatsapp-crm-common';

configureWhatsAppCommon({
  redis: {
    url: 'redis://mi-servidor:6379',
    password: 'mi-password',
    db: 1
  },
  database: {
    url: 'postgresql://user:pass@localhost:5432/mi_db'
  },
  logging: {
    level: 'debug'
  },
  queue: {
    enabled: true,
    concurrency: 10
  },
  webhook: {
    url: 'https://mi-webhook.com/whatsapp'
  }
});

Opción 3: Configuración mixta

El paquete seguirá esta prioridad:

  1. Configuración programática (la más alta)
  2. Variables de entorno de tu proyecto
  3. Valores por defecto del paquete
// Ejemplo: Configurar solo Redis programáticamente,
// el resto se tomará de variables de entorno o defaults
configureWhatsAppCommon({
  redis: {
    url: process.env.CUSTOM_REDIS_URL || 'redis://mi-redis:6379'
  }
});

Inicialización básica

import { 
  RedisClient, 
  WhatsAppMessageQueue,
  logger 
} from 'whatsapp-crm-common';

// Inicializar Redis (usa configuración global automáticamente)
const redisClient = RedisClient.getInstance();

// Inicializar cola de mensajes
const messageQueue = new WhatsAppMessageQueue(redisClient);

logger.info('Sistema inicializado correctamente');

💡 Ejemplos de Uso

Manejo de Eventos

import { 
  EventPublisher, 
  WhatsAppEventType,
  HybridEventRouter 
} from 'whatsapp-crm-common';

const eventPublisher = new EventPublisher();

// Publicar mensaje recibido
await eventPublisher.publishMessageReceived(
  'tenant-001', 
  1, 
  [message]
);

// Publicar código QR
await eventPublisher.publishQRCodeGenerated(
  'tenant-001',
  1,
  'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...'
);

Formateo de Números

import { formatPhoneNumber, isValidPhoneNumber } from 'whatsapp-crm-common';

const formattedNumber = formatPhoneNumber('5491155555555');
// Resultado: '[email protected]'

const isValid = isValidPhoneNumber('5491155555555');
// Resultado: true

Logging Contextual

import { logger } from 'whatsapp-crm-common';

logger.info({
  tenantId: 'tenant-001',
  agentId: 1,
  messageId: 'msg-123',
  msg: 'Mensaje procesado correctamente'
});

🏗️ Arquitectura

Sistema Híbrido de Eventos

// Eventos críticos → BullMQ (persistencia)
MESSAGE_NEW, MESSAGE_UPDATE, HISTORY_SYNC, CONTACT_UPDATE

// Eventos tiempo real → Redis Pub/Sub (velocidad)
QR_CODE_GENERATED, CONNECTION_UPDATE, PRESENCE_UPDATE, TYPING_START

Colas Especializadas

  • REALTIME: Mensajes nuevos, actualizaciones críticas
  • BULK: Sincronización masiva de historial
  • WEBHOOK: Notificaciones HTTP externas
  • NOTIFICATIONS: Actualizaciones de contactos, presencia

📋 API Principal

Configuración

  • configureWhatsAppCommon() - Configuración programática
  • getConfig() - Obtener configuración actual mezclada
  • environment - Variables de entorno centralizadas (legacy)
  • RedisClient - Cliente Redis singleton
  • defaultRedisConfig - Configuración Redis por defecto

Eventos

  • EventPublisher - Publicador de eventos tipado
  • HybridEventRouter - Router inteligente de eventos
  • WhatsAppEventType - Tipos de eventos disponibles

Infraestructura

  • WhatsAppMessageQueue - Sistema de colas BullMQ
  • WhatsAppPubSubSystem - Sistema Pub/Sub Redis

Utilidades

  • logger - Logger estructurado con Pino
  • formatPhoneNumber() - Formato números WhatsApp
  • extractMessageContent() - Extrae contenido de mensajes

Tipos de Dominio

  • IChat, IMessage, IContact, IGroup - Interfaces de entidades
  • WhatsAppConfig, ChatInfo - Tipos de configuración
  • HistoryOptions, MessageType - Tipos de operaciones

🔧 Variables de Entorno

# Redis Configuration
REDIS_URL=redis://localhost:6379
REDIS_HOST=localhost
REDIS_PORT=6379

# Database
DATABASE_URL=postgresql://user:password@localhost:5432/whatsapp_crm

# Queue Configuration  
ENABLE_MESSAGE_QUEUE=true
QUEUE_CONCURRENCY=5
MAX_SESSIONS_PER_PROCESS=100

# WhatsApp Configuration
WEBHOOK_URL=http://localhost:3000/webhook
MAX_RECONNECT_ATTEMPTS=5
QR_TIMEOUT_MS=60000

🚀 Scripts de Desarrollo

# Construir el paquete
npm run build

# Desarrollo con watch
npm run dev

# Limpiar build
npm run clean

# Verificar tipos
npm run type-check

📊 Casos de Uso

Este paquete está optimizado para:

  1. Sistemas CRM de WhatsApp - Gestión completa de conversaciones
  2. APIs de WhatsApp - Envío y recepción de mensajes
  3. Automatización - Bots y respuestas automáticas
  4. Analíticas - Procesamiento de datos de conversación
  5. Webhooks - Integración con sistemas externos

🤝 Contribución

Las contribuciones son bienvenidas. Por favor:

  1. Fork el proyecto
  2. Crea una branch para tu feature
  3. Commit tus cambios
  4. Push a la branch
  5. Abre un Pull Request

📄 Licencia

MIT © WhatsApp CRM Team