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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@cartai2025/sdk

v1.0.2

Published

Comprehensive CartAI SDK with device fingerprinting, browser event tracking, and Socket.IO integration

Readme

CartAI SDK

Comprehensive JavaScript SDK for device fingerprinting, browser event tracking, and real-time analytics with Socket.IO integration.

🚀 Features

Core Functionality

  • Device Fingerprinting: Advanced browser identification with fallback support
  • Socket.IO Integration: Real-time communication with CartAI backend
  • Browser Event Tracking: Comprehensive user behavior analytics
  • Auto-Detection: Email and phone number capture from form inputs
  • Session Management: Cross-session user tracking and analytics
  • TypeScript Support: Full type definitions included

Browser Events Tracking

  • URL Changes: Page navigation and time spent tracking
  • Form Inputs: Email/phone capture with automatic visitor linking
  • Click Events: User interaction monitoring with element details
  • Scroll Events: Engagement tracking and scroll behavior analysis
  • Payment Events: Transaction status and payment method tracking
  • Sales Events: Product views, cart actions, and purchase funnel analysis
  • Custom Events: Track any custom user interactions

Advanced Features

  • Automatic Event Batching: Efficient event sending with configurable batch sizes
  • Fallback Fingerprinting: Works even without CartAI Device SDK
  • Real-time Analytics: Live updates and behavior insights
  • Cross-Device Tracking: Enhanced visitor identification
  • Debug Mode: Comprehensive logging for development
  • Multi-Format Builds: IIFE, UMD, CJS, and ESM support

📦 Installation

NPM/Yarn

npm install @cartai2025/sdk socket.io-client
# or
yarn add @cartai2025/sdk socket.io-client

CDN (Browser)

<!-- Minified version -->
<script src="https://d24lz8mxe7yhfu.cloudfront.net/cartai-sdk/cartai-sdk.min.js"></script>

<!-- Development version -->
<script src="https://d24lz8mxe7yhfu.cloudfront.net/cartai-sdk/cartai-sdk.js"></script>

🎯 Quick Start

Basic Setup

import { createCartAI } from '@cartai2025/sdk'

// Initialize the SDK
const cartai = await createCartAI({
  serverUrl: 'http://localhost:8000',
  apiKey: 'cartai_sk_4f8b5e9a2c1d3f6e8b7a9c2e4f1b8d5a3e7c9f2b4e6a8c1d3f5e7b9a2c4e6f8b1',
  debug: true,
  enableEventTracking: true
})

// Send fingerprint data
await cartai.sendFingerprint()

// Set user information
cartai.setUserInfo({
  email: '[email protected]',
  phone: '+1234567890'
})

// Track custom events
cartai.trackEvent({
  type: 'custom',
  data: {
    action: 'button_click',
    element: 'cta-button'
  }
})

Browser (IIFE)

<!DOCTYPE html>
<html>
<head>
  <script src="./dist/cartai-sdk.min.js"></script>
</head>
<body>
  <script>
    // CartAI SDK is available as CartAISDK global
    CartAISDK.createCartAI({
      serverUrl: 'http://localhost:8000',
      apiKey: 'your-api-key',
      debug: true
    }).then(async (cartai) => {
      console.log('CartAI SDK initialized')
      
      // Send fingerprint
      await cartai.sendFingerprint()
      
      // Track custom event
      cartai.trackSales({
        eventType: 'purchase',
        productId: 'prod_123',
        productName: 'Demo Product',
        category: 'electronics',
        value: 99.99
      })
    })
  </script>
</body>
</html>

🔧 Configuration

CartAIConfig Options

interface CartAIConfig {
  serverUrl: string              // Socket.IO server URL
  apiKey: string                 // Authentication API key
  loadOptions?: any              // Device SDK options
  autoConnect?: boolean          // Auto-connect on init (default: true)
  debug?: boolean                // Debug logging (default: false)
  enableEventTracking?: boolean  // Auto event tracking (default: true)
  customVisitorId?: string       // Custom visitor ID
  eventBatchSize?: number        // Events per batch (default: 10)
  eventSendInterval?: number     // Batch send interval ms (default: 10000)
}

