@itsmarathon/eqcadt-web-sdk
v0.4.3
Published
Conversational Advertising SDK for Web (TypeScript/JavaScript)
Maintainers
Readme
🚀 EQ CADT Web SDK
A privacy-first conversational advertising SDK that enables intelligent, contextual ad serving within chat interfaces using on-device WebAssembly machine learning and sophisticated commerce orchestration.
🎯 Core Features
🔒 Privacy by Design
- On-Device ML Processing: All conversation analysis happens locally using WebAssembly
- Zero Raw Data Transmission: Only anonymized intent classifications sent to servers
- GDPR/TCF 2.2 Compliant: Built-in consent management and DSAR handling
- Agent-Centric Privacy: User conversations never leave the client device
⚡ High-Performance Architecture
- WebAssembly ML: Sub-100ms intent classification using ONNX models
- Multi-Environment Testing: 4,413+ tests across 55 files with isolated server setups
- Intelligent Caching: Configurable TTL with memory-aware garbage collection
- Worker Thread Support: Non-blocking ML processing in dedicated workers
🛒 Advanced Commerce Orchestration
- Multi-Provider Blending: Intelligent mixing of internal inventory and external ads
- Dynamic Strategies: Balanced, internal-first, external-first, and custom blending logic
- Business Rules Engine: Configurable filtering for inventory, pricing, and quality
- Real-Time Orchestration: Parallel provider queries with sophisticated timeout handling
🛡️ Comprehensive Fraud Detection
- Behavioral Analysis: Mouse movement, keyboard timing, and interaction patterns
- Environmental Signals: Device fingerprinting and browser characteristics
- Viewability Tracking: Ad visibility and engagement metrics
- Risk Scoring: Real-time risk assessment with configurable thresholds
🎨 Flexible Rendering System
- Multiple Ad Formats: Sponsored messages, product cards, video ads, and custom formats
- Plugin Architecture: Extensible format handlers with lifecycle management
- DOM Integration: Safe HTML injection with sanitization and CSP compliance
- Event Tracking: Comprehensive impression, click, and conversion analytics
📦 Installation
NPM/Yarn
# NPM
npm install @itsmarathon/eqcadt-web-sdk
# Yarn
yarn add @itsmarathon/eqcadt-web-sdk
# PNPM
pnpm add @itsmarathon/eqcadt-web-sdkCDN
<!-- ES Modules -->
<script type="module">
import { ConversationalAdSDK } from 'https://unpkg.com/@itsmarathon/eqcadt-web-sdk@latest/dist/index.esm.js';
</script>
<!-- UMD (Global) -->
<script src="https://unpkg.com/@itsmarathon/eqcadt-web-sdk@latest/dist/index.umd.js"></script>
<script>
const { ConversationalAdSDK } = window.ConversationalAdSDK;
</script>🚀 Quick Start
Basic Integration
import { ConversationalAdSDK } from '@itsmarathon/eqcadt-web-sdk';
// Initialize with minimal configuration
const sdk = await ConversationalAdSDK.init({
publisherId: 'your-publisher-id',
apiEndpoint: 'https://your-cssp-server.com',
debug: true
});
// Attach to chat container
const chatContainer = document.getElementById('chat');
sdk.attachToChat(chatContainer);
// Process conversations
const result = await sdk.processConversation('I need help booking a flight to Paris');
console.log('Intent detected:', result.intent, 'Confidence:', result.confidence);Advanced Commerce Configuration
const sdk = await ConversationalAdSDK.init({
publisherId: 'your-publisher-id',
apiEndpoint: 'https://api.example.com',
// Commerce orchestration
commerce: {
enabled: true,
strategy: 'balanced', // or 'internal-first', 'external-first', 'custom'
providers: {
internal: {
endpoint: 'https://your-inventory-api.com',
timeout: 2000,
auth: { type: 'api-key', apiKey: 'your-key' }
},
external: {
enabled: true,
maxPercentage: 0.4 // 40% external, 60% internal
}
},
// Business rules for filtering
rules: {
inventory: { excludeOutOfStock: true, minimumStock: 5 },
pricing: { maxPrice: 1000, minimumDiscountPercent: 10 },
quality: { minimumRelevanceScore: 0.6, maxPerCategory: 3 }
}
},
// Privacy configuration
privacy: {
enableConsent: true,
gdprApplies: true,
consentString: 'your-tcf-consent-string'
},
// Fraud detection
fraudDetection: {
enabled: true,
riskThreshold: 0.75,
collectBehavioral: true,
collectEnvironment: true
}
});🏗️ Architecture Overview
System Design
┌─────────────────────────────────────────────────────────────┐
│ ConversationalAdSDK │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Context Layer │ │ Commerce Layer │ │ Rendering Layer│ │
│ │ • Context Buffer│ │ • Orchestrator │ │ • Ad Pipeline │ │
│ │ • Decision Eng. │ │ • Providers │ │ • Format Handler│ │
│ │ • Conv. Listener│ │ • Business Rules│ │ • Custom Renders│ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │ │ │ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Core Layer │ │ Privacy Layer │ │ Detection Layer │ │
│ │ • Intent Engine │ │ • Consent Mgmt │ │ • Fraud Analysis│ │
│ │ • Model Provider│ │ • DSAR Handler │ │ • Signal Collect│ │
│ │ • Event System │ │ • Privacy Module│ │ • Risk Calc │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │ │ │ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Infrastructure │ │ Utilities │ │ Configuration │ │
│ │ • DI Container │ │ • Logger │ │ • Config Loader │ │
│ │ • Lifecycle Mgr │ │ • Cache/Storage │ │ • Business Rules│ │
│ │ • Error Handling│ │ • Performance │ │ • Validation │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘Data Flow
User Message → Context Listener → Intent Engine (WASM/ML)
↓
Decision Engine ← Fraud Detection → Risk Assessment
↓
Commerce Orchestrator → [Internal Providers | External Providers]
↓
Blending Strategies → Business Rules Engine → Ad Rendering Pipeline
↓
Final Ad Output📁 Project Structure
packages/web-sdk/
├── src/
│ ├── core/ # Core infrastructure
│ │ ├── container.ts # Dependency injection
│ │ ├── event-emitter.ts # Type-safe event system
│ │ ├── errors.ts # Hierarchical error handling
│ │ ├── lifecycle-manager.ts # Component lifecycle
│ │ └── model-provider/ # ML model management
│ │
│ ├── context/ # Context management
│ │ ├── context-buffer.ts # Conversation context
│ │ ├── decision-engine.ts # Ad placement decisions
│ │ ├── contextualization.ts # Context enrichment
│ │ └── conversation-listener.ts
│ │
│ ├── commerce/ # Commerce orchestration
│ │ ├── orchestration/ # Core orchestration logic
│ │ │ ├── commerce-orchestrator.ts
│ │ │ ├── blending-strategies.ts
│ │ │ └── business-rules-engine.ts
│ │ └── providers/ # Recommendation providers
│ │ ├── base-provider.ts
│ │ ├── rest-inventory-provider.ts
│ │ └── external-ad-provider.ts
│ │
│ ├── modules/ # Feature modules
│ │ ├── intent-engine-wasm.ts # WebAssembly ML engine
│ │ ├── privacy/ # Privacy management
│ │ ├── fraud-detection/ # Fraud prevention
│ │ ├── http-cssp-client.ts # cSSP communication
│ │ └── mock-cssp-client.ts # Testing client
│ │
│ ├── rendering/ # Ad rendering system
│ │ ├── ad-rendering-pipeline.ts
│ │ ├── format-handlers/ # Ad format implementations
│ │ └── base-format-handler.ts
│ │
│ ├── types/ # TypeScript definitions
│ │ ├── core.ts # Core types
│ │ ├── events.ts # Event types
│ │ └── commerce.ts # Commerce types
│ │
│ ├── utils/ # Utility functions
│ │ ├── dom.ts # DOM manipulation
│ │ ├── performance.ts # Performance monitoring
│ │ ├── cache.ts # Caching utilities
│ │ └── logger.ts # Logging system
│ │
│ ├── config/ # Configuration management
│ │ └── business-rules.ts # Business rules definitions
│ │
│ ├── sdk.ts # Main SDK class
│ └── index.ts # Public API exports
│
├── tests/ # Test suite
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ │ ├── dom/ # DOM environment tests
│ │ ├── http/ # HTTP integration tests
│ │ └── onnx/ # ML model tests
│ ├── helpers/ # Test utilities
│ └── setup/ # Test environment setup
│
├── docs/ # Documentation
│ ├── USER_GUIDE.md # User integration guide
│ ├── DEVELOPER_GUIDE.md # Technical documentation
│ └── README.md # Documentation index
│
├── dist/ # Build output
├── wasm/ # WebAssembly assets
├── jest.unified.config.js # Multi-environment Jest config
├── vite.config.ts # Vite build configuration
└── package.json # Package metadata🧪 Testing
Test Architecture
The SDK uses a comprehensive multi-environment testing strategy:
# Run all test environments (4,413+ tests)
npm run test:all
# Individual test environments
npm run test:unit # Unit tests (jsdom)
npm run test:integration # All integration tests
npm run test:integration:dom # DOM integration tests
npm run test:integration:http # HTTP integration tests
npm run test:integration:onnx # ML model tests
# Development testing
npm run test:watch # Watch mode
npm run test:coverage # Coverage reportTest Environment Configuration
// jest.unified.config.js
module.exports = {
projects: [
{
displayName: 'unit-tests',
testEnvironment: 'jsdom',
testMatch: ['<rootDir>/tests/unit/**/*.test.ts']
},
{
displayName: 'integration-dom',
testEnvironment: 'jsdom',
testMatch: ['<rootDir>/tests/integration/dom/**/*.test.ts']
},
{
displayName: 'integration-http',
testEnvironment: 'node',
testMatch: ['<rootDir>/tests/integration/http/**/*.test.ts']
},
{
displayName: 'integration-onnx',
testEnvironment: 'node',
testMatch: ['<rootDir>/tests/integration/onnx/**/*.test.ts'],
maxWorkers: 1 // Sequential for memory management
}
]
};🔧 Development
Setup
# Clone and install dependencies
git clone <repository>
cd eqcadt-sdk/packages/web-sdk
npm install
# Development server
npm run dev
# Build for production
npm run build
# Type checking
npm run typecheck
# Linting
npm run lint
npm run lint:fixBuild Configuration
The SDK uses Vite for optimized builds with multiple output formats:
// vite.config.ts
export default defineConfig({
build: {
lib: {
entry: resolve(__dirname, 'src/index.ts'),
name: 'ConversationalAdSDK',
formats: ['es', 'cjs', 'umd']
},
rollupOptions: {
external: ['onnxruntime-web'],
output: {
globals: { 'onnxruntime-web': 'ort' }
}
},
target: 'es2020',
minify: 'esbuild',
sourcemap: true
}
});📊 Performance Metrics
Benchmark Results
| Operation | Average Time | P95 Time | Memory Usage |
|-----------|-------------|----------|-------------|
| SDK Initialization | 150ms | 250ms | 12MB |
| Intent Classification | 45ms | 85ms | 8MB |
| Commerce Orchestration | 120ms | 200ms | 6MB |
| Ad Rendering | 25ms | 50ms | 4MB |
Testing Scale
- 4,413+ Tests across 55 test files
- Multi-Environment Coverage: Unit, DOM, HTTP, and ONNX integration
- Isolated Mock Servers for reliable integration testing
- Memory Management with automatic garbage collection
- Performance Profiling with detailed metrics collection
🔐 Security & Privacy
Privacy Safeguards
- On-Device Processing: All ML inference happens locally
- Data Minimization: Only intent classifications transmitted
- Consent Management: IAB TCF 2.2 compliant
- Input Sanitization: All user inputs validated and sanitized
- CSP Compliance: Compatible with strict Content Security Policies
Fraud Protection
- Behavioral Analysis: Mouse, keyboard, and scroll patterns
- Environmental Signals: Device and browser fingerprinting
- Viewability Metrics: Ad visibility and engagement tracking
- Risk Scoring: Real-time fraud risk assessment
- Pattern Detection: Anomaly detection for suspicious behavior
🌐 Browser Support
| Browser | Version | Support Level | Notes | |---------|---------|---------------|-------| | Chrome | 88+ | ✅ Full | Recommended | | Firefox | 85+ | ✅ Full | WebAssembly optimized | | Safari | 14+ | ✅ Full | iOS 14+ required | | Edge | 88+ | ✅ Full | Chromium-based | | Opera | 74+ | ✅ Full | Chromium-based |
Requirements: WebAssembly, IntersectionObserver, Web Workers
📚 Documentation
Complete Guides
- 📖 User Guide: Integration and configuration guide
- 🔧 Developer Guide: Technical architecture and development
- 📚 Documentation Index: Complete documentation overview
API Reference
- TypeScript Definitions: Complete type definitions
- Module Documentation: Individual module documentation
- Configuration Reference: Complete configuration options
🎯 Key APIs
Core SDK
// SDK initialization and lifecycle
ConversationalAdSDK.init(config: SDKOptions): Promise<ConversationalAdSDK>
sdk.attachToChat(container: HTMLElement): void
sdk.processConversation(message: string): Promise<EnrichedIntent>
sdk.cleanup(): Promise<void>Commerce Orchestration
// Commerce configuration and orchestration
CommerceOrchestrator.orchestrate(intent, context, providers): Promise<OrchestrationResult>
RESTInventoryProvider.getRecommendations(intent, context): Promise<Recommendation[]>
applyBlendingStrategy(internal, external, strategy): Promise<Recommendation[]>Privacy & Security
// Privacy and consent management
PrivacyModule.updateConsent(consentString: string): Promise<void>
FraudDetectionModule.analyzeRisk(signals: FraudSignals): Promise<RiskScore>
ConsentManager.handleDSAR(request: DSARRequest): Promise<DSARResponse>Event System
// Type-safe event handling
sdk.on('intent:classified', (data) => { /* handle intent */ });
sdk.on('commerce:recommendation:received', (data) => { /* handle recs */ });
sdk.on('fraud:risk:detected', (data) => { /* handle fraud */ });🚢 Release Information
- Current Version: 0.2.2
- Release Date: July 28, 2025
- Stability: Production Ready
- Breaking Changes: See CHANGELOG.md
- Migration Guide: See MIGRATION.md
Version History
- 0.2.2: Commerce orchestration enhancements, fraud detection improvements
- 0.2.1: Multi-environment testing, performance optimizations
- 0.2.0: Major commerce refactoring, provider system redesign
- 0.1.x: Initial privacy-first implementation, basic ad serving
🤝 Contributing
We welcome contributions! Please see our Contributing Guidelines for:
- Code style and standards
- Testing requirements
- Pull request process
- Issue reporting guidelines
- Development setup
Development Principles
- Privacy by Design: All features must maintain privacy-first principles
- Test-Driven Development: Comprehensive testing required
- Performance First: Optimize for real-time performance
- Type Safety: Comprehensive TypeScript coverage
- Modular Architecture: Maintain loose coupling between modules
📞 Support & Resources
- GitHub Repository: eqcadt-sdk
- Issues & Bugs: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: Complete Docs
- Email Support: [email protected]
📄 License
MIT License - see LICENSE file for details.
Built with privacy, performance, and developer experience in mind. The EQ CADT Web SDK represents the next generation of conversational advertising technology.
