# ThriveStack Analytics

A universal analytics library that works in both Node.js and browser environments. This package provides two distinct implementations:

- **Node.js Package**: For server-side analytics in Node.js, React, Next.js, and other frameworks
- **Browser Script**: For client-side analytics via CDN or script tags

## 🚀 Quick Start

### NPM Package (Node.js/React/Next.js)

```bash
npm install thrivestack-analytics
```

**Node.js Usage:**
```typescript
import { ThriveStack } from 'thrivestack-analytics';

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

await analytics.captureEvent('user_action', { action: 'login' });
```

**Next.js Usage:**
```typescript
// pages/_app.tsx
import { ThriveStack } from 'thrivestack-analytics';

const analytics = new ThriveStack({
  apiKey: process.env.NEXT_PUBLIC_THRIVESTACK_API_KEY!,
  source: 'my-nextjs-app'
});

export default function App({ Component, pageProps }) {
  useEffect(() => {
    analytics.init();
    analytics.capturePageVisit();
  }, []);

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

### Browser Script (CDN)

```html
<script src="https://unpkg.com/thrivestack-analytics/dist/thrivestack.min.js" 
        data-api-key="your-api-key" 
        data-source="my-website">
</script>

<script>
  // Auto-initialized and available globally
  window.thriveStack.captureEvent('page_view', { page: 'home' });
</script>
```

## 📦 Package Structure

This package provides **two separate implementations**:

### 1. Node.js Package (`thrivestack-analytics`)
- **Entry Point**: `dist/index.js`
- **TypeScript**: `dist/index.d.ts`
- **Dependencies**: `node-fetch`, `os`, `crypto`
- **Use Case**: Server-side analytics, React/Next.js applications

### 2. Browser Script (`thrivestack.min.js`)
- **Entry Point**: `dist/thrivestack.min.js`
- **Dependencies**: None (uses native browser APIs)
- **Use Case**: Client-side analytics, CDN usage

## 🔧 Configuration

### Node.js Configuration

```typescript
const analytics = new ThriveStack({
  apiKey: 'your-api-key',           // Required
  source: 'your-source-id',         // Required
  apiEndpoint: 'https://api.app.thrivestack.ai/api', // Optional
  batchSize: 10,                    // Optional: Events per batch
  batchInterval: 2000,              // Optional: Batch interval (ms)
  sessionTimeout: 30 * 60 * 1000,   // Optional: Session timeout (ms)
  debounceDelay: 2000,              // Optional: Session update delay
  enableConsent: false,             // Optional: Enable consent management
  defaultConsent: true              // Optional: Default consent state
});
```

### Browser Configuration

```html
<script src="https://unpkg.com/thrivestack-analytics/dist/thrivestack.min.js" 
        data-api-key="your-api-key"
        data-source="your-source-id"
        data-track-clicks="true"
        data-track-forms="true"
        data-respect-dnt="true">
</script>
```

## 📊 API Reference

### Core Methods

#### `init(userId?, source?)`
Initialize the analytics instance.

```typescript
await analytics.init('user123', 'my-app');
```

#### `captureEvent(eventName, properties?)`
Track custom events.

```typescript
await analytics.captureEvent('user_signup', {
  method: 'email',
  plan: 'premium'
});
```

#### `capturePageVisit(pageInfo?)`
Track page visits (Node.js) or automatically track (browser).

```typescript
// Node.js
await analytics.capturePageVisit({
  title: 'Dashboard',
  url: 'https://app.example.com/dashboard',
  path: '/dashboard'
});

// Browser (automatic)
// No manual call needed - tracks automatically
```

#### `setUser(userId, emailId?, properties?)`
Identify a user.

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

#### `setGroup(groupId, groupDomain?, groupName?, properties?)`
Identify a group/account.

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

#### `enableDebugMode()`
Enable debug logging.

```typescript
analytics.enableDebugMode();
```

### Browser-Specific Methods

#### Auto-tracking
The browser version automatically tracks:
- Page visits (load, navigation, SPA routing)
- Click events (if enabled)
- Form interactions (if enabled)

#### Manual Event Tracking
```javascript
// Available globally in browser
window.thriveStack.captureEvent('custom_action', {
  action: 'button_click',
  element: 'signup_button'
});
```

## 🌐 Environment Compatibility

### Node.js Package
- ✅ Node.js 14+
- ✅ React 16+
- ✅ Next.js 10+
- ✅ TypeScript
- ✅ CommonJS/ES Modules
- ❌ Browser (due to Node.js dependencies)

### Browser Script
- ✅ All modern browsers
- ✅ Vanilla JavaScript
- ✅ React/Next.js (client-side)
- ✅ Vue.js, Angular, etc.
- ✅ CDN usage
- ❌ Node.js (no server-side APIs)

## 🔄 Migration Guide

### From Old Browser Script
```html
<!-- Old -->
<script src="old-thrivestack.js" data-api-key="key"></script>

<!-- New -->
<script src="https://unpkg.com/thrivestack-analytics/dist/thrivestack.min.js" 
        data-api-key="key" 
        data-source="your-source">
</script>
```

### From Old NPM Package
```typescript
// Old
import ThriveStack from 'old-package';

// New
import { ThriveStack } from 'thrivestack-analytics';
```

## 🛠️ Development

### Building

```bash
# Build both Node.js and browser versions
npm run build

# Build Node.js version only
npm run build:node

# Build browser version only
npm run build:browser
```

### Testing

```bash
# Test Node.js version
npm run dev

# Test browser version
# Open dist/thrivestack.min.js in a browser
```

## 📋 Features

### ✅ Universal Features
- Event tracking with batching
- User and group identification
- Session management
- IP geolocation
- UTM parameter tracking
- PII cleaning
- Debug mode
- TypeScript support

### ✅ Node.js Features
- Server-side event tracking
- Platform information (OS, architecture)
- Node.js version tracking
- No browser dependencies

### ✅ Browser Features
- Automatic page visit tracking
- Click event tracking
- Form interaction tracking
- DOM element hierarchy
- Cookie-based persistence
- Do Not Track support
- Consent management

## 🔒 Privacy & Compliance

- **GDPR Compliant**: Built-in consent management
- **Do Not Track**: Respects browser DNT settings
- **PII Protection**: Automatic PII cleaning
- **Cookie Management**: Secure cookie handling
- **Privacy First**: Minimal data collection

## 📄 License

ISC License - see [LICENSE](LICENSE) file for details.

## 🤝 Support

For support, please contact the ThriveStack team or open an issue on GitHub. 