# StackScope SDK Integration Guide

## 🚀 Complete Integration Guide

This guide covers all integration scenarios for the StackScope SDK with comprehensive examples and troubleshooting.

## 📦 Installation

```bash
npm install stackscope
```

## ⚡ Quick Start Options

### Option 1: Vanilla JavaScript (Minimal Setup)

```javascript
import { createStackScope } from 'stackscope';

// Auto-detects environment variables
const stackscope = createStackScope({
  debug: true // Logs to console for development
});
```

### Option 2: React Integration (Recommended)

```jsx
import { StackScopeProvider, StackScopeErrorBoundary } from 'stackscope/react';

function App() {
  return (
    <StackScopeProvider config={{ debug: true }}>
      <StackScopeErrorBoundary>
        <YourApp />
      </StackScopeErrorBoundary>
    </StackScopeProvider>
  );
}
```

### Option 3: Manual Configuration

```javascript
import { init } from 'stackscope';

const stackscope = init({
  endpoint: 'https://your-worker.workers.dev/webhook/browser',
  debug: false,
  logLevel: 'error',
  batchInterval: 2000
});
```

## 🌐 Framework-Specific Integration

### Vite + React

1. **Environment Setup:**
```bash
# .env.local
VITE_STACKSCOPE_WORKER_URL=https://your-worker.workers.dev
VITE_STACKSCOPE_DEBUG=true
```

2. **Integration:**
```jsx
// main.tsx
import { createStackScope } from 'stackscope';

const stackscope = createStackScope(); // Auto-detects VITE_* variables

// App.tsx
import { StackScopeProvider } from 'stackscope/react';

export function App() {
  return (
    <StackScopeProvider>
      <YourComponents />
    </StackScopeProvider>
  );
}
```

### Next.js

1. **Environment Setup:**
```bash
# .env.local
NEXT_PUBLIC_STACKSCOPE_WORKER_URL=https://your-worker.workers.dev
NEXT_PUBLIC_STACKSCOPE_DEBUG=true
```

2. **Integration:**
```jsx
// _app.tsx
import { StackScopeProvider } from 'stackscope/react';

export default function MyApp({ Component, pageProps }) {
  return (
    <StackScopeProvider>
      <Component {...pageProps} />
    </StackScopeProvider>
  );
}
```

### Create React App

1. **Environment Setup:**
```bash
# .env.local
REACT_APP_STACKSCOPE_WORKER_URL=https://your-worker.workers.dev
REACT_APP_STACKSCOPE_DEBUG=true
```

2. **Integration:**
```jsx
// index.js
import { createStackScope } from 'stackscope';

createStackScope(); // Auto-detects REACT_APP_* variables

// App.js
import { StackScopeErrorBoundary } from 'stackscope/react';

function App() {
  return (
    <StackScopeErrorBoundary>
      <YourComponents />
    </StackScopeErrorBoundary>
  );
}
```

## 🎯 Development vs Production

### Development Mode
```javascript
const stackscope = createStackScope({
  debug: true,              // Shows logs in console for immediate feedback
  logLevel: 'debug',        // Capture everything for debugging
  workerUrl: 'https://your-worker.workers.dev' // Required for centralized logging
});
```

### Production Mode
```javascript
const stackscope = createStackScope({
  debug: false,             // No console logs
  logLevel: 'error',        // Only errors
  workerUrl: process.env.STACKSCOPE_WORKER_URL, // Required
  batchInterval: 5000       // Less frequent batching
});
```

## ⚛️ React Hooks Usage

### useStackScopeLogger

```jsx
import { useStackScopeLogger } from 'stackscope/react';

function MyComponent() {
  const logger = useStackScopeLogger();
  
  const handleAction = () => {
    logger.info('User action performed', {
      component: 'MyComponent',
      action: 'button_click'
    });
  };
  
  return <button onClick={handleAction}>Action</button>;
}
```

### useUserActionTracking

```jsx
import { useUserActionTracking } from 'stackscope/react';

function FormComponent() {
  const { trackFormSubmit, trackClick } = useUserActionTracking();
  
  const handleSubmit = () => {
    trackFormSubmit('contact', { fields: 5 });
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <button onClick={() => trackClick('submit')}>Submit</button>
    </form>
  );
}
```

## 🔧 Configuration Options

### Complete Configuration Object

