# @thrivestack/analytics

ThriveStack Analytics Platform - Comprehensive web analytics tracking with privacy-first approach

## Features

- **Privacy-First**: Respects Do Not Track settings and provides consent management
- **Automatic Tracking**: Captures page visits, clicks, and form interactions
- **Device Fingerprinting**: Uses FingerprintJS for reliable device identification
- **Session Management**: Automatic session tracking with configurable timeouts
- **Event Batching**: Efficient event batching to reduce API calls
- **Geolocation**: Automatic IP-based location detection
- **UTM Tracking**: Automatic UTM parameter capture
- **TypeScript Support**: Full TypeScript definitions included
- **Simple API**: Easy-to-use singleton pattern

## Installation

```bash
npm install @thrivestack/analytics
```

## Build Modes

This package is available in 4 different build modes to support various deployment scenarios:

### 1. Production Package Mode

Default mode for npm package installations. Uses production API endpoint: `https://api.app.thrivestack.ai/api`

```bash
npm install @thrivestack/analytics-browser
```

```javascript
import { ThriveStack } from '@thrivestack/analytics-browser';
// Or CommonJS: const { ThriveStack } = require('@thrivestack/analytics-browser');

const analytics = new ThriveStack({
  apiKey: 'your-api-key',
});
```

**Files generated:**

- `dist/index.production.js` (CommonJS)
- `dist/index.production.esm.js` (ES modules)

### 2. Development Package Mode

Development version for npm package installations. Uses development API endpoint: `https://azure.dev.app.thrivestack.ai/api`

```javascript
// Import the development build specifically
import { ThriveStack } from '@thrivestack/analytics-browser/dist/index.development.esm.js';

const analytics = new ThriveStack({
  apiKey: 'your-api-key',
});
```

**Files generated:**

- `dist/index.development.js` (CommonJS)
- `dist/index.development.esm.js` (ES modules)

### 3. CDN Production Mode

Single vanilla JS file for CDN hosting with production API endpoint.

```html
<!-- Production CDN build -->
<script src="https://your-cdn.com/thrivestack.production.min.js"></script>
<script>
  const analytics = new ThriveStack({
    apiKey: 'your-api-key',
  });
</script>
```

**File generated:**

- `dist/thrivestack.production.min.js` (UMD, minified, standalone)

### 4. CDN Development Mode

Single vanilla JS file for CDN hosting with development API endpoint.

```html
<!-- Development CDN build -->
<script src="https://your-cdn.com/thrivestack.development.min.js"></script>
<script>
  const analytics = new ThriveStack({
    apiKey: 'your-api-key',
  });
</script>
```

**File generated:**

- `dist/thrivestack.development.min.js` (UMD, minified, standalone)

### Build Commands

To build all modes:

```bash
npm run build
```

To build specific modes:

```bash
npm run build:production    # Production package mode
npm run build:development   # Development package mode
npm run build:cdn          # Both CDN modes
npm run build:cdn:production    # CDN production mode only
npm run build:cdn:development   # CDN development mode only
```

### API Endpoints

- **Production**: `https://api.app.thrivestack.ai/api`
- **Development**: `https://azure.dev.app.thrivestack.ai/api`

You can always override the API endpoint by passing `apiEndpoint` in the options:

```javascript
const analytics = new ThriveStack({
  apiKey: 'your-api-key',
  apiEndpoint: 'https://custom-endpoint.com/api',
});
```

## Publish

```bash
 npm publish --registry=https://registry.npmjs.org/
```

## Quick Start

### Basic Usage

```typescript
import * as thrivestack from '@thrivestack/analytics';

// Initialize ThriveStack
await thrivestack.init('your-api-key', 'your-source-identifier');
```

### With User Identification

```typescript
import * as thrivestack from '@thrivestack/analytics';

// Initialize
await thrivestack.init('your-api-key', 'your-source-identifier');

// Set user information
await thrivestack.setUser('user@example.com', 'user123', {
  firstName: 'John',
  lastName: 'Doe',
  plan: 'premium',
});

// Set group information
await thrivestack.setGroup('group123', 'example.com', 'Example Corp', {
  industry: 'technology',
  size: 'medium',
});

// Track custom events
await thrivestack.track('button_clicked', {
  button_name: 'signup',
  page: 'homepage',
});
```

## API Reference

### `init(apiKey: string, source?: string, options?: ThriveStackOptions)`

Initialize ThriveStack analytics.

```typescript
await thrivestack.init('your-api-key', 'web-app', {
  trackClicks: true,
  trackForms: true,
  enableConsent: true,
});
```

### `setUser(email: string, userId: string, properties?: Record<string, any>)`

Set user information and optionally make identify API call.

```typescript
await thrivestack.setUser('user@example.com', 'user123', {
  firstName: 'John',
  lastName: 'Doe',
  plan: 'premium',
});
```

