@easyflow/pixel
v1.8.21
Published
Easyflow client-side pixel SDK
Maintainers
Readme
@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
npm install @easyflow/pixelUsage
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: "[email protected]",
},
});
pixel.track(Events.PURCHASE_COMPLETED, {
id: "ORDER_ID_HERE",
valueInCents: 34990,
quantity: 1,
currency: "BRL",
paymentMethod: "credit-card",
buyer: {
id: "USER_ID_HERE",
email: "[email protected]",
name: "Any Name",
},
});Available Events
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",
// Form Initialization Events
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",
}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_idto 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
Testing & Quality Assurance
Comprehensive Test Coverage
- 516 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
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: 516 tests cobrindo funcionalidades e cenários críticos
- 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 24 comprehensive tracking events
Reliability & Resilience
- Circuit Breaker + Exponential Backoff (client API): proteção contra falhas em cascata no envio à API da Easyflow
- Sem retry para plataformas (Meta/Google/TikTok/GTM): evita risco de duplicidade; eventos incluem
event_idpara dedupe server-side - Sem dedupe na inicialização:
loadPixels()carrega múltiplos pixels por plataforma (útil para diferentes eventos)
CI/CD Integration
Available Scripts
npm run test:ci- Run tests in CI mode with coveragenpm run ci:build- Run tests, clean, and build (no publish)npm run ci:publish- Run tests, clean, build, and publishnpm 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 workflowci-config.md- Configuration guide for other CI/CD systems
Additional Resources
- Easyflow Digital: Official website of Easyflow.
- Easyflow API Documentation: Detailed API documentation for Easyflow.
- Support Site: Contact Easyflow support for assistance.
- Support Email: Email Easyflow support for queries.
License
MIT License © Easyflow
Built with ❤️ by the Easyflow Team