📊 Event Tracking

Automatic Event Tracking

When enableEventTracking is true, the SDK automatically tracks:

  • URL Changes: Page navigation with time spent
  • Clicks: All click events with element details
  • Scrolling: Scroll behavior and engagement
  • Form Inputs: Input events with email/phone detection
  • Page Visibility: Tab switching and focus changes

Manual Event Tracking

Form Input Events

cartai.trackFormInput({
  inputType: 'email',
  fieldName: 'signup-email',
  value: '[email protected]',
  isEmail: true,
  fieldId: 'email-field'
})

Payment Events

cartai.trackPayment({
  status: 'completed',
  amount: 99.99,
  currency: 'USD',
  transactionId: 'txn_123456',
  paymentMethod: 'credit_card',
  salesAttributes: {
    productId: 'prod_123',
    orderId: 'order_789'
  }
})

Sales Events

cartai.trackSales({
  eventType: 'purchase',
  productId: 'prod_123',
  productName: 'Demo Product',
  category: 'electronics',
  value: 99.99,
  salesAttributes: {
    orderId: 'order_789',
    couponCode: 'SAVE10'
  }
})

Custom Events

cartai.trackEvent({
  type: 'custom',
  data: {
    eventType: 'video_play',
    videoId: 'demo_video',
    duration: 120
  }
})

🔗 Socket.IO Integration

Server Events Sent

  • fingerprint-data: Device fingerprint data
  • browser-events: Batched browser events
  • get-visitor-data: Request visitor information
  • get-stats: Request analytics

Server Events Received

  • fingerprint-stored: Fingerprint confirmation
  • browser-events-processed: Events processed confirmation
  • new-browser-activity: Real-time activity updates
  • error: Error messages

🎮 API Reference

Main Methods

createCartAI(config: CartAIConfig): Promise<CartAI>

Factory function to create and initialize the SDK.

initialize(): Promise<void>

Initialize the SDK (called automatically by createCartAI).

connect(): Promise<void>

Connect to Socket.IO server.

disconnect(): void

Disconnect from server and cleanup.

getFingerprint(): Promise<FingerprintResult>

Get device fingerprint data.

sendFingerprint(customData?: Record<string, any>): Promise<void>

Send fingerprint to server.

User & Location Data

setUserInfo(userInfo: UserInfo): void

Set user information for enhanced tracking.

setLocationData(locationData: LocationData): void

Set location data for user tracking.

Event Tracking Methods

trackEvent(event: BrowserEvent): void

Track a custom browser event.

trackFormInput(data: FormInputData): void

Track form input with auto email/phone detection.

trackPayment(data: PaymentData): void

Track payment events.

trackSales(data: SalesData): void

Track sales events.

sendBrowserEvents(events?: BrowserEvent[]): Promise<void>

Send browser events to server.

Utility Methods

getSessionInfo(): SessionInfo

Get current session information.

getQueuedEvents(): BrowserEvent[]

Get queued events.

clearQueuedEvents(): void

Clear queued events.

🏗️ Build & Development

Build Commands

# Install dependencies
npm install

# Build all formats
npm run build

# Build with watch mode
npm run dev

# Lint code
npm run lint

# Fix lint issues
npm run lint:fix

Output Formats

  • cartai-sdk.js - IIFE for direct browser use
  • cartai-sdk.min.js - Minified IIFE
  • cartai-sdk.umd.js - UMD for universal usage
  • cartai-sdk.umd.min.js - Minified UMD
  • cartai-sdk.cjs.js - CommonJS for Node.js
  • cartai-sdk.esm.js - ES modules for bundlers
  • cartai-sdk.d.ts - TypeScript definitions

🔒 Security & Privacy

  • API Key Authentication: Secure Socket.IO connections
  • Password Field Exclusion: Passwords are never tracked
  • Data Truncation: Form values limited to prevent large data
  • Debug Mode Control: Sensitive data logging controlled by debug flag