```javascript
const config = {
  // Required (one of these)
  workerUrl: 'https://your-worker.workers.dev',
  endpoint: 'https://your-worker.workers.dev/webhook/browser',
  
  // Optional
  apiKey: 'your-api-key',                    // For authentication
  debug: false,                              // Console logging
  logLevel: 'error',                         // 'debug' | 'info' | 'warn' | 'error'
  batchInterval: 2000,                       // ms between batch sends
  maxBatchSize: 50,                          // max logs per batch
  
  // Feature flags
  captureConsole: true,                      // console.* calls
  captureNetwork: true,                      // fetch/xhr requests
  captureInteractions: true,                 // clicks/form submissions
  captureNavigation: true,                   // route changes
  capturePerformance: true,                  // Core Web Vitals
  captureVisibility: true,                   // page visibility changes
  captureResources: true                     // resource loading
};
```

## 🌍 Environment Variables

The SDK automatically detects environment variables based on your build tool:

| Build Tool | Variable Pattern | Example |
|------------|------------------|---------|
| Vite | `VITE_STACKSCOPE_*` | `VITE_STACKSCOPE_WORKER_URL` |
| Next.js | `NEXT_PUBLIC_STACKSCOPE_*` | `NEXT_PUBLIC_STACKSCOPE_WORKER_URL` |
| CRA | `REACT_APP_STACKSCOPE_*` | `REACT_APP_STACKSCOPE_WORKER_URL` |

**Supported Variables:**
- `*_STACKSCOPE_WORKER_URL` - Your worker endpoint
- `*_STACKSCOPE_API_KEY` - API key for authentication
- `*_STACKSCOPE_DEBUG` - Enable debug mode (`'true'` or `'false'`)
- `*_STACKSCOPE_ENABLED` - Disable all capture (`'false'` to disable)

## 📊 Automatic Capture Features

### Console Logs
```javascript
console.log('Info message');    // ✅ Captured
console.error('Error message'); // ✅ Captured
console.warn('Warning');        // ✅ Captured
console.debug('Debug info');    // ✅ Captured
```

### Network Requests
```javascript
fetch('/api/users')             // ✅ Captured (URL, method, status, duration)
  .then(response => response.json())
  .catch(error => console.error(error));

// XMLHttpRequest also captured automatically
```

### User Interactions
```javascript
// All automatically captured:
button.click();                 // ✅ Element, event type
form.submit();                  // ✅ Form data summary
input.onChange();               // ✅ Field changes (sanitized)
```

### Performance Metrics
```javascript
// Automatically captured:
// - Largest Contentful Paint (LCP)
// - First Input Delay (FID)
// - Cumulative Layout Shift (CLS)
// - Long tasks (>50ms)
// - Resource loading times
```

## 🔄 Manual Logging API

### Direct Logging
```javascript
import { logger, trackUserAction, trackPerformance } from 'stackscope';

// Log levels
logger.debug('Debug info', { module: 'auth' });
logger.info('User logged in', { userId: 123 });
logger.warn('Deprecated function used', { function: 'oldApi' });
logger.error('API call failed', { endpoint: '/users', status: 500 });

// Utility functions
trackUserAction('purchase', { productId: 'abc123', amount: 29.99 });
trackPerformance('api_response_time', 245, 'ms');
```

### Custom Metadata
```javascript
logger.info('Custom event', {
  // Standard fields
  timestamp: new Date().toISOString(),
  sessionId: 'session-123',
  userId: 'user-456',
  
  // Custom fields
  feature: 'checkout',
  version: '2.1.0',
  experiment: 'variant-a'
});
```

## 🏗️ Worker is Always Required

StackScope requires a worker for all environments:

```javascript
const stackscope = createStackScope({
  debug: true,           // Shows logs in console AND sends to worker
  workerUrl: 'https://your-worker.workers.dev' // Required for log collection
});
```

The worker is essential for:
- ✅ Development - centralized logging and debugging
- ✅ Production - monitoring and observability  
- ✅ Testing - consistent log capture
- ✅ CI/CD - automated error tracking

## 📱 TypeScript Support

Full TypeScript support with proper type inference:

```typescript
import { createStackScope, type SdkConfig, type LogLevel } from 'stackscope';
import { useStackScopeLogger, type UseStackScopeLoggerReturn } from 'stackscope/react';

const config: Partial<SdkConfig> = {
  debug: true,
  logLevel: 'info' as LogLevel
};

const stackscope = createStackScope(config);

// React hooks are fully typed
const logger: UseStackScopeLoggerReturn = useStackScopeLogger();
```

## 🎯 Best Practices

### 1. Environment-Based Configuration
```javascript
const stackscope = createStackScope({
  debug: process.env.NODE_ENV === 'development',
  logLevel: process.env.NODE_ENV === 'production' ? 'error' : 'debug',
  batchInterval: process.env.NODE_ENV === 'production' ? 5000 : 1000
});
```

