npm package: @firstdistro/sdk
Description: FirstDistro SDK - Churn detection and customer health scoring for B2B SaaS
Author: FirstDistro
Latest version: 1.2.2

# @firstdistro/sdk

Customer engagement tracking and product fit analytics for B2B SaaS.

**Bundle Size:** ~13KB gzipped (core) | ~1KB (React wrapper)

## Installation

```bash
npm install @firstdistro/sdk
```

## Quick Start (React)

```tsx
// app/layout.tsx or _app.tsx
import { FirstDistroProvider } from '@firstdistro/sdk/react'

export default function RootLayout({ children }) {
  return (
    <FirstDistroProvider token="fd_your_token_here">
      {children}
    </FirstDistroProvider>
  )
}
```

```tsx
// In any component
import { useTrack, useFirstDistroSetup } from '@firstdistro/sdk/react'

function Dashboard({ user, organization }) {
  // Set up user & account context on mount
  useFirstDistroSetup({
    userId: user.id,
    userEmail: user.email,
    userName: user.name,
    accountId: organization.id,
    accountName: organization.name,
    accountPlan: organization.plan,
  })

  const track = useTrack()

  return (
    <button onClick={() => track('button_clicked', { button: 'upgrade' })}>
      Upgrade Plan
    </button>
  )
}
```

## React Hooks

### `useFirstDistro()`

Access the full SDK context:

```tsx
const { track, setup, reset, isReady, error } = useFirstDistro()
```

### `useTrack()`

Track custom events:

```tsx
const track = useTrack()
track('feature_used', { feature: 'export', format: 'csv' })
```

### `useSetup()`

Set user/account context:

```tsx
const setup = useSetup()
setup({
  userId: 'user-123',
  userEmail: 'jane@acme.com',
  accountId: 'acme-corp',
  accountName: 'Acme Corporation',
})
```

### `useFirstDistroSetup(options)`

Automatically call setup when SDK is ready (recommended for most use cases):

```tsx
useFirstDistroSetup({
  userId: user.id,
  accountId: org.id,
})
```

## Vanilla JavaScript

For non-React projects or advanced use cases:

```typescript
import FirstDistro from '@firstdistro/sdk'

// Initialize with token
await FirstDistro.initWithToken('fd_your_token_here')

// Set user/account context
FirstDistro.setup({
  user: { id: 'user-123', email: 'jane@acme.com' },
  account: { id: 'acme-corp', name: 'Acme Corporation' },
})

// Track events
FirstDistro.track('feature_used', { feature: 'export' })
```

## Script Tag Installation

For non-bundled projects, add the script tag directly:

```html
<script src="https://firstdistro.com/sdk/install/fd_your-token.js"></script>
```

The SDK auto-initializes with your token. Then use:

```javascript
FirstDistro.setup({
  user: { id: 'user-123', name: 'John Doe', email: 'john@example.com' },
  account: { id: 'acme-corp', name: 'Acme Corp', plan: 'pro' }
});

FirstDistro.track('feature_used', { feature: 'export' });
```

## TypeScript Support

Full TypeScript support with exported types:

```typescript
import type { SetupOptions, TrackProperties } from '@firstdistro/sdk/react'
```

## API Reference

### Provider Props

| Prop | Type | Description |
|------|------|-------------|
| `token` | `string` | Your FirstDistro installation token (starts with `fd_`) |
| `apiUrl` | `string?` | Custom API URL (defaults to `https://firstdistro.com`) |
| `onReady` | `() => void` | Called when SDK finishes initializing |
| `onError` | `(error: Error) => void` | Called if initialization fails |

### Setup Options (React)

| Option | Type | Description |
|--------|------|-------------|
| `userId` | `string` | User ID (required) |
| `userEmail` | `string?` | User email |
| `userName` | `string?` | User display name |
| `userProperties` | `Record<string, unknown>?` | Additional user properties |
| `accountId` | `string?` | Account/Organization ID |
| `accountName` | `string?` | Account/Organization name |
| `accountPlan` | `string?` | Account plan (e.g., 'free', 'pro') |
| `accountProperties` | `Record<string, unknown>?` | Additional account properties |

### Setup Options (Vanilla JS)

```typescript
FirstDistro.setup({
  user: {
    id: string;        // Required
    name?: string;
    email?: string;
    [key: string]: any; // Additional properties
  },
  account: {
    id: string;        // Required
    name?: string;
    plan?: string;
    [key: string]: any; // Additional properties
  }
});
```

## Features

- **Event Tracking** - Product usage tracking with batching
- **Remote Configuration** - Control features from dashboard
- **Automatic Batching** - 20 events per batch, 5-second flush
- **Offline Support** - Works with cached config
- **Persistence** - User/account context saved to localStorage
- **SSR Safe** - Works in Server-Side Rendering environments
- **Tree Shakeable** - Only import what you use

## How It Works

Events tracked by the SDK feed into FirstDistro's **Signal Stack** — a weighted behavioral formula that calculates customer health scores in real time:

```
Health Score = (Activity × 0.40) + (Engagement × 0.30) + (Milestones × 0.20) + (Recency × 0.10)
```

| Signal | Weight | What the SDK Measures |
|--------|--------|----------------------|
| Activity | 40% | Event frequency over the last 30 days |
| Engagement | 30% | Session depth, return frequency, feature breadth |
| Milestones | 20% | Feature adoption checkpoints (all-time) |
| Recency | 10% | Days since last meaningful action |

When CRM data is also connected, the composite score becomes: `(Signal Stack × 0.85) + (CRM Health × 0.15)`.

Learn more: [Customer Health Score methodology](https://firstdistro.com/learn/customer-health-score) | [Health Score Formula](https://firstdistro.com/learn/health-score-formula)

## Getting Your Token

Get your installation token from:
[Dashboard → Settings → SDK Configuration](https://firstdistro.com/dashboard/settings/sdk-configuration)

## License

MIT