@easyflow/pixel
Version:
Easyflow client-side pixel SDK
462 lines (353 loc) • 18.1 kB
Markdown
# @easyflow/pixel
Client-side SDK for event tracking in Easyflow checkouts.
This SDK encapsulates the **Google Tag Manager (GTM)**, **Meta Ads (Facebook)**, **Google Analytics (GA4)**, and *
*TikTok
Ads** tracking pixels, allowing standardized event
sending through a unified interface. In addition, all events are also reported to Easyflow's API for storage, auditing,
and retry processing.
## Features
- Dynamic loading of third-party pixel scripts
- Automatic mapping of Easyflow events to platform-specific events
- Simultaneous dispatch to Meta, Google, and TikTok
- Full logging of all events to Easyflow backend
- Rich metadata collection from the client environment
- **PII Data Anonymization**: Automatic anonymization of personally identifiable information for external platforms
- **Data Normalization**: Standardized data formatting before processing
- **Comprehensive Test Coverage**: 516 tests passing with robust coverage
- **Version injection**: The SDK version is injected at build time and logged during init
- **Robust Error Handling**: Graceful fallback mechanisms and retry logic
---
## Installation
```bash
npm install @easyflow/pixel
```
---
## Usage
```ts
import {EasyflowPixel, Events} from "@easyflow/pixel";
const pixel = new EasyflowPixel("BUSINESS_ID_HERE", "FINGERPRINT_ID_HERE", {
product: "PRODUCT_ID_HERE",
offer: "OFFER_ID_HERE",
checkout: "CHECKOUT_ID_HERE",
paymentLink: "PAYMENT_LINK_ID_HERE",
});
await pixel.init();
pixel.track(Events.CHECKOUT_INITIALIZED);
pixel.track(Events.CREDIT_CARD_FORM_INIT, {
formData: {
name: "John Doe",
email: "john@example.com",
},
});
pixel.track(Events.PURCHASE_COMPLETED, {
id: "ORDER_ID_HERE",
valueInCents: 34990,
quantity: 1,
currency: "BRL",
paymentMethod: "credit-card",
buyer: {
id: "USER_ID_HERE",
email: "any@email.com",
name: "Any Name",
},
});
```
---
## Available Events
```ts
export enum Events {
CHECKOUT_INITIALIZED = "checkout-initialized",
PURCHASE_COMPLETED = "purchase-completed",
PURCHASE_FAILED = "purchase-failed",
PURCHASE_BTN_CLICKED = "purchase-btn-clicked",
PIX_SELECTED = "pix-selected",
PIX_GENERATED = "pix-generated",
PIX_EXPIRED = "pix-expired",
PIX_COPIED = "pix-copied",
CREDIT_CARD_SELECTED = "credit-card-selected",
CREDIT_CARD_FORM_COMPLETED = "credit-card-form-completed",
BANK_BILLET_SELECTED = "bank-slip-selected",
BANK_BILLET_GENERATED = "bank-slip-form-completed",
ADDRESS_FORM_COMPLETED = "address-form-completed",
DELIVERY_ADDRESS_COMPLETED = "delivery-address-completed",
COUPON_ADDED = "coupon-added",
COUPON_BOX_CLICKED = "coupon-box-clicked",
COUPON_FORM_COMPLETED = "coupon-form-completed",
COUPON_APPLY_FAILED = "coupon-apply-failed",
USER_FORM_COMPLETED = "user-form-completed",
PRE_CHECKOUT_FORM_COMPLETED = "pre-checkout-form-completed",
CREDIT_CARD_FORM_INIT = "credit-card-form-init",
COUPON_FORM_INIT = "coupon-form-init",
USER_FORM_INIT = "user-form-init",
PRE_CHECKOUT_FORM_INIT = "pre-checkout-form-init",
CUSTOM_EVENT = "custom-event",
}
```
---
## Custom Events
The SDK supports custom events, allowing you to track any business-specific event using `CUSTOM_EVENT`. This provides complete flexibility to track custom actions beyond the predefined events.
### How to Use Custom Events
```ts
import {EasyflowPixel, PixelEvent} from "@easyflow/pixel";
const pixel = new EasyflowPixel("BUSINESS_ID", "FINGERPRINT_ID", {
product: "PRODUCT_ID",
});
await pixel.init();
// Track custom event with specific name
pixel.track(PixelEvent.CUSTOM_EVENT, {
customEventName: "video_watched",
videoId: "video123",
duration: 120,
category: "tutorial",
userId: "user456"
});
// Track custom event for newsletter
pixel.track(PixelEvent.CUSTOM_EVENT, {
customEventName: "newsletter_signup",
source: "homepage",
email: "user@example.com"
});
// Track custom event for button interactions
pixel.track(PixelEvent.CUSTOM_EVENT, {
customEventName: "button_clicked",
buttonId: "checkout-btn",
page: "product-page",
productId: "prod123"
});
// Track custom event without specific name (uses 'custom_event' as default)
pixel.track(PixelEvent.CUSTOM_EVENT, {
action: "view",
page: "home",
timestamp: Date.now()
});
```
### Important Requirements
1. **Pixel Configuration**: The pixel must have `CUSTOM_EVENT` in its allowed events list in the backend:
```json
{
"id": "pixel1",
"platform": "easyflow",
"code": "ef123",
"events": [
"purchase-completed",
"custom-event" // ← Must be present
]
}
```
2. **Event Name**: Use `customEventName` in the payload to define the event name. If not provided, `'custom_event'` will be used as default.
3. **Payload Data**: All data provided in the payload is preserved and sent to both the Easyflow API and external platforms (Meta, Google, TikTok, GTM).
### Behavior
- **Easyflow API**: The event is sent with the name defined in `customEventName` (or `'custom-event'` if not provided)
- **External Platforms**: The event is mapped using the provided `customEventName`, enabling custom tracking across all platforms
- **Data Preservation**: All payload data is included in the event data, ensuring complete context
### Use Case Examples
```ts
// Track product view
pixel.track(PixelEvent.CUSTOM_EVENT, {
customEventName: "product_viewed",
productId: "prod123",
category: "electronics",
price: 299.99
});
// Track file download
pixel.track(PixelEvent.CUSTOM_EVENT, {
customEventName: "file_downloaded",
fileId: "file456",
fileType: "pdf",
fileName: "manual.pdf"
});
// Track chat interaction
pixel.track(PixelEvent.CUSTOM_EVENT, {
customEventName: "chat_opened",
chatType: "support",
page: "checkout"
});
```
---
## Production Deployment
Make sure to:
- Only include the SDK in your checkout pages
- Call `await pixel.init()` before tracking any events
- Initialization uses `loadPixels()` (no dedupe at init), allowing multiple pixels per platform
---
## Telemetry & Logging
All events are reported to Easyflow with:
- Navigation context
- UTM metadata
- Fingerprint identification
- Page visibility state
- Page performance metrics
- Delivery attempts and platform status
- **Complete Client Metadata**: User agent, screen resolution, device memory, hardware concurrency, touch support, and
more
- **Performance Timing**: Detailed page load metrics and timing information
- **Session Management**: Persistent session tracking with TTL
---
## Privacy & Data Protection
- **PII Anonymization**: Personally Identifiable Information is automatically anonymized before sending to external
platforms (Meta, Google, TikTok, GTM)
- **Data Preservation**: Original data is preserved for Easyflow's internal API to maintain data integrity
- **Idempotency Protection**: Unique identifiers are preserved to ensure proper deduplication (client also sends
`event_id` to supported platforms)
- **Compliance Ready**: Follows market standards for data privacy and GDPR compliance
- **No Sensitive Storage**: No sensitive user data is stored locally
- **Cookie Policy Support**: Supports cookie policy and Do Not Track (DNT)
- **Data Normalization**: All data is normalized and standardized before processing
### Session Correlation Identifier
The SDK includes a `sessionId` in telemetry payloads whose sole purpose is to group
events from the same browsing session for analytics, attribution, and funnel
stitching. It is a **non-authoritative correlation identifier**: it is not a
credential, not a proof of identity, and must not be used for authorization or
access control by any consumer of the event stream. Identity, authentication,
and authorization are handled by other parts of the platform and are outside the
scope of this SDK.
---
## Testing & Quality Assurance
### Comprehensive Test Coverage
- **525 Tests Passing**: Complete test suite covering all functionality and critical scenarios
- **32 Test Suites**: Organized test structure for maintainability and reliability
- **Jest Framework**: Modern testing framework with TypeScript support
- **JSDOM Environment**: Browser-like testing environment for accurate simulation
### Test Categories
- **Unit Tests**: Individual component testing for utilities, adapters, and core functionality
- **Integration Tests**: End-to-end testing of event tracking and data processing
- **Mock Testing**: Comprehensive mocking of external APIs and browser environments
- **Error Handling Tests**: Validation of graceful error handling and fallback mechanisms
- **Coverage Tests**: Specific tests targeting uncovered code paths and edge cases
- **Deduplication Tests**: Validation of proper event deduplication based on content
- **Content-Based Tests**: Testing of hash-based uniqueness for different payloads
- **Edge Case Tests**: Comprehensive testing of edge cases and potential failure points
- **Enum Tests**: Complete validation of all platform and event enumerations
- **Utility Tests**: Comprehensive testing of object manipulation, hashing, and normalization functions
- **Metadata Tests**: Validation of client metadata collection and processing
- **Cache Tests**: Testing of localStorage operations and cache key management
### Quality Metrics
- **Zero Test Failures**: All tests pass consistently
- **Type Safety**: Full TypeScript coverage with strict type checking
- **Code Isolation**: Tests are completely isolated from production code
- **CI/CD Ready**: Fully configured for continuous integration pipelines
- **Automated Publishing**: Tests must pass before any publish operation
- **Multi-Platform Support**: GitHub Actions, Jenkins, GitLab CI, Azure DevOps
### Coverage Breakdown
- **Statements**: 84.69% coverage
- **Branches**: 79.69% coverage
- **Functions**: 88.97% coverage
- **Lines**: 85.25% coverage
- **High Coverage Files**: Multiple files with 90%+ coverage including adapters, constants, enums, and utilities
- **Critical Path Coverage**: 100% coverage of idempotency and data processing logic
### Detailed Coverage by Module
#### Core Modules (100% Coverage)
- **Constants**: `cache-keys.ts` - 100% coverage
- **Enums**: `platform.ts`, `pixel-event.enum.ts` - 100% coverage
- **Mappers**: `event-mapper.ts` - 100% coverage
#### Adapters (97.67% Average Coverage)
- **Easyflow**: `easyflow.ts` - 100% coverage
- **TikTok**: `tiktok.ts` - 100% coverage
- **Google**: `google.ts` - 100% coverage
- **GTM**: `gtm.ts` - 96.96% coverage
- **Meta**: `meta.ts` - 93.54% coverage
#### Utilities (90.47% Average Coverage)
- **Core Utils**: `base64.ts`, `compression.ts`, `debounce.ts`, `fingerprint.ts`, `session.ts`, `utm.ts` - 100% coverage
- **Data Processing**: `normalize.ts` - 98.55% coverage, `object.ts` - 96.72% coverage
- **Client Metadata**: `get-client-metadata.ts` - 78.04% coverage
- **PII Handling**: `pii.ts` - 82.08% coverage
#### Main Application (61.46% Coverage)
- **EasyflowPixel**: `easyflow-pixel.ts` - 57.36% coverage (complex integration logic with external APIs)
#### Helpers (92.85% Coverage)
- **Hasher**: `hasher.ts` - 92.85% coverage
### Data Security Testing
- **PII Anonymization Tests**: Validation of data anonymization for external platforms (90%+ coverage)
- **Data Normalization Tests**: Verification of data standardization processes (90%+ coverage)
- **Privacy Compliance Tests**: Assurance of GDPR and privacy standard compliance
- **Idempotency Security Tests**: Critical validation of unique ID generation and collision prevention
- **Performance Security Tests**: Validation of memory management and cache security
---
## Recent Updates & Enhancements
### Custom Events Support (v1.9.0)
- **Flexible Event Tracking**: New `CUSTOM_EVENT` type allows tracking any custom event with dynamic naming
- **Dynamic Event Names**: Use `customEventName` in payload to define custom event names on-the-fly
- **Full Platform Support**: Custom events are properly mapped and sent to all platforms (Meta, Google, TikTok, GTM,
Easyflow)
- **Complete Data Preservation**: All payload data is preserved and sent to both Easyflow API and external platforms
- **Backward Compatible**: Existing events continue to work without changes
- **525 Tests Passing**: Comprehensive test coverage including 7 new tests for custom events
### Data Privacy & Security
- **Enhanced PII Anonymization**: Advanced anonymization system that masks, hashes, or nullifies personally identifiable
information
- **Smart Data Processing**: Automatic detection of PII patterns in both keys and values
- **Platform-Specific Handling**: Different anonymization strategies for different external platforms
- **Idempotency Preservation**: Critical identifiers are preserved to maintain deduplication capabilities
### Data Normalization
- **Phone Number Standardization**: Converts complex phone objects to standardized string format
- **Email Normalization**: Ensures consistent email formatting across all platforms
- **Document Processing**: Standardizes CPF, CNPJ, and other document formats
- **Address Normalization**: Consistent address formatting and validation
- **Currency Handling**: Proper BRL currency parsing and formatting
### Advanced Idempotency Strategy
- **Content-Based Uniqueness**: 7-layer unique ID generation with owner, fingerprint, session, pixel, platform, event,
and payload hash
- **Smart Payload Processing**: Optimized hashing strategy with cache-based storage for performance
- **True Deduplication**: Events with identical content generate identical IDs, enabling proper deduplication
- **Performance Optimized**: Cache-based hash storage with intelligent eviction for high-volume scenarios
- **Memory Efficient**: Limited cache size (1000 entries) with automatic cleanup to prevent memory leaks
- **No Temporal Dependencies**: Removed timestamp and sequence counters to prevent false positives
### Enhanced Metadata Collection
- **Complete Client Context**: Comprehensive collection of browser, device, and performance data
- **Extended Performance Metrics**: Detailed timing information and resource usage
- **Advanced Fingerprinting**: Enhanced device identification capabilities
- **Session Intelligence**: Sophisticated session management with TTL and persistence
### Testing & Reliability
- **Comprehensive Test Suite**: 525 tests covering all functionality and critical scenarios
- **Mock Environment**: Complete browser API simulation for reliable testing
- **Error Resilience**: Robust error handling and graceful degradation
- **Fallback Mechanisms**: Automatic retry and offline storage capabilities
- **Coverage Optimization**: Targeted tests for uncovered code paths and edge cases
- **Rigorous Validation**: Critical testing of idempotency, performance, and failure scenarios
- **Production Ready**: Extensive testing ensures reliability in high-volume production environments
### Recent Test Enhancements
- **New Test Files Added**: 6 new comprehensive test files covering previously untested modules
- **112 New Tests**: Added extensive test coverage for utilities, constants, enums, and metadata collection
- **Complete Enum Coverage**: 100% test coverage for all platform and event enumerations
- **Utility Function Testing**: Comprehensive testing of object manipulation, hashing, and normalization
- **Metadata Collection Tests**: Full validation of client metadata gathering and processing
- **Cache Management Tests**: Complete testing of localStorage operations and cache key handling
- **Mock Improvements**: Enhanced mocking strategies for crypto APIs, DOM operations, and browser environments
### New Form Initialization Events
- **Enhanced Form Tracking**: Added 4 new form initialization events for better user journey tracking
- **Credit Card Form Init**: Track when users start filling credit card information
- **Coupon Form Init**: Monitor coupon code input initiation
- **User Form Init**: Track user information form initialization
- **Pre-Checkout Form Init**: Monitor pre-checkout form initialization
- **Complete Platform Support**: All new events are mapped to Facebook, Google, TikTok, and GTM platforms
- **Consistent Naming**: Follows established kebab-case naming convention
- **Total Events**: Now supporting 25 comprehensive tracking events (including custom events)
### Reliability & Resilience
- **Circuit Breaker + Exponential Backoff (client API)**: Protection against cascading failures when sending to Easyflow API
- **No retry for platforms (Meta/Google/TikTok/GTM)**: Avoids duplication risk; events include `event_id` for server-side deduplication
- **No deduplication on initialization**: `loadPixels()` loads multiple pixels per platform (useful for different events)
---
## CI/CD Integration
### Available Scripts
- `npm run test:ci` - Run tests in CI mode with coverage
- `npm run ci:build` - Run tests, clean, and build (no publish)
- `npm run ci:publish` - Run tests, clean, build, and publish
- `npm run publish` - Legacy script (same as ci:publish)
### Pipeline Requirements
- ✅ All 516 tests must pass before publish
- ✅ Coverage reports generated automatically
- ✅ Node.js 18.x or 20.x (LTS versions)
- ✅ Tests run on multiple Node.js versions
- ✅ Rigorous idempotency and performance validation
### Configuration Files
- `.github/workflows/ci.yml` - GitHub Actions workflow
- `ci-config.md` - Configuration guide for other CI/CD systems
## Additional Resources
- [Easyflow Digital](https://easyflow.digital): Official website of Easyflow.
- [Easyflow API Documentation](https://docs.easyflow.digital): Detailed API documentation for Easyflow.
- [Support Site](https://easyflow.digital/contact): Contact Easyflow support for assistance.
- [Support Email](mailto:contato@easyflow.digital): Email Easyflow support for queries.
---
## License
MIT License © [Easyflow](https://easyflow.digital)
---
Built with ❤️ by the Easyflow Team