npm package: @localxp/sdk
Description: LocalXP JavaScript SDK with White Label API support
Author: LocalXP
Latest version: 1.1.0

# LocalXP JavaScript SDK

Official JavaScript SDK for the LocalXP platform with full White Label API support.

## Features

- ✅ Event tracking with offline queue
- ✅ XP balance management
- ✅ QR code generation
- ✅ Automatic retry logic with exponential backoff
- ✅ TypeScript support with full type definitions
- ✅ **NEW: White Label API support**
  - User Management API
  - Business Management API
  - Webhook Management API

## Installation

```bash
npm install @localxp/sdk
```

## Quick Start

### Basic Usage

```typescript
import { LocalXP } from '@localxp/sdk';

const localxp = new LocalXP({
  apiKey: 'your-api-key',
  debug: true,
});

await localxp.init();
await localxp.track('page_view', { page: '/home' });
```

### White Label API Usage

```typescript
import { LocalXP } from '@localxp/sdk';

const localxp = new LocalXP({
  apiKey: 'your-api-key',
  apiUrl: 'https://api.localxp.ca/v1',
});

await localxp.init();

// User Management
const users = await localxp.whiteLabel.listUsers({ limit: 10 });
const user = await localxp.whiteLabel.createUser({
  email: 'user@example.com',
  username: 'johndoe',
  display_name: 'John Doe',
});

// Business Management
const businesses = await localxp.whiteLabel.listBusinesses({
  radius: {
    latitude: 43.6532,
    longitude: -79.3832,
    meters: 5000,
  },
});

// Webhook Management
const webhook = await localxp.whiteLabel.createWebhook({
  url: 'https://your-domain.com/webhooks',
  events: ['user.created', 'business.created'],
  description: 'Production webhook',
});
```

## Configuration

### LocalXPConfig

```typescript
interface LocalXPConfig {
  /** Your LocalXP API key (required) */
  apiKey: string;
  
  /** API base URL (default: https://api.localxp.ca/v1) */
  apiUrl?: string;
  
  /** Enable debug logging (default: false) */
  debug?: boolean;
  
  /** Auto-generate UUID if not provided (default: true) */
  autoGenerateUUID?: boolean;
  
  /** Enable offline queue (default: true) */
  enableOfflineQueue?: boolean;
  
  /** Maximum retry attempts for failed requests (default: 3) */
  maxRetries?: number;
  
  /** Retry delay in milliseconds (default: 1000) */
  retryDelay?: number;
}
```

## Core Methods

### init(user?)

Initialize the SDK with optional user identity.

```typescript
await localxp.init({
  uuid: 'user-uuid',
  email: 'user@example.com',
  phone: '+1234567890',
});
```

### track(event, properties?)

Track an event with optional properties.

```typescript
await localxp.track('purchase', {
  product_id: '123',
  amount: 99.99,
  currency: 'USD',
});
```

### getBalance(communityId?)

Get user's XP balance.

```typescript
const balance = await localxp.getBalance('community-id');
console.log(balance.communityXP, balance.universalXP);
```

### generateQR(options?)

Generate a QR code for the user.

```typescript
const qr = await localxp.generateQR({
  size: 256,
  format: 'data',
  expiresIn: 3600,
});
```

## White Label API

### User Management

#### List Users

```typescript
const response = await localxp.whiteLabel.listUsers({
  limit: 50,
  offset: 0,
  status: 'active',
  sort_by: 'created_at',
  sort_order: 'desc',
});

console.log(response.data); // Array of users
console.log(response.pagination); // Pagination info
```

#### Create User

```typescript
const response = await localxp.whiteLabel.createUser({
  email: 'newuser@example.com',
  username: 'newuser',
  display_name: 'New User',
  user_type: 'user',
  send_welcome_email: true,
});

console.log(response.data); // Created user
```

#### Get User

```typescript
const response = await localxp.whiteLabel.getUser('user-id');
console.log(response.data); // User details
```

#### Update User

```typescript
const response = await localxp.whiteLabel.updateUser('user-id', {
  display_name: 'Updated Name',
  location: 'Toronto, ON',
});
```

