npm package: @omniconvert/server-side-testing-sdk
Description: TypeScript SDK for server-side A/B testing and experimentation
Author: Omniconvert
Latest version: 1.2.17

# Client-Side Testing SDK (TypeScript)

A TypeScript SDK for client-side A/B testing with IndexedDB storage support.

## Features

- 🧪 **A/B Testing** - Complete experiment management and variation assignment
- 📊 **Analytics Tracking** - Page views, variation views, and goal tracking
- 💾 **IndexedDB Storage** - High-capacity persistent storage (50MB+ vs 5-10MB for localStorage)
- 🌐 **Browser Optimized** - Hybrid sync/async architecture for maximum performance
- 📱 **Context Aware** - Rich context parameters (device, browser, location, UTM, etc.)
- 🎯 **Smart Targeting** - Advanced audience and segment targeting
- 🔧 **TypeScript** - Full type safety and excellent developer experience
- 📦 **Multiple Formats** - ES modules, CommonJS, and UMD builds
- 🔄 **Graceful Fallback** - Automatically falls back to memory storage if IndexedDB is unavailable

## Installation

```bash
npm install @omniconvert/client-side-testing-sdk
```

## Quick Start

```typescript
import { ExploreClient, ContextBuilder } from '@omniconvert/client-side-testing-sdk';

// Initialize the client
const client = new ExploreClient({
  apiKey: 'your-api-key',
  userId: 'unique-user-id',
  sessionParams: {
    deviceType: 'desktop',
    referrerUrl: 'https://example.com',
    // ... other session parameters
  }
});

// Create context for decision making
const context = ContextBuilder.create()
  .url(window.location.href)
  .userAgent(navigator.userAgent)
  .resolution(`${screen.width}x${screen.height}`)
  .deviceType('desktop')
  .build();

// Make experiment decisions
const decisions = await client.decide(context);

// Handle experiment variations
decisions.forEach(decision => {
  const experimentKey = decision.getExperimentKey();
  const variationKey = decision.getVariationKey();
  const variables = decision.getVariationVariables();
  
  // Apply variation logic
  console.log(`Experiment: ${experimentKey}, Variation: ${variationKey}`, variables);
});

// Track goals
await client.getTracker().track('purchase', 99.99, {
  transaction: 'tx_123',
  skus: ['PROD_A', 'PROD_B']
});
```

## React Integration

```tsx
import React, { useEffect, useState } from 'react';
import { ExploreClient, Decision } from '@omniconvert/client-side-testing-sdk';

const MyComponent: React.FC = () => {
  const [decisions, setDecisions] = useState<Decision[]>([]);
  
  useEffect(() => {
    const client = new ExploreClient({
      apiKey: 'your-api-key',
      userId: 'user-123'
    });
    
    client.decide(context).then(setDecisions);
  }, []);
  
  return (
    <div>
      {decisions.map(decision => (
        <div key={decision.getExperimentKey()}>
          {/* Render variation content */}
        </div>
      ))}
    </div>
  );
};
```

## API Reference

### ExploreClient

Main SDK interface for experiment management.

```typescript
const client = new ExploreClient(config);
```

### Context System

Rich context parameters for targeting:

```typescript
const context = ContextBuilder.create()
  .url(string)
  .userAgent(string)
  .deviceType('desktop' | 'mobile' | 'tablet')
  .resolution(string)
  .browser(string)
  .os(string)
  .language(string)
  .ip(string)
  .custom(key, value)
  .utm({ source, medium, campaign, content, term })
  .build();
```

## Storage Drivers

The SDK uses **IndexedDB** as the default storage driver, providing significantly more storage capacity than localStorage (typically 50MB+ vs 5-10MB).

### IndexedDB Driver (Default)

The IndexedDB driver provides:
- **High Capacity**: 50MB+ storage (vs 5-10MB for localStorage)
- **Hybrid Architecture**: In-memory cache for instant synchronous reads, async persistence to IndexedDB
- **Auto-initialization**: Pre-loads all data into cache on startup
- **Graceful Fallback**: Falls back to memory-only mode if IndexedDB is unavailable
- **TTL Support**: Automatic expiration and cleanup of old data
- **Storage Quota API**: Real-time storage usage information

