npm package: @solute-ai/sdk
Description: Event tracking and A/B testing SDK for Solute - AI-powered product analytics
Author: Ricky
Latest version: 0.1.3

# Solute SDK

> Event tracking and A/B testing SDK for Solute - AI-powered product analytics platform

Solute SDK is a lightweight, TypeScript-first analytics SDK that tracks user events and enables A/B testing. Similar to PostHog or Amplitude, but designed specifically for the Solute platform.

## Features

- 📊 **Event Tracking** - Track custom events, page views, and user actions
- 🔬 **A/B Testing** - Run experiments with feature flags and variants
- 🎯 **User Identification** - Identify and track users across sessions
- 📦 **Offline Support** - Queue events when offline, sync when back online
- ⚡ **Lightweight** - < 20KB gzipped
- 🔒 **Type-Safe** - Full TypeScript support
- ⚛️ **Next.js Integration** - First-class Next.js App Router support
- 🎨 **Flexible** - Works with vanilla JS, React, Next.js, and more

## Installation

```bash
npm install @solute-ai/sdk
# or
yarn add @solute-ai/sdk
# or
pnpm add @solute-ai/sdk
```

## Quick Start

### Vanilla JavaScript / TypeScript

```typescript
import { SoluteClient } from '@solute-ai/sdk';

const solute = new SoluteClient({
  apiKey: 'your_api_key',
  host: 'https://api.solute.dev',
});

// Track events
solute.track('Button Clicked', {
  button_id: 'signup-cta',
  page: '/homepage',
});

// Identify users
solute.identify('user_123', {
  email: 'user@example.com',
  plan: 'premium',
});

// Track page views
solute.page('/pricing');

// Check feature flags
if (solute.isFeatureEnabled('new-checkout')) {
  // Show new checkout flow
}

// Get A/B test variant
const variant = solute.getExperimentVariant('pricing-test');
if (variant === 'variant-a') {
  // Show variant A
}
```

### Next.js App Router

#### 1. Wrap your app with SoluteProvider

```tsx
// app/layout.tsx
import { SoluteProvider } from '@solute-ai/sdk/nextjs';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <SoluteProvider
          config={{
            apiKey: process.env.NEXT_PUBLIC_SOLUTE_API_KEY!,
            host: 'https://api.solute.dev',
            debug: process.env.NODE_ENV === 'development',
          }}
        >
          {children}
        </SoluteProvider>
      </body>
    </html>
  );
}
```

#### 2. Use hooks in client components

```tsx
// app/components/SignupButton.tsx
'use client';

import { useTrack, useFeatureEnabled } from '@solute-ai/sdk/nextjs';

export function SignupButton() {
  const track = useTrack();
  const showNewDesign = useFeatureEnabled('new-signup-button');

  const handleClick = () => {
    track('Signup Button Clicked', {
      design: showNewDesign ? 'new' : 'old',
    });
  };

  return (
    <button onClick={handleClick}>
      {showNewDesign ? 'Get Started →' : 'Sign Up'}
    </button>
  );
}
```

#### 3. Server-side tracking

```tsx
// app/page.tsx
import { trackServerEvent, getServerFeatureFlag } from '@solute-ai/sdk/nextjs';

export default async function HomePage() {
  // Track server-side event
  await trackServerEvent(
    {
      apiKey: process.env.SOLUTE_API_KEY!,
      host: 'https://api.solute.dev',
    },
    'Page Viewed',
    { page: '/homepage' }
  );

  // Get feature flag on server
  const showHero = await getServerFeatureFlag(
    {
      apiKey: process.env.SOLUTE_API_KEY!,
      host: 'https://api.solute.dev',
    },
    'new-hero-section',
    false
  );

  return (
    <div>
      {showHero ? <NewHeroSection /> : <OldHeroSection />}
    </div>
  );
}
```

#### 4. Add middleware for automatic page tracking (optional)

```typescript
// middleware.ts
import { createSoluteMiddleware } from '@solute-ai/sdk/nextjs';

export const middleware = createSoluteMiddleware({
  apiKey: process.env.SOLUTE_API_KEY!,
  host: 'https://api.solute.dev',
  excludePaths: ['/admin/*', '/api/*'],
  debug: process.env.NODE_ENV === 'development',
});

export const config = {
  matcher: [
    '/((?!_next/static|_next/image|favicon.ico|.*\\..*|api).*)',
  ],
};
```

## API Reference

### Core SDK

#### `new SoluteClient(config)`

Create a new Solute client.

```typescript
const solute = new SoluteClient({
  apiKey: string;              // Required: Your API key
  host?: string;               // API host (default: 'https://api.solute.dev')
  debug?: boolean;             // Enable debug logging
  disabled?: boolean;          // Disable SDK
  autoPageViews?: boolean;     // Auto-track page views (default: true)
  capturePII?: boolean;        // Capture personal data (default: true)
  sessionTimeout?: number;     // Session timeout in ms (default: 30min)
  storage?: {
    type?: 'localStorage' | 'cookie' | 'memory';
    prefix?: string;
  };
  queue?: {
    maxQueueSize?: number;     // Max events in queue (default: 1000)
    flushInterval?: number;    // Auto-flush interval (default: 10s)
    flushAt?: number;          // Flush at N events (default: 20)
  };
  featureFlags?: {
    enabled?: boolean;         // Enable feature flags (default: true)
    refreshInterval?: number;  // Refresh interval (default: 5min)
  };
});
```

