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

myavana-bot-test-core

v2.2.0

Published

Shared bot functionality with enhanced features

Readme

Core Package - Myavana Chatbot

The core package provides shared functionality, utilities, and infrastructure components used across all chatbot implementations.

=� Package Overview

Package Name: myavana-bot-test-core
Version: 2.0.0
Purpose: Shared infrastructure and utilities for all chatbot packages

<� Architecture

core/
�� src/
   �� ai.js                    # AI model integration
   �� config.js                # Configuration management
   �� conversation.js          # Conversation handling
   �� database.js              # Legacy database connection
   �� enhancedDatabase.js      # Enhanced database with pooling
   �� errorHandler.js          # Error handling system
   �� errorRecovery.js         # Error recovery strategies
   �� hairIssues.js           # Hair issue tracking
   �� healthMonitor.js        # System health monitoring
   �� logger.js               # Structured logging system
   �� personalizationEngine.js # User personalization
   �� postResponseProcessing.js # Response post-processing
   �� proactiveEngagement.js  # Proactive user engagement
   �� responseCache.js        # Response caching system
   �� session.js              # Session management
   �� smartPromptManager.js   # Intelligent prompt management
   �� unifiedChatHandler.js   # Unified chat handler
   �� user.js                 # User management
   �� utils.js                # Utility functions
   �� validation.js           # Input validation & security
�� migrations/                  # Database migrations
�� __tests__/                  # Comprehensive test suite
�� index.js                    # Main exports

=� Quick Start

Installation

cd packages/core
npm install

Basic Usage

const core = require('myavana-bot-test-core');

// Initialize enhanced database
const dbManager = core.createDatabaseManager({
  logger: core.getLogger(),
  maxRetries: 3
});

// Initialize unified chat handler
const handler = new core.UnifiedChatHandler({
  packageName: 'myavana',
  logger: core.getLogger(),
  validator: new core.Validator()
});

=� Core Components

1. UnifiedChatHandler

Central chat handling system that consolidates all bot functionality.

const handler = new UnifiedChatHandler({
  packageName: 'myavana',           // Package identifier
  logger: logger,                   // Logging instance
  validator: validator,             // Input validation
  analytics: analytics,             // Analytics tracking
  smartPromptManager: promptMgr,    // Smart prompt generation
  responseCache: cache,             // Response caching
  errorRecovery: recovery,          // Error recovery
  personalization: personalization, // User personalization
  ai: aiInstance,                   // AI integration
  xaiApiKey: process.env.XAI_API_KEY
});

// Handle incoming requests
app.post('/webhook', async (req, res) => {
  await handler.handleRequest(req, res);
});

Features:

  • Multi-model AI support (Gemini, xAI)
  • Intelligent fallback strategies
  • Request/response logging
  • Error handling and recovery
  • Performance monitoring
  • Security validation

2. Enhanced Database Manager

Advanced database connection management with pooling and caching.

const dbManager = core.createDatabaseManager({
  logger: logger,
  maxRetries: 3,
  retryDelay: 5000,
  memoryCacheTTL: 300
});

await dbManager.connect();

// Query with caching
const result = await dbManager.query(
  'SELECT * FROM users WHERE user_id = $1',
  [userId],
  {
    cacheKey: `user:${userId}`,
    cacheTTL: 600,
    useCache: true
  }
);

// Transaction support
await dbManager.transaction(async (client) => {
  await client.query('INSERT INTO users ...');
  await client.query('INSERT INTO profiles ...');
});

// Redis operations
await dbManager.redisSet('session:123', sessionData, 3600);
const session = await dbManager.redisGet('session:123');

Features:

  • Connection pooling (5-20 connections)
  • Query result caching
  • Transaction support
  • Redis integration
  • Health monitoring
  • Automatic reconnection

3. Logging System

Structured logging with multiple transports and contextual information.

const logger = core.createLogger({
  serviceName: 'myavana-chatbot',
  environment: 'production',
  logLevel: 'info'
});

// Basic logging
logger.info('User message received', { userId, message });
logger.error('Database error', { error: err.message });

// Specialized logging
logger.logRequest(requestId, 'POST', '/webhook', requestBody);
logger.logAIInteraction(requestId, 'gemini-pro', prompt, response, 1500);
logger.logPerformance('ai_response', 2000);
logger.logSecurityEvent('suspicious_input', userId, 'medium');

// Child logger with context
const childLogger = logger.child({ requestId, userId });
childLogger.info('Processing request');

Features:

  • Structured JSON logging
  • Multiple log levels and transports
  • Request tracing with unique IDs
  • Performance metrics logging
  • Security event tracking
  • Child loggers for context

4. Input Validation & Security

Comprehensive input validation, sanitization, and security features.

const validator = new core.Validator({
  logger: logger,
  maxMessageLength: 5000,
  allowedImageTypes: ['image/jpeg', 'image/png']
});

// Validate request
const result = await validator.validateRequest(requestBody);
if (!result.isValid) {
  return res.status(400).json({ errors: result.errors });
}

