@inputless/tracker
v1.0.6
Published
Core behavioral event tracking engine for the Inputless Analytics SDK
Maintainers
Readme
@inputless/tracker
Core behavioral event tracking engine for the Inputless Analytics SDK.
Purpose
Captures user interactions without requiring explicit input, providing a foundation for behavioral analytics with semantic understanding through an embedded ontology system.
Features
Core Event Capture
- Click Events: Left click, right click, middle click, single/double click, coordinates, timing patterns
- Hover Events: Enter/leave, duration, position, pattern analysis, conversion metrics
- Mouse Movements: Path tracking, speed calculation, trajectory analysis
- Drag & Drop: Drag start/progress/end, distance, direction, velocity
- Context Menu: Right-click detection, menu interactions
Keyboard & Text Interactions
- Key Press Events: All keys with codes, modifier states, shortcuts
- Form Input: Focus/blur, value changes, validation, completion progress
- Text Selection: Selection tracking, copy/cut/paste
- Special Keys: Tab, Enter, Escape, Arrow navigation
- Accessibility: Screen reader, voice input support
Mobile & Touch Interactions
- Touch Events: Single/double tap, long press, multi-touch
- Gestures: Pinch-to-zoom, swipe, pan, rotation
- Device Orientation: Rotation, motion, shake detection
- Mobile-Specific: Pull-to-refresh, PWA installation prompts
Scroll & Viewport Tracking
- Scroll Events: Position, depth percentage, speed, direction changes
- Viewport Changes: Resize, fullscreen, engagement metrics
- Scroll Behavior: Deep scroll, bounce detection, hesitation patterns
- Infinite Scroll: Interaction tracking, pagination behavior
Form & Input Analysis
- Form Level: Focus/blur, submission, abandonment, completion time
- Input Field: Value changes, cursor position, typing hesitations
- Autocomplete: Dropdown interactions, selection patterns
- Multi-Step Forms: Step progression, abandonment, back navigation
Focus & Attention Metrics
- Window Focus: Tab focus/blur, duration, multi-tab behavior
- Element Focus: Focus order, duration, transitions
- Attention Span: Active vs. passive time, distraction detection
- Session Continuity: Return patterns, engagement tracking
Page & Navigation Events
- Page Load: Load start/complete, time to interactive, performance
- Navigation: URL changes, back/forward, hash changes
- Page Visibility: Tab switching, hidden duration, lifecycle
- Referrer Tracking: Traffic sources, deep linking patterns
Media Interaction Tracking
- Video: Play/pause, seek, fullscreen, completion, volume, speed
- Audio: Play/pause, seek, volume, mute toggles
- Image: View, zoom, gallery navigation, lightbox
- Engagement: Time spent, completion rate, skip behavior
Search & Filter Behavior
- Search: Query input, result clicks, refinement, abandonment
- Filters: Application, removal, combinations, impact analysis
- Sort: Option changes, preference patterns
Social & E-commerce
- Social Sharing: Share button clicks, platform selection
- Product Interactions: View, zoom, variants, add/remove cart
- Checkout: Step progression, abandonment, payment, shipping
- Recommendations: Related product clicks, cross-sell engagement
Advanced Capabilities
- Error Detection: JavaScript errors, form validation, network errors
- Frustration Indicators: Rage clicks, form abandonment, rapid navigation
- Heatmap Data: Element positions, click/move/scroll heat
- Journey Mapping: Navigation paths, loops, dead-ends
- Performance Monitoring: FCP, LCP, CLS, TTFB, layout shifts
- Contextual Metadata: Element/page/device/temporal/user context
- Semantic Enrichment: Intent classification, behavioral patterns
Additional Features
- Context Awareness: Automatic page context, device info, viewport details
- Session Management: Automatic session tracking and identification
- Batch Processing: Efficient event batching and upload
- Privacy-First: Configurable data collection levels, GDPR compliance
- Semantic Ontology: Intelligent meaning extraction from user actions
Installation
Option 1: npm (Recommended for Development)
npm install @inputless/trackerOption 2: CDN/Browser (No Build Required)
UMD Build (Any Browser)
<script src="https://cdn.inputless.io/@inputless/[email protected]/dist/index.umd.js"></script>
<script>
const tracker = new Inputless.InputlessTracker({
sessionId: 'unique-session-id',
apiEndpoint: 'https://api.example.com/events'
});
</script>ES Modules (Modern Browsers)
<script type="module">
import { InputlessTracker } from 'https://cdn.inputless.io/@inputless/[email protected]/dist/index.esm.js';
const tracker = new InputlessTracker({
sessionId: 'unique-session-id',
apiEndpoint: 'https://api.example.com/events'
});
</script>Option 3: Direct Download
Download the build files from npm and include locally:
<script src="./js/@inputless/tracker.js"></script>Dependencies
@inputless/events- Type definitions and validation schemas- Browser APIs (no external runtime dependencies)
Package Boundary & Responsibilities
This package (@inputless/tracker) implements HOW events are captured, using types from @inputless/events.
✅ What This Package Provides:
- Event Capture: Browser event listeners (click, hover, scroll, etc.)
- Collection Logic: DOM observation, performance monitoring, network interception
- Event Creation: Creates typed events using
@inputless/eventstypes - Tracking Implementation: Session management, batching, buffering
- Browser Integration: Wrappers for browser APIs (PerformanceObserver, IntersectionObserver, etc.)
- Semantic Enrichment: Ontology engine for intent classification
❌ What This Package Does NOT Provide:
- Type Definitions: Uses types from
@inputless/events(does NOT redefine them) - Validation Schemas: Uses schemas from
@inputless/events(does NOT duplicate) - Type Utilities: Uses utilities from
@inputless/events(does NOT reimplement)
Separation from @inputless/events:
| Aspect | @inputless/tracker | @inputless/events |
|--------|---------------------|---------------------|
| Purpose | Event capture & collection | Type system & validation |
| Contains | Browser listeners, tracking logic | Types, schemas, utilities |
| Dependencies | @inputless/events + browser APIs | zod only |
| Exports | Tracker classes, collection logic | Type definitions, validators |
| Usage | Uses events package types | Used BY tracker (and others) |
Example Boundary:
// ✅ CORRECT: Tracker imports types from events package
import { BaseEvent, EventType, UIEventMetadata, generateEventId } from '@inputless/events';
class InputlessTracker {
// Tracker implements capture logic
private setupClickListener() {
document.addEventListener('click', (e) => {
// ✅ Tracker captures browser event
const event: BaseEvent<UIEventMetadata> = {
id: generateEventId(), // from events package
type: 'ui.click', // from events package
timestamp: Date.now(),
sessionId: this.sessionId,
// ... tracker populates event using events types
};
this.emit(event);
});
}
}
// ❌ WRONG: Tracker should NOT redefine types
// DO NOT add this to tracker package:
interface BaseEvent { ... } // ❌ Already defined in @inputless/events
export const EventSchema = z.object({ ... }); // ❌ Already defined in @inputless/eventsDependency Relationship:
@inputless/tracker
↓ depends on
@inputless/events
↓ depends on
zodTracker depends on Events, not the other way around.
Key Principles:
- No Duplication: Never redefine types/schemas already in
@inputless/events - Type Usage: Always import types from
@inputless/events, never redefine - Single Source of Truth: All event type definitions live in
@inputless/events - Clear Separation: Events = types, Tracker = implementation using those types
Usage
Basic Setup (Local Only - No API Endpoint)
import { InputlessTracker } from '@inputless/tracker';
import type { BaseEvent } from '@inputless/events';
// Initialize tracker WITHOUT API endpoint - all processing is local
const tracker = new InputlessTracker({
// No apiEndpoint - events processed locally only
sessionId: undefined, // Optional, auto-generated if not provided
userId: undefined, // Optional, for identified users
enabledCategories: {
ui: true, // UI events (click, hover, scroll)
form: true, // Form events (focus, input, submit)
performance: true, // Performance metrics (Web Vitals)
network: false, // Network events (fetch/XHR)
},
privacy: {
consentLevel: 'analytics', // 'none' | 'analytics' | 'full'
maskSelectors: false, // Mask PII in selectors
quantizeCoordinates: true, // Reduce coordinate precision
},
debug: true, // Enable debug logging
});
// Register event handler to process events locally
tracker.onEvent((event: BaseEvent) => {
console.log('Event captured:', {
id: event.id,
type: event.type,
timestamp: new Date(event.timestamp).toISOString(),
sessionId: event.sessionId,
data: event.data,
});
// Process event locally (store, analyze, etc.)
// No API calls required
});
// Start tracking (attaches event listeners)
tracker.start();
// Manual event tracking (optional - automatic tracking also works)
const button = document.querySelector('#my-button');
if (button) {
tracker.trackClick(button);
tracker.trackHover(button, 2000); // 2 second hover
}
tracker.trackScroll(100, 25, 'down'); // Scroll position, depth %, direction
tracker.trackPerformance({
metric: 'lcp',
value: 1500,
unit: 'ms',
});
// Custom event tracking
tracker.trackCustom('biz.product.view', {
productId: 'prod-123',
category: 'electronics',
});
// Get session ID
const sessionId = tracker.getSessionId();
console.log('Session ID:', sessionId);
// Get queue size
const queueSize = tracker.getQueueSize();
console.log('Queue size:', queueSize);
// Flush queue manually (if needed)
await tracker.flush();
// Stop tracking (removes listeners, flushes queue)
await tracker.stop();Event Handlers
// Register handler to receive events
tracker.onEvent((event) => {
console.log('Event captured:', event);
// Route to dispatcher or send to backend
});
// Unregister handler
tracker.offEvent(handler);Console Logging (Visualize Events)
To visualize all tracker events in the console:
import { InputlessTracker } from '@inputless/tracker';
const tracker = new InputlessTracker({
debug: true, // Enable debug logs for tracker lifecycle
});
// Log all events to console
tracker.onEvent((event) => {
console.log('📊 Event:', {
type: event.type,
timestamp: new Date(event.timestamp).toISOString(),
sessionId: event.sessionId,
properties: event.properties || event.data
});
});
tracker.start();
// Now all captured events will appear in the console:
// - Clicks, hovers, scrolls
// - Form interactions
// - Page views
// - Keyboard events
// - Touch gestures (mobile)Custom Console Formatting:
tracker.onEvent((event) => {
// Simple format
console.log(`[${event.type}]`, event);
// Or detailed format
console.group(`Event: ${event.type}`);
console.log('Timestamp:', new Date(event.timestamp));
console.log('Session:', event.sessionId);
console.log('Data:', event.properties || event.data);
console.groupEnd();
});Session Management
// Get current session ID
const sessionId = tracker.getSessionId();
// Flush queue manually
await tracker.flush();
// Get queue size
const queueSize = tracker.getQueueSize();Advanced Configuration
const tracker = new InputlessTracker({
// Sampling configuration
sampling: {
rate: 0.8, // 80% of events tracked
strategy: 'adaptive', // 'uniform' | 'adaptive' | 'priority'
},
// Batching configuration
batching: {
maxBatchSize: 50, // Flush when 50 events queued
maxBatchAge: 5000, // Flush after 5 seconds
autoFlush: true, // Enable automatic flushing
},
// Performance configuration
performance: {
throttleMouseMove: 100, // Throttle mousemove to 100ms
throttleScroll: 150, // Throttle scroll to 150ms
debounceResize: 250, // Debounce resize to 250ms
maxQueueSize: 1000, // Max events in queue
},
// Ontology configuration
ontology: {
enabled: true,
confidenceThreshold: 0.7,
customRules: [
{
matches: (event) => event.type === 'ui.click' &&
(event.data as any).selector?.includes('special'),
meanings: ['special_interaction'],
confidenceBoost: 0.2,
},
],
},
debug: true, // Enable debug logging
});Usage Examples
Example 1: E-commerce Product Page Tracking
import { InputlessTracker } from '@inputless/tracker';
// Initialize tracker
const tracker = new InputlessTracker({
sessionId: 'session-123',
userId: 'user-456',
apiEndpoint: 'https://api.example.com/events',
enabledCategories: {
ui: true,
form: true,
performance: true,
business: true, // Enable business event detection
media: true,
},
privacy: {
consentLevel: 'analytics',
maskSelectors: false,
},
});
tracker.start();
// The tracker automatically captures:
// - Product image views (when images are clicked)
// - Add to cart clicks (detected from button selectors)
// - Wishlist interactions (detected from selectors)
// - Filter/sort changes (detected from form interactions)
// - Scroll depth (measures how far user scrolls on product page)
// - Video interactions (play, pause, seek if product videos exist)
// - Form validation errors (email, shipping, etc.)
// Manual tracking for specific interactions
const productCard = document.querySelector('.product-card');
if (productCard) {
tracker.trackHover(productCard, 2000); // Track 2s hover on product
}Example 2: Form Completion Tracking
import { InputlessTracker } from '@inputless/tracker';
const tracker = new InputlessTracker({
enabledCategories: {
ui: true,
form: true, // Critical for form tracking
performance: false,
},
privacy: {
consentLevel: 'analytics',
maskSelectors: true, // Mask form field selectors containing PII
},
});
tracker.start();
// Automatic form tracking captures:
// - Focus events (when user focuses on input fields)
// - Input changes (typed values - masked if contains PII)
// - Validation errors (HTML5 validation, custom validation)
// - Form submission (successful or abandoned)
// - Multi-step form progression (tracks step navigation)
// Custom tracking for form abandonment
let formStartTime = Date.now();
const form = document.querySelector('#signup-form');
form?.addEventListener('submit', () => {
const completionTime = Date.now() - formStartTime;
tracker.trackCustom('form.completion', {
formId: 'signup-form',
completionTime,
stepCount: 3,
});
});Example 3: Media Consumption Tracking
import { InputlessTracker } from '@inputless/tracker';
const tracker = new InputlessTracker({
enabledCategories: {
ui: true,
media: true, // Enable media event tracking
performance: true,
},
});
tracker.start();
// Automatic media tracking captures:
// - Video play/pause events
// - Video seek (when user jumps to different time)
// - Volume changes
// - Fullscreen toggles
// - Video completion (when video ends)
// - Audio play/pause (for audio players)
// - Image views (when images are clicked for zoom/view)
// Example: Track video engagement
const video = document.querySelector('video');
if (video) {
// Tracker automatically captures all video events
// You can also manually track specific moments:
video.addEventListener('ended', () => {
tracker.trackCustom('media.video.completed', {
videoId: video.src,
duration: video.duration,
});
});
}Example 4: Mobile App Tracking (PWA)
import { InputlessTracker } from '@inputless/tracker';
const tracker = new InputlessTracker({
enabledCategories: {
ui: true,
mobile: true, // Enable mobile-specific tracking
touch: true,
performance: true,
},
});
tracker.start();
// Automatic mobile tracking captures:
// - Touch events (tap, swipe, pinch-to-zoom)
// - Device orientation changes (portrait/landscape)
// - PWA install prompts (when user sees install prompt)
// - PWA install responses (accept/decline)
// - Pull-to-refresh gestures
// - Long press interactions
// Example: Track PWA installation
window.addEventListener('beforeinstallprompt', (e) => {
// Tracker automatically captures this event
// You can also track custom install flow:
e.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
tracker.trackCustom('mobile.pwa.installed', {
installTime: Date.now(),
});
}
});
});Example 5: Error Monitoring
import { InputlessTracker } from '@inputless/tracker';
const tracker = new InputlessTracker({
enabledCategories: {
ui: true,
form: true,
// Error events are automatically captured when enabled
},
});
tracker.start();
// Automatic error tracking captures:
// - JavaScript errors (window.onerror)
// - Unhandled promise rejections
// - Form validation errors (HTML5 and custom)
// Custom error tracking
tracker.onEvent((event) => {
if (event.type.startsWith('error.')) {
// Send critical errors to error monitoring service
sendToErrorService(event);
}
});Example 6: Accessibility Tracking
import { InputlessTracker } from '@inputless/tracker';
const tracker = new InputlessTracker({
enabledCategories: {
ui: true,
accessibility: true, // Enable accessibility tracking
},
});
tracker.start();
// Automatic accessibility tracking captures:
// - Keyboard navigation patterns (Tab, arrow keys)
// - Screen reader interactions (if detectable)
// - Focus management patterns
// - Keyboard-only navigation flows
// Track accessibility compliance
tracker.onEvent((event) => {
if (event.type === 'a11y.keyboard.navigate') {
console.log('User navigated using keyboard:', event);
// Track accessibility metrics
}
});Example 7: Integration with Signal Dispatcher
import { InputlessTracker } from '@inputless/tracker';
import { SignalDispatcher } from '@inputless/dispatcher';
// Initialize dispatcher
const dispatcher = new SignalDispatcher({
modules: ['ads', 'cognitive', 'analytics'],
});
// Initialize tracker with dispatcher integration
const tracker = new InputlessTracker({
apiEndpoint: 'https://api.example.com/events',
});
// Route all tracker events through dispatcher
tracker.onEvent((event) => {
dispatcher.dispatch(event);
});
tracker.start();
// Events are now automatically routed to:
// - @inputless/ads (for ad optimization)
// - @inputless/sdk-cognitive (for insight generation)
// - Analytics backend (for storage and analysis)Example 8: Privacy-First Configuration
import { InputlessTracker } from '@inputless/tracker';
// GDPR-compliant configuration
const tracker = new InputlessTracker({
enabledCategories: {
ui: true,
form: false, // Disable form tracking for privacy
performance: true,
network: false, // Disable network tracking
},
privacy: {
consentLevel: 'analytics', // 'none' | 'analytics' | 'full'
maskSelectors: true, // Mask element selectors that might contain PII
quantizeCoordinates: true, // Reduce coordinate precision
hashUrls: true, // Hash URLs to prevent tracking specific pages
},
});
// Check consent before starting
if (hasUserConsent()) {
tracker.start();
} else {
// Only track basic performance metrics
tracker.start();
// Disable all PII-capturing features
}Example 9: Custom Business Event Detection
import { InputlessTracker } from '@inputless/tracker';
const tracker = new InputlessTracker({
enabledCategories: {
ui: true,
business: true, // Enable business event detection
},
ontology: {
enabled: true,
customRules: [
{
// Custom rule for subscription button
matches: (event) =>
event.type === 'ui.click' &&
(event.data as any).selector?.includes('subscribe-button'),
meanings: ['subscription_intent', 'high_value'],
confidenceBoost: 0.3,
},
{
// Custom rule for demo request
matches: (event) =>
event.type === 'ui.click' &&
(event.data as any).selector?.includes('request-demo'),
meanings: ['sales_qualified_lead', 'conversion_likely'],
confidenceBoost: 0.4,
},
],
},
});
tracker.start();
// Automatic detection for common e-commerce patterns:
// - Add to cart (from button selectors like 'add-to-cart', 'cart-add')
// - Checkout (from selectors like 'checkout', 'proceed-to-payment')
// - Wishlist (from selectors like 'wishlist', 'save-for-later')
// - Social share (from selectors like 'share', 'social-share')
// - Filter/sort (from selectors like 'filter', 'sort')
// Custom business events are also detected based on ontology rulesExample 10: Performance Monitoring
import { InputlessTracker } from '@inputless/tracker';
const tracker = new InputlessTracker({
enabledCategories: {
ui: true,
performance: true, // Enable performance monitoring
},
performance: {
throttleMouseMove: 100,
throttleScroll: 150,
maxQueueSize: 1000,
},
});
tracker.start();
// Automatic performance tracking captures:
// - Web Vitals (LCP, FCP, CLS, FID, TTFB)
// - Resource timing (load times, transfer sizes)
// - Long tasks (JavaScript blocking time)
// Listen to performance events
tracker.onEvent((event) => {
if (event.type.startsWith('perf.')) {
console.log('Performance metric:', event);
// Alert if performance is poor
if (event.type === 'perf.lcp' && event.data.value > 2500) {
console.warn('LCP is slow:', event.data.value);
// Send to monitoring service
}
}
});Example 11: Real-Time Event Streaming
import { InputlessTracker } from '@inputless/tracker';
const tracker = new InputlessTracker({
enabledCategories: {
ui: true,
form: true,
performance: true,
},
batching: {
maxBatchSize: 1, // Send immediately (no batching)
maxBatchAge: 0, // No delay
autoFlush: true,
},
});
tracker.start();
// Stream events in real-time
tracker.onEvent((event) => {
// Send to WebSocket or Server-Sent Events
websocket.send(JSON.stringify(event));
});Example 12: Conditional Tracking Based on User Segment
import { InputlessTracker } from '@inputless/tracker';
// Determine tracking configuration based on user segment
function getTrackingConfig(userSegment: 'premium' | 'free' | 'trial') {
const baseConfig = {
enabledCategories: {
ui: true,
form: true,
},
};
switch (userSegment) {
case 'premium':
return {
...baseConfig,
enabledCategories: {
...baseConfig.enabledCategories,
performance: true,
network: true,
business: true,
},
sampling: { rate: 1.0 }, // Track everything for premium users
};
case 'trial':
return {
...baseConfig,
sampling: { rate: 0.7 }, // Sample 70% for trial users
};
case 'free':
return {
...baseConfig,
sampling: { rate: 0.3 }, // Sample 30% for free users
};
}
}
const userSegment = getUserSegment(); // Your function to determine segment
const tracker = new InputlessTracker(getTrackingConfig(userSegment));
tracker.start();Example 13: Integration with React
import { InputlessTracker } from '@inputless/tracker';
import { useEffect, useRef } from 'react';
function useInputlessTracker(config: TrackerConfig) {
const trackerRef = useRef<InputlessTracker | null>(null);
useEffect(() => {
// Initialize tracker
trackerRef.current = new InputlessTracker(config);
trackerRef.current.start();
// Cleanup on unmount
return () => {
trackerRef.current?.stop();
};
}, [config]);
return trackerRef.current;
}
// Usage in component
function App() {
const tracker = useInputlessTracker({
apiEndpoint: 'https://api.example.com/events',
enabledCategories: { ui: true, form: true },
});
// Tracker is now active for this component tree
return <div>Your app</div>;
}Example 14: Debugging and Development
import { InputlessTracker } from '@inputless/tracker';
const tracker = new InputlessTracker({
debug: true, // Enable debug logging
enabledCategories: {
ui: true,
form: true,
performance: true,
},
});
tracker.start();
// Log all events to console in development
tracker.onEvent((event) => {
if (process.env.NODE_ENV === 'development') {
console.log('📊 Event:', {
type: event.type,
timestamp: new Date(event.timestamp).toISOString(),
sessionId: event.sessionId,
data: event.data,
});
}
});
// Check queue status
setInterval(() => {
const queueSize = tracker.getQueueSize();
console.log(`Queue size: ${queueSize}`);
}, 5000);Semantic Ontology System
The tracker includes an ontology layer that maps raw user actions to semantic meanings, enabling the system to understand user intent and behavior patterns at a conceptual level rather than just tracking low-level events.
Conceptual Approach
The ontology system defines a structured vocabulary for understanding what user actions mean in context:
1. Action Semantics
Every tracked action receives semantic annotations:
- Raw Action:
click,hover,scroll - Semantic Meaning:
intent_to_purchase,exploratory_behavior,decision_making,engagement_interest
2. Intent Classification
Actions are classified by intent category:
// Example semantic classifications
{
action_type: 'click',
element_id: 'checkout-button',
semantics: {
primary_intent: 'purchase_intent',
confidence: 0.85,
contextual_meanings: ['conversion_likely', 'high_value_action'],
behavioral_context: 'cart_abandonment_prevention'
}
}3. Behavioral Dimensions
The ontology maps actions to behavioral dimensions:
Engagement Levels
passive_observation- Window focus, idle behavioractive_exploration- Hover, scroll, viewinteraction_intent- Click, form focusconversion_likely- Add to cart, checkout initiation
User Journey Stages
discovery- Early exploration, information gatheringconsideration- Comparing options, hesitation patternsdecision_making- Final steps, form completionconversion- Purchase, sign-up, commitment
Emotional/Affective States (inferred from patterns)
highly_engaged- Rapid, confident interactionsexploratory- Slow, methodical browsinghesitant- Pauses, backtracking, revisitingfrustrated- Rapid clicks, frequent changes
4. Contextual Meaning Resolution
The ontology system considers multiple contexts to resolve meaning:
Element Context
// Same action type, different semantic meaning
{ element: 'login-button', action: 'click', meaning: 'authentication_intent' }
{ element: 'logout-button', action: 'click', meaning: 'session_termination' }
{ element: 'product-card', action: 'click', meaning: 'product_interest' }
{ element: 'add-to-cart', action: 'click', meaning: 'purchase_intent' }Temporal Context
// Time-based semantic inference
{ action: 'scroll', speed: 'slow', meaning: 'content_engagement' }
{ action: 'scroll', speed: 'fast', meaning: 'content_scanning' }
{ action: 'hover', duration: 5000, meaning: 'high_interest' }
{ action: 'hover', duration: 500, meaning: 'cursory_view' }Sequence Context
// Action sequences reveal intent
sequence: ['view_product', 'compare_products', 'add_to_cart']
→ semantic_meaning: 'purchase_intent_with_consideration'
sequence: ['landing_page', 'scroll_fast', 'leave']
→ semantic_meaning: 'low_engagement', 'bounce_likely'5. Ontology Hierarchy
The system uses a hierarchical taxonomy:
Action
├── Interaction Level
│ ├── Passive (view, focus)
│ ├── Active (click, input)
│ └── Behavioral (hover patterns, scroll)
├── Intent Category
│ ├── Exploration (browsing, comparing)
│ ├── Engagement (reading, viewing)
│ ├── Conversion (purchase intent)
│ └── Exit (leaving intent)
└── Value Dimension
├── High Value (conversion, commitment)
├── Medium Value (engagement, interest)
└── Low Value (passive, scanning)6. Domain-Specific Extensions
The ontology can be extended for specific domains:
E-commerce
- Product browsing behaviors
- Shopping cart dynamics
- Checkout abandonment patterns
SaaS/Enterprise
- Feature adoption patterns
- Workflow completion rates
- User onboarding behaviors
Content/Media
- Content consumption patterns
- Engagement metrics (time spent, completion)
- Sharing and viral behaviors
7. Semantic Enrichment Pipeline
Raw Event → Context Extraction → Ontology Mapping → Semantic Enrichment → Metadata Tagging
↓ ↓ ↓ ↓ ↓
[click] [page, element] [intent classification] [meaning extraction] [semantic_event]8. Configurable Ontology Rules
Users can define custom semantic mappings using OntologyRule:
const ontologyConfig = {
enabled: true,
confidenceThreshold: 0.7,
customRules: [
{
matches: (event) =>
event.type === 'ui.click' &&
(event.data as any).selector?.includes('checkout-button'),
meanings: ['conversion_intent', 'high_value'],
confidenceBoost: 0.2,
},
{
matches: (event) =>
event.type === 'ui.click' &&
(event.data as any).selector?.includes('newsletter-signup'),
meanings: ['engagement_interest', 'nurturing'],
confidenceBoost: 0.15,
},
],
};Real-World Usage Examples
Example 1: Local Event Storage (No API)
import { InputlessTracker } from '@inputless/tracker';
import type { BaseEvent } from '@inputless/events';
// Initialize tracker without API endpoint
const tracker = new InputlessTracker({
enabledCategories: {
ui: true,
form: true,
performance: true,
},
debug: true,
});
// Local event storage (using browser storage)
const eventStorage: BaseEvent[] = [];
tracker.onEvent((event: BaseEvent) => {
// Store events locally
eventStorage.push(event);
// Keep only last 1000 events
if (eventStorage.length > 1000) {
eventStorage.shift();
}
console.log(`Stored event: ${event.type} (Total: ${eventStorage.length})`);
});
// Function to get stored events
function getStoredEvents(): BaseEvent[] {
return [...eventStorage];
}
// Function to get events by type
function getEventsByType(type: string): BaseEvent[] {
return eventStorage.filter(e => e.type === type);
}
// Function to get events by session
function getEventsBySession(sessionId: string): BaseEvent[] {
return eventStorage.filter(e => e.sessionId === sessionId);
}
tracker.start();
// Export stored events (e.g., for analysis)
setInterval(() => {
const stats = {
total: eventStorage.length,
clicks: getEventsByType('ui.click').length,
hovers: getEventsByType('ui.hover').length,
scrolls: getEventsByType('scroll').length,
sessionId: tracker.getSessionId(),
};
console.log('Event Statistics:', stats);
}, 10000);Example 2: Local Event Processing with Ontology
import { InputlessTracker } from '@inputless/tracker';
import { OntologyEngine } from '@inputless/tracker';
import type { BaseEvent } from '@inputless/events';
// Initialize tracker with ontology enabled
const tracker = new InputlessTracker({
ontology: {
enabled: true,
confidenceThreshold: 0.7,
customRules: [
{
matches: (event) =>
event.type === 'ui.click' &&
(event.data as any)?.selector?.includes('subscribe'),
meanings: ['subscription_intent', 'high_value'],
confidenceBoost: 0.3,
},
],
},
debug: true,
});
// Create ontology engine for semantic analysis
const ontologyEngine = new OntologyEngine({
enabled: true,
confidenceThreshold: 0.7,
customRules: [
{
matches: (event) =>
event.type === 'ui.click' &&
(event.data as any)?.selector?.includes('subscribe'),
meanings: ['subscription_intent', 'high_value'],
confidenceBoost: 0.3,
},
],
});
tracker.onEvent((event: BaseEvent) => {
// Extract semantic metadata using ontology engine
const semantics = ontologyEngine.extractSemantics(event);
console.log('Semantic Analysis:', {
eventType: event.type,
primaryIntent: semantics.primaryIntent, // 'exploration' | 'engagement' | 'conversion' | 'exit'
confidence: semantics.confidence, // 0.0 - 1.0
behavioralDimension: semantics.behavioralDimension, // 'passive' | 'active' | 'highly_engaged' | 'hesitant' | 'frustrated'
valueDimension: semantics.valueDimension, // 'high' | 'medium' | 'low'
contextualMeanings: semantics.contextualMeanings, // ['subscription_intent', 'high_value']
});
// Use semantics for local processing decisions
if (semantics.primaryIntent === 'conversion' && semantics.confidence > 0.8) {
console.log('🎯 High-confidence conversion event detected:', event);
// Process locally (e.g., update UI, show notification, etc.)
}
});
tracker.start();Example 3: Local Intent State Classification
import { InputlessTracker } from '@inputless/tracker';
import { SemanticClassifier } from '@inputless/tracker';
import type { BaseEvent } from '@inputless/events';
// Initialize tracker
const tracker = new InputlessTracker({
ontology: {
enabled: true,
confidenceThreshold: 0.7,
},
debug: true,
});
// Create semantic classifier for intent state analysis
const semanticClassifier = new SemanticClassifier();
// Store recent events for pattern analysis
const recentEvents: BaseEvent[] = [];
tracker.onEvent((event: BaseEvent) => {
// Store recent events
recentEvents.push(event);
// Keep only last 100 events
if (recentEvents.length > 100) {
recentEvents.shift();
}
// Classify intent state when we have enough events
if (recentEvents.length >= 5) {
const intentState = semanticClassifier.classifyIntentState(
recentEvents.slice(-10) // Use last 10 events
);
console.log('Intent State:', {
state: intentState.state, // 'focused' | 'deliberative' | 'frustrated' | 'wandering'
confidence: intentState.confidence, // 0.0 - 1.0
});
// React to intent state locally
switch (intentState.state) {
case 'focused':
console.log('✅ User is focused on task');
// Implement local action: showProactiveSupport()
break;
case 'frustrated':
console.warn('⚠️ User may need assistance');
// Implement local action: triggerHelpIntervention()
break;
case 'deliberative':
console.log('🤔 User is comparing options');
// Implement local action: showComparisonTools()
break;
case 'wandering':
console.log('🔍 User is exploring');
// Implement local action: showDiscoveryContent()
break;
}
}
});
tracker.start();Example 4: Local Behavioral Pattern Detection
import { InputlessTracker } from '@inputless/tracker';
import { SemanticClassifier } from '@inputless/tracker';
import type { BaseEvent } from '@inputless/events';
const tracker = new InputlessTracker({
ontology: {
enabled: true,
},
debug: true,
});
const semanticClassifier = new SemanticClassifier();
const recentEvents: BaseEvent[] = [];
tracker.onEvent((event: BaseEvent) => {
recentEvents.push(event);
if (recentEvents.length > 100) {
recentEvents.shift();
}
// Detect behavioral patterns when we have enough events
if (recentEvents.length >= 5) {
const patterns = semanticClassifier.detectPatterns(recentEvents);
patterns.forEach((pattern) => {
console.log('Pattern Detected:', {
type: pattern.type, // 'rage_click' | 'hesitation' | 'loop' | 'rapid_scroll' | 'backtracking'
confidence: pattern.confidence, // 0.0 - 1.0
description: pattern.description, // Human-readable description
});
// React to specific patterns locally
if (pattern.type === 'rage_click' && pattern.confidence > 0.8) {
console.warn('⚠️ Rage clicking detected - user may be frustrated');
// Implement local action: triggerErrorCheck()
}
if (pattern.type === 'hesitation' && pattern.confidence > 0.75) {
console.log('💭 User hesitating - offer guidance');
// Implement local action: showTooltip('Need help? We\'re here to assist')
}
if (pattern.type === 'backtracking' && pattern.confidence > 0.7) {
console.log('↩️ User backtracking - may have missed content');
// Implement local action: highlightImportantContent()
}
});
}
});
tracker.start();Example 5: Local Event Analytics Dashboard
import { InputlessTracker } from '@inputless/tracker';
import type { BaseEvent } from '@inputless/events';
const tracker = new InputlessTracker({
enabledCategories: {
ui: true,
form: true,
performance: true,
},
debug: true,
});
// Local analytics data
const analytics = {
totalEvents: 0,
eventsByType: {} as Record<string, number>,
eventsBySession: {} as Record<string, number>,
performanceMetrics: {
lcp: [] as number[],
fcp: [] as number[],
cls: [] as number[],
},
};
tracker.onEvent((event: BaseEvent) => {
// Update analytics
analytics.totalEvents++;
analytics.eventsByType[event.type] = (analytics.eventsByType[event.type] || 0) + 1;
analytics.eventsBySession[event.sessionId] = (analytics.eventsBySession[event.sessionId] || 0) + 1;
// Track performance metrics
if (event.type.startsWith('perf.')) {
const metric = (event.data as any)?.metric;
const value = (event.data as any)?.value;
if (metric === 'lcp' && typeof value === 'number') {
analytics.performanceMetrics.lcp.push(value);
} else if (metric === 'fcp' && typeof value === 'number') {
analytics.performanceMetrics.fcp.push(value);
} else if (metric === 'cls' && typeof value === 'number') {
analytics.performanceMetrics.cls.push(value);
}
}
});
// Display analytics dashboard every 10 seconds
setInterval(() => {
const avgLCP = analytics.performanceMetrics.lcp.length > 0
? analytics.performanceMetrics.lcp.reduce((a, b) => a + b, 0) / analytics.performanceMetrics.lcp.length
: 0;
console.log('📊 Local Analytics Dashboard:', {
totalEvents: analytics.totalEvents,
eventsByType: analytics.eventsByType,
sessions: Object.keys(analytics.eventsBySession).length,
performance: {
avgLCP: Math.round(avgLCP),
lcpCount: analytics.performanceMetrics.lcp.length,
},
currentSession: tracker.getSessionId(),
queueSize: tracker.getQueueSize(),
});
}, 10000);
tracker.start();Example 6: E-commerce Local Tracking with Custom Ontology
import { InputlessTracker } from '@inputless/tracker';
import { OntologyEngine } from '@inputless/tracker';
import type { BaseEvent } from '@inputless/events';
const tracker = new InputlessTracker({
ontology: {
enabled: true,
confidenceThreshold: 0.7,
customRules: [
// Rule 1: Add to cart button
{
matches: (event) =>
event.type === 'ui.click' &&
(event.data as any)?.selector?.includes('add-to-cart'),
meanings: ['purchase_intent', 'cart_engagement', 'high_value'],
confidenceBoost: 0.3,
},
// Rule 2: Product view
{
matches: (event) =>
event.type === 'ui.click' &&
(event.data as any)?.selector?.includes('product-card'),
meanings: ['product_interest', 'exploration'],
confidenceBoost: 0.15,
},
// Rule 3: Checkout button
{
matches: (event) =>
event.type === 'ui.click' &&
((event.data as any)?.selector?.includes('checkout') ||
(event.data as any)?.selector?.includes('proceed-to-payment')),
meanings: ['conversion_intent', 'high_value', 'purchase_likely'],
confidenceBoost: 0.4,
},
// Rule 4: Wishlist button
{
matches: (event) =>
event.type === 'ui.click' &&
(event.data as any)?.selector?.includes('wishlist'),
meanings: ['future_purchase_intent', 'engagement'],
confidenceBoost: 0.2,
},
// Rule 5: Long hover on product (3+ seconds)
{
matches: (event) =>
event.type === 'ui.hover' &&
(event.data as any)?.duration > 3000 &&
(event.data as any)?.selector?.includes('product'),
meanings: ['deep_interest', 'consideration', 'high_engagement'],
confidenceBoost: 0.25,
},
],
},
debug: true,
});
// Create ontology engine for semantic analysis
const ontologyEngine = new OntologyEngine({
enabled: true,
confidenceThreshold: 0.7,
customRules: [
{
matches: (event) =>
event.type === 'ui.click' &&
(event.data as any)?.selector?.includes('add-to-cart'),
meanings: ['purchase_intent', 'cart_engagement', 'high_value'],
confidenceBoost: 0.3,
},
// ... other rules
],
});
// Local conversion tracking
const conversionEvents: Array<{ event: BaseEvent; semantics: any }> = [];
tracker.onEvent((event: BaseEvent) => {
const semantics = ontologyEngine.extractSemantics(event);
// Check for high-value conversion events
if (semantics.valueDimension === 'high' && semantics.confidence > 0.8) {
console.log('🎯 High-value event detected:', {
eventType: event.type,
intent: semantics.primaryIntent,
meanings: semantics.contextualMeanings,
});
// Store conversion event locally
conversionEvents.push({ event, semantics });
// Process locally (e.g., update UI, show notification)
console.log('High-value conversion event stored locally');
}
// Check for purchase intent
if (semantics.contextualMeanings.includes('purchase_intent')) {
console.log('💰 Purchase intent detected!');
// Implement local action: showCartReminder()
}
});
tracker.start();
// Export conversion events (e.g., for analysis)
function getConversionEvents() {
return conversionEvents;
}Example 5: SaaS Application - Feature Adoption Tracking
import { InputlessTracker } from '@inputless/tracker';
const tracker = new InputlessTracker({
ontology: {
enabled: true,
confidenceThreshold: 0.7,
customRules: [
// Rule 1: Feature discovery (click on new feature)
{
matches: (event) =>
event.type === 'ui.click' &&
(event.data?.selector?.includes('new-feature-badge')),
meanings: ['feature_discovery', 'exploration'],
confidenceBoost: 0.2,
},
// Rule 2: Feature activation (enable feature toggle)
{
matches: (event) =>
event.type === 'ui.click' &&
(event.data?.selector?.includes('enable-feature')),
meanings: ['feature_adoption', 'engagement', 'high_value'],
confidenceBoost: 0.35,
},
// Rule 3: Workflow completion (multi-step form submit)
{
matches: (event) =>
event.type === 'form.submit' &&
(event.data?.formId?.includes('workflow')),
meanings: ['workflow_completion', 'conversion', 'high_value'],
confidenceBoost: 0.4,
},
// Rule 4: Help/documentation access
{
matches: (event) =>
event.type === 'ui.click' &&
((event.data?.selector?.includes('help') ||
event.data?.selector?.includes('docs'))),
meanings: ['learning_intent', 'engagement'],
confidenceBoost: 0.15,
},
],
},
});
const semanticClassifier = tracker.semanticClassifier;
tracker.onEvent(() => {
const recentEvents = tracker.recentEvents.slice(-10);
// Detect user onboarding patterns
if (recentEvents.length >= 5 && semanticClassifier) {
const intentState = semanticClassifier.classifyIntentState(recentEvents);
const patterns = semanticClassifier.detectPatterns(recentEvents);
// Check for frustration during onboarding
if (intentState.state === 'frustrated' && intentState.confidence > 0.8) {
console.warn('⚠️ User frustration detected during onboarding');
// Trigger proactive help (implement your own function)
// showOnboardingHelp();
}
// Check for hesitation (user may need guidance)
const hesitationPattern = patterns.find(p => p.type === 'hesitation');
if (hesitationPattern && hesitationPattern.confidence > 0.75) {
console.log('💭 User hesitating - offer guidance');
// Implement: showContextualTooltip();
}
}
});
tracker.start();Example 6: Real-Time Semantic Analysis Dashboard
import { InputlessTracker } from '@inputless/tracker';
const analytics = {
intentDistribution: {},
valueDistribution: {},
behavioralPatterns: [],
highValueEvents: 0,
};
const tracker = new InputlessTracker({
ontology: {
enabled: true,
confidenceThreshold: 0.7,
},
});
const ontologyEngine = tracker.ontologyEngine;
const semanticClassifier = tracker.semanticClassifier;
tracker.onEvent(() => {
const recentEvents = tracker.recentEvents;
// Update intent distribution
recentEvents.forEach((event) => {
if (ontologyEngine?.isEnabled()) {
const semantics = ontologyEngine.extractSemantics(event);
// Track intent distribution
analytics.intentDistribution[semantics.primaryIntent] =
(analytics.intentDistribution[semantics.primaryIntent] || 0) + 1;
// Track value distribution
analytics.valueDistribution[semantics.valueDimension] =
(analytics.valueDistribution[semantics.valueDimension] || 0) + 1;
// Count high-value events
if (semantics.valueDimension === 'high') {
analytics.highValueEvents++;
}
}
});
// Update behavioral patterns
if (recentEvents.length >= 5 && semanticClassifier) {
const patterns = semanticClassifier.detectPatterns(recentEvents);
analytics.behavioralPatterns = patterns.map(p => p.type);
}
});
// Update dashboard every 5 seconds
setInterval(() => {
console.log('📊 Semantic Analytics Dashboard:', {
intentDistribution: analytics.intentDistribution,
valueDistribution: analytics.valueDistribution,
currentPatterns: analytics.behavioralPatterns,
highValueEvents: analytics.highValueEvents,
});
}, 5000);
tracker.start();Example 7: Local Adaptive Sampling Monitoring
The tracker automatically adapts sampling based on intent state (this is built-in):
import { InputlessTracker } from '@inputless/tracker';
import { AdaptiveTracker } from '@inputless/tracker';
import type { BaseEvent } from '@inputless/events';
const tracker = new InputlessTracker({
ontology: {
enabled: true,
confidenceThreshold: 0.7,
},
sampling: {
rate: 0.8, // Base 80% sampling
strategy: 'adaptive', // Enable adaptive sampling
},
debug: true,
});
// Create adaptive tracker to monitor sampling
const adaptiveTracker = new AdaptiveTracker('adaptive');
// Track sampling decisions
let samplingStats = {
total: 0,
tracked: 0,
skipped: 0,
};
tracker.onEvent((event: BaseEvent) => {
samplingStats.total++;
samplingStats.tracked++;
console.log(`Event tracked: ${event.type}`);
});
// The tracker automatically:
// - Increases sampling when user is 'focused' (high engagement)
// - Decreases sampling when user is 'frustrated' (low engagement)
// - Maintains base rate for 'deliberative' and 'wandering' states
// Monitor sampling statistics
setInterval(() => {
const rate = samplingStats.total > 0
? (samplingStats.tracked / samplingStats.total) * 100
: 0;
console.log('Sampling Statistics:', {
totalEvents: samplingStats.total,
tracked: samplingStats.tracked,
skipped: samplingStats.skipped,
currentRate: `${rate.toFixed(1)}%`,
sessionId: tracker.getSessionId(),
});
}, 10000);
tracker.start();Example 8: Complete Local Integration - All Features Working Together
This example demonstrates a complete local setup using all tracker features:
import { InputlessTracker } from '@inputless/tracker';
import { OntologyEngine, SemanticClassifier, AdaptiveTracker } from '@inputless/tracker';
import type { BaseEvent } from '@inputless/events';
// Initialize tracker with all features enabled
const tracker = new InputlessTracker({
enabledCategories: {
ui: true,
form: true,
performance: true,
business: true,
media: true,
},
ontology: {
enabled: true,
confidenceThreshold: 0.7,
customRules: [
{
matches: (event) =>
event.type === 'ui.click' &&
(event.data as any)?.selector?.includes('checkout'),
meanings: ['conversion_intent', 'high_value'],
confidenceBoost: 0.4,
},
],
},
sampling: {
rate: 0.8,
strategy: 'adaptive',
},
batching: {
maxBatchSize: 50,
maxBatchAge: 5000,
autoFlush: true,
},
privacy: {
consentLevel: 'analytics',
maskSelectors: false,
quantizeCoordinates: true,
},
debug: true,
});
// Create analysis components
const ontologyEngine = new OntologyEngine({
enabled: true,
confidenceThreshold: 0.7,
customRules: [],
});
const semanticClassifier = new SemanticClassifier();
const adaptiveTracker = new AdaptiveTracker('adaptive');
// Local data storage
const eventStorage: BaseEvent[] = [];
const recentEvents: BaseEvent[] = [];
const analytics = {
totalEvents: 0,
eventsByType: {} as Record<string, number>,
highValueEvents: 0,
intentStates: {} as Record<string, number>,
patterns: [] as string[],
};
// Complete event processing pipeline
tracker.onEvent((event: BaseEvent) => {
// 1. Store events
eventStorage.push(event);
recentEvents.push(event);
if (eventStorage.length > 1000) eventStorage.shift();
if (recentEvents.length > 100) recentEvents.shift();
// 2. Update analytics
analytics.totalEvents++;
analytics.eventsByType[event.type] = (analytics.eventsByType[event.type] || 0) + 1;
// 3. Semantic analysis
const semantics = ontologyEngine.extractSemantics(event);
if (semantics.valueDimension === 'high') {
analytics.highValueEvents++;
}
// 4. Intent state classification (when enough events)
if (recentEvents.length >= 5) {
const intentState = semanticClassifier.classifyIntentState(recentEvents.slice(-10));
analytics.intentStates[intentState.state] = (analytics.intentStates[intentState.state] || 0) + 1;
// 5. Pattern detection
const patterns = semanticClassifier.detectPatterns(recentEvents);
patterns.forEach(p => {
if (!analytics.patterns.includes(p.type)) {
analytics.patterns.push(p.type);
}
});
}
// 6. Log important events
if (semantics.valueDimension === 'high' && semantics.confidence > 0.8) {
console.log('🎯 High-value event:', {
type: event.type,
intent: semantics.primaryIntent,
meanings: semantics.contextualMeanings,
});
}
});
// Display comprehensive dashboard
setInterval(() => {
console.log('📊 Complete Analytics Dashboard:', {
session: tracker.getSessionId(),
queue: tracker.getQueueSize(),
events: {
total: analytics.totalEvents,
byType: analytics.eventsByType,
highValue: analytics.highValueEvents,
},
intent: analytics.intentStates,
patterns: analytics.patterns,
storage: {
total: eventStorage.length,
recent: recentEvents.length,
},
});
}, 15000);
tracker.start();
// Export functions for external use
export function getAnalytics() {
return { ...analytics };
}
export function getStoredEvents() {
return [...eventStorage];
}
export function getRecentEvents() {
return [...recentEvents];
}Benefits
- Intent Recognition: Understand user goals without explicit input
- Predictive Analytics: Identify conversion patterns early
- Contextual Intelligence: Meaningful behavior interpretation
- Actionable Insights: Focus on semantically significant events
- Domain Adaptation: Extensible to any application domain
- 100% Local Processing: No API calls required - all processing happens in the browser
Implementation Specification
📚 Complete Implementation Guide: doc/TRACKER_COMPONENT_IMPLEMENTATION.md
For detailed implementation specifications, including:
- Complete component architecture
- Event capture modules for all 280+ event types
- Integration with
@inputless/events,@inputless/sdk-cognitive,@inputless/dispatcher - Implementation phases and testing strategy
- Performance considerations and browser compatibility
See: doc/TRACKER_COMPONENT_IMPLEMENTATION.md for the complete implementation guide.
Module Structure
This module contains:
InputlessTracker.ts- Main tracker class (orchestrates all tracking)EventCollector.ts- Browser event collection logicEventQueue.ts- Queue management and batchingBrowserUtils.ts- Browser API utilities and compatibility layerSessionManager.ts- Session management and persistenceOntologyEngine.ts- Semantic ontology and meaning extractionSemanticClassifier.ts- Intent classification and pattern recognitionPrivacyManager.ts- Privacy controls and PII detectionPerformanceMonitor.ts- Performance metrics tracking (Web Vitals)AdaptiveTracker.ts- Adaptive behavior trackingtypes/TrackerConfig.ts- Configuration interfacestypes/OntologyTypes.ts- Ontology type definitions
Implementation Status
✅ Implementation Complete - All core components implemented and tested
📚 Specification: See doc/TRACKER_COMPONENT_IMPLEMENTATION.md
Implementation Summary
Status: ✅ COMPLETE - All core components implemented with comprehensive test coverage
✅ Completed Components
Core Infrastructure ✅
- ✅
InputlessTracker- Main tracker class (orchestrates all tracking) - ✅
SessionManager- Session management with localStorage persistence - ✅ Configuration system with type-safe defaults
- ✅ Event emission system with batching
- ✅
Browser Event Collection ✅ COMPREHENSIVE - All interaction types covered
- ✅ DOM event listeners (click, hover, keyboard, scroll, form, touch)
- ✅ Drag & drop events (dragstart, drag, dragend, drop)
- ✅ Text selection & clipboard events (select, copy, cut, paste)
- ✅ Advanced media events (video: seek, volume, fullscreen, ended, timeupdate; audio: play, pause, seek, volume; image: view)
- ✅ Error events (JavaScript errors, unhandled promise rejections, form validation errors)
- ✅ Accessibility events (keyboard navigation patterns)
- ✅ Mobile-specific events (PWA install prompt, device orientation)
- ✅ Viewport events (fullscreen enter/exit, resize)
- ✅ Business event detection (e-commerce: cart, checkout, wishlist; social: share; search/filter: filter, sort)
- ✅ Browser utilities (device detection, selectors, context extraction)
- ✅ Event transformation to
@inputless/eventstypes - ✅ Network event capture (fetch/XHR interception)
- ✅ MutationObserver for dynamic content tracking
- ✅ IntersectionObserver for viewport tracking
Queue & Batching ✅
- ✅ Event queue implementation with size limits
- ✅ Batching logic (size and time-based auto-flush)
- ✅ Retry logic with exponential backoff
- ✅ Queue overflow handling
Semantic Ontology ✅
- ✅ Ontology engine implementation
- ✅ Intent classification (focused, deliberative, frustrated, wandering)
- ✅ Pattern detection (rage clicks, hesitation, backtracking, rapid scroll)
- ✅ Behavioral dimension analysis
- ✅ Custom ontology rules support
Privacy & Performance ✅
- ✅ PII detection and minimization
- ✅ Consent management (none, analytics, full)
- ✅ Adaptive sampling (uniform, adaptive strategies)
- ✅ Performance optimization (throttling, debouncing)
Additional Components ✅
- ✅
PrivacyManager- PII detection, masking, coordinate quantization - ✅
PerformanceMonitor- Web Vitals tracking (LCP, FCP, CLS, FID, TTFB) - ✅
AdaptiveTracker- Dynamic sampling based on engagement - ✅
BrowserUtils- Device detection, element selectors, feature detection
- ✅
Test Coverage
✅ Comprehensive Unit Tests - 211 passing tests (163 core + 48 EventCollector), 2 skipped (complex async)
Test Files:
- ✅
SessionManager.test.ts- Session lifecycle, persistence, expiration - ✅
BrowserUtils.test.ts- Device detection, selectors, context utilities - ✅
PrivacyManager.test.ts- PII detection, minimization, masking - ✅
EventQueue.test.ts- Queueing, batching, auto-flush, overflow - ✅
AdaptiveTracker.test.ts- Sampling strategies, engagement adaptation - ✅
SemanticClassifier.test.ts- Intent classification, pattern detection - ✅
OntologyEngine.test.ts- Semantic extraction, value dimensions - ✅
PerformanceMonitor.test.ts- Web Vitals monitoring - ✅
EventCollector.test.ts- 48 tests covering:- ✅ Basic UI events (click, keyboard, scroll)
- ✅ Drag & drop events (dragstart, drag, dragend, drop)
- ✅ Text selection & clipboard (select, copy, cut, paste)
- ✅ Advanced media events (video: play, pause, seek, volume, fullscreen, ended; audio: play, pause, seek, volume; image: view)
- ✅ Error events (JavaScript errors, unhandled rejections, validation errors)
- ✅ Accessibility events (keyboard navigation)
- ✅ Mobile-specific events (orientation change, PWA install)
- ✅ Viewport events (resize, fullscreen enter/exit)
- ✅ Business event detection (e-commerce, social, filter, sort)
- ✅ Form events, touch events, network events, observers
- ✅
InputlessTracker.test.ts- Main tracker class, lifecycle, integration - ✅
integration/FullTrackingFlow.test.ts- End-to-end tracking scenarios
Coverage:
- All core components tested
- All interaction types tested
- Edge cases handled
- Browser compatibility verified
- Integration flows tested
Reference: See doc/TRACKER_COMPONENT_IMPLEMENTATION.md and COMPREHENSIVE_INTERACTIONS.md for detailed specifications.
Exports
Public API
InputlessTracker- Main tracker class ⭐ IMPLEMENTEDTrackerConfig- Configuration interface ⭐ IMPLEMENTED
Internal Components (Exported for Advanced Usage)
EventCollector- Event collection logic ⭐ IMPLEMENTEDEventQueue- Queue management ⭐ IMPLEMENTEDBrowserUtils- Browser API utilities ⭐ IMPLEMENTEDSessionManager- Session management ⭐ IMPLEMENTEDPrivacyManager- Privacy controls ⭐ IMPLEMENTEDPerformanceMonitor- Performance metrics ⭐ IMPLEMENTEDAdaptiveTracker- Adaptive sampling ⭐ IMPLEMENTEDOntologyEngine- Semantic ontology engine ⭐ IMPLEMENTEDSemanticClassifier- Intent classifier ⭐ IMPLEMENTED
Type Exports
TrackerConfig- Configuration interfaceOntologyConfig- Ontology configuration interfaceOntologyRule- Custom ontology rule interfaceIntentState- Intent classification statesBehavioralPattern- Pattern detection results
Note: Event types (BaseEvent, EventType, UIEventMetadata, etc.) are imported from @inputless/events, not exported by this package.
Distribution
npm package: @inputless/tracker
Version: 1.0.0+
Registries:
- npm (
npm install @inputless/tracker) - CDN (
https://cdn.inputless.io/@inputless/tracker)
Build Formats:
- UMD (Universal Module Definition) - browser/HTML
- ES Modules - modern JavaScript
- CommonJS - Node.js compatibility
Testing
📚 Test Strategy: See doc/TEST_STRATEGY.md for complete testing guidelines.
Test Structure ✅
All test files implemented and passing:
- ✅
__tests__/InputlessTracker.test.ts- Main tracker tests (23 tests) - ✅
__tests__/EventCollector.test.ts- Event collection tests (comprehensive) - ✅
__tests__/EventQueue.test.ts- Queue management tests (12 tests) - ✅
__tests__/BrowserUtils.test.ts- Browser utility tests (comprehensive) - ✅
__tests__/OntologyEngine.test.ts- Ontology tests (comprehensive) - ✅
__tests__/SemanticClassifier.test.ts- Pattern detection tests (comprehensive) - ✅
__tests__/SessionManager.test.ts- Session management tests (17 tests) - ✅
__tests__/PrivacyManager.test.ts- Privacy tests (comprehensive) - ✅
__tests__/PerformanceMonitor.test.ts- Performance monitoring tests - ✅
__tests__/AdaptiveTracker.test.ts- Adaptive tracking tests - ✅
__tests__/integration/FullTrackingFlow.test.ts- Integration tests - ✅
__tests__/helpers/testHelpers.ts- Test utilities and fixtures - ✅
__tests__/setup.ts- Jest test environment setup
Test Results
Status: ✅ 163 passing tests, 2 skipped (complex async retry tests)
Test Suites: 11 passed, 11 total
Tests: 163 passed, 2 skipped, 165 totalCoverage Status
- ✅ Core classes: Comprehensive coverage (>90% achieved)
- ✅ Event collectors: Comprehensive coverage (all event types tested)
- ✅ Utilities: Comprehensive coverage (all utility functions tested)
- ✅ Ontology engine: Comprehensive coverage (intent classification, pattern detection)
- ✅ Integration tests: Full flow scenarios tested
Test Infrastructure:
- ✅ Jest configured with jsdom environment
- ✅ Fake timers for async testing
- ✅ Mock helpers for DOM/browser APIs
- ✅ Test fixtures and utilities
Next Steps
Integration
- Connect to Cognitive SDK - Integrate with
@inputless/sdk-cognitivefor signal processing - Connect to Dispatcher - Route events through
@inputless/dispatcherfor module distribution - Connect to Storage - Use
@inputless/storagefor persistent event storage - Backend Integration - Connect to Python API for batch processing and analysis
Enhancement Opportunities
- Performance Optimization - Further optimize event capture overhead
- Browser Compatibility - Test across more browser versions
- Advanced Patterns - Extend pattern detection capabilities
- Real-time Streaming - Add WebSocket support for real-time event streaming
Documentation
- ✅ Implementation complete
- ✅ Unit tests complete
- ✅ README updated
- ⬜ Add usage examples to documentation
- ⬜ Create integration guides