#### Event Tracking

```typescript
// Track custom event
solute.track(event: string, properties?: object): void

// Identify user
solute.identify(userId: string, traits?: object): void

// Track page view
solute.page(name?: string, properties?: object, category?: string): void

// Track group/organization
solute.group(groupId: string, traits?: object): void

// Alias user identities
solute.alias(newId: string, previousId?: string): void

// Reset user (logout)
solute.reset(): void

// Flush events immediately
await solute.flush(): Promise<void>
```

#### Feature Flags & A/B Testing

```typescript
// Get feature flag value
solute.getFeatureFlag<T>(key: string, options?: {
  defaultValue?: T;
  skipTracking?: boolean;
}): T | undefined

// Check if feature is enabled
solute.isFeatureEnabled(key: string, options?: {
  defaultValue?: boolean;
}): boolean

// Get experiment variant
solute.getExperimentVariant(key: string, options?: {
  defaultValue?: string;
}): string | undefined

// Get all flags
solute.getAllFlags(): Record<string, FeatureFlag>

// Reload flags
await solute.reloadFeatureFlags(userProperties?: object): Promise<void>
```

#### User Management

```typescript
// Get current user ID
solute.getUserId(): string | undefined

// Get anonymous ID
solute.getAnonymousId(): string

// Get session ID
solute.getSessionId(): string
```

### Next.js Integration

#### Hooks

```typescript
import {
  useSolute,          // Access full SDK
  useTrack,           // Track events
  useIdentify,        // Identify users
  usePage,            // Track page views
  useFeatureFlag,     // Get feature flag
  useFeatureEnabled,  // Check if feature enabled
  useExperiment,      // Get experiment variant
  useUser,            // Get user info
  usePageTracking,    // Auto-track page views
} from '@solute-ai/sdk/nextjs';

// Example usage
function MyComponent() {
  const track = useTrack();
  const enabled = useFeatureEnabled('new-feature');
  const variant = useExperiment('pricing-test');
  const { userId, sessionId } = useUser();

  return <div>{/* Your component */}</div>;
}
```

#### Server-Side Utilities

```typescript
import {
  trackServerEvent,
  getServerFeatureFlag,
  isServerFeatureEnabled,
  getServerExperimentVariant,
} from '@solute-ai/sdk/nextjs';

// Example usage in Server Component
export default async function Page() {
  const enabled = await isServerFeatureEnabled(
    { apiKey: process.env.SOLUTE_API_KEY! },
    'feature-key'
  );

  return <div>{/* Your page */}</div>;
}
```

## Backend Integration

The SDK requires a backend API to receive events and serve feature flags. See [API_CONTRACTS.md](./API_CONTRACTS.md) for complete backend API specifications.

### Required Endpoints

- `POST /api/events` - Receive batched events
- `GET /api/feature-flags` - Serve feature flags for a user

## Development

```bash
# Install dependencies
yarn install

# Start development mode
yarn start

# Build
yarn build

# Run tests
yarn test

# Check bundle size
yarn size
```

## Publishing

### Prerequisites

1. **Login to npm** (must have access to `@solute-ai` organization):
   ```bash
   npm login
   npm whoami  # Verify you're logged in
   ```

### Publishing Steps

1. **Update version** (if needed):
   ```bash
   npm version patch   # 0.1.0 -> 0.1.1
   npm version minor   # 0.1.0 -> 0.2.0
   npm version major   # 0.1.0 -> 1.0.0
   ```

2. **Build and publish**:
   ```bash
   npm run build && npm publish
   ```
   
   Or simply:
   ```bash
   npm publish
   ```
   (The `prepublishOnly` script will automatically build before publishing)

3. **Verify publication**:
   ```bash
   npm view @solute-ai/sdk
   ```
   Or visit: https://www.npmjs.com/package/@solute-ai/sdk

### Testing Locally Before Publishing

Test the package locally before publishing:

```bash
# Create a tarball
npm pack

# Install in your test project
npm install ../solute-sdk/solute-ai-sdk-0.1.2.tgz
```

Or use `npm link`:
```bash
# In solute-sdk directory
npm link

# In your test project
npm link @solute-ai/sdk
```

For detailed publishing instructions, see [PUBLISH.md](./PUBLISH.md).

## TypeScript

Solute SDK is written in TypeScript and provides full type definitions. All SDK methods are fully typed.

## Browser Support

- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
- iOS Safari 12+
- Chrome Android (latest)

## License

MIT © Ricky

## Contributing

Contributions are welcome! Please open an issue or submit a pull request.

## Acknowledgments

Inspired by [PostHog](https://posthog.com), [Amplitude](https://amplitude.com), and [Segment](https://segment.com).