npm package: @gemx-dev/trackers
Description: A high-performance tracking SDK with dual Web Worker architecture for optimal performance and scalability.
Latest version: 3.5.3

# @gemx-dev/trackers

A high-performance tracking SDK with dual Web Worker architecture for optimal performance and scalability.

## Features

- **Dual Worker Architecture**: Separate workers for event processing and callback handling
- **TypeScript Support**: Full TypeScript definitions and type safety
- **Performance Optimized**: Non-blocking event processing using Web Workers
- **Fault Tolerant**: Isolated workers prevent crashes from affecting the main thread
- **Scalable**: Easy to extend with additional workers for specific event types
- **Modern API**: Clean, intuitive API with callback support

## Architecture

```
Page Event (click/load)
    ↓
Main Thread (tracking-sdk.js)
    ↓ postMessage
Event Worker (event-worker.js)
    → Process logic → Calculate metrics
    ↓ postMessage
Callback Worker (callback-worker.js)
    → Execute callbacks → API calls → Logging
    ↓ postMessage (summaries)
Main Thread
    → User callbacks → Console/UI updates
```

## Installation

```bash
npm install @gemx-dev/trackers
```

## Usage

### Basic Setup

```typescript
import { TrackingSDK } from '@gemx-dev/trackers';

// Initialize the SDK
TrackingSDK.init({
  apiEndpoint: 'https://your-analytics-server.com/track',
  events: ['pageLoad', 'click', 'performance'],
  workerTimeout: 5000,
});

// Register callbacks
TrackingSDK.on('performanceResult', (data) => {
  console.log('Performance metrics:', data.metrics);
});

TrackingSDK.on('clickTracked', (data) => {
  console.log('Click tracked:', data.data);
});

TrackingSDK.on('error', (error) => {
  console.error('Tracking error:', error);
});

// Track custom events
TrackingSDK.trackEvent('customEvent', {
  userId: '123',
  action: 'button_click',
  timestamp: Date.now(),
});
```

### Advanced Configuration

```typescript
import { TrackingSDK, type TrackingConfig } from '@gemx-dev/trackers';

const config: TrackingConfig = {
  apiEndpoint: 'https://analytics.example.com/track',
  events: ['pageLoad', 'click', 'performance', 'scroll'],
  workerTimeout: 10000,
};

TrackingSDK.init(config);

// Get SDK status
const status = TrackingSDK.getStatus();
console.log('Worker status:', status.workerStatus);
console.log('Registered callbacks:', status.registeredCallbacks);

// Cleanup when done
TrackingSDK.destroy();
```

### Callback Management

```typescript
// Register callback and get unsubscribe function
const unsubscribe = TrackingSDK.on('pageLoad', (data) => {
  console.log('Page loaded:', data.data);
});

// Unsubscribe when no longer needed
unsubscribe();

// Register multiple callbacks for the same event
TrackingSDK.on('click', callback1);
TrackingSDK.on('click', callback2);
```

## API Reference

### TrackingSDK

#### Methods

- `init(config?: Partial<TrackingConfig>)` - Initialize the SDK
- `trackEvent(eventName: string, data: EventData)` - Track a custom event
- `on(eventType: string, callback: EventCallback)` - Register a callback
- `getStatus()` - Get current SDK status
- `destroy()` - Clean up and destroy the SDK

#### Configuration

```typescript
interface TrackingConfig {
  apiEndpoint: string;
  events: string[];
  workerTimeout: number;
}
```

#### Event Data

```typescript
interface EventData {
  timestamp: number;
  [key: string]: any;
}
```

#### Callback Data

```typescript
interface CallbackData {
  type: string;
  data: ProcessedEventData;
  metrics?: PerformanceMetrics;
  timestamp: number;
  processingTime: number;
  workerId: string;
}
```

## Built-in Event Types

- `pageLoad` - Page load events
- `pageLoadComplete` - Complete page load with performance metrics
- `userClick` - User click events
- `performance` - Performance metrics
- `performanceEntry` - Performance observer entries
- `scroll` - Scroll events (throttled)

## Worker Files

The package includes three JavaScript files that need to be served from your public directory:

- `event-worker.js` - Processes tracking events
- `callback-worker.js` - Handles callbacks and communication
- `tracking-sdk.js` - Main SDK file (for non-module usage)

## Browser Support

- Modern browsers with Web Worker support
- ES6+ features required
- TypeScript support for development

## Performance Benefits

1. **Non-blocking Processing**: Event processing happens in workers
2. **Parallel Execution**: Event and callback workers run simultaneously
3. **Fault Isolation**: Worker crashes don't affect the main thread
4. **Scalable Architecture**: Easy to add more workers for specific tasks

## Development

```bash
# Install dependencies
npm install

# Build the package
npm run build

# Run tests
npm test

# Lint code
npm run lint
```

## License

MIT

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## Changelog

### 0.0.0

- Initial release
- Dual worker architecture
- TypeScript support
- Basic event tracking
- Performance monitoring