```typescript
import { ExploreClient, IndexedDBDriver, StorageFacadeFactory } from '@omniconvert/client-side-testing-sdk';

// Default: uses IndexedDB automatically
const client = new ExploreClient({
  apiKey: 'your-api-key',
  userId: 'user-123'
});
```

### LocalStorage Driver (Legacy)

If you need to use localStorage instead of IndexedDB:

```typescript
import { StorageFacadeFactory } from '@omniconvert/client-side-testing-sdk';

// Create client with localStorage
const storageFacade = StorageFacadeFactory.createWithLocalStorage();
```

### Custom Storage Driver

You can implement your own storage driver by implementing the `StorageDriverInterface`:

```typescript
import { StorageDriverInterface } from '@omniconvert/client-side-testing-sdk';

class MyCustomDriver implements StorageDriverInterface {
  get(key: string): string | null {
    // Your implementation
  }

  save(key: string, data: unknown): boolean {
    // Your implementation
  }

  remove(key: string): void {
    // Your implementation
  }

  clear(): void {
    // Your implementation
  }

  getAllKeys(): string[] {
    // Your implementation
  }
}

// Use custom driver with ExploreClient
const client = ExploreClient.createWithDriver(
  { apiKey: 'your-api-key', userId: 'user-123' },
  new MyCustomDriver()
);
```

### Storage Comparison

| Feature | IndexedDB (Default) | LocalStorage (Legacy) |
|---------|--------------------|-----------------------|
| Capacity | 50MB+ | 5-10MB |
| Speed | Very Fast (memory cache) | Fast |
| Async Support | Yes (background) | No |
| Structured Data | Yes | Limited (JSON only) |
| Browser Support | Chrome 24+, Firefox 16+, Safari 10+ | All browsers |
| Fallback | Memory-only | None needed |

## Migration from LocalStorage

If you're upgrading from a previous version that used localStorage, the migration is **automatic and seamless**:

### What Changed
- **Default Storage**: Changed from localStorage to IndexedDB
- **API Compatibility**: All APIs remain the same - no code changes required
- **Data Migration**: Data will automatically migrate on first run with the new version

### For Most Users
No action needed! The SDK will automatically use IndexedDB with all the same APIs.

### If You Need LocalStorage
If you explicitly need to keep using localStorage (e.g., for compatibility with older browsers):

```typescript
import { StorageFacadeFactory, ExploreClient } from '@omniconvert/client-side-testing-sdk';

// Option 1: Use factory method
const storage = StorageFacadeFactory.createWithLocalStorage();

// Option 2: Create with driver directly
import { LocalStorageDriver } from '@omniconvert/client-side-testing-sdk';
const driver = new LocalStorageDriver();
const storage = StorageFacadeFactory.createWithDriver(driver);
```

### Benefits of Upgrading
- **10x More Storage**: Store more experiment data without quota issues
- **Better Performance**: Instant reads via memory cache
- **Auto-cleanup**: Expired data is automatically removed
- **Future-proof**: IndexedDB is the modern standard for browser storage

## Browser Support

### IndexedDB Driver (Default)
- Chrome 24+ (Chrome 70+ recommended)
- Firefox 16+ (Firefox 65+ recommended)
- Safari 10+ (Safari 12+ recommended)
- Edge 79+

### LocalStorage Driver (Legacy)
- All modern browsers
- IE 8+

## Development

```bash
# Install dependencies
npm install

# Build the library
npm run build

# Run tests
npm test

# Development mode
npm run dev
```

## Examples & Demo

The SDK includes several example implementations to help you get started:

### Browser Demo (Interactive UI)

Experience the SDK in action with a comprehensive browser demo featuring:
- Interactive A/B testing simulation
- Real-time context detection
- User management and tracking
- Live experiment preview with visual variations

