npm package: @powerit/cms-analytics
Description: Analytics tracking plugin for PowerIT CMS Client with gRPC support
Author: PowerIT
Latest version: 2.1.0

# @powerit/analytics

Lightweight analytics tracking library for PowerIT CMS. Track page views, user interactions, and custom events with automatic scroll depth and time-on-page tracking.

## Features

- Page view tracking with automatic session management
- Scroll depth tracking
- Time on page tracking
- Custom event tracking
- UTM parameter capture
- Do Not Track (DNT) respect
- TypeScript support
- Zero dependencies (uses native `fetch`)
- Works in browsers and Node.js (with fetch polyfill)

## Installation

```bash
npm install @powerit/analytics
```

## Quick Start

```javascript
import { createTracker } from '@powerit/analytics';

// Create tracker instance
const tracker = createTracker({
  baseUrl: 'https://cms.example.com',
  apiKey: 'your-api-key'
});

// Initialize (sets up scroll and exit tracking)
tracker.init();

// Track page view
await tracker.trackPageView();

// Track custom events
await tracker.trackClick('signup-button');
await tracker.trackFormSubmit('contact-form');
```

## Configuration

```javascript
const tracker = createTracker({
  // Required
  baseUrl: 'https://cms.example.com',
  apiKey: 'your-api-key',

  // Optional
  locale: 'en',                    // Default locale for tracking
  timeout: 10000,                  // Request timeout in ms (default: 10000)
  logger: true,                    // Enable console logging
  headers: {                       // Additional request headers
    'X-Custom-Header': 'value'
  },

  // Tracking options
  tracking: {
    scrollDepth: true,             // Track scroll depth (default: true)
    timeOnPage: true,              // Track time on page (default: true)
    exitPage: true,                // Detect exit pages (default: true)
    heartbeatInterval: 15000,      // Update interval in ms (default: 15000)
    storageKey: 'powerit_analytics', // LocalStorage key prefix
    respectDoNotTrack: true        // Respect DNT header (default: true)
  }
});
```

## API Reference

### Page View Tracking

```javascript
// Basic page view
await tracker.trackPageView();

// With additional data
await tracker.trackPageView({
  content_id: 123,
  content_type: 'article',
  content_slug: 'my-article'
});

// Manual page view update
await tracker.updatePageView({
  time_on_page_seconds: 120,
  scroll_depth_percent: 75
});
```

### Event Tracking

```javascript
// Generic event
await tracker.trackEvent('custom_event', {
  event_category: 'engagement',
  event_action: 'interaction',
  event_label: 'my-label',
  event_value: 42,
  event_data: { custom: 'data' }
});

// Convenience methods
await tracker.trackClick('button-id');
await tracker.trackFormSubmit('form-name');
await tracker.trackOutboundLink('https://example.com');
await tracker.trackDownload('document.pdf');
await tracker.trackVideoPlay('video-123');
```

### Utility Methods

```javascript
// Get current page view data
const pageView = tracker.getCurrentPageView();

// Get visitor/session IDs
const visitorId = tracker.getVisitorId();
const sessionId = tracker.getSessionId();

// Set locale
tracker.setLocale('fr');

// Enable/disable tracking
tracker.disable();
tracker.enable();

// Check if tracking is enabled
if (tracker.isTrackingEnabled()) {
  // ...
}

// Clean up (remove event listeners)
tracker.destroy();
```

## Framework Integration

### React

```jsx
import { useEffect, useRef } from 'react';
import { createTracker } from '@powerit/analytics';

function useAnalytics(config) {
  const trackerRef = useRef(null);

  useEffect(() => {
    trackerRef.current = createTracker(config).init();

    return () => {
      trackerRef.current?.destroy();
    };
  }, []);

  return trackerRef.current;
}

// In your app
function App() {
  const tracker = useAnalytics({
    baseUrl: 'https://cms.example.com',
    apiKey: 'your-api-key'
  });

  useEffect(() => {
    tracker?.trackPageView();
  }, [location.pathname]);

  return <div>...</div>;
}
```

