@achado/core
v0.0.2
Published
Core SDK functionality for Achado analytics platform
Downloads
18
Readme
@achado/core
⚠️ Internal Package: This package contains the internal infrastructure for Achado analytics. Most users should use @achado/client instead, which provides a cleaner consumer-facing API.
The core SDK for Achado analytics platform, providing foundational functionality for event tracking, user management, and data collection.
For End Users
Recommended: Use @achado/client package instead:
npm install @achado/clientSee the client package documentation for the recommended API.
For Advanced Users & Internal Use
If you need direct access to internal components:
npm install @achado/coreDirect Usage
import { AchadoClient } from '@achado/core';
const client = new AchadoClient({
apiKey: 'your-api-key',
debug: true,
});
await client.initialize();
// Track an event
client.track('button_clicked', {
buttonId: 'signup',
location: 'header',
});
// Identify a user
client.identify('user-123', {
name: 'John Doe',
email: '[email protected]',
});Package Architecture
This package serves as the internal infrastructure layer (similar to 's client-core):
- @achado/client: Consumer-facing API (recommended for end users)
- @achado/core: Internal infrastructure (this package)
The client package re-exports the necessary APIs from core while providing additional convenience functions.
Configuration
AchadoConfig
interface AchadoConfig {
apiKey: string; // Required: Your API key
apiEndpoint?: string; // API endpoint (default: production)
debug?: boolean; // Enable debug logging
userId?: string; // Initial user ID
sessionId?: string; // Custom session ID
enableTracking?: boolean; // Enable/disable tracking
enableSessionReplay?: boolean; // Enable session replay
enableFeatureTracking?: boolean; // Enable feature tracking
customProperties?: Record<string, any>; // Global properties
}API Reference
AchadoClient
Constructor
new AchadoClient(config: AchadoConfig)Methods
initialize(): Promise<void>
Initialize the client and start tracking.
track(eventName: string, properties?: Record<string, any>): void
Track a custom event.
client.track('purchase_completed', {
productId: 'prod-123',
price: 29.99,
currency: 'USD',
});identify(userId: string, traits?: Record<string, any>): void
Identify a user with optional traits.
client.identify('user-123', {
name: 'John Doe',
email: '[email protected]',
plan: 'premium',
});setUserProperties(properties: Record<string, any>): void
Update user properties.
client.setUserProperties({
lastLogin: new Date().toISOString(),
loginCount: 42,
});getUser(): AchadoUser
Get current user information.
getConfig(): AchadoConfig
Get current configuration.
flush(): Promise<void>
Manually flush the event queue.
reset(): void
Reset the client state (clears user data).
destroy(): void
Clean up and stop the client.
Event Queue
The core includes an intelligent event queue that:
- Batches Events: Collects events for efficient transmission
- Auto-Flush: Sends events based on size or time thresholds
- Retry Logic: Handles network failures gracefully
- Background Processing: Non-blocking event processing
// Events are automatically queued and sent
client.track('event1', { data: 'value1' });
client.track('event2', { data: 'value2' });
// Batch will be sent automaticallyStorage
Browser Storage
import { BrowserStorageAdapter } from '@achado/core';
// Use localStorage (default)
const storage = new BrowserStorageAdapter(false);
// Use sessionStorage
const sessionStorage = new BrowserStorageAdapter(true);Memory Storage
import { MemoryStorageAdapter } from '@achado/core';
const storage = new MemoryStorageAdapter();Custom Storage
import { StorageAdapter } from '@achado/core';
class CustomStorage implements StorageAdapter {
getItem(key: string): string | null {
// Your implementation
}
setItem(key: string, value: string): void {
// Your implementation
}
removeItem(key: string): void {
// Your implementation
}
}Utilities
ID Generation
import {
generateId,
generateSessionId,
generateAnonymousId,
} from '@achado/core';
const eventId = generateId(); // UUID v4
const sessionId = generateSessionId(); // session_timestamp_random
const anonId = generateAnonymousId(); // anon_uuidPage Metadata
import { getPageMetadata } from '@achado/core';
const metadata = getPageMetadata();
// Returns: { url, referrer, title, userAgent, viewport, screen }Utility Functions
import { debounce, throttle, deepMerge } from '@achado/core';
// Debounce function calls
const debouncedFunction = debounce(myFunction, 250);
// Throttle function calls
const throttledFunction = throttle(myFunction, 1000);
// Deep merge objects
const merged = deepMerge(target, source);Logger
import { AchadoLogger } from '@achado/core';
const logger = new AchadoLogger(true); // debug enabled
logger.debug('Debug message', { data: 'value' });
logger.info('Info message');
logger.warn('Warning message');
logger.error('Error message', error);Data Flow
- Event Creation: Events are created with metadata
- Queue Addition: Events are added to the internal queue
- Batching: Queue collects events until flush conditions are met
- Transmission: Batched events are sent to the API
- Storage: User state is persisted locally
Error Handling
The core SDK handles errors gracefully:
- Network Errors: Events are retried with exponential backoff
- Storage Errors: Fallback to memory storage
- API Errors: Logged and events are preserved for retry
Performance
- Minimal Bundle Size: Core functionality only
- Lazy Loading: Optional features loaded on demand
- Efficient Queuing: Batched network requests
- Memory Management: Automatic cleanup of old events
Browser Support
- Chrome 70+
- Firefox 65+
- Safari 12+
- Edge 79+
TypeScript
Full TypeScript support with comprehensive type definitions.
import type { AchadoEvent, AchadoUser, AchadoConfig } from '@achado/core';