UNPKG

eventify-sdk

Version:

High-performance JavaScript/TypeScript SDK for Eventify analytics platform with fire-and-forget event sending and smart connection management

343 lines (265 loc) • 9.85 kB
# Eventify JavaScript SDK [![npm version](https://img.shields.io/npm/v/eventify-sdk.svg)](https://www.npmjs.com/package/eventify-sdk) [![license](https://img.shields.io/npm/l/eventify-sdk.svg)](https://github.com/amrrdev/eventify-sdk/blob/main/LICENSE) High-performance JavaScript/TypeScript SDK for the Eventify analytics platform. Built with gRPC streaming for maximum throughput and minimal latency. ## Features - šŸš€ **High Performance**: gRPC streaming with <10ms latency - šŸ“Š **Real-time Analytics**: Direct connection to Eventify backend - šŸ”’ **Type Safe**: Full TypeScript support with detailed type definitions - šŸ”„ **Auto-Reconnection**: Intelligent reconnection with exponential backoff - ⚔ **Fast**: Binary serialization via Protocol Buffers - šŸ›”ļø **Reliable**: Built-in retry mechanisms and error handling - šŸ”§ **Easy to Use**: Simple, intuitive API ## Installation ```bash npm install eventify-sdk ``` ## Quick Start ```javascript const eventify = require('eventify-sdk'); // Initialize the SDK (connects immediately) await eventify.init('your-api-key'); // Send events (fire-and-forget - no await needed!) eventify.event({ eventName: 'user_action', payload: { action: 'click' }, category: 'user', severity: 'INFO', tags: ['ui', 'interaction'], timestamp: '2025-01-01T00:00:00Z' // Optional - auto-generated if not provided }); // Send multiple events instantly for (let i = 0; i < 100; i++) { eventify.event({ eventName: 'batch_event', payload: { index: i }, category: 'analytics', severity: 'INFO', tags: ['batch'] }); } // All events queued instantly! // Check connection status if (eventify.isOnline()) { console.log('Connected to Eventify!'); } ``` ## API Reference ### `init(apiKey, config?)` Initialize the SDK with your API key and optional configuration. ```typescript await eventify.init('evntfy_user_abc123...', { host: 'api.evntfy.tech:4000', // Optional: gRPC server endpoint secure: true, // Optional: use TLS (default: true) timeout: 30000, // Optional: connection timeout (ms) maxRetries: 3, // Optional: max retry attempts retryDelay: 1000 // Optional: retry delay (ms) }); ``` **Parameters:** - `apiKey` (string): Your Eventify API key - `config` (object, optional): Configuration options ### `event(eventData)` Send an event to the Eventify platform (fire-and-forget). ```typescript // Fire-and-forget - returns immediately eventify.event({ eventName: 'purchase', // REQUIRED: Event identifier payload: { // REQUIRED: Event data (any object) userId: '12345', amount: 99.99, currency: 'USD' }, category: 'ecommerce', // REQUIRED: Event category severity: 'INFO', // REQUIRED: 'INFO' | 'WARN' | 'ERROR' tags: ['conversion', 'revenue'], // REQUIRED: Array of tags timestamp: '2025-01-01T00:00:00Z' // OPTIONAL: ISO 8601 timestamp }); ``` **Parameters:** - `eventData` (object): Event data with all required fields **Returns:** `void` - Events are processed asynchronously in the background ### `isOnline()` Check if the SDK is connected to Eventify. ```typescript const connected = eventify.isOnline(); console.log('Status:', connected ? 'ONLINE' : 'OFFLINE'); ``` **Returns:** `boolean` - Connection status ### `disconnect()` Disconnect from Eventify (cleanup). ```typescript await eventify.disconnect(); ``` ## Event Data Structure All events must include the following fields: | Field | Type | Required | Description | |-------|------|----------|-------------| | `eventName` | string | āœ… | Event identifier | | `payload` | any | āœ… | Event data (will be JSON stringified) | | `category` | string | āœ… | Event category for grouping | | `severity` | 'INFO' \| 'WARN' \| 'ERROR' | āœ… | Event severity level | | `tags` | string[] | āœ… | Array of tags for filtering | | `timestamp` | string | āŒ | ISO 8601 timestamp (auto-generated if omitted) | ## Usage Examples ### Basic Event Tracking ```javascript const eventify = require('eventify-sdk'); await eventify.init('your-api-key'); // Track user actions await eventify.event({ eventName: 'button_click', payload: { buttonId: 'signup-cta', page: '/landing' }, category: 'user-interaction', severity: 'INFO', tags: ['ui', 'conversion'] }); ``` ### E-commerce Tracking ```javascript // Track purchases await eventify.event({ eventName: 'purchase_completed', payload: { orderId: 'order_123', userId: 'user_456', items: [ { productId: 'prod_1', price: 29.99 }, { productId: 'prod_2', price: 19.99 } ], total: 49.98, currency: 'USD' }, category: 'ecommerce', severity: 'INFO', tags: ['purchase', 'revenue', 'conversion'] }); ``` ### Error Tracking ```javascript // Track errors await eventify.event({ eventName: 'api_error', payload: { endpoint: '/api/users', method: 'POST', statusCode: 500, error: 'Internal server error', stack: error.stack }, category: 'error', severity: 'ERROR', tags: ['api', 'backend', 'critical'] }); ``` ### High-Volume Analytics ```javascript // Send multiple events efficiently const events = [ { eventName: 'page_view', payload: { page: '/home' } }, { eventName: 'page_view', payload: { page: '/about' } }, { eventName: 'page_view', payload: { page: '/contact' } } ]; // Events are sent immediately via streaming (no batching needed) await Promise.all(events.map(eventData => eventify.event({ ...eventData, category: 'analytics', severity: 'INFO', tags: ['navigation'] }) )); ``` ## TypeScript Support The SDK is written in TypeScript and provides full type definitions. ```typescript import { init, event, isOnline, EventData } from 'eventify-sdk'; const eventData: EventData = { eventName: 'user_signup', payload: { userId: '123', plan: 'premium' }, category: 'user', severity: 'INFO', tags: ['signup', 'premium'] }; await init('your-api-key'); await event(eventData); ``` ## Error Handling The SDK provides detailed error information: ```javascript import { EventifyError, ErrorCode } from 'eventify-sdk'; try { await eventify.event({ eventName: 'test_event', payload: { test: true }, category: 'test', severity: 'INFO', tags: ['test'] }); } catch (error) { if (error instanceof EventifyError) { console.log('Error code:', error.code); console.log('Error message:', error.message); if (error.code === ErrorCode.RATE_LIMIT_EXCEEDED) { console.log('Rate limit exceeded - please wait'); } } } ``` ## Configuration Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `host` | string | `'api.evntfy.tech:4000'` | gRPC server endpoint | | `secure` | boolean | `true` | Use TLS for secure communication | | `timeout` | number | `30000` | Connection timeout in milliseconds | | `maxRetries` | number | `3` | Maximum retry attempts on failure | | `retryDelay` | number | `1000` | Delay between retries in milliseconds | ## Performance The Eventify SDK is optimized for high performance: - **Latency**: <10ms average event processing - **Throughput**: 10,000+ events/second per instance - **Memory**: <50MB memory usage under normal load - **Binary Protocol**: Protocol Buffers for efficient serialization - **Streaming**: Persistent gRPC connections for minimal overhead ## Architecture The SDK uses gRPC streaming for optimal performance: ``` Your App → SDK → gRPC Stream → api.evntfy.tech:4000 → Eventify Backend ``` - **No batching**: Events are sent immediately - **Auto-reconnection**: Intelligent reconnection on failures - **Backpressure**: Handles server backpressure gracefully - **Keep-alive**: Maintains persistent connections ## Environment Support - **Node.js**: 16.0.0 or higher - **TypeScript**: Full support with type definitions - **Platforms**: Windows, macOS, Linux ## Changelog ### v1.1.0 - Improved User Experience šŸŽ‰ **Major improvements for cleaner console output and better process lifecycle:** - **šŸ“ Significantly Reduced Logging**: Much cleaner console output with minimal noise - Silent auto-reconnection attempts - Only logs large batches (≄50 events) and warnings for large queues (>100 events) - Removed verbose connection and processing logs - **šŸ”„ Smart Process Management**: Simple scripts now exit cleanly after idle timeout - Automatic process exit after 30 seconds of inactivity - No more hanging Node.js processes for fire-and-forget usage - Graceful shutdown with proper cleanup - **🤫 Silent Error Handling**: Connection failures handled quietly unless persistent - **⚔ Same Performance**: All performance optimizations and features preserved **Perfect for simple scripts and production environments where clean logs matter!** ### v1.0.0 - Initial Release - High-performance gRPC streaming - Fire-and-forget event sending - Auto-reconnection with exponential backoff - TypeScript support - Comprehensive error handling ## License MIT License - see [LICENSE](LICENSE) file for details. ## Support - šŸ“– [Documentation](https://eventify-ebon-ten.vercel.app/) - šŸ› [Issue Tracker](https://github.com/amrrdev/eventify-sdk/issues) - šŸ’¬ [Discord Community](https://discord.gg/eventify) - šŸ“§ [Email Support](mailto:support@eventify.com) --- Built with ā¤ļø by the [Eventify Team](https://eventify-ebon-ten.vercel.app/)