@tracelog/lib 0.11.5 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,6 +11,12 @@ Lightweight web analytics library for tracking user behavior. Works standalone o
11
11
  - **Event-driven** - Subscribe via `on()`/`off()` for real-time events
12
12
  - **Lightweight** - Single dependency (`web-vitals`), 15KB gzipped
13
13
 
14
+ ## Live Demo
15
+
16
+ [https://nacorga.github.io/tracelog-lib](https://nacorga.github.io/tracelog-lib)
17
+
18
+ ---
19
+
14
20
  ## Installation
15
21
 
16
22
  ### NPM (Recommended)
@@ -51,191 +57,256 @@ await tracelog.init({
51
57
  ## Quick Start
52
58
 
53
59
  ```typescript
54
- // Basic initialization
60
+ // 1. Initialize (standalone mode - no backend required)
55
61
  await tracelog.init();
56
62
 
57
- // Custom events
58
- tracelog.event('product_viewed', {
59
- productId: 'abc-123',
60
- price: 299.99
63
+ // 2. Track custom events
64
+ tracelog.event('button_clicked', {
65
+ buttonId: 'signup-cta',
66
+ source: 'homepage'
61
67
  });
62
68
 
63
- // Subscribe to events
69
+ // 3. Subscribe to events (real-time)
64
70
  tracelog.on('event', (event) => {
65
71
  console.log(event.type, event);
66
72
  });
67
73
 
68
- // Cleanup
69
- await tracelog.destroy();
74
+ // 4. Cleanup (on consent revoke or app unmount)
75
+ tracelog.destroy();
70
76
  ```
71
77
 
78
+ **That's it!** TraceLog now automatically tracks:
79
+ - Page views & navigation (including SPA routes)
80
+ - Click interactions
81
+ - Scroll behavior
82
+ - User sessions
83
+ - Web Vitals (LCP, INP, CLS, FCP, TTFB)
84
+ - JavaScript errors
85
+
86
+ ---
87
+
88
+ ## Core API
89
+
90
+ | Method | Description |
91
+ |--------|-------------|
92
+ | `init(config?)` | Initialize tracking (see [Configuration](#configuration)) |
93
+ | `event(name, metadata?)` | Track custom events |
94
+ | `on(event, callback)` | Subscribe to events (`'event'` or `'queue'`) |
95
+ | `off(event, callback)` | Unsubscribe from events |
96
+ | `isInitialized()` | Check initialization status |
97
+ | `setQaMode(enabled)` | Enable/disable QA mode (console logging) |
98
+ | `destroy()` | Stop tracking and cleanup |
99
+
100
+ **→ [Complete API Reference](./API_REFERENCE.md)**
101
+
102
+ ---
103
+
72
104
  ## Configuration
73
105
 
106
+ All configuration is **optional**. TraceLog works out-of-the-box with sensible defaults.
107
+
74
108
  ```typescript
75
109
  await tracelog.init({
76
110
  // Session
77
- sessionTimeout: 900000, // 15 min (default)
78
-
79
- // Sampling
80
- samplingRate: 1.0, // 100% (default)
81
- errorSampling: 1.0, // 100% (default)
111
+ sessionTimeout: 900000, // 15 min (default)
82
112
 
83
113
  // Privacy
84
- sensitiveQueryParams: ['token'], // Merged with defaults
114
+ samplingRate: 1.0, // 100% (default)
115
+ sensitiveQueryParams: ['token'], // Add to defaults
85
116
 
86
- // Integrations
117
+ // Integrations (pick one or none)
87
118
  integrations: {
88
- tracelog: { projectId: 'your-id' },
89
- custom: { collectApiUrl: 'https://api.example.com/collect' },
90
- googleAnalytics: { measurementId: 'G-XXXXXX' }
119
+ tracelog: { projectId: 'your-id' }, // TraceLog SaaS
120
+ custom: { collectApiUrl: 'https://api.com' }, // Custom backend
121
+ googleAnalytics: { measurementId: 'G-XXXXXX' } // GA4 forwarding
91
122
  },
92
123
 
93
- // Viewport tracking
124
+ // Web Vitals filtering
125
+ webVitalsMode: 'needs-improvement', // 'all' | 'needs-improvement' | 'poor'
126
+
127
+ // Viewport tracking (element visibility)
94
128
  viewport: {
95
- elements: [
96
- { selector: '.cta-button', id: 'pricing-cta', name: 'Pricing CTA' }
97
- ],
129
+ elements: [{ selector: '.cta', id: 'hero-cta' }],
98
130
  threshold: 0.5, // 50% visible
99
131
  minDwellTime: 1000 // 1 second
100
132
  }
101
133
  });
102
134
  ```
103
135
 
104
- ### Methods
105
-
106
- - `init(config?)` - Initialize tracking
107
- - `event(name, metadata?)` - Send custom event
108
- - `on(event, callback)` - Subscribe to events
109
- - `off(event, callback)` - Unsubscribe
110
- - `destroy()` - Cleanup
136
+ **→ [Full Configuration Guide](./API_REFERENCE.md#configuration)**
111
137
 
112
- ## Event Types
138
+ ---
113
139
 
114
- All events include: `id`, `type`, `page_url`, `timestamp`, `sessionId`, `utm`
140
+ ## Automatic Event Types
115
141
 
116
- | Type | Data Fields |
117
- |------|-------------|
118
- | `PAGE_VIEW` | `page_view.{title, pathname, referrer}` |
119
- | `CLICK` | `click_data.{x, y, tag, id, text, href}` |
120
- | `SCROLL` | `scroll_data.{depth, direction, velocity, is_primary}` |
121
- | `SESSION_START` | Session initialization |
122
- | `SESSION_END` | `session_end_reason` |
123
- | `CUSTOM` | `custom_event.{name, metadata}` |
124
- | `WEB_VITALS` | `web_vitals.{type, value}` (LCP, CLS, INP, FCP, TTFB) |
125
- | `ERROR` | `error_data.{type, message, filename, line}` |
126
- | `VIEWPORT_VISIBLE` | `viewport_data.{selector, dwellTime, visibilityRatio}` |
142
+ TraceLog captures these events automatically (no code required):
127
143
 
128
- ## Examples
144
+ | Event Type | What It Tracks |
145
+ |------------|----------------|
146
+ | `PAGE_VIEW` | Navigation, SPA route changes |
147
+ | `CLICK` | User interactions with elements |
148
+ | `SCROLL` | Scroll depth, velocity, engagement |
149
+ | `SESSION_START` | New session creation |
150
+ | `SESSION_END` | Session termination (timeout, page unload) |
151
+ | `WEB_VITALS` | Core Web Vitals (LCP, INP, CLS, FCP, TTFB) |
152
+ | `ERROR` | JavaScript errors, promise rejections |
153
+ | `VIEWPORT_VISIBLE` | Element visibility (requires `viewport` config) |
129
154
 
130
- ### Event Subscription
155
+ **Custom Events:**
131
156
  ```typescript
132
- // Register BEFORE init() to catch initial events
133
- tracelog.on('event', (event) => {
134
- console.log(event.type, event);
157
+ tracelog.event('purchase_completed', {
158
+ orderId: 'ord-123',
159
+ total: 99.99,
160
+ currency: 'USD'
135
161
  });
162
+ ```
136
163
 
137
- tracelog.on('queue', (batch) => {
138
- console.log('Queued:', batch.events.length);
139
- });
164
+ **→ [Event Types Reference](./API_REFERENCE.md#event-types)**
140
165
 
166
+ ---
167
+
168
+ ## Integration Modes
169
+
170
+ TraceLog supports multiple integration modes. Choose what fits your needs:
171
+
172
+ ### 1. Standalone (No Backend)
173
+ ```typescript
141
174
  await tracelog.init();
175
+
176
+ // Consume events locally
177
+ tracelog.on('event', (event) => {
178
+ myAnalytics.track(event);
179
+ });
142
180
  ```
143
181
 
144
- ### Privacy Controls
182
+ ### 2. TraceLog SaaS
145
183
  ```typescript
146
- // Exclude sensitive elements
147
- <div data-tlog-ignore>
148
- <input type="password">
149
- </div>
150
-
151
- // Filter URL params
152
184
  await tracelog.init({
153
- sensitiveQueryParams: ['affiliate_id', 'promo'],
154
- samplingRate: 0.5 // Track 50% of users
185
+ integrations: {
186
+ tracelog: { projectId: 'your-project-id' }
187
+ }
155
188
  });
156
189
  ```
157
190
 
158
- ### Filter Primary Scroll
191
+ ### 3. Custom Backend
159
192
  ```typescript
160
- tracelog.on('event', (event) => {
161
- if (event.type === 'scroll' && event.scroll_data.is_primary) {
162
- console.log('Main content scroll:', event.scroll_data.depth);
193
+ await tracelog.init({
194
+ integrations: {
195
+ custom: {
196
+ collectApiUrl: 'https://api.example.com/collect',
197
+ allowHttp: false // Only true for local testing
198
+ }
163
199
  }
164
200
  });
165
201
  ```
166
202
 
167
- ### Global Disable
203
+ ### 4. Google Analytics
168
204
  ```typescript
169
- window.__traceLogDisabled = true;
205
+ await tracelog.init({
206
+ integrations: {
207
+ googleAnalytics: { measurementId: 'G-XXXXXX' }
208
+ }
209
+ });
170
210
  ```
171
211
 
212
+ **→ [Integration Setup Guide](./API_REFERENCE.md#integration-configuration)**
213
+
214
+ ---
215
+
172
216
  ## Privacy & Security
173
217
 
174
- - **PII Sanitization** - Auto-redacts emails, phones, credit cards, API keys
175
- - **Input Protection** - Never captures input/textarea/select values
176
- - **URL Filtering** - Removes sensitive query params (token, auth, key, password, etc.)
177
- - **Element Exclusion** - Use `data-tlog-ignore` attribute
178
- - **Client-Side Controls** - All validation/sampling happens in browser
218
+ TraceLog is **privacy-first** by design:
219
+
220
+ - **PII Sanitization** - Auto-redacts emails, phones, credit cards, API keys
221
+ - **Input Protection** - Never captures `<input>`, `<textarea>`, `<select>` values
222
+ - **URL Filtering** - Removes sensitive query params (15 defaults + custom)
223
+ - ✅ **Element Exclusion** - Use `data-tlog-ignore` to exclude sensitive areas
224
+ - ✅ **Client-Side Controls** - All sampling and validation happens in browser
225
+
226
+ **Example:**
227
+ ```html
228
+ <!-- Exclude sensitive forms -->
229
+ <div data-tlog-ignore>
230
+ <input type="password" name="password">
231
+ <input type="text" name="credit_card">
232
+ </div>
233
+ ```
179
234
 
180
235
  **Your Responsibilities:**
181
- - Get user consent before calling `init()` (GDPR)
182
- - Sanitize custom event metadata
236
+ - Get user consent before calling `init()` (GDPR/CCPA)
237
+ - Sanitize custom event metadata (avoid PII)
183
238
  - Call `destroy()` on consent revoke
184
239
 
185
- [Full Security Guide](./SECURITY.md)
186
-
187
- ## Error Handling & Reliability
240
+ **→ [Complete Security Guide](./SECURITY.md)**
188
241
 
189
- TraceLog uses a **persistence-based recovery model** with no in-session retries:
242
+ ---
190
243
 
191
- - **Success (2xx)** - Events sent immediately, queue cleared
192
- - **Permanent errors (4xx)** - Events discarded immediately (invalid data won't succeed on retry)
193
- - **Temporary errors (5xx/network)** - Events removed from queue and persisted to localStorage
194
- - **Recovery** - Persisted events automatically recovered and retried on next page load
195
- - **Expiration** - Persisted events expire after 2 hours
196
- - **Page unload** - Uses `sendBeacon()` for synchronous delivery of session end events
244
+ ## QA Mode
197
245
 
198
- **Why no in-session retries?**
199
- - Prevents infinite retry loops during API outages
200
- - Reduces server load and network traffic during failures
201
- - Better battery life on mobile devices
202
- - Natural recovery on page navigation (common in SPAs)
246
+ Enable QA mode for debugging and development:
203
247
 
204
- ## Debug
248
+ ### URL Activation
249
+ ```bash
250
+ # Enable
251
+ ?tlog_mode=qa
205
252
 
206
- Enable QA mode: `?tlog_mode=qa`
253
+ # Disable
254
+ ?tlog_mode=qa_off
255
+ ```
207
256
 
257
+ ### Programmatic API
208
258
  ```typescript
209
- console.log(tracelog.isInitialized()); // true
259
+ tracelog.setQaMode(true); // Enable
260
+ tracelog.setQaMode(false); // Disable
210
261
  ```
211
262
 
212
- ## Development
263
+ **Features:**
264
+ - Custom events logged to browser console
265
+ - Strict validation (throws errors instead of warnings)
266
+ - Session state visible in console
267
+ - Persistent across page reloads (sessionStorage)
213
268
 
214
- ```bash
215
- npm install
216
- npm run build:all # ESM + CJS + Browser
217
- npm run check # Lint + format
218
- npm run test # All tests
219
- npm run test:coverage # With coverage
220
- ```
269
+ **→ [QA Mode Documentation](./API_REFERENCE.md#setqamodeenabled-boolean-void)**
270
+
271
+ ---
221
272
 
222
273
  ## Browser Support
223
274
 
224
- Chrome 60+, Firefox 55+, Safari 12+, Edge 79+
275
+ - Chrome 60+
276
+ - Firefox 55+
277
+ - Safari 12+
278
+ - Edge 79+
225
279
 
226
- ## SSR/SSG Support
280
+ **SSR/SSG Compatible:** Safe to import in Angular Universal, Next.js, Nuxt, SvelteKit (no-ops in Node.js).
227
281
 
228
- Safe to import in SSR frameworks (Angular Universal, Next.js, Nuxt, SvelteKit). All methods silently no-op in Node.js environments.
282
+ ---
229
283
 
230
- **Best practice**
231
- Register listeners AFTER init() in browser-only lifecycle hooks.
284
+ ## Development
285
+
286
+ ```bash
287
+ npm install # Install dependencies
288
+ npm run build:all # Build ESM + CJS + Browser bundles
289
+ npm run check # Lint + format validation
290
+ npm run test # Run all tests
291
+ npm run test:coverage # Generate coverage report
292
+ ```
293
+
294
+ **→ [Contributing Guide](./CONTRIBUTING.md)**
295
+
296
+ ---
232
297
 
233
298
  ## Documentation
234
299
 
235
- - [Handlers](./src/handlers/README.md) - Event capture implementation
236
- - [Managers](./src/managers/README.md) - Core components
237
- - [Security](./SECURITY.md) - Privacy & security guide
238
- - [Changelog](./CHANGELOG.md) - Release history
300
+ | Document | Description |
301
+ |----------|-------------|
302
+ | **[API Reference](./API_REFERENCE.md)** | Complete API documentation with all methods, config options, and event types |
303
+ | **[Best Practices](./BEST_PRACTICES.md)** | Patterns, anti-patterns, and optimization tips |
304
+ | **[Security Guide](./SECURITY.md)** | Privacy, GDPR compliance, and security best practices |
305
+ | **[Changelog](./CHANGELOG.md)** | Release history and migration guides |
306
+ | **[Handlers](./src/handlers/README.md)** | Event capture implementation details |
307
+ | **[Managers](./src/managers/README.md)** | Core component architecture |
308
+
309
+ ---
239
310
 
240
311
  ## License
241
312