#### Delete User

```typescript
// Soft delete
await localxp.whiteLabel.deleteUser('user-id');

// Hard delete (requires admin:users scope)
await localxp.whiteLabel.deleteUser('user-id', true);
```

#### Map External User

```typescript
const response = await localxp.whiteLabel.mapUser({
  external_user_id: 'external-123',
  external_system: 'your-system',
  email: 'user@example.com',
  name: 'User Name',
  external_user_data: {
    tier: 'premium',
  },
});
```

#### Bulk Map Users

```typescript
const response = await localxp.whiteLabel.bulkMapUsers('your-system', [
  {
    external_user_id: 'ext-1',
    external_system: 'your-system',
    email: 'user1@example.com',
    name: 'User 1',
  },
  {
    external_user_id: 'ext-2',
    external_system: 'your-system',
    email: 'user2@example.com',
    name: 'User 2',
  },
]);

console.log(response.results); // { total, successful, failed, errors }
```

### Business Management

#### List Businesses

```typescript
// List all businesses
const response = await localxp.whiteLabel.listBusinesses({
  limit: 20,
  categories: ['restaurant', 'cafe'],
  status: 'active',
});

// Geographic filtering - Radius
const nearby = await localxp.whiteLabel.listBusinesses({
  radius: {
    latitude: 43.6532,
    longitude: -79.3832,
    meters: 5000, // 5km radius
  },
});

// Geographic filtering - Bounds
const inBounds = await localxp.whiteLabel.listBusinesses({
  bounds: {
    north: 43.7,
    south: 43.6,
    east: -79.3,
    west: -79.4,
  },
});
```

#### Create Business

```typescript
const response = await localxp.whiteLabel.createBusiness({
  name: 'New Restaurant',
  description: 'A great place to eat',
  address: '123 Main St, Toronto, ON',
  categories: ['restaurant'],
  phone: '+1234567890',
  email: 'info@restaurant.com',
  website: 'https://restaurant.com',
  auto_geocode: true, // Automatically geocode the address
});
```

#### Update Business

```typescript
const response = await localxp.whiteLabel.updateBusiness('business-id', {
  description: 'Updated description',
  phone: '+1987654321',
});
```

#### Claim Business

```typescript
const response = await localxp.whiteLabel.claimBusiness('business-id', {
  user_id: 'user-id',
  verification_data: {
    document_type: 'business_license',
    document_number: '12345',
  },
});
```

#### Bulk Import Businesses

```typescript
const response = await localxp.whiteLabel.bulkImportBusinesses({
  businesses: [
    {
      name: 'Business 1',
      address: '123 Main St',
      categories: ['retail'],
    },
    {
      name: 'Business 2',
      address: '456 Oak Ave',
      categories: ['service'],
    },
  ],
  auto_geocode: true,
  batch_size: 50,
});

console.log(response.job_id); // Job ID for tracking
console.log(response.results); // Import results
```

### Webhook Management

#### List Webhooks

```typescript
const response = await localxp.whiteLabel.listWebhooks();
console.log(response.webhooks); // Array of webhooks
```

#### Create Webhook

```typescript
const response = await localxp.whiteLabel.createWebhook({
  url: 'https://your-domain.com/webhooks',
  events: [
    'user.created',
    'user.updated',
    'business.created',
    'order.completed',
  ],
  description: 'Production webhook for user events',
});

console.log(response.data.secret); // Webhook secret for signature verification
```

#### Update Webhook

```typescript
const response = await localxp.whiteLabel.updateWebhook('webhook-id', {
  events: ['user.created', 'user.deleted'],
  active: true,
});
```

#### Test Webhook

```typescript
const result = await localxp.whiteLabel.testWebhook('webhook-id');
console.log(result.success); // true/false
console.log(result.details); // Response details
```

#### Get Webhook Deliveries

```typescript
const response = await localxp.whiteLabel.getWebhookDeliveries('webhook-id');
console.log(response.deliveries); // Array of delivery attempts
```

#### Get Webhook Statistics

