npm package: @pulsora/core
Description: Privacy-first analytics tracking library - Core package
Author: Pulsora.co
Latest version: 1.0.1

# @pulsora/core

Privacy-first, cookieless analytics tracking library. Core package for Pulsora Analytics.

## Features

- 🔒 **Privacy-First**: No cookies, no localStorage (by default)
- 🎯 **Lightweight**: <1KB gzipped
- 🚀 **High Performance**: Uses sendBeacon API, async processing
- 🔧 **Extensible**: Plugin system for additional features
- 📊 **Browser Fingerprinting**: Stable, anonymous visitor identification
- 🔄 **Retry Logic**: Automatic retry with exponential backoff
- 📱 **SPA Support**: Automatic pageview tracking on route changes
- 💪 **TypeScript**: Full type definitions included

## Installation

### NPM

```bash
npm install @pulsora/core
```

### CDN

```html
<script
  async
  src="https://cdn.pulsora.co/v1/pulsora.min.js"
  data-token="YOUR_API_TOKEN"
></script>
```

## Usage

### For NPM Users (Recommended for Apps)

Create and manage your own tracker instances:

```typescript
import { Pulsora } from '@pulsora/core';

// Create a tracker instance
const tracker = new Pulsora();

// Initialize
tracker.init({
  apiToken: 'your-api-token',
  endpoint: 'https://pulsora.co/api/ingest', // optional, this is the default
  autoPageviews: true, // optional, default: true
  debug: false, // optional, default: false
});

// Track pageview
tracker.pageview();

// Track custom event
tracker.event('button_click', {
  button: 'signup',
  location: 'header',
});

// Identify user
tracker.identify('user_123');

// Get visitor fingerprint (useful for server-side attribution)
const fingerprint = await tracker.getVisitorFingerprint();
const sessionId = tracker.getSessionId();
```

#### Multiple Tracker Instances

Perfect for tracking multiple websites or separating different types of analytics:

```typescript
import { Pulsora } from '@pulsora/core';

const mainSiteTracker = new Pulsora();
mainSiteTracker.init({ apiToken: 'token-1' });

const blogTracker = new Pulsora();
blogTracker.init({ apiToken: 'token-2' });

// Each tracker operates independently
mainSiteTracker.pageview();
blogTracker.pageview();
```

### For CDN Users (Recommended for Websites)

Add the script tag with your API token:

```html
<!-- Auto-initializes and tracks pageviews -->
<script
  async
  src="https://cdn.pulsora.co/v1/pulsora.min.js"
  data-token="YOUR_API_TOKEN"
  data-debug="false"
></script>

<script>
  // Track custom event
  window.pulsora.event('purchase', {
    amount: 99.99,
    currency: 'USD',
  });

  // Identify user
  window.pulsora.identify('user_123');
</script>
```

## API Reference

### `init(config: PulsoraConfig)`

Initialize the tracker.

```typescript
interface PulsoraConfig {
  apiToken: string; // Required: Your Pulsora API token
  endpoint?: string; // Optional: API endpoint (default: https://api.pulsora.co/ingest)
  autoPageviews?: boolean; // Optional: Auto-track pageviews (default: true)
  debug?: boolean; // Optional: Enable debug logging (default: false)
  maxRetries?: number; // Optional: Max retry attempts (default: 10)
  retryBackoff?: number; // Optional: Initial retry backoff in ms (default: 1000)
}
```

### `pageview(options?: PageviewOptions)`

Track a pageview.

```typescript
tracker.pageview(); // Current page

tracker.pageview({
  url: 'https://example.com/page',
  referrer: 'https://google.com',
  title: 'Page Title',
});
```

### `event(eventName: string, eventData?: object)`

Track a custom event.

```typescript
tracker.event('button_click');

tracker.event('purchase', {
  product: 'Premium Plan',
  amount: 99,
  currency: 'USD',
});
```

### `identify(customerId: string)`

Identify a user. Links all previous anonymous activity to this user.

```typescript
tracker.identify('user_123');
```

### `reset()`

Reset the session and clear user identification.

```typescript
tracker.reset();
```

### `getVisitorFingerprint(): Promise<string>`

Get the current visitor's fingerprint. Useful for server-side revenue attribution.

```typescript
const fingerprint = await tracker.getVisitorFingerprint();
// Send to your backend for revenue tracking
```

### `getSessionId(): string`

Get the current session ID.

```typescript
const sessionId = tracker.getSessionId();
```

### `isIdentified(): boolean`

Check if the current visitor is identified.

```typescript
if (tracker.isIdentified()) {
  console.log('User is logged in');
}
```

### `use(extension: PulsoraExtension)`

Register an extension/plugin.

```typescript
import { Pulsora } from '@pulsora/core';
import revenue from '@pulsora/revenue';

const tracker = new Pulsora();
tracker.use(revenue);
tracker.init({ apiToken: 'token' });
```

## TypeScript

Full TypeScript support with type definitions included:

```typescript
import { Pulsora, PulsoraConfig, PageviewOptions } from '@pulsora/core';

const config: PulsoraConfig = {
  apiToken: 'token',
  debug: true,
};

const tracker = new Pulsora();
tracker.init(config);
```

## Privacy & GDPR Compliance

- **No cookies**: Pulsora doesn't use cookies
- **No localStorage**: All data is in-memory by default
- **Browser fingerprinting**: Uses non-PII technical characteristics
- **Anonymous by default**: Identification is opt-in via `identify()`
- **Transparent**: Open source and auditable

## SPA Support

Automatic pageview tracking for Single Page Applications:

```typescript
// Automatically tracks pageviews on:
// - history.pushState()
// - history.replaceState()
// - popstate events (back/forward buttons)

const tracker = new Pulsora();
tracker.init({
  apiToken: 'token',
  autoPageviews: true, // ← Enables SPA tracking
});
```

## Error Handling

Pulsora handles errors gracefully with automatic retry:

- Network failures: Exponential backoff retry
- Rate limiting: Respects Retry-After headers
- Max retries: Events dropped after max attempts
- Debug mode: Console warnings for troubleshooting

## Browser Support

- Chrome/Edge (latest 2 versions)
- Firefox (latest 2 versions)
- Safari (latest 2 versions)
- Mobile browsers (iOS Safari, Chrome Mobile)

## License

MIT

## Links

- [Documentation](https://pulsora.co/docs)
- [GitHub](https://github.com/pulsora/javascript-sdk)
- [Website](https://pulsora.co)