// Rate limiting middleware
app.use(validator.createRateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100
}));

// Content moderation
const moderation = await validator.moderateContent(userMessage);
if (!moderation.isClean) {
  // Handle inappropriate content
}

Features:

  • XSS prevention
  • SQL injection detection
  • Rate limiting
  • Content moderation
  • Image URL validation
  • Request sanitization

5. Error Handling System

Advanced error handling with categorization and recovery strategies.

const errorHandler = new core.ErrorHandler({
  logger: logger,
  environment: 'production'
});

// Handle errors with context
try {
  // ... some operation
} catch (error) {
  const errorResponse = await errorHandler.handleError(error, {
    requestId,
    userId,
    operation: 'ai_request'
  });
  res.status(500).json(errorResponse);
}

// Create structured errors
const error = errorHandler.createError(
  'AI model unavailable',
  'AI_MODEL',
  'high',
  originalError,
  { model: 'gemini-pro' }
);

// Express middleware
app.use(errorHandler.middleware());

Features:

  • Error categorization (AI_MODEL, DATABASE, NETWORK, etc.)
  • Severity levels (low, medium, high, critical)
  • Recovery strategies with retries
  • Circuit breaker patterns
  • Error analytics and reporting
  • User-friendly error messages

=� Database Schema

Core Tables

The core package expects these database tables:

  • users - User profiles and preferences
  • conversations - Chat conversation history
  • sessions - User session data
  • hair_issues - Hair-related issues and advice
  • products - Product catalog
  • product_recommendations - AI product recommendations
  • faqs - Frequently asked questions
  • youtube_videos - Educational content
  • testimonials - User testimonials

Enhanced Tables (v2.0)

New tables for advanced features:

  • system_health_logs - Health monitoring data
  • error_logs - Error tracking and recovery
  • performance_metrics - Performance analytics
  • ai_model_usage - AI model usage tracking
  • request_analytics - Request and response analytics
  • cache_analytics - Cache performance data

See migrations/ directory for complete schema.

>� Testing

Run Tests

npm test                 # All tests
npm run test:watch       # Watch mode
npm run test:coverage    # With coverage

Test Structure

__tests__/
�� unifiedChatHandler.test.js    # Chat handler tests
�� logger.test.js                # Logging system tests
�� validation.test.js            # Validation tests
�� errorHandler.test.js          # Error handling tests
�� enhancedDatabase.test.js      # Database tests
�� healthMonitor.test.js         # Health monitoring tests

=' Configuration

Environment Variables

# Database
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DB=myavana_bot
POSTGRES_USER=username
POSTGRES_PASSWORD=password

# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=password

# AI Services
GOOGLE_AI_API_KEY=your_gemini_key
XAI_API_KEY=your_xai_key
OPENAI_API_KEY=your_openai_key

# Application
NODE_ENV=production
LOG_LEVEL=info

=� Performance

Benchmarks

  • Database Query: ~10-50ms (with connection pooling)
  • Redis Operations: ~1-5ms
  • AI Model Response: 1-5 seconds (varies by model)
  • Request Processing: ~100-500ms (excluding AI)
  • Memory Usage: ~100-200MB per instance

= Security

Security Features

  • Input Validation: XSS prevention, SQL injection detection
  • Rate Limiting: IP-based request limiting
  • Content Moderation: Profanity and inappropriate content filtering
  • Secure Headers: CORS, CSP, and security headers
  • Error Sanitization: Sensitive data removal from logs

=� Deployment

Production Checklist

  • [ ] Environment variables configured
  • [ ] Database migrations applied
  • [ ] Redis server running
  • [ ] Health monitoring enabled
  • [ ] Logging configured
  • [ ] Error alerting set up

> Contributing

Development Setup

git clone <repository>
cd packages/core
npm install
npm run test:watch

=� API Reference

Core Exports

const core = require('myavana-bot-test-core');

// Classes
core.UnifiedChatHandler
core.DatabaseManager
core.Logger
core.Validator
core.ErrorHandler
core.HealthMonitor

// Functions
core.createLogger(options)
core.createDatabaseManager(options)
core.connectDatabases()

// Legacy Functions (maintained for compatibility)
core.getUserDetails(userId)
core.saveConversation(conversationId, userId, history)
core.postProcessConversation(history, message)

<� Troubleshooting

Common Issues

Database Connection Errors

Error: Connection terminated unexpectedly

Solution: Check database credentials and network connectivity

High Memory Usage

Warning: Memory usage above threshold

Solution: Monitor cache size and connection pool settings

Slow Response Times

Warning: AI response time > 5000ms

Solution: Check AI model status and network latency

Debug Mode

NODE_ENV=development LOG_LEVEL=debug npm start

Health Check

curl http://localhost:3000/health

=� License

Proprietary - Myavana Technology


Version: 2.0.0
Last Updated: 2024-01-15
Maintainer: Myavana Development Team