mohiit1502 ab88ce6e04
All checks were successful
armco-org/analytics/pipeline/head This commit looks good
Fixed module resolution errors
2025-12-23 00:46:30 +05:30
2025-12-23 00:46:30 +05:30
2025-12-23 00:46:30 +05:30

@armco/analytics

Universal Analytics Library for Browser and Node.js

npm version License: ISC

A production-ready, enterprise-grade analytics library that works seamlessly in both browser and Node.js environments. Built with TypeScript, fully typed, and designed for modern web applications.

Features

Universal Platform Support

  • 🌐 Browser: Full support for modern browsers with auto-tracking of clicks, forms, pages, and errors
  • 🖥️ Node.js: Backend analytics with HTTP request tracking
  • 🔄 Environment Detection: Automatically adapts to the runtime environment

Core Capabilities

  • 📊 Event Tracking: Track custom events, page views, user actions
  • 👤 User Identification: Identify and track users across sessions
  • 🎯 Session Management: Automatic session tracking and management
  • 🔌 Plugin System: Extensible architecture with built-in and custom plugins
  • 💾 Flexible Storage: Cookie, localStorage, hybrid (browser), or in-memory (Node.js)
  • 🚀 Multiple Submission Strategies: ONEVENT (immediate) or DEFER (batched)
  • 🎲 Event Sampling: Built-in sampling support for high-traffic applications
  • 🔒 Privacy: Do Not Track (DNT) support
  • 📦 Batch Processing: Automatic event batching and flushing
  • 🛡️ Type Safety: Full TypeScript support with comprehensive type definitions

Node.js Specific Features

  • 🌐 HTTP Request Tracking: Auto-track incoming requests with metadata
  • 📍 Client IP Detection: Multi-header IP extraction (x-forwarded-for, cf-connecting-ip, etc.)
  • 🖥️ Server Identification: Automatic server hostname detection
  • ⚙️ Framework Agnostic: Works with Express, Fastify, NestJS, and more
  • 📝 Config File Support: Load settings from analyticsrc.json

📦 Installation

npm install @armco/analytics
# or
yarn add @armco/analytics
# or
pnpm add @armco/analytics

🚀 Quick Start

Browser Usage

import { createAnalytics } from '@armco/analytics';

const analytics = createAnalytics()
  .withApiKey('your-api-key')
  // or .withEndpoint('https://analytics.example.com/events')
  .withConfig({
    hostProjectName: 'my-web-app',
    submissionStrategy: 'DEFER',
    batchSize: 50,
  })
  .build();

analytics.init();

// Track custom events
analytics.track('BUTTON_CLICK', {
  button: 'subscribe',
  page: '/pricing',
});

// Track page views
analytics.trackPageView('/pricing', {
  campaign: 'summer-sale',
});

// Identify users
analytics.identify({
  email: 'user@example.com',
  name: 'John Doe',
  plan: 'pro',
});

Node.js Usage

1. Create analyticsrc.json in your project root:

{
  "endpoint": "https://analytics.example.com/events",
  "hostProjectName": "my-backend-service",
  "logLevel": "info",
  "submissionStrategy": "DEFER",
  "batchSize": 100,
  "flushInterval": 15000
}

2. Initialize Analytics:

import { createAnalytics, loadConfig, HTTPRequestTrackingPlugin } from '@armco/analytics';

// Load config from analyticsrc.json
const config = await loadConfig();

const analytics = createAnalytics()
  .withConfig(config)
  .build();

analytics.init();

// Create HTTP request tracker
const httpTracker = new HTTPRequestTrackingPlugin({
  trackRequests: true,
  trackResponses: true,
  ignoreRoutes: ['/health', '/metrics'],
});

// Initialize the plugin
httpTracker.init({
  config: analytics['config'],
  storage: analytics['storage'],
  track: (eventType, data) => analytics.track(eventType, data),
  getSessionId: () => analytics.getSessionId(),
  getUserId: () => analytics.getUserId(),
});

3. Express Middleware Example:

import express from 'express';

const app = express();

// Analytics middleware
app.use((req, res, next) => {
  const startTime = Date.now();
  const requestId = req.headers['x-request-id'] || `req_${Date.now()}`;
  
  // Track request start
  httpTracker.trackRequestStart({
    method: req.method,
    path: req.path,
    query: req.query,
    headers: req.headers,
    clientIp: req.ip,
    serverHostname: req.hostname,
    requestId,
    startTime,
  });
  
  // Track request end
  res.on('finish', () => {
    httpTracker.trackRequestEnd(requestId, res.statusCode);
  });
  
  next();
});

// Track custom backend events
app.post('/api/checkout', async (req, res) => {
  await analytics.track('CHECKOUT_COMPLETED', {
    orderId: req.body.orderId,
    amount: req.body.total,
    currency: 'USD',
  });
  
  res.json({ success: true });
});

📖 Documentation

🔌 Built-in Plugins

Browser Plugins

  • ClickTrackingPlugin: Auto-track user clicks
  • PageTrackingPlugin: Auto-track page views and navigation
  • FormTrackingPlugin: Auto-track form submissions
  • ErrorTrackingPlugin: Auto-track JavaScript errors
  • SessionPlugin: Session management and tracking
  • UserPlugin: User identification and tracking

Node.js Plugins

  • HTTPRequestTrackingPlugin: Auto-track HTTP requests with metadata

🛠️ Configuration

Core Configuration Options

interface AnalyticsConfig {
  // Required: Either apiKey or endpoint must be provided
  apiKey?: string;
  endpoint?: string;
  
  // Project identification
  hostProjectName?: string;
  
  // Submission strategy
  submissionStrategy?: 'ONEVENT' | 'DEFER';
  batchSize?: number;
  flushInterval?: number;
  
  // Sampling
  samplingRate?: number; // 0-1, default 1 (100%)
  
  // Privacy
  respectDoNotTrack?: boolean;
  
  // Logging
  logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent';
  
  // Storage
  storageType?: 'cookie' | 'local' | 'hybrid' | 'memory';
}

📊 Event Types

Standard Events

  • ANALYTICS_INITIALIZED - Analytics system initialized
  • PAGE_VIEW - Page view tracked
  • CLICK - User click tracked
  • FORM_SUBMIT - Form submission tracked
  • ERROR - JavaScript error tracked
  • HTTP_REQUEST_START - HTTP request started (Node.js)
  • HTTP_REQUEST_END - HTTP request completed (Node.js)

Custom Events

Track any custom event with:

analytics.track('CUSTOM_EVENT_TYPE', {
  // Your custom data
  key: 'value',
});

🧪 Testing

# Run all tests
npm test

# Watch mode
npm run test:watch

# Coverage report
npm run test:coverage

# Unit tests only
npm run test:unit

# Integration tests only
npm run test:integration

🏗️ Build

npm run build

Builds TypeScript to JavaScript in the dist/ directory with type definitions.

📝 License

ISC © Armco

🤝 Contributing

Contributions are welcome! Please read our contributing guidelines before submitting PRs.

📧 Support

For issues and questions, please open an issue on GitHub.


Built with ❤️ by the Armco team

Description
No description provided
Readme 281 KiB
Languages
TypeScript 95.9%
JavaScript 3.9%
Shell 0.2%