npm package: @regpilot/regpilot
Description: Comprehensive API call logging for Node.js applications - RegPilot platform integration
Author: RegPilot Team
Latest version: 6.0.0

# @regpilot/regpilot

Comprehensive API call logging for Node.js applications with RegPilot platform integration.

## 🚀 Quick Start

### Option 1: Install as NPM Package

```bash
npm install @regpilot/regpilot
```

### Option 2: Use with VS Code Extension

The RegPilot VS Code extension automatically includes this module. Install from the marketplace:
- Search for "RegPilot" in VS Code Extensions
- Install and configure with your API credentials

## 📦 Installation Methods

### 1. Programmatic Usage

```javascript
const { RegPilotLogger } = require('@regpilot/regpilot');

const logger = new RegPilotLogger({
  apiKey: 'your-api-key',
  orgId: 'your-org-id',
  debug: true
});

logger.start();

// Your application code here
// All HTTP/HTTPS requests will be automatically logged

// Graceful shutdown
process.on('SIGINT', async () => {
  await logger.stop();
  process.exit(0);
});
```

### 2. Auto-Register (Easiest)

```bash
# Run your app with automatic API logging
node -r @regpilot/regpilot/register your-app.js
```

### 3. CLI Tool

```bash
# Initialize configuration
npx regpilot init

# Start monitoring
npx regpilot start

# Real-time monitoring
npx regpilot monitor

# Test the setup
npx regpilot test
```

## ⚙️ Configuration

### Configuration File (`regpilot.config.json`)

```json
{
  "apiKey": "your-regpilot-api-key",
  "orgId": "your-organization-id",
  "userId": "optional-user-id",
  "apiUrl": "https://api.regpilot.dev",
  "enabled": true,
  "debug": false,
  "batchSize": 20,
  "flushInterval": 5000,
  "maxQueueSize": 1000
}
```

### Environment Variables

```bash
export REGPILOT_API_KEY="your-api-key"
export REGPILOT_ORG_ID="your-org-id"
export REGPILOT_USER_ID="optional-user-id"
export REGPILOT_DEBUG="true"
export REGPILOT_ENABLED="true"
```

## 🔍 What Gets Logged

The logger captures **ALL** HTTP/HTTPS requests made by your Node.js application:

- **Request Details**: Method, URL, headers, body
- **Response Details**: Status code, headers, body
- **Performance Metrics**: Request duration, timestamps
- **Error Information**: Network errors, timeouts
- **Context**: Process ID, hostname, user agent

### Supported Request Types

- ✅ **fetch()** API calls
- ✅ **http.request()** and **https.request()**
- ✅ **Third-party libraries** (axios, request, etc.)
- ✅ **Framework requests** (Express, Fastify, etc.)

## 📊 API Events

Each logged API call includes:

```typescript
interface APICallEvent {
  type: 'api_call';
  method: string;
  url: string;
  headers: Record<string, string>;
  requestBody?: any;
  responseStatus?: number;
  responseHeaders?: Record<string, string>;
  responseBody?: any;
  duration: number;
  timestamp: number;
  error?: string;
  userAgent?: string;
  source: 'node' | 'fetch' | 'unknown';
  processId: number;
  hostname: string;
}
```

## 🔐 Security & Privacy

### Automatic Data Sanitization

- **Sensitive Headers**: Authorization, cookies, API keys are automatically redacted
- **Body Size Limits**: Request/response bodies truncated if over 5KB
- **Configurable Privacy**: Disable telemetry collection entirely

### Data Protection

```javascript
// Sensitive data is automatically redacted
{
  "headers": {
    "authorization": "[REDACTED]",
    "x-api-key": "[REDACTED]",
    "cookie": "[REDACTED]"
  }
}
```

## 📈 Usage Examples

### Express.js Application

```javascript
const express = require('express');
const { startLogging } = require('@regpilot/regpilot');

// Start API logging
const logger = startLogging({
  apiKey: process.env.REGPILOT_API_KEY,
  orgId: process.env.REGPILOT_ORG_ID,
  debug: true
});

const app = express();

app.get('/api/users', async (req, res) => {
  // This external API call will be logged
  const response = await fetch('https://jsonplaceholder.typicode.com/users');
  const users = await response.json();
  res.json(users);
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
```

### Microservice with Event Handling

