npm package: @flightdev/analytics
Description: Agnostic analytics for Flight Framework. Choose your backend: Plausible, Umami, PostHog, or custom.
Latest version: 0.0.3

# @flightdev/analytics

Privacy-focused, universal analytics for Flight Framework. Works with any analytics provider through adapters.

## Table of Contents

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Adapters](#adapters)
- [Core API](#core-api)
- [React Integration](#react-integration)
- [Server-Side Tracking](#server-side-tracking)
- [Privacy and Consent](#privacy-and-consent)
- [API Reference](#api-reference)
- [License](#license)

---

## Features

- Single API for multiple analytics providers
- Privacy-first design with consent management
- Automatic page view tracking
- Server-side event tracking
- Type-safe event definitions
- Batching and retry logic
- React hooks for easy integration
- GDPR/CCPA compliant consent handling

---

## Installation

```bash
npm install @flightdev/analytics
```

---

## Quick Start

```typescript
import { createAnalytics } from '@flightdev/analytics';
import { plausible } from '@flightdev/analytics/plausible';

const analytics = createAnalytics(plausible({
    domain: 'example.com',
}));

// Track page view
analytics.trackPageview('/about');

// Track custom event
analytics.trackEvent('signup', { plan: 'pro', source: 'landing' });

// Identify user (for providers that support it)
analytics.identify('user_123', { email: 'user@example.com' });
```

---

## Adapters

### Plausible (Privacy-Focused)

Simple, privacy-friendly analytics without cookies.

```typescript
import { plausible } from '@flightdev/analytics/plausible';

const adapter = plausible({
    domain: 'example.com',
    apiHost: 'https://plausible.io',  // Or self-hosted
    hashMode: false,                   // Hash-based routing
});
```

### PostHog (Product Analytics)

Full-featured product analytics with session recording.

```typescript
import { posthog } from '@flightdev/analytics/posthog';

const adapter = posthog({
    apiKey: process.env.POSTHOG_API_KEY,
    host: 'https://app.posthog.com',  // Or self-hosted
    autocapture: true,
    sessionRecording: true,
});
```

### Google Analytics 4

```typescript
import { ga4 } from '@flightdev/analytics/ga4';

const adapter = ga4({
    measurementId: 'G-XXXXXXXXXX',
    debug: process.env.NODE_ENV === 'development',
});
```

### Mixpanel

```typescript
import { mixpanel } from '@flightdev/analytics/mixpanel';

const adapter = mixpanel({
    token: process.env.MIXPANEL_TOKEN,
    debug: false,
});
```

### Amplitude

```typescript
import { amplitude } from '@flightdev/analytics/amplitude';

const adapter = amplitude({
    apiKey: process.env.AMPLITUDE_API_KEY,
    serverZone: 'US',  // or 'EU'
});
```

### Multiple Providers

Send events to multiple providers simultaneously:

```typescript
import { multi } from '@flightdev/analytics/multi';

const analytics = createAnalytics(multi([
    plausible({ domain: 'example.com' }),
    posthog({ apiKey: '...' }),
]));
```

---

## Core API

### trackPageview(path, properties?)

Track a page view:

```typescript
analytics.trackPageview('/products/widget');

// With additional properties
analytics.trackPageview('/products/widget', {
    referrer: document.referrer,
    title: document.title,
});
```

### trackEvent(name, properties?)

Track a custom event:

```typescript
// Simple event
analytics.trackEvent('button_click');

// With properties
analytics.trackEvent('purchase', {
    product_id: 'prod_123',
    price: 49.99,
    currency: 'USD',
});
```

### identify(userId, traits?)

Identify a user for user-level analytics:

```typescript
analytics.identify('user_123', {
    email: 'user@example.com',
    plan: 'pro',
    company: 'Acme Inc',
    signupDate: new Date(),
});
```

### reset()

Clear user identity (on logout):

```typescript
analytics.reset();
```

---

## React Integration

### AnalyticsProvider

Wrap your app with the provider:

```tsx
import { AnalyticsProvider } from '@flightdev/analytics/react';

function App() {
    return (
        <AnalyticsProvider client={analytics}>
            <Routes />
        </AnalyticsProvider>
    );
}
```

### useAnalytics Hook

```tsx
import { useAnalytics } from '@flightdev/analytics/react';

function SignupButton() {
    const { trackEvent } = useAnalytics();
    
    return (
        <button onClick={() => trackEvent('signup_click', { location: 'header' })}>
            Sign Up
        </button>
    );
}
```

### usePageview Hook

Automatic page view tracking:

```tsx
import { usePageview } from '@flightdev/analytics/react';

function Page() {
    usePageview();  // Tracks on mount and route changes
    
    return <div>...</div>;
}
```

### TrackEvent Component

Declarative event tracking:

```tsx
import { TrackEvent } from '@flightdev/analytics/react';

function PricingPage() {
    return (
        <>
            <TrackEvent name="pricing_view" properties={{ variant: 'A' }} />
            <h1>Pricing</h1>
        </>
    );
}
```

---

## Server-Side Tracking

Track events from your server or API routes:

```typescript
import { createServerAnalytics } from '@flightdev/analytics/server';

const serverAnalytics = createServerAnalytics(posthog({
    apiKey: process.env.POSTHOG_API_KEY,
}));

// In your API handler
export async function POST(request: Request) {
    const { userId, action } = await request.json();
    
    await serverAnalytics.trackEvent('api_action', {
        action,
        userId,
        ip: request.headers.get('x-forwarded-for'),
    });
    
    return Response.json({ success: true });
}
```

---

## Privacy and Consent

### Consent Management

```typescript
const analytics = createAnalytics(adapter, {
    consent: {
        required: true,      // Wait for consent before tracking
        cookieName: 'consent',
        defaultValue: false,
    },
});

// User gives consent
analytics.setConsent(true);

// Check consent status
if (analytics.hasConsent()) {
    // Track
}
```

### React Consent Hook

```tsx
import { useConsent } from '@flightdev/analytics/react';

function CookieBanner() {
    const { hasConsent, setConsent } = useConsent();
    
    if (hasConsent) return null;
    
    return (
        <div className="cookie-banner">
            <p>We use analytics to improve our site.</p>
            <button onClick={() => setConsent(true)}>Accept</button>
            <button onClick={() => setConsent(false)}>Decline</button>
        </div>
    );
}
```

---

## API Reference

### createAnalytics Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `debug` | `boolean` | `false` | Log events to console |
| `disabled` | `boolean` | `false` | Disable all tracking |
| `consent.required` | `boolean` | `false` | Require consent before tracking |
| `batch.enabled` | `boolean` | `true` | Batch events |
| `batch.size` | `number` | `10` | Max events per batch |
| `batch.timeout` | `number` | `5000` | Flush timeout in ms |

### Analytics Methods

| Method | Description |
|--------|-------------|
| `trackPageview(path, props?)` | Track page view |
| `trackEvent(name, props?)` | Track custom event |
| `identify(userId, traits?)` | Identify user |
| `reset()` | Clear user identity |
| `setConsent(value)` | Update consent |
| `hasConsent()` | Check consent status |

---

## License

MIT