peach-collector-js
v2.0.0
Published
JS collector for EBU - peach
Readme
peach-collector
Browser analytics SDK for the EBU Peach collect API. Track user interactions, page views, media playback, and more with a lightweight, modular TypeScript library.
Features
✨ Modular architecture — Import only what you need
📊 Event tracking — Page views, user interactions, custom events
🎬 Media tracking — Monitor video/audio playback events
🌐 Cross-browser — Works in modern browsers (ES2020+)
💾 Offline queue — Retry failed requests with localStorage persistence
🔒 Privacy-first — Respects user consent settings
📦 Small footprint — ~4–7 KB gzipped per entry point
Installation
npm install peach-collector
# or with pnpm
pnpm add peach-collectorQuick Start
Basic Usage
import { PeachCollector } from '@peach/peach-collector';
const collector = PeachCollector({
endpoints: {
collect: 'https://your-api.example.com/v3/collect'
}
});
// Initialize and start tracking
await collector.init();
// Send a page view
collector.send({
type: 'page_view',
url: window.location.href,
title: document.title
});With Consent Management
import { PeachCollector } from 'peach-collector';
import { PeachTracking } from 'peach-collector';
const collector = PeachCollector({ /* ... */ });
await collector.init();
// Enable tracking when user consents
PeachTracking.enable();
// Events are now sent. Disable on opt-out:
PeachTracking.disable();Modular Entry Points
Import only what you need to keep bundle size minimal:
| Entry Point | Size | Purpose |
|---|---|---|
| peach-collector | 4.2 KB | Full collector with all features |
| peach-collector/events | 2.0 KB | Event tracking only |
| peach-collector/context | 0.4 KB | Context utilities |
| peach-collector/props | 0.5 KB | Property builders |
| peach-collector/media-tracking | 2.5 KB | Media playback events |
| peach-collector/metadata | 0.2 KB | Metadata types |
// Minimal: just events
import { PeachCollector } from 'peach-collector/events';
// With media tracking
import { PeachCollector } from 'peach-collector';
import { enableMediaTracking } from 'peach-collector/media-tracking';API Reference
PeachCollector(options)
Initialize the collector with configuration:
interface PeachCollectorOptions {
endpoints: {
collect: string; // Required: collect endpoint URL
};
payload_func?: (payload: any) => any; // Optional: transform payload
auto_track?: boolean; // Optional: enable automatic tracking
}collector.init()
Async initialization. Fetches remote config if available.
const client = await collector.init();collector.send(event)
Send an analytics event:
collector.send({
type: 'custom_event',
properties: {
action: 'click',
element: 'button'
}
});PeachTracking.enable() / disable()
Control consent-based tracking:
import { PeachTracking } from 'peach-collector';
// User opts in
PeachTracking.enable();
// User opts out
PeachTracking.disable();Script Tag Integration (UMD)
Use the UMD bundle for non-module environments:
<script src="https://cdn.example.com/peach-collector/full.umd.cjs"></script>
<script>
const collector = window._pc.PeachCollector({
endpoints: { collect: 'https://your-api.example.com/v3/collect' }
});
collector.init().then(() => {
collector.send({ type: 'page_view' });
});
</script>Configuration
Remote Config
The SDK can fetch remote configuration from your endpoints:
const { endpoints, config } = await collector.init();
// config includes: max_events_per_request, retry_timeout, etc.Local Storage
Failed requests are stored in localStorage and retried automatically. The queue persists across page reloads using the key _peach_queue.
Browser Support
- Chrome 91+
- Firefox 89+
- Safari 14+
- Edge 91+
- Any browser supporting ES2020
Requires fetch API and localStorage support.
Error Handling
The SDK handles network errors gracefully:
// Failed events are queued automatically
collector.send(event).catch(error => {
console.warn('Event queued for retry:', error.message);
});View the retry queue:
import { safeLocalstorageGet } from 'peach-collector';
const queue = safeLocalstorageGet('_peach_queue');
console.log('Queued events:', queue);Development
Setup
pnpm install --frozen-lockfile
pnpm run check:types # Type check
pnpm run check:codestyle # Lint
pnpm run test:ci # Run testsBuild
# Build all entry points
pnpm run build
# Build single entry point
LIB_NAME=collector pnpm run build:collectorDemo
# Vite dev server (with separate backend)
pnpm run demo:server # Terminal 1: collect API echo server
pnpm run dev # Terminal 2: Vite dev server on :5173
# Or full production bundle demo
pnpm run demo:full # UMD bundle on :4000Testing
pnpm run test:ci # Run all tests once
pnpm run test:watch # Watch mode
pnpm run test:path -- --run lib/events/*.test.js # Single file
pnpm run test:e2e # Playwright E2E (local only)Performance Tips
Tree-shake unused entry points
// Good: only import what you need import { PeachCollector } from '@peach/peach-collector/events'; // Avoid: pulling in full lib import * as peach from '@peach/peach-collector';Batch events — The SDK automatically batches events (max 5 per request)
Use
payload_functo filter or transform data before sending:const collector = PeachCollector({ endpoints: { collect: '...' }, payload_func: (payload) => { // Remove sensitive fields delete payload.user_id; return payload; } });Disable auto-tracking if not needed:
const collector = PeachCollector({ endpoints: { collect: '...' }, auto_track: false });
Contributing
Contributions are welcome! Please:
- Follow Conventional Commits for commit messages
- Run
pnpm run check:codestyle --fixbefore committing - Ensure
pnpm run test:cipasses - Add tests for new features
License
MIT © EBU
Support
Related
- EBU Peach — Analytics and metadata framework
- Vite — Build tool
- TypeScript — Language