```javascript
const { RegPilotLogger } = require('@regpilot/regpilot');

const logger = new RegPilotLogger({
  apiKey: process.env.REGPILOT_API_KEY,
  orgId: process.env.REGPILOT_ORG_ID
});

// Listen to API call events
logger.on('apiCall', (event) => {
  console.log(`API Call: ${event.method} ${event.url} (${event.duration}ms)`);
});

logger.on('flushed', (count) => {
  console.log(`Sent ${count} events to RegPilot platform`);
});

logger.start();
```

## 🛠️ CLI Commands

### Initialize Configuration

```bash
npx regpilot init
```

Interactive setup that creates `regpilot.config.json` with your credentials.

### Start Logging

```bash
npx regpilot start --file ./regpilot.config.json
```

Starts API logging with existing configuration.

### Real-time Monitoring

```bash
npx regpilot monitor --no-upload
```

Monitor API calls in real-time without uploading to RegPilot platform.

### Test Setup

```bash
npx regpilot test
```

Validates your configuration and tests API interception.

### Check Status

```bash
npx regpilot status
```

Shows current configuration and status.

## 🔧 Advanced Configuration

### Custom Event Handling

```javascript
const logger = new RegPilotLogger(config);

logger.on('started', () => {
  console.log('API logging started');
});

logger.on('apiCall', (event) => {
  // Custom processing of API calls
  if (event.error) {
    console.error(`API Error: ${event.error}`);
  }
});

logger.on('flushError', (error) => {
  console.error('Failed to send events:', error);
});

logger.start();
```

### Dynamic Configuration Updates

```javascript
// Update configuration at runtime
logger.updateConfig({
  debug: true,
  batchSize: 50
});
```

### Manual Event Flushing

```javascript
// Force immediate flush of queued events
await logger.flush();
```

## 🚀 Integration with RegPilot Platform

### Dashboard Features

When connected to RegPilot platform, you get:

- **Real-time API Monitoring**: Live view of all API calls
- **Performance Analytics**: Latency, error rates, usage patterns
- **Security Insights**: Detect suspicious API behavior
- **Compliance Tracking**: Monitor API usage against policies
- **Team Collaboration**: Share insights across development teams

### API Endpoints

The logger sends data to these RegPilot endpoints:

- `POST /api/batch` - Bulk event submission
- `GET /api/health` - Health checks
- WebSocket connection for real-time streaming

## 🔄 VS Code Extension Integration

The RegPilot VS Code extension automatically includes this node module:

1. **Install Extension**: Search "RegPilot" in VS Code marketplace
2. **Configure Credentials**: Set API key and organization ID
3. **Automatic Activation**: Node logger starts with extension
4. **Unified Dashboard**: View both IDE and application API calls

### Extension Benefits

- **Zero Configuration**: Automatically configured with extension settings
- **IDE Integration**: See API calls directly in VS Code
- **Unified Monitoring**: Combined view of development and runtime API usage
- **Team Synchronization**: Shared settings across team members

## 📝 TypeScript Support

Full TypeScript support with type definitions:

```typescript
import { RegPilotLogger, RegPilotConfig, APICallEvent } from '@regpilot/regpilot';

const config: RegPilotConfig = {
  apiKey: 'your-key',
  orgId: 'your-org',
  debug: true
};

const logger = new RegPilotLogger(config);

logger.on('apiCall', (event: APICallEvent) => {
  console.log(`${event.method} ${event.url}`);
});
```

## 🐛 Troubleshooting

### Common Issues

**Logger not capturing requests:**
```bash
# Check if logger is active
npx regpilot status

# Test with debug mode
npx regpilot monitor --debug
```

**Authentication errors:**
```bash
# Verify credentials
npx regpilot test
```

**Performance impact:**
```javascript
// Reduce batch size and increase flush interval
const logger = new RegPilotLogger({
  batchSize: 10,
  flushInterval: 10000,
  maxQueueSize: 500
});
```

### Debug Mode

Enable debug logging to see detailed information:

```javascript
const logger = new RegPilotLogger({
  debug: true,
  // ... other config
});
```

## 📄 License

MIT License - see LICENSE file for details.

## 🤝 Support

- **Documentation**: [https://regpilot.dev/docs](https://regpilot.dev/docs)
- **Issues**: [GitHub Issues](https://github.com/regpilot/regpilot-app/issues)
- **Discord**: [RegPilot Community](https://discord.gg/regpilot)

## 🔗 Related Packages

- **@regpilot/vscode-extension**: VS Code extension with integrated logging
- **@regpilot/jetbrains-plugin**: JetBrains IDE plugin
- **regpilot-sdk**: Core SDK for custom integrations