```typescript
const response = await localxp.whiteLabel.getWebhookStats('webhook-id');
console.log(response.stats);
// {
//   total_deliveries: 150,
//   successful_deliveries: 145,
//   failed_deliveries: 3,
//   pending_deliveries: 2,
//   success_rate: 96.67,
//   avg_attempts: 1.2,
//   last_delivery_at: '2026-01-09T12:00:00Z'
// }
```

## Error Handling

The SDK uses a custom `WhiteLabelAPIError` class for White Label API errors:

```typescript
import { WhiteLabelAPIError } from '@localxp/sdk';

try {
  await localxp.whiteLabel.createUser({
    email: 'invalid-email',
    username: 'test',
  });
} catch (error) {
  if (error instanceof WhiteLabelAPIError) {
    console.error('API Error:', error.message);
    console.error('Status Code:', error.statusCode);
    console.error('Details:', error.details);
    console.error('Field:', error.field);
  }
}
```

## TypeScript Support

The SDK is written in TypeScript and includes full type definitions:

```typescript
import type {
  User,
  Business,
  Webhook,
  CreateUserRequest,
  ListBusinessesRequest,
  WebhookStats,
} from '@localxp/sdk';

const createUser = async (data: CreateUserRequest): Promise<User> => {
  const response = await localxp.whiteLabel.createUser(data);
  return response.data;
};
```

## Offline Queue

The SDK automatically queues events when offline and syncs them when the connection is restored:

```typescript
// Events are automatically queued when offline
await localxp.track('offline_event', { data: 'value' });

// Manually sync the queue
const result = await localxp.syncOfflineQueue();
console.log(`Synced ${result.success} events, ${result.failed} failed`);

// Get queue status
const status = await localxp.getQueueStatus();
console.log(status.pending); // Number of pending events

// Clear the queue
await localxp.clearQueue();
```

## Advanced Configuration

### Custom API URL

```typescript
const localxp = new LocalXP({
  apiKey: 'your-api-key',
  apiUrl: 'https://custom-api.example.com/v1',
});
```

### Disable Offline Queue

```typescript
const localxp = new LocalXP({
  apiKey: 'your-api-key',
  enableOfflineQueue: false,
});
```

### Custom Retry Configuration

```typescript
const localxp = new LocalXP({
  apiKey: 'your-api-key',
  maxRetries: 5,
  retryDelay: 2000, // 2 seconds
});
```

## Event Types

### Supported Webhook Events

- `user.created` - When a new user signs up
- `user.updated` - When user profile is updated
- `user.deleted` - When a user is deleted
- `business.created` - When a new business is added
- `business.updated` - When business info is updated
- `business.claimed` - When a business is claimed
- `order.created` - When a new order is placed
- `order.completed` - When an order is completed
- `subscription.created` - When a subscription starts
- `subscription.updated` - When subscription changes
- `subscription.cancelled` - When subscription ends

## Best Practices

### 1. Initialize Once

```typescript
// Good
const localxp = new LocalXP({ apiKey: 'key' });
await localxp.init();

// Bad - Don't create multiple instances
const localxp1 = new LocalXP({ apiKey: 'key' });
const localxp2 = new LocalXP({ apiKey: 'key' });
```

### 2. Handle Errors

```typescript
try {
  await localxp.whiteLabel.createUser(userData);
} catch (error) {
  console.error('Failed to create user:', error);
  // Handle error appropriately
}
```

### 3. Use TypeScript

```typescript
import type { CreateUserRequest } from '@localxp/sdk';

const userData: CreateUserRequest = {
  email: 'user@example.com',
  username: 'user',
};
```

### 4. Batch Operations

```typescript
// Use bulk operations for multiple items
await localxp.whiteLabel.bulkMapUsers('system', mappings);
await localxp.whiteLabel.bulkImportBusinesses({ businesses });
```

## License

MIT

## Support

- Documentation: https://docs.localxp.ca
- API Reference: https://api.localxp.ca/docs
- Issues: https://github.com/localxp/sdk/issues
- Email: support@localxp.ca