Error monitoring and logging system for Telegram Mini Apps
npm install @ultron.studio/telescopeA comprehensive, enterprise-grade error monitoring and performance tracking system specifically designed for Telegram Mini Apps. Telescope helps you capture, track, and analyze errors in your JavaScript/TypeScript applications with advanced features including performance monitoring, session replay, offline support, and enhanced debugging capabilities.



Simply include the Telescope script with your project ID:
``html
data-environment="production"
data-debug="true">
`
That's it! Telescope will automatically:
- Initialize with your project ID
- Start monitoring for errors
- Track performance metrics
- Capture unhandled exceptions
- Send data to your Telescope backend
#### Script Tag Configuration Options
You can configure Telescope using data attributes on the script tag:
| Attribute | Description | Example |
|-----------|-------------|---------|
| data-project-id | Your Telescope project ID | data-project-id="your-project-id" |data-environment
| | Environment (production, development, staging) | data-environment="production" |data-debug
| | Enable debug mode (true/false) | data-debug="true" |data-endpoint
| | Custom Telescope backend endpoint | data-endpoint="https://your-backend.com" |
Example with all options:
`html`
data-environment="production"
data-debug="false"
data-endpoint="https://api.your-telescope.com">
`bash`
npm install @ultron.studio/telescope
`javascript
import { init, captureException } from '@ultron.studio/telescope';
const telescope = init({
dsn: 'https://your-telescope-endpoint.com/your-project-id',
environment: 'production',
performance: { enabled: true },
sessionReplay: { enabled: true },
offline: { enabled: true }
});
// Capture errors with enhanced context
captureException(new Error('Something went wrong'));
`
`bash`
npm install @ultron.studio/telescope
`html`
`html`
`javascript
import { init, captureException, captureMessage } from '@ultron.studio/telescope';
// Initialize Telescope
const telescope = init({
dsn: 'https://your-telescope-endpoint.com/your-project-id',
environment: 'production',
debug: true
});
// Capture an error
try {
// Your code here
throw new Error('Something went wrong!');
} catch (error) {
captureException(error);
}
// Capture a custom message
captureMessage('User performed important action', 'info');
`
`javascript
import { init } from '@ultron.studio/telescope';
const telescope = init({
dsn: 'https://ingest.telescope.dev/project-id',
environment: 'production',
release: '1.0.0',
debug: false,
maxBreadcrumbs: 100,
sampleRate: 1.0,
// Enhanced stack traces
stackTrace: {
sourceMaps: true,
offline: false,
maxDepth: 50
},
// Performance monitoring
performance: {
enabled: true,
webVitals: true,
resourceTiming: true,
memoryUsage: true
},
// Session replay
sessionReplay: {
enabled: false,
maxDuration: 300000, // 5 minutes
maxEvents: 1000,
privacy: {
maskText: true,
maskInputs: true,
blockUrls: [],
blockSelectors: []
}
},
// Offline support
offline: {
enabled: true,
maxQueueSize: 100,
maxRetries: 3,
retryDelay: 1000
},
// Advanced sampling configuration (disabled by default)
sampling: {
enabled: false, // Set to true to enable sampling
baseRate: 1.0, // Base sampling rate (0.0 to 1.0)
levelRates: {
fatal: 1.0, // Always sample fatal errors
error: 1.0, // Always sample errors
warning: 0.5, // 50% of warnings
info: 0.1, // 10% of info messages
debug: 0.01 // 1% of debug messages
},
userSampling: {
enabled: false,
newUserBoost: 1.5, // Boost sampling for new users
newUserThreshold: 10 // First 10 errors per user
},
timeSampling: {
enabled: false,
businessHoursMultiplier: 1.2, // Boost during business hours
businessHoursStart: 9, // 9 AM
businessHoursEnd: 17 // 5 PM
},
rateLimiting: {
enabled: false,
maxEventsPerMinute: 100 // Rate limit per minute
}
},
beforeSend: (event) => {
// Filter or modify events before sending
if (event.exception?.values?.[0]?.value?.includes('ignore')) {
return null; // Don't send this event
}
return event;
},
beforeBreadcrumb: (breadcrumb) => {
// Filter or modify breadcrumbs
return breadcrumb;
}
});
`
#### init(config: TelescopeConfig): Telescope
Initialize Telescope with the given configuration.
Parameters:
- config.dsn (string): Your Telescope DSN endpointconfig.environment
- (string, optional): Environment name (default: 'production')config.release
- (string, optional): Release versionconfig.debug
- (boolean, optional): Enable debug logging (default: false)config.maxBreadcrumbs
- (number, optional): Maximum breadcrumbs to store (default: 50)config.sampleRate
- (number, optional): Legacy sampling rate 0-1 (default: 1.0)config.sampling
- (object, optional): Advanced sampling configuration (disabled by default)config.sampling.enabled
- (boolean): Enable advanced sampling (default: false)config.sampling.baseRate
- (number): Base sampling rate 0-1 (default: 1.0)config.sampling.levelRates
- (object): Per-level sampling ratesconfig.sampling.userSampling
- (object): User-based sampling settingsconfig.sampling.timeSampling
- (object): Time-based sampling settingsconfig.sampling.rateLimiting
- (object): Rate limiting settingsconfig.beforeSend
- (function, optional): Event filter functionconfig.beforeBreadcrumb
- (function, optional): Breadcrumb filter function
#### captureException(error: Error, context?: Partial
Capture a JavaScript error with full stack trace.
`javascript`
try {
// Your code
} catch (error) {
captureException(error, {
tags: { component: 'user-auth' },
extra: { userId: '12345' }
});
}
#### captureMessage(message: string, level?: LogLevel, context?: Partial
Capture a custom message.
`javascript`
captureMessage('User logged in successfully', 'info');
captureMessage('API request failed', 'warning', {
tags: { endpoint: '/api/users' }
});
#### addBreadcrumb(breadcrumb: Breadcrumb): void
Add a breadcrumb to track user actions.
`javascript`
addBreadcrumb({
type: 'user',
category: 'auth',
message: 'User clicked login button',
data: { buttonId: 'login-btn' }
});
#### setUser(user: User): void
Set user information for context.
`javascript`
setUser({
id: '12345',
username: 'john_doe',
email: 'john@example.com'
});
#### setTag(key: string, value: string): void
Set a tag for filtering and grouping.
`javascript`
setTag('environment', 'staging');
setTag('version', '1.2.3');
#### setContext(key: string, context: any): void
Set custom context data.
`javascript`
setContext('custom', {
feature: 'new-checkout',
experiment: 'variant-a'
});
Telescope provides sophisticated client-side sampling capabilities similar to Sentry, allowing you to control which errors are captured and sent to your backend.
#### Sampling Configuration
`javascript
import { init } from '@ultron.studio/telescope';
const telescope = init({
dsn: 'https://your-telescope-endpoint.com/your-project-id',
sampling: {
enabled: true, // Enable advanced sampling
baseRate: 0.5, // 50% base sampling rate
// Per-level sampling rates
levelRates: {
fatal: 1.0, // Always sample fatal errors
error: 1.0, // Always sample errors
warning: 0.5, // 50% of warnings
info: 0.1, // 10% of info messages
debug: 0.01 // 1% of debug messages
},
// User-based sampling
userSampling: {
enabled: true,
newUserBoost: 1.5, // 50% boost for new users
newUserThreshold: 10 // First 10 errors per user
},
// Time-based sampling
timeSampling: {
enabled: true,
businessHoursMultiplier: 1.2, // 20% boost during business hours
businessHoursStart: 9, // 9 AM
businessHoursEnd: 17 // 5 PM
},
// Rate limiting
rateLimiting: {
enabled: true,
maxEventsPerMinute: 50 // Max 50 events per minute
}
}
});
`
#### Sampling Statistics
`javascript
import { getSamplingStats } from '@ultron.studio/telescope';
// Get current sampling statistics
const stats = getSamplingStats();
console.log('Sampled events:', stats.sampled);
console.log('Dropped events:', stats.dropped);
console.log('Effective rate:', stats.effectiveRate);
`
#### Sampling Decision Reasons
When sampling is enabled, you can see why events were sampled or dropped:
`javascript
// Enable debug mode to see sampling decisions
const telescope = init({
dsn: 'your-dsn',
debug: true,
sampling: {
enabled: true,
baseRate: 0.5
}
});
// This will log sampling decisions to console:
// [Telescope] Error sampled out: rate_limit (rate: 0.0)
// [Telescope] Error sampled: random (rate: 0.5)
`
#### getPerformanceMetrics(): PerformanceMetrics
Get current performance metrics including Web Vitals.
`javascript`
const metrics = getPerformanceMetrics();
console.log('LCP:', metrics.lcp);
console.log('FID:', metrics.fid);
console.log('CLS:', metrics.cls);
#### measurePerformance
Measure the execution time of a function.
`javascript`
const result = measurePerformance('data-processing', () => {
// Your expensive operation
return processLargeDataset(data);
});
#### measurePerformanceAsync
Measure the execution time of an async function.
`javascript`
const result = await measurePerformanceAsync('api-call', async () => {
return await fetch('/api/data');
});
#### markPerformance(name: string): void
Mark a performance milestone.
`javascript`
markPerformance('user-interaction-start');
// ... some operation
const duration = measureBetween('user-interaction-start', 'user-interaction-end');
#### startSessionReplay(): void
Start recording user interactions.
`javascript`
startSessionReplay();
#### stopSessionReplay(): void
Stop recording user interactions.
`javascript`
stopSessionReplay();
#### getSessionEvents(): SessionEvent[]
Get recorded session events.
`javascript`
const events = getSessionEvents();
console.log('Recorded events:', events);
#### isOffline(): boolean
Check if the application is currently offline.
`javascript`
if (isOffline()) {
console.log('App is offline, errors will be queued');
}
#### getOfflineQueueSize(): number
Get the number of events in the offline queue.
`javascript${queueSize} events queued for sync
const queueSize = getOfflineQueueSize();
console.log();`
#### processOfflineQueue(): Promise
Manually process the offline queue.
`javascript`
await processOfflineQueue();
console.log('Offline queue processed');
#### Enhanced Stack Traces
Telescope automatically captures enhanced stack traces with:
- Source code context
- Function arguments (sanitized)
- Module information
- Source map support
`javascript`
// Errors automatically include enhanced context
try {
throw new Error('Something went wrong');
} catch (error) {
captureException(error); // Enhanced stack trace included
}
Telescope works with any JavaScript framework or vanilla JavaScript. Here are some integration examples:
#### Vanilla JavaScript
`javascript
// Global error handling
window.addEventListener('error', (event) => {
captureException(event.error);
});
// Performance monitoring
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
measurePerformance(entry.name, entry.duration);
}
});
observer.observe({ entryTypes: ['measure', 'navigation'] });
`
#### Vue.js Integration
`javascript`
// In your Vue app
app.config.errorHandler = (err, instance, info) => {
captureException(err, {
extra: { component: instance?.$options.name, info }
});
};
#### Angular Integration
`javascript
// In your Angular app
import { ErrorHandler } from '@angular/core';
export class TelescopeErrorHandler implements ErrorHandler {
handleError(error: any): void {
captureException(error);
}
}
`
Telescope automatically detects and captures Telegram Mini App context:
`javascript`
// Telescope automatically detects:
// - Telegram WebApp version
// - Platform information
// - User data from initData
// - Mini app specific context
// - Performance metrics
// - User interactions
// - Network conditions
`bashInstall dependencies
npm install
$3
`bash
Run all tests
npm testRun tests with coverage
npm run test -- --coverageRun specific test file
npm test -- telescope.test.ts
`Demo
$3
Open demo/index.html in your browser to see the basic Telescope features:- Error triggering buttons
- Console output showing captured errors
- Breadcrumb tracking
- User context management
$3
Open demo/enhanced-demo.html` in your browser to see all advanced features:- Real-time Performance Metrics: Live Web Vitals display (LCP, FID, CLS, FCP)
- Interactive Error Testing: Various error types with enhanced stack traces
- Session Replay Controls: Start/stop recording with event tracking
- Offline Simulation: Test offline queuing and automatic sync
- Breadcrumb Testing: User action and navigation tracking
- Advanced Features: Error filtering, context collection, and sampling
- Status Indicators: Connection status, recording status, and queue size
- Performance Monitoring: Custom measurements and Web Vitals tracking
- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+
MIT License - see LICENSE file for details.
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request