**To run the browser demo:**

1. **Build the SDK** (required for browser bundle):
   ```bash
   npm run build
   ```

2. **Start a local web server** (required to serve files with proper MIME types):
   ```bash
   python3 -m http.server 8000
   ```

3. **Open the demos** in your browser:
   ```
   # Browser Bundle Demo
   http://localhost:8000/examples/browser-bundle.html
   
   # React Ecommerce Demo
   http://localhost:8000/examples/react-ecommerce/
   
   # Vanilla JS Ecommerce Demo
   http://localhost:8000/examples/vanilla-ecommerce/
   ```

### React Ecommerce Demo

A comprehensive ecommerce demonstration built with React that showcases:

- **Product Catalog**: Browse 14 hardcoded products across 6 categories
- **Category Navigation**: Filter products by Electronics, Clothing, Home & Garden, Food & Beverages, and Sports & Fitness
- **Product Details**: Individual product pages with quantity selection
- **Shopping Cart**: Add/remove items, update quantities, view totals
- **Checkout Flow**: Complete checkout form with billing and payment
- **A/B Testing**: Live experiments affecting UI elements like:
  - Product grid layout variations
  - Cart button text experiments
  - Checkout button color tests
  - Product ratings display toggle
  - Category filter style variations
  - Category icon display toggle
  - Recommendation section experiments

The demo uses the official npm package:

1. Install dependencies: `cd examples/react-ecommerce && npm run build`
2. Start web server: `python3 -m http.server 8000` (from project root)
3. Open: `http://localhost:8000/examples/react-ecommerce/`

**Features:**
- Real A/B testing with experiment tracking
- Event tracking for add-to-cart, purchases, and conversions
- Persistent user sessions with localStorage
- Debug mode showing active experiments
- Responsive design for mobile and desktop
- Modern React hooks and functional components

### Vanilla JS Ecommerce Demo

A complete ecommerce application built with pure HTML, CSS, and JavaScript (no frameworks) that demonstrates the same A/B testing capabilities as the React version:

- **Framework-Free**: Pure vanilla JavaScript with no dependencies beyond the SDK
- **Same Features**: Identical product catalog, cart, and checkout functionality
- **A/B Testing**: All the same experiments as the React version:
  - Product grid layout variations
  - Cart button text experiments  
  - Checkout button color tests
  - Product ratings display toggle
  - Category filter style variations
  - Category icon display toggle
  - Recommendation section experiments
- **Manual DOM Manipulation**: Direct DOM updates instead of virtual DOM
- **Event-Driven Architecture**: Traditional event listeners and callbacks
- **Global State Management**: Simple state object instead of React hooks

The demo uses the official npm package:

1. Install dependencies: `cd examples/vanilla-ecommerce && npm run build`
2. Start web server: `python3 -m http.server 8000` (from project root)
3. Open: `http://localhost:8000/examples/vanilla-ecommerce/`

**Perfect for:**
- Developers who want to understand SDK integration without React complexity
- Projects that need to avoid framework dependencies
- Learning how A/B testing works with vanilla JavaScript
- Comparing framework vs. framework-free implementations

### Node.js Demo

For server-side testing and validation:

```bash
# Build first
npm run build

# Run the Node.js demo
node examples/node-demo.js
```

### Available Examples

- `examples/browser-bundle.html` - Complete interactive browser demo (uses local build)
- `examples/react-ecommerce/` - React ecommerce demo using npm package (requires `cd examples/react-ecommerce && npm run build`)
- `examples/vanilla-ecommerce/` - Vanilla JS ecommerce demo using npm package (requires `cd examples/vanilla-ecommerce && npm run build`)
- `examples/node-demo.js` - Node.js command-line demo
- `examples/basic-usage.ts` - TypeScript usage examples
- `examples/react-example.tsx` - React integration example

> **Note**: The browser examples require a web server due to CORS restrictions and module loading. The Python HTTP server is the simplest solution, but you can use any web server (Apache, nginx, Node.js http-server, etc.).