npm package: @sleekio/sdk
Description: Modern A/B Testing SDK for JavaScript Applications - Production-ready with graceful fallbacks
Author: Bestine Payyappilly
Latest version: 1.0.0

# 🧪 Sleek SDK

Modern A/B Testing SDK for JavaScript Applications

[![npm version](https://badge.fury.io/js/sleek-sdk.svg)](https://badge.fury.io/js/sleek-sdk)
[![Build Status](https://github.com/your-org/sleek-sdk/workflows/CI/badge.svg)](https://github.com/your-org/sleek-sdk/actions)
[![Coverage Status](https://coveralls.io/repos/github/your-org/sleek-sdk/badge.svg)](https://coveralls.io/github/your-org/sleek-sdk)

## ✨ Features

- 🚀 **Zero Dependencies** - Lightweight and fast
- 🔧 **Framework Agnostic** - Works with React, Vue, Angular, or vanilla JS
- 🎯 **Type Safe** - Full TypeScript support
- 📱 **Cross Platform** - Browser, Node.js, React Native
- 🔒 **Privacy Focused** - GDPR compliant user management
- ⚡ **Performance Optimized** - Caching, batching, and minimal overhead
- 🧪 **Session Management** - Configurable experiment expiration
- 📊 **Analytics Ready** - Rich event tracking and conversion metrics

## 🚀 Quick Start

### Installation

```bash
npm install sleek-sdk
# or
yarn add sleek-sdk
# or
pnpm add sleek-sdk
```

### Basic Usage

```javascript
import { createAnonymousSleek } from 'sleek-sdk';

// Initialize SDK
const sleek = createAnonymousSleek('https://your-api.com');

// Get variant assignment
const variant = await sleek.getVariant('homepage_cta_test');

// Track events
sleek.track('homepage_cta_test', 'button_click', {
  position: 'hero',
  timestamp: Date.now()
});

// Track conversions
sleek.trackConversion('homepage_cta_test', {
  value: 29.99,
  currency: 'USD'
});
```

### React Integration

```jsx
import { SleekProvider, useSleekExperiment } from 'sleek-sdk/react';
import { createAnonymousSleek } from 'sleek-sdk';

const sleek = createAnonymousSleek('https://your-api.com');

function App() {
  return (
    <SleekProvider sdk={sleek}>
      <Homepage />
    </SleekProvider>
  );
}

function Homepage() {
  const { variant, config, track } = useSleekExperiment('homepage_cta_test');
  
  const handleClick = () => {
    track('cta_click');
  };

  return (
    <button 
      onClick={handleClick}
      style={{ backgroundColor: config.buttonColor }}
    >
      {config.buttonText || 'Default Text'}
    </button>
  );
}
```

## 📖 API Reference

### Core SDK

#### `createAnonymousSleek(apiUrl, options?)`

Creates an SDK instance for anonymous users.

```javascript
const sleek = createAnonymousSleek('https://api.example.com', {
  batchEvents: true,
  batchSize: 10,
  flushInterval: 5000,
  autoRefresh: true
});
```

#### `createAuthenticatedSleek(apiUrl, userId, userProperties?, options?)`

Creates an SDK instance for authenticated users.

```javascript
const sleek = createAuthenticatedSleek(
  'https://api.example.com',
  'user_123',
  { email: 'user@example.com', plan: 'pro' }
);
```

#### `createSleekSDK(apiUrl, userManager, options?)`

Advanced SDK creation with custom user management.

```javascript
import { SleekUserManager } from 'sleek-sdk';

const userManager = new SleekUserManager({
  useDeviceFingerprint: true,
  cookieExpireDays: 30
});

const sleek = createSleekSDK('https://api.example.com', userManager);
```

### SDK Methods

#### Assignment Methods

```javascript
// Get variant assignment
const variant = await sleek.getVariant('experiment_id');

// Get variant configuration
const config = await sleek.getVariantConfig('experiment_id');

// Get assignment metadata
const info = sleek.getAssignmentInfo('experiment_id');

// Check if assignment is expired
const isExpired = sleek.isAssignmentExpired('experiment_id');

// Force refresh assignment
const newVariant = await sleek.refreshAssignment('experiment_id');
```

#### Event Tracking

```javascript
// Track custom events
sleek.track('experiment_id', 'event_name', {
  property1: 'value1',
  property2: 42
});

// Track conversions
sleek.trackConversion('experiment_id', {
  value: 10.99,
  currency: 'USD',
  product: 'premium_plan'
});

// Flush pending events
await sleek.flushEvents();
```

#### User Management

```javascript
// Set authenticated user
sleek.setUser('user_456', { 
  email: 'user@example.com',
  segment: 'premium' 
});

// Get current user ID
const userId = sleek.getUserId();

// Check if user is anonymous
const isAnonymous = sleek.isAnonymous();

// Get user context
const context = sleek.getUserContext();

// Clear user data (logout)
sleek.clearUser();
```

#### Utility Methods

```javascript
// Get all assignments
const assignments = sleek.getAssignments();

// Clear all assignments
sleek.clearAssignments();

// Get session ID
const sessionId = sleek.getSessionId();

// Cleanup resources
sleek.cleanup();
```

### React Hooks

#### `useSleekExperiment(experimentId)`

Main hook for A/B testing in React components.

```jsx
function MyComponent() {
  const { variant, config, loading, error, track, trackConversion } = 
    useSleekExperiment('my_experiment');

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      <h1>Variant: {variant}</h1>
      <button onClick={() => track('click')}>
        {config.buttonText}
      </button>
    </div>
  );
}
```

#### `useFeatureFlag(flagId)`

Alias for `useSleekExperiment` with better semantics for feature flags.

```jsx
function NewFeature() {
  const { variant } = useFeatureFlag('new_dashboard');
  
  if (variant === 'enabled') {
    return <NewDashboard />;
  }
  
  return <OldDashboard />;
}
```

#### `useSleekExperiments(experimentIds)`

Hook for managing multiple experiments.

```jsx
function MultiExperimentComponent() {
  const { experiments, loading, track } = useSleekExperiments([
    'header_test',
    'footer_test',
    'sidebar_test'
  ]);

  if (loading) return <div>Loading experiments...</div>;

  return (
    <div>
      {Object.entries(experiments).map(([id, data]) => (
        <div key={id}>
          {id}: {data.variant}
          <button onClick={() => track(id, 'interaction')}>
            Track
          </button>
        </div>
      ))}
    </div>
  );
}
```

#### `useAdvancedExperiment(experimentId, options)`

Advanced hook with automatic tracking and additional features.

```jsx
function AdvancedComponent() {
  const { 
    variant, 
    config, 
    track, 
    isVariant,
    getVariantValue 
  } = useAdvancedExperiment('checkout_test', {
    autoTrackPageView: true,
    autoTrackMount: true,
    componentName: 'CheckoutFlow'
  });

  const theme = getVariantValue('theme', 'default');
  
  return (
    <div className={`checkout-${theme}`}>
      {isVariant('multi_step') ? (
        <MultiStepCheckout />
      ) : (
        <SinglePageCheckout />
      )}
    </div>
  );
}
```

## 🎛️ Configuration Options

### SDK Options

```javascript
const options = {
  // Event batching
  batchEvents: true,
  batchSize: 10,
  flushInterval: 5000,
  
  // Network settings
  timeout: 5000,
  retryAttempts: 3,
  
  // Assignment settings
  autoRefresh: true,
  
  // User management
  userManager: {
    storageKey: 'sleek_user_id',
    useLocalStorage: true,
    useSessionStorage: true,
    cookieName: 'sleek_uid',
    cookieExpireDays: 365,
    useDeviceFingerprint: false
  }
};
```

### User Manager Options

```javascript
const userManager = new SleekUserManager({
  // Storage configuration
  storageKey: 'my_app_user_id',
  useLocalStorage: true,
  useSessionStorage: true,
  
  // Cookie configuration
  cookieName: 'my_app_uid',
  cookieExpireDays: 30,
  
  // Fingerprinting
  useDeviceFingerprint: true,
  fallbackToFingerprint: true
});
```

## 🔐 Privacy & GDPR

Sleek SDK is built with privacy in mind: