# BugMail SDK - Frequently Asked Questions

## General Questions

### What is the BugMail SDK?

The BugMail SDK is a JavaScript error tracking library that automatically captures unhandled errors, promise rejections, and console errors from your web application and sends them to your BugMail backend for analysis and monitoring.

### Which browsers are supported?

The SDK supports all modern browsers:
- Chrome 60+
- Firefox 55+
- Safari 11+
- Edge 16+

For IE11 support, you'll need to include appropriate polyfills for Promise, fetch, and other modern APIs.

### Is the SDK free to use?

The SDK itself is open source and free to use. However, you need a BugMail account and backend to receive and analyze errors. Check BugMail pricing for backend hosting options.

## Installation & Setup

### How do I install the SDK?

Via npm:
```bash
npm install @bugmail-js/sdk
```

Via CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/@bugmail-js/sdk@latest/dist/bugmail.umd.js"></script>
```

### How do I get an API key?

1. Sign up for a BugMail account
2. Create a project in your dashboard
3. Copy the API key from project settings
4. Use it in your SDK initialization

### Can I use the SDK without npm?

Yes! Use the CDN version:

```html
<script>
  window.BUGMAIL_CONFIG = {
    apiKey: 'YOUR_API_KEY',
    endpoint: 'https://api.bugmail.site'
  };
