npm package: @saastoast/node
Description: Official Node.js/TypeScript SDK for SaasToast analytics
Author: SaasToast Team
Latest version: 1.0.2

# @saastoast/node

Official Node.js/TypeScript SDK for SaasToast analytics platform.

## Installation

```bash
npm install @saastoast/node
# or
yarn add @saastoast/node
```

## Quick Start

```typescript
import { SaasToast } from '@saastoast/node';

// Initialize client
const client = new SaasToast({
  apiKey: 'api_live_your_api_key_here' // Get this from your SaasToast dashboard
});

// Or use the shorthand
const client = SaasToast.create('api_live_your_api_key_here');

// Track an event
const response = await client.track({
  type: 'user_signup',
  user_id: 'user123',
  email: 'user@example.com',
  metadata: {
    plan: 'pro',
    source: 'organic'
  }
});

if (response.success) {
  console.log('Event tracked:', response.eventId);
} else {
  console.error('Failed to track event:', response.error);
}

// Track with revenue
await client.track({
  type: 'purchase',
  user_id: 'user123',
  email: 'customer@example.com',
  revenue: 2999, // $29.99 in cents
  metadata: {
    product: 'premium_plan',
    billing_period: 'monthly'
  }
});
```

## Configuration

### Configuration Options

```typescript
const client = new SaasToast({
  apiKey: 'api_live_your_key_here',        // Required
  baseUrl: 'https://api.saastoast.com',    // Optional: Override default API URL
  maxRetries: 3,                           // Retry attempts for failed requests (default: 3)
  timeout: 10000,                          // Request timeout in milliseconds (default: 10000)
  debug: false                             // Enable debug logging (default: false)
});
```

## API Reference

### track(event)

Track a single event.

```typescript
interface Event {
  type: string;                            // Required: Event type
  user_id?: string;                        // Optional: User identifier
  email?: string;                          // Optional: User email
  revenue?: number;                        // Optional: Revenue in cents
  metadata?: Record<string, any>;          // Optional: Custom properties
  timestamp?: string;                      // Optional: ISO 8601 timestamp (defaults to now)
}

const response = await client.track({
  type: 'subscription_created',
  user_id: 'user123',
  email: 'customer@example.com',
  revenue: 9999, // $99.99 in cents
  metadata: {
    plan: 'annual',
    seats: 5
  }
});
```

### Response Format

```typescript
interface TrackResponse {
  success: boolean;
  eventId?: string;   // Present when success is true
  error?: string;     // Present when success is false
}
```

## Examples

### Basic Event Tracking

```typescript
// Track a simple event
await client.track({
  type: 'feature_used',
  user_id: 'user123',
  metadata: {
    feature: 'export_csv',
    records_count: 1500
  }
});

// Track user actions
await client.track({
  type: 'settings_updated',
  user_id: 'user123',
  email: 'user@example.com',
  metadata: {
    setting: 'notification_preferences',
    value: 'email_only'
  }
});
```

### Revenue Tracking

Always send revenue in cents to avoid floating-point issues:

```typescript
// Track a purchase
await client.track({
  type: 'purchase',
  user_id: 'user123',
  revenue: 4999, // $49.99 in cents
  metadata: {
    product_id: 'prod_123',
    product_name: 'Premium Plan',
    quantity: 1
  }
});

// Track a refund (negative revenue)
await client.track({
  type: 'refund',
  user_id: 'user123',
  revenue: -2999, // -$29.99 in cents
  metadata: {
    reason: 'customer_request',
    order_id: 'order_456'
  }
});

// Track subscription changes
await client.track({
  type: 'subscription_upgraded',
  user_id: 'user123',
  revenue: 5000, // Additional $50.00 in cents
  metadata: {
    from_plan: 'basic',
    to_plan: 'premium',
    monthly_difference: 5000
  }
});
```

### Error Handling

```typescript
try {
  const response = await client.track({
    type: 'important_event',
    user_id: 'user123'
  });

  if (!response.success) {
    console.error('Event tracking failed:', response.error);
    // Handle the error appropriately
    // Maybe retry, queue for later, or alert
  }
} catch (error) {
  // Network or unexpected errors
  console.error('Unexpected error:', error);
}
```

### Using with Express

```typescript
import express from 'express';
import { SaasToast } from '@saastoast/node';

const app = express();
const saastoast = SaasToast.create(process.env.SAASTOAST_API_KEY);

app.post('/api/register', async (req, res) => {
  // Your registration logic
  const user = await createUser(req.body);

  // Track the signup event
  await saastoast.track({
    type: 'user_signup',
    user_id: user.id,
    email: user.email,
    metadata: {
      referral_source: req.body.referral,
      plan: req.body.plan
    }
  });

  res.json({ success: true, userId: user.id });
});
```

### Environment Variables

```bash
# .env
SAASTOAST_API_KEY=api_live_your_api_key
SAASTOAST_DEBUG=true
```

```typescript
const client = new SaasToast({
  apiKey: process.env.SAASTOAST_API_KEY!,
  debug: process.env.SAASTOAST_DEBUG === 'true'
});
```

## TypeScript Support

The SDK is written in TypeScript and provides full type definitions:

```typescript
import { SaasToast, Event, TrackResponse, SaasToastConfig } from '@saastoast/node';

const config: SaasToastConfig = {
  apiKey: 'api_live_your_key',
  debug: true
};

const event: Event = {
  type: 'test_event',
  user_id: 'user123',
  metadata: { test: true }
};

const client = new SaasToast(config);
const response: TrackResponse = await client.track(event);
```

## Best Practices

1. **Always check response status**: Verify `response.success` before assuming the event was tracked
2. **Use meaningful event types**: Choose descriptive names like `subscription_created` over generic names
3. **Include user context**: Always include `user_id` or `email` when available for better analytics
4. **Track revenue in cents**: Use integer cents to avoid floating-point precision issues
5. **Add relevant metadata**: Include contextual data that will help with analysis later
6. **Handle errors gracefully**: Implement proper error handling to avoid losing important events

## Testing

```typescript
// Mock the client for testing
const mockClient = {
  track: jest.fn().mockResolvedValue({
    success: true,
    eventId: 'test_123'
  })
};

// In your tests
describe('User Registration', () => {
  it('should track signup event', async () => {
    await registerUser(userData);

    expect(mockClient.track).toHaveBeenCalledWith({
      type: 'user_signup',
      user_id: expect.any(String),
      email: userData.email,
      metadata: expect.any(Object)
    });
  });
});
```

## Support

- Documentation: [https://docs.saastoast.com](https://docs.saastoast.com)
- Issues: [GitHub Issues](https://github.com/saastoast/saastoast/issues)
- Email: support@saastoast.com

## License

MIT License - see LICENSE file for details.