🌐 Browser Compatibility

  • Modern Browsers: Chrome 60+, Firefox 60+, Safari 12+, Edge 79+
  • Legacy Support: Graceful degradation for older browsers
  • Mobile Support: iOS Safari 12+, Android Chrome 60+

🤝 Integration with CartAI Device SDK

The SDK works seamlessly with @cartai2025/device-sdk:

<!-- Include both SDKs -->
<script src="./path-to/cartai.min.js"></script>
<script src="./path-to/cartai-sdk.min.js"></script>

<script>
// CartAI Device SDK will be detected automatically
CartAISDK.createCartAI({
  serverUrl: 'http://localhost:8000',
  apiKey: 'your-api-key'
}).then(cartai => {
  // Full fingerprinting + event tracking ready
})
</script>

📈 Example Use Cases

E-commerce Tracking

// Track product views
cartai.trackSales({
  eventType: 'product_view',
  productId: 'prod_123',
  productName: 'Wireless Headphones',
  category: 'electronics',
  value: 199.99
})

// Track add to cart
cartai.trackEvent({
  type: 'custom',
  data: {
    action: 'add_to_cart',
    productId: 'prod_123',
    quantity: 1
  }
})

// Track purchase
cartai.trackPayment({
  status: 'completed',
  amount: 199.99,
  currency: 'USD',
  transactionId: 'txn_abc123',
  paymentMethod: 'credit_card'
})

Lead Generation

// Form completion tracking
cartai.trackFormInput({
  inputType: 'email',
  fieldName: 'newsletter-signup',
  value: '[email protected]',
  isEmail: true
})

// Custom lead scoring
cartai.trackEvent({
  type: 'custom',
  data: {
    action: 'whitepaper_download',
    leadScore: 25,
    category: 'high-intent'
  }
})

Content Analytics

// Article engagement
cartai.trackEvent({
  type: 'custom',
  data: {
    action: 'article_read',
    articleId: 'art_456',
    readingTime: 180,
    completion: 75
  }
})

// Video engagement
cartai.trackEvent({
  type: 'custom',
  data: {
    action: 'video_engagement',
    videoId: 'vid_789',
    watchTime: 120,
    completion: 50
  }
})

🛠️ Troubleshooting

Common Issues

Connection Issues

// Check connection status
const sessionInfo = cartai.getSessionInfo()
console.log('Connected:', sessionInfo.isConnected)

// Manual reconnection
if (!sessionInfo.isConnected) {
  await cartai.connect()
}

Event Queue Management

// Check queued events
const queuedEvents = cartai.getQueuedEvents()
console.log(`${queuedEvents.length} events queued`)

// Force send events
await cartai.sendBrowserEvents()

// Clear queue if needed
cartai.clearQueuedEvents()

Debug Mode

// Enable debug logging
const cartai = await createCartAI({
  serverUrl: 'http://localhost:8000',
  apiKey: 'your-api-key',
  debug: true // Enable detailed logging
})

📚 TypeScript Support

Full TypeScript definitions included:

import { CartAI, CartAIConfig, BrowserEvent, UserInfo } from '@cartai2025/sdk'

const config: CartAIConfig = {
  serverUrl: 'http://localhost:8000',
  apiKey: 'your-api-key',
  debug: true
}

const cartai: CartAI = await createCartAI(config)

const userInfo: UserInfo = {
  email: '[email protected]',
  phone: '+1234567890',
  userId: 'user_123'
}

cartai.setUserInfo(userInfo)

🚀 Getting Started Checklist

  • [ ] Install the SDK via npm or include via CDN
  • [ ] Configure your CartAI backend server with Socket.IO
  • [ ] Initialize the SDK with your server URL and API key
  • [ ] Enable debug mode for development
  • [ ] Test fingerprint collection and event tracking
  • [ ] Set up user information and location data
  • [ ] Implement custom event tracking for your use case
  • [ ] Monitor real-time analytics in your backend
  • [ ] Deploy to production with proper API keys

Need help? Check the troubleshooting section above or create an issue in the repository.


CartAI SDK - Powering comprehensive user analytics with device fingerprinting and real-time event tracking