</script>
<script src="https://cdn.jsdelivr.net/npm/@bugmail-js/sdk@latest/dist/bugmail.umd.js"></script>
```

## Error Filtering

### Why aren't SDK errors appearing in my dashboard?

This is intentional! The SDK automatically filters out its own internal errors to prevent infinite loops and reduce noise. SDK errors are logged to the browser console for debugging but not sent to your dashboard.

Examples of filtered errors:
- `[BugMail Network] Failed to send error: 401`
- `[BugMail] Invalid configuration`
- Any error with SDK code in the stack trace

### How do I know if my API key is invalid?

Check the browser console. You'll see:
```
[BugMail Network] Failed to send error: { status: 401, body: { detail: "Invalid API key" } }
```

This message appears once and is not captured (preventing an infinite loop).

### Can I disable error filtering?

No. Error filtering is essential to prevent infinite loops when the SDK encounters issues. However, you can:
- Enable debug mode to see what's being filtered
- Check browser console for all SDK messages
- Use browser DevTools Network tab to see failed requests

### What if my code has "bugmail" in the filename?

If your application code includes "bugmail" in filenames or paths, those errors might be filtered. To avoid this:
- Don't use "bugmail" in your application filenames
- Don't use `[BugMail` prefix in your error messages
- Avoid SDK-specific patterns in your code

### How do I filter out specific errors from my app?

Use the `beforeSend` hook:

```javascript
const bugmail = new BugMail({
  apiKey: 'YOUR_API_KEY',
  beforeSend: (error, context) => {
    // Filter out third-party errors
    if (error.stack && error.stack.includes('third-party-lib')) {
      return null;  // Don't send
    }
    
    // Filter out known issues
    if (error.message.includes('ResizeObserver loop')) {
      return null;  // Don't send
    }
    
    return error;  // Send this error
  }
});
```

## Debug Mode

### What is debug mode?

Debug mode enables detailed console logging to help you understand what the SDK is doing:

```javascript
const bugmail = new BugMail({
  apiKey: 'YOUR_API_KEY',
  debug: true
});
```

### What information does debug mode show?

- Which errors are being filtered and why
- Network requests and responses
- Retry attempts
- Configuration issues
- Internal SDK operations

Example output:
```
[BugMail] Initialized with config: { apiKey: "proj_...", endpoint: "..." }
[BugMail Filter] Filtered: SDK pattern in message
[BugMail Network] Sending error to backend...
[BugMail Network] Response: 201 Created
```

### Should I use debug mode in production?

No. Debug mode is for development only. It:
- Logs sensitive information to console
- May impact performance slightly
- Exposes internal SDK operations

Always disable debug mode in production:
```javascript
const bugmail = new BugMail({
  apiKey: 'YOUR_API_KEY',
  debug: process.env.NODE_ENV === 'development'
});
```

## Network & Connectivity

### What happens if the network is down?

The SDK handles network failures gracefully:
1. Error is captured locally
2. SDK attempts to send to backend
3. Network request fails
4. SDK logs failure to console
5. Error is stored offline (if configured)
6. SDK retries when network is restored

Network errors are NOT captured as new errors (preventing loops).

### Does the SDK retry failed requests?

Yes, but only for server errors (5xx):
- 4xx errors (client errors) are NOT retried
- 5xx errors are retried up to 3 times
- Exponential backoff between retries
- Network errors are retried when connectivity is restored

### Can I change the retry behavior?

Currently, retry behavior is built-in and cannot be customized. If you need different retry logic, please file a feature request on GitHub.

### What if my backend is slow?

The SDK uses asynchronous requests that don't block your application. Slow backend responses won't affect your app's performance. However:
- Very slow responses may timeout
- Errors may queue up if backend is consistently slow
- Consider increasing backend capacity if this happens frequently

## Configuration

### What's the minimum configuration needed?

Just an API key:

```javascript
const bugmail = new BugMail({
  apiKey: 'YOUR_API_KEY'
});
```

### What are all the configuration options?

```javascript
const bugmail = new BugMail({
  // Required
  apiKey: 'YOUR_PROJECT_API_KEY',
  
  // Optional
  endpoint: 'https://api.bugmail.site',  // Backend URL
  environment: 'production',            // 'development', 'staging', 'production'
  release: '1.2.3',                     // App version
  captureUnhandledErrors: true,         // Capture window.onerror
  captureUnhandledRejections: true,     // Capture unhandled promises
  captureConsoleErrors: true,           // Capture console.error
  maxBreadcrumbs: 100,                  // Max breadcrumbs to store
  sampleRate: 1.0,                      // 1.0 = 100%, 0.5 = 50%
  debug: false,                         // Enable debug logging
  enableAIAnalysis: true,               // Enable AI error analysis
  beforeSend: (error, context) => error // Hook to modify/filter errors
});
```

### Can I change configuration after initialization?

Some settings can be changed:

```javascript
// Change user context
bugmail.setUser({ id: '123', email: 'user@example.com' });

// Change custom context
bugmail.setContext({ theme: 'dark', plan: 'premium' });

// Add breadcrumbs
bugmail.addBreadcrumb({ message: 'User clicked button' });
```

Core configuration (apiKey, endpoint, etc.) cannot be changed after initialization. Create a new instance if needed.

### What's the difference between environment and release?

- **environment**: Where your code is running (`development`, `staging`, `production`)
- **release**: Version of your code (`1.2.3`, `v2.0.0-beta`, etc.)

Both are optional but recommended for filtering and grouping errors in your dashboard.

## Error Capture

### What types of errors are captured?

By default, the SDK captures:
1. **Unhandled errors** - `window.onerror` events
2. **Unhandled promise rejections** - `unhandledrejection` events
3. **Console errors** - `console.error()` calls (optional)

### Can I manually capture errors?

Yes:

```javascript
try {
  riskyOperation();
} catch (error) {
  bugmail.captureError(error, {
    component: 'PaymentForm',
    action: 'processPayment',
    userId: '123'
  });
}
```

### How do I capture errors in async functions?

Async errors are automatically captured if unhandled:

```javascript
async function fetchData() {
  const response = await fetch('/api/data');
  const data = await response.json();  // If this fails, SDK captures it
  return data;
}
```

Or capture manually:

```javascript
async function fetchData() {
  try {
    const response = await fetch('/api/data');
    return await response.json();
  } catch (error) {
    bugmail.captureError(error, { endpoint: '/api/data' });
    throw error;  // Re-throw if needed
  }
}
```

### Can I capture non-Error objects?

Yes, but it's not recommended:

```javascript
// Works, but not ideal
bugmail.captureError('Something went wrong');

// Better - create an Error object
bugmail.captureError(new Error('Something went wrong'));

// Best - include context
bugmail.captureError(new Error('Payment failed'), {
  amount: 99.99,
  currency: 'USD',
  paymentMethod: 'credit_card'
});
```

## User Context

### How do I set user information?

```javascript
bugmail.setUser({
  id: '123',
  email: 'user@example.com',
  name: 'John Doe',
  role: 'admin'
});
```

### When should I set user context?

Set user context as soon as you know who the user is:
- After login
- After authentication check
- When loading user profile

### Can I clear user context?

Yes:

```javascript
// Clear user context (e.g., on logout)
bugmail.setUser(null);
```

### Is user information sent with every error?

Yes. User context is included with every error report, helping you:
- Identify which users are affected
- Contact users about issues
- Filter errors by user segment

## Breadcrumbs

### What are breadcrumbs?

Breadcrumbs are a trail of events leading up to an error. They help you understand what the user was doing when the error occurred.

### How do I add breadcrumbs?

```javascript
bugmail.addBreadcrumb({
  type: 'user',
  message: 'User clicked checkout button',
  level: 'info',
  data: { cartTotal: '$45.67', itemCount: 3 }
});
```

### Are breadcrumbs added automatically?

Some breadcrumbs are added automatically:
- Navigation events (page changes)
- Console messages
- Network requests (if configured)

You can add custom breadcrumbs for important user actions.

### How many breadcrumbs are stored?

By default, the SDK stores the last 100 breadcrumbs. Configure with:

```javascript
const bugmail = new BugMail({
  apiKey: 'YOUR_API_KEY',
  maxBreadcrumbs: 50  // Store last 50 breadcrumbs
});
```

## Performance

### Does the SDK impact my app's performance?

The SDK is designed to have minimal performance impact:
- Asynchronous error capture (doesn't block UI)
- Lightweight error filtering (< 1ms per check)
- Batched network requests (reduces overhead)
- Small bundle size (~15KB gzipped)

### Can I reduce the SDK's impact further?

Yes:
- Use `sampleRate` to capture fewer errors
- Disable console capture if not needed
- Reduce `maxBreadcrumbs` to use less memory
- Use lazy loading to load SDK only when needed

### Does the SDK work with code splitting?

Yes. The SDK works with code splitting and lazy loading. Just ensure it's initialized before your application code runs.

## Security & Privacy

### Is user data encrypted?

Yes. All data is sent over HTTPS. The SDK uses secure connections to your BugMail backend.

### What data is collected?

The SDK collects:
- Error messages and stack traces
- Browser and OS information
- User context (if you provide it)
- Custom context (if you provide it)
- Breadcrumbs
- Page URL and referrer

The SDK does NOT collect:
- Passwords or sensitive form data
- Cookies or local storage
- Full page HTML or screenshots (unless explicitly configured)

### Can I redact sensitive data?

Yes, use the `beforeSend` hook:

```javascript
const bugmail = new BugMail({
  apiKey: 'YOUR_API_KEY',
  beforeSend: (error, context) => {
    // Redact sensitive data from error message
    error.message = error.message.replace(/password=\w+/g, 'password=[REDACTED]');
    
    // Remove sensitive context
    if (context.creditCard) {
      delete context.creditCard;
    }
    
    return error;
  }
});
```

### Is the SDK GDPR compliant?

The SDK itself doesn't store any data - it only sends data to your BugMail backend. GDPR compliance depends on:
- How you configure the SDK
- What data you collect
- How your backend stores and processes data

Recommendations:
- Don't collect PII unless necessary
- Use `beforeSend` to redact sensitive data
- Implement data retention policies in your backend
- Provide users with data access and deletion options

## Troubleshooting

### Errors aren't being captured

Check:
1. API key is correct
2. Backend endpoint is accessible
3. No Content Security Policy blocking requests
4. SDK is initialized before errors occur
5. Debug mode shows what's happening

### Errors are captured but not appearing in dashboard

Check:
1. Backend is receiving requests (check Network tab)
2. Backend is returning 201 Created
3. Project API key matches dashboard project
4. No backend errors in logs
5. Dashboard is showing correct project

### Too many errors are being captured

Solutions:
1. Use `sampleRate` to capture fewer errors
2. Use `beforeSend` to filter specific errors
3. Fix the underlying issues causing errors
4. Disable console capture if too noisy

### SDK is causing errors in my app

This shouldn't happen! The SDK is designed to never break your app. If you're seeing issues:
1. Enable debug mode to see what's happening
2. Check browser console for SDK errors
3. Try disabling specific features (console capture, etc.)
4. File a bug report on GitHub with details

## Framework Integration

### Does the SDK work with React?

Yes! Use the browser SDK directly or use the React package (when available):

```jsx
import BugMail from '@bugmail-js/sdk';

// Initialize in your app root
const bugmail = new BugMail({ apiKey: 'YOUR_API_KEY' });

// Use in components
function MyComponent() {
  const handleClick = () => {
    try {
      riskyOperation();
    } catch (error) {
      bugmail.captureError(error);
    }
  };
  
  return <button onClick={handleClick}>Click me</button>;
}
```

### Does the SDK work with Vue?

Yes! Use the browser SDK directly or use the Vue plugin (when available):

```javascript
import { createApp } from 'vue';
import BugMail from '@bugmail-js/sdk';

const app = createApp(App);

// Initialize SDK
const bugmail = new BugMail({ apiKey: 'YOUR_API_KEY' });

// Make available globally
app.config.globalProperties.$bugmail = bugmail;

app.mount('#app');
```

### Does the SDK work with Angular?

Yes! Initialize the SDK in your app module:

```typescript
import { Component, OnInit } from '@angular/core';
import BugMail from '@bugmail-js/sdk';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  private bugmail: any;
  
  ngOnInit() {
    this.bugmail = new BugMail({ apiKey: 'YOUR_API_KEY' });
  }
}
```

## Support

### Where can I get help?

1. Check this FAQ
2. Read the [documentation](./README.md)
3. Search [GitHub issues](https://github.com/yourusername/bugmail-sdk/issues)
4. File a new issue with details
5. Contact support@bugmail.io for urgent issues

### How do I report a bug?

File an issue on GitHub with:
- SDK version
- Browser and OS
- Steps to reproduce
- Expected vs actual behavior
- Console errors (with debug mode enabled)
- Network requests (from DevTools)

### How do I request a feature?

File a feature request on GitHub with:
- Use case description
- Why existing features don't work
- Proposed API or behavior
- Examples from other tools (if applicable)

### Is there a community forum?

Check the BugMail website for community resources:
- Discord server
- GitHub Discussions
- Stack Overflow tag
- Twitter updates
