# rozmova-analytics

[![npm-version](https://img.shields.io/npm/v/rozmova-analytics.svg)](https://www.npmjs.com/package/rozmova-analytics)
[![minified-size](https://img.shields.io/bundlephobia/minzip/rozmova-analytics@1.0.7)](https://bundlephobia.com/package/rozmova-analytics)

A lightweight JavaScript analytics library designed to streamline event tracking, user identification, and common analytics parameter management. This package integrates with Mixpanel, Google Analytics, Customer.io, and Microsoft Clarity to provide seamless data collection and insights.

## Installation

Install the package using npm:

```bash
npm install rozmova-analytics
```

Alternatively, you can include the library via jsDelivr to use in browser:

```html
<script src="https://cdn.jsdelivr.net/npm/rozmova-analytics/dist/index.umd.js"></script>
```

## Usage

Import the library in your project and initialize it:

```javascript
import Analytics from "rozmova-analytics";

// Initialize the library
Analytics.init({ locale: "en", platform: "web", isClearly: true });

// Set user
Analytics.setUser("user-id-123", {
  email: "user@example.com",
  name: "John Doe",
  numberOfSessions: 5,
  locale: "en",
  phone: "+1234567890",
  isB2B: false
});

// Track an event
Analytics.trackEvent("button_click", { button_name: "Sign Up" });
```

Or use in browser:

```javascript
// Initialize the library
window.Analytics.init({ locale: "en", platform: "web" });

// Set user
window.Analytics.setUser("user-id-123", {
  email: "user@example.com",
  name: "John Doe",
  numberOfSessions: 1,
  locale: "en"
});

// Track an event
window.Analytics.trackEvent("button_click", { button_name: "Sign Up" });
```

## API Reference

### `init(config?)`

Initializes the analytics library, setting up Mixpanel, Google Analytics, Customer.io, and Microsoft Clarity integrations.

**Parameters:**
- `config.isProd?: boolean` - Whether the environment is production (default: true)
- `config.locale?: string` - The locale for analytics data (default: auto-detected or "uk")
- `config.platform?: string` - The platform identifier (default: "web")
- `config.isClearly?: boolean` - Whether to enable Clearly-specific features like cookie consent banner
- `config.trackPageScroll?: boolean` - Whether to automatically track page scroll to bottom (default: true)
- `config.config?: object` - Initial configuration object with userId and email
  - `config.config.userId?: string` - Initial user ID
  - `config.config.email?: string` - Initial user email

**Example:**
```javascript
Analytics.init({
  isProd: true,
  locale: "en",
  platform: "web",
  isClearly: true,
  config: {
    userId: "user-123",
    email: "user@example.com"
  }
});
```

### `trackEvent(eventName, properties?, services?)`

Tracks an event across the specified analytics providers.

**Parameters:**
- `eventName: string` - The name of the event to track
- `properties?: EventParams` - Additional event properties (optional)
- `services?: object` - Which services to track to (optional, default: all enabled)
    - `ga?: boolean` - Google Analytics (default: true)
    - `mixpanel?: boolean` - Mixpanel (default: true)
    - `customerIO?: boolean` - Customer.io (default: true)

**Example:**

```javascript
// Track to all services
Analytics.trackEvent("purchase", {
  product_id: "123",
  price: 29.99,
  currency: "USD"
});

// Track to specific services only
Analytics.trackEvent("newsletter_signup", {
  source: "footer"
}, {
  ga: true,
  mixpanel: false,
  customerIO: true
});
```

### `setUser(userId, userParams)`

Associates a user with the provided user ID and sets user properties across all analytics providers.

**Parameters:**
- `userId: string` - Unique user identifier
- `userParams: object` - User properties
    - `email: string` - User's email address
    - `name: string` - User's full name
    - `numberOfSessions: number` - Number of user sessions
    - `locale: string` - User's locale
    - `phone?: string` - User's phone number (optional)
    - `isB2B?: boolean` - Whether the user is a business user (optional)
    - `CIOParams?: EventParams` - Additional properties for Customer.io (optional)
    - `mixpanelParams?: Dict` - Additional properties for Mixpanel (optional)

**Example:**
```javascript
Analytics.setUser("user-456", {
  email: "jane@example.com",
  name: "Jane Doe",
  numberOfSessions: 3,
  locale: "en",
  phone: "+1234567890",
  isB2B: true,
  CIOParams: {
    custom_field: "value"
  },
  mixpanelParams: {
    $created: "2024-01-01"
  }
});
```

### `resetUser()`

Resets the current user across all analytics providers, clears stored user data, generates a new user ID, and reinitializes the library. Automatically calls `init()` after reset.

**Example:**
```javascript
Analytics.resetUser();
```

### `setUserTag(key, value)`

Sets a user tag in Microsoft Clarity for enhanced user identification and session analysis.

**Parameters:**
- `key: string` - The tag key
- `value: string` - The tag value

**Example:**
```javascript
Analytics.setUserTag("user_type", "premium");
Analytics.setUserTag("subscription_plan", "pro");
```

### `setConfig(params?)`

Updates the analytics configuration with new parameters. This is a private method but can be called indirectly through `setUser()` or `resetUser()`.

**Parameters:**
- `params.userId?: string` - User ID to set (default: from profile)
- `params.email?: string` - User email to set (default: from profile)

**Note:** This method is called automatically when setting or resetting users. Direct usage is not recommended.

### `setLocale(newLocale)`

Updates the locale for analytics data.

**Parameters:**
- `newLocale: string` - The new locale to set

**Example:**
```javascript
Analytics.setLocale("es");
```

### `trackPageScroll(bodyElementQuerySelector?)`

Tracks a `page_scroll` event in Mixpanel when the user scrolls to the bottom of the page. Called automatically during `init()` unless `trackPageScroll` is set to `false`.

**Parameters:**
- `customElement?: HTMLElement` - Optional scrollable HTML element to track. If not provided, defaults to tracking the window scroll against `document.body`.

**Returns:** `() => void` - A cleanup function that removes the scroll listener.

**Example:**
```javascript
// Automatically tracked during init (default behavior)
Analytics.init({ locale: "en", platform: "web" });

// Disable automatic tracking and call manually
Analytics.init({ locale: "en", trackPageScroll: false });
const cleanup = Analytics.trackPageScroll(document.querySelector(".main-content"));

// Remove the scroll listener when no longer needed
cleanup();
```

### `trackPageView(options?)`

Tracks a page view event with current page information including title, location, and referrer.

**Parameters:**
- `options.referrer?: string` - Custom referrer URL (optional, defaults to document.referrer)

**Example:**
```javascript
// Track with default referrer
Analytics.trackPageView();

// Track with custom referrer
Analytics.trackPageView({ referrer: "https://example.com" });
```

### `getCommonParams()`

Returns an object with common analytics parameters including device information, browser details, UTM parameters, user data, and session information.

**Returns:** `AnalyticsCommonParams`

**Example:**
```javascript
const params = Analytics.getCommonParams();
console.log(params.device, params.browser, params.locale);
```

### `getUserId()`

Retrieves the current user ID from cookies, localStorage, or URL query parameters. Generates a new one if not found.

**Returns:** `string`

**Example:**
```javascript
const userId = Analytics.getUserId();
```

### `getGAClientId()`

Retrieves the Google Analytics client ID asynchronously.

**Returns:** `Promise<string | null>`

**Example:**
```javascript
const gaClientId = await Analytics.getGAClientId();
```

### `setGAClientId(clientId)`

Sets the Google Analytics client ID.

**Parameters:**
- `clientId: string` - The GA client ID to set

**Example:**
```javascript
Analytics.setGAClientId("1234567890.1234567890");
```

### `getAttributionProperties(forcedAttributionProperties?)`

Retrieves comprehensive attribution properties including funnel info, tracking parameters, and external analytics user information.

**Parameters:**
- `forcedAttributionProperties?: ForcedAttributionProperties` - Optional forced attribution properties
  - `forcedAttributionProperties.funnelName?: string` - Override funnel name

**Returns:** `Promise<UserAttributionProperties>`

**Example:**
```javascript
const attribution = await Analytics.getAttributionProperties({
  funnelName: "custom_funnel"
});

console.log(attribution.funnelInfo);
console.log(attribution.trackingParams);
console.log(attribution.externalAnalyticsUserInfo);
```

### `trackFirstPartyEvent(eventName, properties?, forcedAttributionProperties?)`

Tracks an event to your first-party analytics endpoint with comprehensive attribution data encoded in headers.

**Parameters:**
- `eventName: string` - The name of the event to track
- `properties?: EventParams` - Additional event properties (optional)
- `forcedAttributionProperties?: ForcedAttributionProperties` - Optional forced attribution properties

**Returns:** `Promise<Response>`

**Example:**
```javascript
// Track first-party event
await Analytics.trackFirstPartyEvent("purchase_completed", {
  product_id: "123",
  price: 29.99
});

// Track with forced attribution
await Analytics.trackFirstPartyEvent("signup", {
  source: "landing_page"
}, {
  funnelName: "marketing_campaign"
});
```

## Analytics Providers

The library integrates with multiple analytics providers out of the box:

### Mixpanel
- Event tracking with custom properties
- User identification and profile management
- Automatic page view tracking
- User property registration

### Google Analytics 4
- Event tracking with enhanced ecommerce support
- User identification with custom user properties
- Server-side container support
- Automatic ecommerce event handling

### Customer.io
- Behavioral event tracking
- User identification and profile management
- Automated messaging and email triggers

### Microsoft Clarity
- Session recording and heatmaps
- User tagging for enhanced insights
- Automatic session tracking

## Features

### Event Queuing
Events tracked before initialization are queued and processed once the library is ready.

### Error Handling
Individual service failures don't affect other providers - the library includes comprehensive error handling.

### Cookie Consent
Automatic cookie consent banner integration for GDPR compliance when `isClearly` is enabled.

### Meta Browser Detection
Special handling for Meta (Facebook) browsers with automatic URL parameter tracking.

### Geo Parameter Storage
Automatic storage and tracking of geographic parameters.

### Session Management
Comprehensive session tracking with Google Analytics session IDs and user pseudo IDs.

## Browser Support

The package works on modern browsers and supports:

- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)

## Example Integration

```javascript
import Analytics from "rozmova-analytics";

// Initialize analytics
Analytics.init({ 
  locale: "en", 
  platform: "web", 
  isClearly: true 
});

// Track a page view (automatically called during init)
Analytics.trackPageView();

// Set user details
Analytics.setUser("user-456", {
  email: "user456@example.com",
  name: "Jane Doe",
  numberOfSessions: 1,
  locale: "en",
  phone: "+1234567890",
  isB2B: false
});

// Track custom events
Analytics.trackEvent("feature_used", {
  feature_name: "advanced_search",
  user_tier: "premium"
});

// Track first-party event with attribution
await Analytics.trackFirstPartyEvent("purchase", {
  product_id: "123",
  amount: 99.99
});

// Get attribution properties
const attribution = await Analytics.getAttributionProperties();
console.log(attribution.funnelInfo, attribution.trackingParams);

// Get GA client ID
const gaClientId = await Analytics.getGAClientId();

// Set user tags for Clarity
Analytics.setUserTag("subscription", "premium");
Analytics.setUserTag("user_segment", "power_user");

// Update locale
Analytics.setLocale("fr");

// Reset user on logout
Analytics.resetUser();
```

## Configuration

Make sure to configure your analytics provider tokens in your constants file:

```javascript
// constants.js
export const MIXPANEL_TOKEN = "your-mixpanel-token";
export const GOOGLE_ANALYTICS_ID = "your-ga-measurement-id";
export const CLARITY_ID = "your-clarity-project-id";
export const GA_SERVER_CONTAINER_URL = "your-server-container-url";
```

## Common Parameters

The library automatically collects and includes common parameters with every event:

- Device type, browser, and operating system
- User language and locale
- UTM parameters and referrer information
- Session IDs and user pseudo IDs
- Facebook tracking parameters (fbc, fbp)
- Current URL and page information
- User login status and profile data

## TypeScript Support

The library includes TypeScript definitions for better development experience:

```typescript
import Analytics from "rozmova-analytics";
import type { 
  EventParams, 
  UserAttributionProperties,
  ForcedAttributionProperties 
} from "rozmova-analytics";

// Type-safe event tracking
const eventParams: EventParams = {
  product_id: "123",
  category: "electronics"
};

Analytics.trackEvent("product_view", eventParams);

// Type-safe attribution properties
const attribution: UserAttributionProperties = await Analytics.getAttributionProperties();

// Type-safe first-party event tracking
const forcedAttribution: ForcedAttributionProperties = {
  funnelName: "custom_funnel"
};

await Analytics.trackFirstPartyEvent("signup", eventParams, forcedAttribution);
```

## Contributing

Contributions are welcome! Please fork the repository and create a pull request with your changes.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

This project is licensed under the MIT License.