### `setGroup(groupId: string, groupDomain: string, groupName: string, properties?: Record<string, any>)`

Set group information and optionally make group API call.

```typescript
await thrivestack.setGroup('group123', 'example.com', 'Example Corp', {
  industry: 'technology',
  size: 'medium',
});
```

### `track(eventName: string, properties?: Record<string, any>)`

Track custom events.

```typescript
await thrivestack.track('purchase_completed', {
  amount: 99.99,
  currency: 'USD',
  product_id: 'prod_123',
});
```

### `getInstance(): ThriveStack | null`

Get the ThriveStack instance for advanced usage.

### `isInitialized(): boolean`

Check if ThriveStack is initialized.

## Configuration Options

```typescript
interface ThriveStackOptions {
  apiKey: string; // Required: Your ThriveStack API key
  apiEndpoint?: string; // Optional: Custom API endpoint
  trackClicks?: boolean; // Optional: Enable click tracking (default: true)
  trackForms?: boolean; // Optional: Enable form tracking (default: false)
  respectDoNotTrack?: boolean; // Optional: Respect DNT setting (default: true)
  enableConsent?: boolean; // Optional: Enable consent management (default: false)
  batchSize?: number; // Optional: Events per batch (default: 10)
  batchInterval?: number; // Optional: Batch interval in ms (default: 2000)
  geoIpServiceUrl?: string; // Optional: Custom geolocation service
  source?: string; // Optional: Source identifier
  sessionTimeout?: number; // Optional: Session timeout in ms (default: 30min)
  debounceDelay?: number; // Optional: Session update delay (default: 2000ms)
  defaultConsent?: boolean; // Optional: Default consent state
}
```

## Advanced Usage

For advanced usage, you can access the underlying ThriveStack instance:

```typescript
import * as thrivestack from '@thrivestack/analytics';

await thrivestack.init('your-api-key');

const instance = thrivestack.getInstance();
if (instance) {
  // Access advanced methods
  instance.setConsent('analytics', true);
  instance.enableDebugMode();

  // Direct event tracking
  await instance.track([
    {
      event_name: 'custom_event',
      properties: { custom: 'data' },
      context: { device_id: instance.getDeviceId() },
      timestamp: new Date().toISOString(),
    },
  ]);
}
```

## Event Types

### Page Visit Event

Automatically captured when:

- Page loads
- Navigation occurs (SPA support)
- History API is used

### Click Event

Automatically captured for elements with the `thrivestack-event` class:

```html
<button class="thrivestack-event">Click me</button>
```

### Form Events

Automatically captured for form interactions:

- Form submissions
- Form field interactions
- Form abandonment

## Consent Management

```typescript
import * as thrivestack from '@thrivestack/analytics';

// Initialize with consent management
await thrivestack.init('your-api-key', 'web-app', {
  enableConsent: true,
});

const instance = thrivestack.getInstance();
if (instance) {
  // Set consent for different categories
  instance.setConsent('analytics', true);
  instance.setConsent('marketing', false);

  // Check if tracking is allowed
  if (instance.isTrackingAllowed('analytics')) {
    // Track analytics events
  }
}
```

## Debug Mode

```typescript
import * as thrivestack from '@thrivestack/analytics';

await thrivestack.init('your-api-key');

const instance = thrivestack.getInstance();
if (instance) {
  // Enable debug mode to see events in console
  instance.enableDebugMode();
}
```

## Next.js Integration

```typescript
// In _app.tsx or layout.tsx
import { useEffect } from 'react';
import * as thrivestack from '@thrivestack/analytics';

export default function App({ Component, pageProps }) {
  useEffect(() => {
    thrivestack.init(
      process.env.NEXT_PUBLIC_THRIVESTACK_API_KEY || '',
      'nextjs-app'
    );
  }, []);

  return <Component {...pageProps} />;
}

// In a component
import { useEffect } from 'react';
import * as thrivestack from '@thrivestack/analytics';

export default function HomePage() {
  useEffect(() => {
    thrivestack.track('page_view', {
      page_name: 'Home Page',
      page_url: window.location.href
    });
  }, []);

  const handleButtonClick = () => {
    thrivestack.track('button_clicked', {
      button_name: 'signup',
      page: 'homepage'
    });
  };

  return (
    <button onClick={handleButtonClick}>
      Sign Up
    </button>
  );
}
```

## Browser Support

- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+

## Node.js Support

This package is designed for browser environments. For Node.js server-side tracking, use the appropriate server SDK.

## Development

### Install Dependencies

```bash
npm install
```

### Build

```bash
npm run build
```

### Test

```bash
npm test
```

### Lint

```bash
npm run lint
```

### Format Code

```bash
npm run format
```

## License

MIT

## Support

For support, please contact support@thrivestack.ai or visit our documentation at https://docs.thrivestack.ai
