npm package: @plainapps/analytics-js
Description: Plain Web Analytics vanilla JavaScript library - privacy-focused, cookie-free analytics with global API
Author: Plain Web Analytics
Latest version: 1.0.2

# @plainapps/analytics-js

Vanilla JavaScript library for Plain Web Analytics - privacy-focused, cookie-free web analytics.

## Features

- 🔒 **Privacy-first**: Cookie-free tracking using IP hashing
- 🚀 **Lightweight**: < 2KB gzipped
- 🌐 **Universal**: Works with any website, framework, or CMS
- 📦 **Multiple formats**: ESM, CommonJS, and UMD (for CDN)
- 💪 **TypeScript**: Full type definitions included
- 🔧 **Auto-init**: Automatically initializes from script data attributes
- 🎯 **Simple API**: `window.plainAnalytics` global for easy access

## Installation

### CDN (Recommended for most sites)

Add this script tag before `</body>`:

```html
<script defer 
    data-site="YOUR_SITE_KEY"
    src="https://cdn.jsdelivr.net/npm/@plainapps/analytics-js"></script>
```

That's it! Pageviews are automatically tracked.

### npm/yarn/pnpm

```bash
npm install @plainapps/analytics-js
# or
yarn add @plainapps/analytics-js
# or
pnpm add @plainapps/analytics-js
```

```javascript
import { init, event, goal } from '@plainapps/analytics-js';

init({ siteId: 'YOUR_SITE_KEY' });

// Track custom events
event('signup', { plan: 'pro' });

// Track goal conversions
goal('purchase', { revenue: 9900 }); // in cents
```

## Quick Start

### Basic Usage (CDN)

```html
<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
</head>
<body>
    <h1>Welcome!</h1>
    <button onclick="plainAnalytics.event('button_click')">Click Me</button>
    
    <!-- Plain Web Analytics - add before </body> -->
    <script defer 
        data-site="pwa_site_abc123"
        src="https://cdn.jsdelivr.net/npm/@plainapps/analytics-js"></script>
</body>
</html>
```

### Track Custom Events

```javascript
// Track a button click
plainAnalytics.event('button_click', {
    button: 'signup',
    location: 'header'
});

// Track a form submission
plainAnalytics.event('form_submit', {
    form: 'contact',
    source: 'footer'
});

// Track a file download
plainAnalytics.event('download', {
    file: 'whitepaper.pdf',
    category: 'resources'
});
```

### Track Goal Conversions

```javascript
// Track a goal with revenue
plainAnalytics.goal('purchase', {
    revenue: 9900,  // in cents ($99.00)
    properties: {
        plan: 'pro',
        period: 'annual'
    }
});

// Track a goal without revenue
plainAnalytics.goal('free_trial');
```

### Manual Pageviews (for SPAs)

```javascript
// Track current page
plainAnalytics.pageview();

// Track a specific URL
plainAnalytics.pageview('/dashboard/settings');
```

## Configuration Options

### Data Attributes (CDN)

| Attribute | Description | Default |
|-----------|-------------|---------|
| `data-site` | Your site key (required) | - |
| `data-api` | Custom API endpoint | `https://api.plainwebanalytics.com/api/events` |
| `data-auto-pageview` | Auto-track pageview on load | `true` |
| `data-hash-mode` | Track hash changes as pageviews | `false` |
| `data-debug` | Enable debug logging | `false` |

Example with all options:

```html
<script defer 
    data-site="pwa_site_abc123"
    data-api="https://your-api.com/events"
    data-auto-pageview="true"
    data-hash-mode="false"
    data-debug="false"
    src="https://cdn.jsdelivr.net/npm/@plainapps/analytics-js"></script>
```

### Programmatic Configuration (npm)

```typescript
import { init } from '@plainapps/analytics-js';

init({
    siteId: 'pwa_site_abc123',    // Required
    apiEndpoint: 'custom-url',    // Optional
    autoPageview: true,            // Optional (default: true)
    hashMode: false,               // Optional (default: false)
    debug: false                   // Optional (default: false)
});
```

## API Reference

### Global API (`window.plainAnalytics`)

When using the CDN, the following methods are available on `window.plainAnalytics`:

#### `init(config)`

Initialize analytics (usually not needed with CDN as it auto-initializes).

```javascript
plainAnalytics.init({
    siteId: 'pwa_site_abc123',
    debug: true
});
```

#### `pageview(url?)`

Track a pageview. If no URL is provided, uses the current page URL.

```javascript
plainAnalytics.pageview();
plainAnalytics.pageview('/custom/path');
```

