@syntropysoft/syntropyfront
v0.3.0
Published
π Observability library with automatic capture - Just 1 line of code! Automatically captures clicks, errors, HTTP calls, and console logs with flexible error handling.
Maintainers
Keywords
Readme
π Observability library with automatic capture - Just 1 line of code!
SyntropyFront automatically captures user interactions, errors, HTTP calls, and console logs, providing comprehensive observability for your web applications with minimal setup.
β¨ Features
- π― Automatic click capture - Tracks all user interactions
- π¨ Error detection - Catches uncaught exceptions and promise rejections
- π HTTP monitoring - Intercepts fetch calls automatically
- π Console logging - Records console.log, console.error, console.warn
- πΎ Smart storage - Keeps the last N events (configurable)
- π€ Flexible posting - Posts errors to your endpoint or logs to console
- β‘ Zero configuration - Works out of the box with just an import
π Quick Start
Basic Usage (1 line of code!)
import syntropyFront from '@syntropysoft/syntropyfront';
// That's it! Auto-initializes and captures everything automaticallyWith Custom Configuration
import syntropyFront from '@syntropysoft/syntropyfront';
// Option 1: Console only (default)
syntropyFront.configure({
maxEvents: 50
});
// Option 2: With endpoint (automatic fetch)
syntropyFront.configure({
maxEvents: 50,
fetch: {
url: 'https://your-api.com/errors',
options: {
headers: {
'Authorization': 'Bearer your-token',
'Content-Type': 'application/json'
},
mode: 'cors'
}
}
});
// Option 3: With custom error handler (maximum flexibility)
syntropyFront.configure({
maxEvents: 50,
onError: (errorPayload) => {
// You can do anything with the error:
// - Send to your API
// - Save to localStorage
// - Send to a repository
// - Upload to cloud
// - Whatever you want!
console.log('Error captured:', errorPayload);
// Example: send to multiple places
fetch('https://api1.com/errors', {
method: 'POST',
body: JSON.stringify(errorPayload)
});
// Also save locally
localStorage.setItem('lastError', JSON.stringify(errorPayload));
}
});π¦ Installation
npm install @syntropysoft/syntropyfrontπ Performance Optimizations (v0.3.0)
SyntropyFront has been optimized for maximum performance and minimal bundle size:
π― Testing Excellence
- Mutation Score: Improved from 58.14% to 74.96% (+16.82 points!)
- Test Coverage: 91.01% with 488 comprehensive tests
- Database Modules: All modules now have 77-100% mutation score
- Core Components: 92.70% average mutation score across agent modules
π¦ Ultra-Lightweight Bundle
- Only 1 Runtime Dependency:
flattedfor circular reference handling - 45+ Dependencies Removed: Eliminated unnecessary packages
- Bundle Size: 4.88 KB minified (4,884 bytes)
- ES Module: 10.9 KB
- CommonJS: 10.98 KB
- Faster Installation: Reduced npm install time and disk usage
π§ Smart Dependency Management
- Clean Architecture: All testing tools properly categorized as devDependencies
- Dependabot Optimized: Smart configuration prevents incompatible updates
- Stable CI/CD: Eliminated dependency conflicts and CI failures
- Cross-Node Compatibility: Full support for Node.js 18, 20, 22
β‘ Production Ready
- Zero Breaking Changes: All existing code continues to work
- Same API: Identical usage patterns and configuration
- Better Performance: Optimized for production environments
- Maintained Security: All security benefits preserved
π― How It Works
SyntropyFront automatically:
- Captures clicks - Records element info, coordinates, and timestamps
- Detects errors - Intercepts
window.onerrorandwindow.onunhandledrejection - Monitors HTTP - Wraps
window.fetchto track requests and responses - Logs console - Intercepts console methods to capture debug info
- Maintains context - Keeps the last N events as breadcrumbs
- Posts errors - Sends error data with full context to your endpoint
π What Gets Captured
Error Payload Structure
{
"type": "uncaught_exception",
"error": {
"message": "Error message",
"source": "file.js",
"lineno": 42,
"colno": 15,
"stack": "Error stack trace..."
},
"breadcrumbs": [
{
"category": "user",
"message": "click",
"data": {
"element": "BUTTON",
"id": "submit-btn",
"className": "btn-primary",
"x": 100,
"y": 200
},
"timestamp": "2024-01-01T12:00:00.000Z"
}
],
"timestamp": "2024-01-01T12:00:00.000Z"
}Breadcrumb Categories
user- Click events, form submissions, etc.http- Fetch requests, responses, and errorsconsole- Console.log, console.error, console.warnerror- Manual error reports
βοΈ Configuration Options
SyntropyFront uses a priority system for error handling:
- Custom Error Handler (
onError) - Maximum flexibility - Endpoint (
fetch) - Automatic posting - Console - Default fallback
Basic Configuration (Console Only)
syntropyFront.configure({
maxEvents: 50 // Number of events to keep in memory
});With Endpoint (Automatic Fetch)
syntropyFront.configure({
maxEvents: 50,
fetch: {
url: 'https://your-api.com/errors',
options: {
headers: {
'Authorization': 'Bearer your-token',
'X-API-Key': 'your-api-key',
'Content-Type': 'application/json'
},
mode: 'cors',
credentials: 'include'
}
}
});With Custom Error Handler (Maximum Flexibility)
syntropyFront.configure({
maxEvents: 50,
onError: (errorPayload) => {
// You have complete control over what to do with the error
// Send to your API
fetch('https://your-api.com/errors', {
method: 'POST',
body: JSON.stringify(errorPayload)
});
// Save to localStorage
localStorage.setItem('lastError', JSON.stringify(errorPayload));
// Send to multiple services
Promise.all([
fetch('https://service1.com/errors', { method: 'POST', body: JSON.stringify(errorPayload) }),
fetch('https://service2.com/errors', { method: 'POST', body: JSON.stringify(errorPayload) })
]);
// Upload to cloud storage
// Send to repository
// Log to file
// Whatever you want!
}
});π§ API Reference
Core Methods
// Add custom breadcrumb
syntropyFront.addBreadcrumb('user', 'Custom action', { data: 'value' });
// Send manual error
syntropyFront.sendError(new Error('Custom error'));
// Get current breadcrumbs
const breadcrumbs = syntropyFront.getBreadcrumbs();
// Clear breadcrumbs
syntropyFront.clearBreadcrumbs();
// Get statistics
const stats = syntropyFront.getStats();
// Returns: { breadcrumbs: 5, errors: 2, isActive: true, maxEvents: 50, endpoint: 'console' }π― Extending SyntropyFront
SyntropyFront captures the essentials by default, but you can extend it to capture any DOM events you want:
Adding Custom Event Capture
import syntropyFront from '@syntropysoft/syntropyfront';
// Add scroll tracking
window.addEventListener('scroll', () => {
syntropyFront.addBreadcrumb('user', 'scroll', {
scrollY: window.scrollY,
scrollX: window.scrollX
});
});
// Add form submissions
document.addEventListener('submit', (event) => {
syntropyFront.addBreadcrumb('user', 'form_submit', {
formId: event.target.id,
formAction: event.target.action
});
});
// Add window resize
window.addEventListener('resize', () => {
syntropyFront.addBreadcrumb('system', 'window_resize', {
width: window.innerWidth,
height: window.innerHeight
});
});
// Add custom business events
function trackPurchase(productId, amount) {
syntropyFront.addBreadcrumb('business', 'purchase', {
productId,
amount,
timestamp: new Date().toISOString()
});
}Common Events You Can Track
- User interactions:
click,scroll,keydown,focus,blur - Form events:
submit,input,change,reset - System events:
resize,online,offline,visibilitychange - Custom events: Any business logic or user actions
- Performance:
load,DOMContentLoaded, timing events
π CORS Configuration
To use with your API, ensure your server allows CORS:
// Express.js example
app.use(cors({
origin: 'http://localhost:3000',
credentials: true
}));
// Or in headers
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');π± Framework Support
SyntropyFront works with any JavaScript framework:
- β React - Works out of the box
- β Vue - Works out of the box
- β Angular - Works out of the box
- β Svelte - Works out of the box
- β Vanilla JS - Works out of the box
π― Examples
React Example
import React from 'react';
import syntropyFront from '@syntropysoft/syntropyfront';
function App() {
// SyntropyFront auto-initializes on import
return (
<div>
<button onClick={() => console.log('Button clicked')}>
Click me!
</button>
</div>
);
}Vue Example
<template>
<button @click="handleClick">Click me!</button>
</template>
<script>
import syntropyFront from '@syntropysoft/syntropyfront';
export default {
methods: {
handleClick() {
console.log('Button clicked');
}
}
}
</script>Manual Error Reporting
import syntropyFront from '@syntropysoft/syntropyfront';
try {
// Your code here
} catch (error) {
// SyntropyFront will automatically capture this
throw error;
}
// Or manually report
syntropyFront.sendError(new Error('Something went wrong'));Extending with Custom Events
import syntropyFront from '@syntropysoft/syntropyfront';
// Add your custom event listeners
window.addEventListener('scroll', () => {
syntropyFront.addBreadcrumb('user', 'scroll', {
scrollY: window.scrollY,
scrollX: window.scrollX
});
});
// Track business events
function userCompletedCheckout(orderId, total) {
syntropyFront.addBreadcrumb('business', 'checkout_completed', {
orderId,
total,
timestamp: new Date().toISOString()
});
}
// Track performance
window.addEventListener('load', () => {
syntropyFront.addBreadcrumb('performance', 'page_loaded', {
loadTime: performance.now()
});
});ποΈ Architecture & Code Quality
SyntropyFront follows SOLID principles and maintains high code quality through:
Modular Architecture
The codebase is organized into focused modules with single responsibilities:
src/core/
βββ agent/ # Core Agent components
β βββ Agent.js # Main coordinator
β βββ ConfigurationManager.js # Configuration handling
β βββ QueueManager.js # Batching and queuing
β βββ HttpTransport.js # HTTP communication
βββ database/ # IndexedDB management
β βββ DatabaseManager.js # Database coordinator
β βββ DatabaseConfigManager.js # Configuration
β βββ DatabaseConnectionManager.js # Connection handling
β βββ DatabaseTransactionManager.js # Transaction management
β βββ StorageManager.js # CRUD operations
β βββ SerializationManager.js # Data serialization
βββ retry/ # Retry system
β βββ RetryManager.js # Retry coordination
β βββ RetryLogicManager.js # Retry logic
βββ persistent/ # Persistent buffer
β βββ PersistentBufferManager.js # Buffer management
βββ breadcrumbs/ # Event tracking
β βββ BreadcrumbManager.js # Breadcrumb coordination
β βββ BreadcrumbStore.js # Breadcrumb storage
βββ context/ # Context collection
β βββ ContextCollector.js # Context gathering
βββ utils/ # Utilities
βββ Logger.js # Logging utilities
βββ ErrorManager.js # Error handlingDesign Principles
- Single Responsibility Principle (SRP): Each class has one clear purpose
- Dependency Injection: Components receive dependencies through constructors
- Declarative Error Handling: Structured error responses with fallbacks
- Comprehensive Testing: 488 tests with 74.96% mutation score
- Optimized Performance: Timeouts optimized for faster execution
π§ͺ Testing & Quality
SyntropyFront maintains high code quality through comprehensive testing:
Test Coverage & Mutation Testing
- Mutation Score: 74.96% - Our tests effectively detect code changes
- Test Coverage: 91.01% - Comprehensive unit test coverage
- Key Components Performance:
Agent.js: 87.23% mutation scoreConfigurationManager.js: 100% mutation scoreQueueManager.js: 97.37% mutation scoreHttpTransport.js: 86.96% mutation scoreBreadcrumbManager.js: 100% mutation scoreBreadcrumbStore.js: 95.00% mutation scoreSerializationManager.js: 100% mutation scoreDatabaseTransactionManager.js: 100% mutation scoreDatabaseConfigManager.js: 86.89% mutation scoreDatabaseConnectionManager.js: 85.96% mutation scorePersistentBufferManager.js: 77.63% mutation score
Testing Stack
- Jest: Unit testing framework
- Stryker: Mutation testing for test quality validation
- IndexedDB Mocking: Browser storage testing
- Fetch Mocking: HTTP request testing
Running Tests
# Run all tests
npm test
# Run with coverage
npm run test:coverage
# Run mutation testing
npm run test:mutationπ Debugging
SyntropyFront logs helpful information to the console:
π SyntropyFront: Initialized with automatic capture
β
SyntropyFront: Configured - maxEvents: 50, endpoint: https://your-api.com/errors
β Error: { type: "uncaught_exception", error: {...}, breadcrumbs: [...] }π License
This project is licensed under the Apache License, Version 2.0 - see the LICENSE file for details.
Apache License 2.0 - A permissive license that allows for:
- β Commercial use
- β Modification
- β Distribution
- β Patent use
- β Private use
The only requirement is that you include the original copyright notice and license text in any substantial portions of the software you distribute.
For more information, visit: https://www.apache.org/licenses/LICENSE-2.0
π€ Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Made with β€οΈ for better web observability