### 2. Error Boundary Integration
```jsx
import { StackScopeErrorBoundary } from 'stackscope/react';

function App() {
  return (
    <StackScopeErrorBoundary 
      fallback={<ErrorPage />}
      onError={(error, errorInfo) => {
        // Custom error handling
        console.error('React error caught:', error);
      }}
    >
      <YourApp />
    </StackScopeErrorBoundary>
  );
}
```

### 3. Selective Logging
```javascript
const stackscope = createStackScope({
  captureConsole: true,      // Always useful
  captureNetwork: true,      // API monitoring
  captureInteractions: false, // Disable in production for privacy
  capturePerformance: true,  // Core Web Vitals important
});
```

## 🔍 Verification

After integration, verify everything works:

```bash
# Check browser console for debug logs
# Look for: "[StackScope] Initialized successfully"

# Check network tab for batch requests
# Look for: POST requests to your worker endpoint

# Check that automatic capture is working
# Trigger: console.log, fetch requests, button clicks
```

## 🔗 API Log Streaming Setup

**NEW**: Stream logs from your Cloudflare Worker APIs to StackScope for complete full-stack observability.

### Prerequisites

1. **StackScope Worker Deployed**: Your StackScope worker must be running
2. **API Worker on Cloudflare**: Your API must be deployed to Cloudflare Workers  
3. **Wrangler Authentication**: Run `wrangler auth login`

### Quick Setup

```bash
# 1. Navigate to your StackScope worker directory
cd my-app-logs  # (created during worker setup)

# 2. Start streaming API logs
./stream-api-logs.sh ../my-api-worker production
```

### Manual Setup

If you prefer manual control or custom integration:

```bash
# Navigate to your API worker directory
cd path/to/your-api-worker

# Stream logs to StackScope
wrangler tail --env production --format json | \
while read -r line; do
  echo "$line" | curl -s -X POST https://your-stackscope.workers.dev/webhook/api \
    -H "Content-Type: application/json" \
    -H "X-Source: api-production" \
    -d @-
done
```

### Framework Integration Examples

#### Node.js/Express-style Worker

```javascript
// Your API worker can log normally
export default {
  async fetch(request) {
    console.log('API request started', {
      url: request.url,
      method: request.method
    });
    
    try {
      const result = await processRequest(request);
      console.log('API request completed', { status: 200 });
      return new Response(JSON.stringify(result), { status: 200 });
    } catch (error) {
      console.error('API request failed', error);
      return new Response('Internal Error', { status: 500 });
    }
  }
};

// ✅ All console logs, requests, responses, and exceptions 
//    are automatically captured via stream-api-logs.sh
```

#### Hono Framework Worker

```javascript
import { Hono } from 'hono';
const app = new Hono();

app.get('/users/:id', async (c) => {
  console.log('Fetching user', { id: c.req.param('id') });
  
  try {
    const user = await getUser(c.req.param('id'));
    console.log('User fetched successfully');
    return c.json(user);
  } catch (error) {
    console.error('Failed to fetch user', error);
    return c.json({ error: 'User not found' }, 404);
  }
});

export default app;
```

### Environment Configuration

**Development Environment:**
```bash
./stream-api-logs.sh ../my-api-worker development
```

**Production with Custom StackScope URL:**
```bash
STACKSCOPE_URL="https://custom-logs.workers.dev" ./stream-api-logs.sh ../my-api-worker production
```

**Background Streaming (CI/CD):**
```bash
# Start background streaming
nohup ./stream-api-logs.sh ../my-api-worker production > api-stream.log 2>&1 &

# Stop background streaming
pkill -f "stream-api-logs.sh"
```

### What Gets Captured

- **HTTP Requests**: URL, method, headers, Cloudflare edge data
- **HTTP Responses**: Status codes, response times
- **Console Logs**: All your worker's console.log/error/warn statements
- **Exceptions**: Runtime errors with full stack traces
- **Performance Metrics**: Request timing and diagnostics

### Verification

Check your StackScope worker logs to see API data flowing in:

```bash
# Monitor StackScope worker
cd my-app-logs
wrangler tail --env production

# Look for logs like:
# {"level":"info","msg":"API log from Wrangler tail","source":"api","api_log":{"event_timestamp":...}}
```

## 🆘 Need Help?

- 📋 Check [troubleshooting.md](./troubleshooting.md) for common issues
- 🐛 Report issues: [GitHub Issues](https://github.com/JRGCr/StackScope/issues)
- 📖 Examples: See `examples/` folder for working implementations