#### `event(name, properties?)`

Track a custom event with optional properties.

```javascript
plainAnalytics.event('click', { button: 'signup' });
```

#### `goal(goalId, options?)`

Track a goal conversion with optional revenue and properties.

```javascript
plainAnalytics.goal('purchase', { 
    revenue: 9900,
    properties: { plan: 'pro' }
});
```

#### `setEnabled(enabled)`

Enable or disable tracking (e.g., for user opt-out).

```javascript
// Disable tracking
plainAnalytics.setEnabled(false);

// Re-enable tracking
plainAnalytics.setEnabled(true);
```

#### `isInitialized()`

Check if analytics has been initialized.

```javascript
if (plainAnalytics.isInitialized()) {
    console.log('Analytics is ready');
}
```

#### `getConfig()`

Get the current configuration.

```javascript
const config = plainAnalytics.getConfig();
console.log(config.siteId);
```

### Backwards Compatibility

For backwards compatibility with the simple tracking script, `window.pwa` is also available as an alias:

```javascript
// These are equivalent
plainAnalytics.event('signup');
pwa.event('signup');
```

## Integration Examples

### WordPress

See [examples/wordpress.html](./examples/wordpress.html) for detailed WordPress integration including:
- Theme functions.php integration
- Header/footer plugins
- WooCommerce tracking
- Contact form tracking

### Static Site Generators

See [examples/static-sites.html](./examples/static-sites.html) for integration with:
- Hugo
- Jekyll
- Eleventy (11ty)
- Gatsby
- Astro
- VitePress
- Docusaurus
- MkDocs

### Single Page Applications (SPAs)

For SPAs, disable auto-pageview and track manually:

```html
<script defer 
    data-site="pwa_site_abc123"
    data-auto-pageview="false"
    src="https://cdn.jsdelivr.net/npm/@plainapps/analytics-js"></script>
```

Then track pageviews on route changes:

```javascript
// React Router example
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function App() {
    const location = useLocation();
    
    useEffect(() => {
        plainAnalytics.pageview(location.pathname);
    }, [location]);
    
    return <Routes>...</Routes>;
}
```

### User Opt-Out

Respect user privacy preferences:

```javascript
// Check if user has opted out
const hasOptedOut = localStorage.getItem('analytics_optout') === 'true';
plainAnalytics.setEnabled(!hasOptedOut);

// Provide opt-out button
document.getElementById('optout-btn').addEventListener('click', () => {
    localStorage.setItem('analytics_optout', 'true');
    plainAnalytics.setEnabled(false);
    alert('Analytics disabled');
});
```

## TypeScript

Full TypeScript support is included:

```typescript
import type { AnalyticsConfig, EventProperties } from '@plainapps/analytics-js';
import { init, event, goal } from '@plainapps/analytics-js';

const config: AnalyticsConfig = {
    siteId: 'pwa_site_abc123',
    debug: process.env.NODE_ENV === 'development'
};

init(config);

const props: EventProperties = {
    button: 'signup',
    plan: 'pro'
};

event('click', props);
```

## Multiple Instances

For tracking to multiple sites:

```javascript
import { createAnalytics } from '@plainapps/analytics-js';

const site1 = createAnalytics();
site1.init({ siteId: 'pwa_site_site1' });

const site2 = createAnalytics();
site2.init({ siteId: 'pwa_site_site2' });

// Track to both
site1.event('pageview');
site2.event('pageview');
```

## Framework-Specific Libraries

For deeper integration with popular frameworks, use our dedicated packages:

- [@plainapps/analytics-react](../react) - React hooks and components
- [@plainapps/analytics-vue](../vue) - Vue 3 composables and plugin
- [@plainapps/analytics-svelte](../svelte) - Svelte stores and components
- [@plainapps/analytics-angular](../angular) - Angular service and directives

## Browser Support

Works in all modern browsers:
- Chrome (last 2 versions)
- Firefox (last 2 versions)
- Safari (last 2 versions)
- Edge (last 2 versions)

Uses `navigator.sendBeacon()` when available, falls back to XHR.

## Privacy

Plain Web Analytics is privacy-focused:
- No cookies used
- No personal data collected
- GDPR/CCPA/PECR compliant
- Visitor IDs are hashed (IP + UA + Site + Date)
- No cross-site tracking

## License

MIT

## Links

- [Documentation](https://plainwebanalytics.com/docs)
- [Dashboard](https://app.plainwebanalytics.com)
- [GitHub](https://github.com/plainwebanalytics/purewebanalytics.com)
- [Support](https://plainwebanalytics.com/contact)