SDK Architecture

The TraceScout SDK is designed as a modular, production-ready system with excellent performance characteristics and clean separation of concerns.

Package Structure

@tracescout/suite (Full SDK)
├── @tracescout/core          # Main SDK class and managers
├── @tracescout/record        # Session recording
├── @tracescout/replay        # Session replay (dashboard only)
├── @tracescout/interceptors  # Network, console, error capture
├── @tracescout/monitors      # Performance monitoring
└── @tracescout/services      # External integrations

Core Components

SDKContext (Singleton)

The SDKContext is the central source of truth for all SDK operations:

SDKContext {
  // Identity
  apiKey: string
  organizationId: string
  projectId: string
  environment: string
  
  // Session
  sessionId: string
  sessionStartTime: number
  
  // User (optional)
  userId: string | null
  userAttributes: object
  
  // Device (auto-captured)
  device: { userAgent, viewport, platform }
  
  // Page (auto-captured)
  page: { url, referrer, title }
}

Every event and chunk is automatically enriched with context, ensuring perfect multi-tenant data isolation.

TraceScoutMonitoringCore

The main SDK class that orchestrates all functionality:

  • ConfigManager: Validates and manages configuration
  • EventManager: Queues, deduplicates, and batches events
  • ServiceManager: Handles transmission with retry logic
  • UserProfileManager: Manages user identification

Initialization Flow

TraceScout.init({...})
     │
     ▼
┌─────────────────────────────┐
│  1. Validate Required Fields │
│     - apiKey, organizationId    │
│     - projectId, environment │
└────────────┬────────────────┘
             │
             ▼
┌─────────────────────────────┐
│  2. Initialize SDKContext    │
│     - Store identity         │
│     - Generate sessionId     │
│     - Capture device/page    │
└────────────┬────────────────┘
             │
             ▼
┌─────────────────────────────┐
│  3. Fetch Remote Config      │
│     GET /projects/{id}/sdk-config
│     - Feature flags          │
│     - Privacy settings       │
└────────────┬────────────────┘
             │
             ▼
┌─────────────────────────────┐
│  4. Initialize Features      │
│     - Session Recording      │
│     - Network Monitoring     │
│     - Console Capture        │
│     - Error Tracking         │
│     - Performance Monitors   │
└────────────┬────────────────┘
             │
             ▼
┌─────────────────────────────┐
│  5. SDK Ready                │
│     window.TraceScout active │
└─────────────────────────────┘

Session Recording System

The recording system is designed for production reliability:

Recorder Class

User Interactions
       │
       ▼
   rrweb (CDN loaded)
       │
       ▼
 Recorder.emit(event)
       │
       ▼
 currentChunk[] buffer
       │
 [30s timeout OR 500KB limit]
       │
       ▼
 Recorder.flushChunk()
       │
       ▼
 Compression (fflate)
       │
       ▼
 UploadQueue.enqueue()
       │
       ▼
 POST to API

Chunking Strategy

Events are batched into chunks for efficient transmission:

| Trigger | Value | Purpose | |---------|-------|---------| | Time | 30-60 seconds | Regular uploads | | Size | 500KB-1MB | Prevent memory bloat | | Events | 100-200 events | Consistent chunk sizes |

Compression

Multi-level compression achieves significant size reduction:

  1. SDK → API: gzip compression (~70-80% reduction)
  2. API Storage: Double compression (~85% total reduction)

Network Interception

FetchInterceptor

Patches window.fetch to capture all HTTP requests:

// Original
window.fetch(url, options)

// Intercepted
window.fetch = (url, options) => {
  const startTime = performance.now();
  
  return originalFetch(url, options)
    .then(response => {
      // Capture: method, url, status, duration, headers
      monitoringCore.addSessionCustomEvent('network_request', {...});
      return response;
    });
};

ConsoleInterceptor

Patches console methods:

['log', 'warn', 'error', 'info', 'debug'].forEach(method => {
  const original = console[method];
  console[method] = (...args) => {
    // Capture console output
    monitoringCore.addSessionCustomEvent('console', {
      level: method,
      message: args,
      stack: new Error().stack
    });
    return original.apply(console, args);
  };
});

Event Types

Events in session recordings follow the rrweb format:

| Type | Name | Description | |------|------|-------------| | 0 | DomContentLoaded | DOM ready event | | 1 | Load | Page load complete | | 2 | FullSnapshot | Complete DOM snapshot | | 3 | IncrementalSnapshot | DOM mutations, mouse, scroll | | 4 | Meta | Page metadata | | 5 | Custom | Network, console, errors |

Bundle Optimization

The SDK achieves a 97% size reduction through:

  • CDN Loading: rrweb loaded from CDN, not bundled
  • Tree Shaking: Only import what you use
  • Code Splitting: Lazy load features
  • Minification: Production builds heavily optimized

| Build | Size | Use Case | |-------|------|----------| | Production | ~140KB | Live applications | | Development | ~480KB | Debugging with source maps | | Lite | ~70KB | Performance-critical apps |

Remote Configuration

Configuration is fetched from the server, enabling dashboard control:

// SDK fetches on init
GET /api/projects/{projectId}/sdk-config

// Response includes
{
  features: {
    sessionRecording: { enabled, sampleRate, ... },
    errorTracking: { enabled, ignoreErrors, ... },
    performanceMonitoring: { enabled, ... },
  },
  privacy: { maskInputs, blockSelectors, ... },
  telemetry: { endpoint, batchSize, ... }
}

Configuration refreshes every 5 minutes, allowing real-time changes from the dashboard.

See Also