### Vue

```javascript
// plugins/analytics.js
import { createTracker } from '@powerit/analytics';

export default {
  install(app, options) {
    const tracker = createTracker(options).init();

    app.config.globalProperties.$analytics = tracker;
    app.provide('analytics', tracker);
  }
};

// main.js
import Analytics from './plugins/analytics';

app.use(Analytics, {
  baseUrl: 'https://cms.example.com',
  apiKey: 'your-api-key'
});

// In components
import { inject } from 'vue';

const analytics = inject('analytics');
analytics.trackPageView();
```

### Next.js

```jsx
// lib/analytics.js
import { createTracker } from '@powerit/analytics';

let tracker = null;

export function getTracker() {
  if (typeof window === 'undefined') return null;

  if (!tracker) {
    tracker = createTracker({
      baseUrl: process.env.NEXT_PUBLIC_CMS_URL,
      apiKey: process.env.NEXT_PUBLIC_CMS_API_KEY
    }).init();
  }

  return tracker;
}

// app/layout.jsx
'use client';

import { usePathname } from 'next/navigation';
import { useEffect } from 'react';
import { getTracker } from '@/lib/analytics';

export default function RootLayout({ children }) {
  const pathname = usePathname();

  useEffect(() => {
    getTracker()?.trackPageView();
  }, [pathname]);

  return <html><body>{children}</body></html>;
}
```

### SvelteKit

```javascript
// hooks.client.js
import { createTracker } from '@powerit/analytics';

export const tracker = createTracker({
  baseUrl: import.meta.env.VITE_CMS_URL,
  apiKey: import.meta.env.VITE_CMS_API_KEY
}).init();

// +layout.svelte
<script>
  import { page } from '$app/stores';
  import { tracker } from './hooks.client.js';

  $: $page.url.pathname, tracker?.trackPageView();
</script>

<slot />
```

## Custom Logger

```javascript
import pino from 'pino';

const logger = pino({ level: 'debug' });

const tracker = createTracker({
  baseUrl: 'https://cms.example.com',
  apiKey: 'your-api-key',
  logger: {
    debug: (...args) => logger.debug(args),
    info: (...args) => logger.info(args),
    warn: (...args) => logger.warn(args),
    error: (...args) => logger.error(args)
  }
});
```

## Server-Side Usage (Node.js)

```javascript
import { createTracker } from '@powerit/analytics';

const tracker = createTracker({
  baseUrl: 'https://cms.example.com',
  apiKey: 'your-api-key',
  fetch: globalThis.fetch // Node.js 18+ has native fetch
});

// Track server-side events
await tracker.trackEvent('server_event', {
  event_category: 'api',
  event_action: 'request'
});
```

## Privacy & GDPR

The tracker respects user privacy:

- **Do Not Track**: By default, respects the browser's DNT setting
- **IP Anonymization**: The server automatically anonymizes IP addresses
- **No Cookies**: Uses localStorage/sessionStorage (not cookies)
- **Data Retention**: Configurable server-side retention period

To comply with GDPR:

```javascript
// Check for consent before initializing
if (hasUserConsent()) {
  const tracker = createTracker({...}).init();
}

// Or disable until consent is given
const tracker = createTracker({...});
tracker.disable();

// Later, when consent is given
tracker.enable();
tracker.init();
tracker.trackPageView();
```

## TypeScript

Full TypeScript support is included:

```typescript
import { createTracker, AnalyticsTracker, PageViewData, EventData } from '@powerit/analytics';

const tracker: AnalyticsTracker = createTracker({
  baseUrl: 'https://cms.example.com',
  apiKey: 'your-api-key'
});

const pageViewData: Partial<PageViewData> = {
  content_id: 123,
  content_type: 'article'
};

await tracker.trackPageView(pageViewData);
```

## License

MIT