> ## Documentation Index
> Fetch the complete documentation index at: https://docs.onsleek.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Events

> Listen to user interactions and SDK activity with the event system

## Overview

The AI Chat SDK provides a comprehensive event system that notifies your application about user interactions and UI state changes. Events enable you to track user behavior, trigger analytics, and respond to interactions across the chat panel, badge, and inline input.

## Registering event listeners

Pass event listeners to `initializeAiChatSdk` as the third parameter:

```typescript theme={null}
import {
  initializeAiChatSdk,
  AiChatSdkEventType,
  type AiChatSdkEvent,
} from '@sleek/ai-chat-sdk';

initializeAiChatSdk('your-api-key', {
  // ... options
}, [
  // Event listeners
  (event: AiChatSdkEvent) => {
    console.log('Event type:', event.type);
    console.log('Event data:', event.data);

    switch (event.type) {
      case AiChatSdkEventType.CHAT_SHOWN:
        // Handle chat opened
        break;
      case AiChatSdkEventType.BADGE_CLICKED:
        // Handle badge clicked
        break;
      // ... handle other events
    }
  }
]);
```

You can register multiple listeners, and all will be called when an event occurs.

## Event structure

All events follow this structure:

```typescript theme={null}
interface AiChatSdkEvent {
  type: AiChatSdkEventType;
  data: {
    chatSessionId: string;
    // Additional properties vary by event type
  };
}
```

* **type**: The event type (see available events below)
* **data**: Event-specific data
* **chatSessionId**: Unique identifier for the current chat session (present in all events)

## Badge events

Events emitted by the floating badge entry point.

### BADGE\_SHOWN

Emitted when the badge becomes visible.

**Event type**: `AiChatSdkEventType.BADGE_SHOWN`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
  prompts: string[];  // Array of prompts displayed on the badge
}
```

**Example**:

```typescript theme={null}
case AiChatSdkEventType.BADGE_SHOWN:
  analytics.track('badge_shown', {
    sessionId: event.data.chatSessionId,
    promptCount: event.data.prompts.length,
    prompts: event.data.prompts,
  });
  break;
```

### BADGE\_CLICKED

Emitted when the user clicks the badge.

**Event type**: `AiChatSdkEventType.BADGE_CLICKED`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
}
```

**Example**:

```typescript theme={null}
case AiChatSdkEventType.BADGE_CLICKED:
  analytics.track('badge_clicked', {
    sessionId: event.data.chatSessionId,
  });
  break;
```

### BADGE\_CLOSED

Emitted when the badge is closed or hidden.

**Event type**: `AiChatSdkEventType.BADGE_CLOSED`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
}
```

### BADGE\_PROMPT\_CLICKED

Emitted when the user clicks a prompt on the badge.

**Event type**: `AiChatSdkEventType.BADGE_PROMPT_CLICKED`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
  prompt: string;  // The prompt text that was clicked
}
```

**Example**:

```typescript theme={null}
case AiChatSdkEventType.BADGE_PROMPT_CLICKED:
  analytics.track('badge_prompt_clicked', {
    sessionId: event.data.chatSessionId,
    prompt: event.data.prompt,
  });
  break;
```

## Inline events

Events emitted by the inline input entry point.

### INLINE\_SHOWN

Emitted when the inline input becomes visible.

**Event type**: `AiChatSdkEventType.INLINE_SHOWN`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
  prompts: string[];  // Array of prompts displayed
}
```

### INLINE\_CLICKED

Emitted when the user clicks the inline input.

**Event type**: `AiChatSdkEventType.INLINE_CLICKED`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
}
```

### INLINE\_PROMPT\_CLICKED

Emitted when the user clicks a prompt in the inline input.

**Event type**: `AiChatSdkEventType.INLINE_PROMPT_CLICKED`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
  prompt: string;  // The prompt text that was clicked
}
```

## Chat events

Events emitted by the chat panel.

### CHAT\_SHOWN

Emitted when the chat panel becomes visible.

**Event type**: `AiChatSdkEventType.CHAT_SHOWN`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
  initialMessage?: string;  // Optional initial message when chat was opened
}
```

**Example**:

```typescript theme={null}
case AiChatSdkEventType.CHAT_SHOWN:
  analytics.track('chat_opened', {
    sessionId: event.data.chatSessionId,
    hasInitialMessage: !!event.data.initialMessage,
  });
  break;
```

### CHAT\_CLOSED

Emitted when the user closes the chat panel.

**Event type**: `AiChatSdkEventType.CHAT_CLOSED`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
}
```

### CHAT\_MESSAGE\_SENT

Emitted when the user sends a message in the chat.

**Event type**: `AiChatSdkEventType.CHAT_MESSAGE_SENT`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
}
```

<Note>
  For privacy reasons, the message content is not included in the event payload. Use this event to track engagement metrics like message frequency.
</Note>

### CHAT\_PROMPTS\_SHOWN

Emitted when suggested prompts are displayed to the user.

**Event type**: `AiChatSdkEventType.CHAT_PROMPTS_SHOWN`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
  prompts: string[];  // Array of prompt suggestions shown
}
```

### CHAT\_PROMPT\_CLICKED

Emitted when a user clicks a suggested prompt.

**Event type**: `AiChatSdkEventType.CHAT_PROMPT_CLICKED`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
  prompt: string;  // The prompt text that was clicked
}
```

### CHAT\_LINK\_CLICKED

Emitted when a user clicks a link within the chat interface.

**Event type**: `AiChatSdkEventType.CHAT_LINK_CLICKED`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
  url: string;           // The URL that was clicked
  merchantName?: string; // Merchant name if available
  merchantUrl?: string;  // Merchant base URL if available
}
```

**Example**:

```typescript theme={null}
case AiChatSdkEventType.CHAT_LINK_CLICKED:
  analytics.track('chat_link_clicked', {
    sessionId: event.data.chatSessionId,
    url: event.data.url,
    merchantName: event.data.merchantName,
  });
  break;
```

### CHAT\_ERROR\_SHOWN

Emitted when an error is displayed to the user in the chat interface.

**Event type**: `AiChatSdkEventType.CHAT_ERROR_SHOWN`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
}
```

### CHAT\_TOP\_MERCHANTS\_SHOWN

Emitted when a list of top merchants is displayed in the chat.

**Event type**: `AiChatSdkEventType.CHAT_TOP_MERCHANTS_SHOWN`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
  merchants: string[];  // Array of merchant URLs or identifiers
}
```

### CHAT\_TOP\_MERCHANTS\_CLICKED

Emitted when a user clicks on a merchant in the top merchants list.

**Event type**: `AiChatSdkEventType.CHAT_TOP_MERCHANTS_CLICKED`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
  url: string;           // The URL that was clicked
  merchantName?: string; // Merchant name if available
  merchantUrl?: string;  // Merchant base URL if available
}
```

### CHAT\_PRODUCTS\_SHOWN

Emitted when products are displayed in the chat.

**Event type**: `AiChatSdkEventType.CHAT_PRODUCTS_SHOWN`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
}
```

### CHAT\_PRODUCTS\_CLICKED

Emitted when a user clicks on a product.

**Event type**: `AiChatSdkEventType.CHAT_PRODUCTS_CLICKED`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
  url: string;           // The product URL that was clicked
  merchantName?: string; // Merchant name if available
  merchantUrl?: string;  // Merchant base URL if available
}
```

### CHAT\_PRODUCTS\_PAGE\_NEXT\_CLICKED

Emitted when the user clicks to view the next page of products.

**Event type**: `AiChatSdkEventType.CHAT_PRODUCTS_PAGE_NEXT_CLICKED`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
}
```

### CHAT\_PRODUCTS\_PAGE\_PREVIOUS\_CLICKED

Emitted when the user clicks to view the previous page of products.

**Event type**: `AiChatSdkEventType.CHAT_PRODUCTS_PAGE_PREVIOUS_CLICKED`

**Payload**:

```typescript theme={null}
{
  chatSessionId: string;
}
```

## Event types reference

All available event types:

```typescript theme={null}
enum AiChatSdkEventType {
  // Badge events
  BADGE_CLICKED = 'BADGE_CLICKED',
  BADGE_SHOWN = 'BADGE_SHOWN',
  BADGE_CLOSED = 'BADGE_CLOSED',
  BADGE_PROMPT_CLICKED = 'BADGE_PROMPT_CLICKED',

  // Inline events
  INLINE_CLICKED = 'INLINE_CLICKED',
  INLINE_SHOWN = 'INLINE_SHOWN',
  INLINE_PROMPT_CLICKED = 'INLINE_PROMPT_CLICKED',

  // Chat events
  CHAT_SHOWN = 'CHAT_SHOWN',
  CHAT_CLOSED = 'CHAT_CLOSED',
  CHAT_ERROR_SHOWN = 'CHAT_ERROR_SHOWN',
  CHAT_LINK_CLICKED = 'CHAT_LINK_CLICKED',
  CHAT_MESSAGE_SENT = 'CHAT_MESSAGE_SENT',
  CHAT_PROMPT_CLICKED = 'CHAT_PROMPT_CLICKED',
  CHAT_PROMPTS_SHOWN = 'CHAT_PROMPTS_SHOWN',
  CHAT_TOP_MERCHANTS_SHOWN = 'CHAT_TOP_MERCHANTS_SHOWN',
  CHAT_TOP_MERCHANTS_CLICKED = 'CHAT_TOP_MERCHANTS_CLICKED',
  CHAT_PRODUCTS_CLICKED = 'CHAT_PRODUCTS_CLICKED',
  CHAT_PRODUCTS_PAGE_NEXT_CLICKED = 'CHAT_PRODUCTS_PAGE_NEXT_CLICKED',
  CHAT_PRODUCTS_PAGE_PREVIOUS_CLICKED = 'CHAT_PRODUCTS_PAGE_PREVIOUS_CLICKED',
  CHAT_PRODUCTS_SHOWN = 'CHAT_PRODUCTS_SHOWN',
}
```

## Event flow examples

### Badge to chat flow

```
1. User sees badge
   ↓
2. BADGE_SHOWN
   - data: { chatSessionId: '...', prompts: ['Find deals', ...] }
   ↓
3. User clicks a prompt on badge
   ↓
4. BADGE_PROMPT_CLICKED
   - data: { chatSessionId: '...', prompt: 'Find deals' }
   ↓
5. Chat panel opens
   ↓
6. CHAT_SHOWN
   - data: { chatSessionId: '...', initialMessage: 'Find deals' }
   ↓
7. AI responds with merchant recommendations
   ↓
8. CHAT_TOP_MERCHANTS_SHOWN
   - data: { chatSessionId: '...', merchants: ['https://amazon.com', ...] }
```

### Product browsing flow

```
1. User asks about products
   ↓
2. CHAT_MESSAGE_SENT
   - data: { chatSessionId: '...' }
   ↓
3. AI responds with products
   ↓
4. CHAT_PRODUCTS_SHOWN
   - data: { chatSessionId: '...' }
   ↓
5. User clicks next page
   ↓
6. CHAT_PRODUCTS_PAGE_NEXT_CLICKED
   - data: { chatSessionId: '...' }
   ↓
7. User clicks a product
   ↓
8. CHAT_PRODUCTS_CLICKED
   - data: { chatSessionId: '...', url: '...', merchantName: 'Amazon' }
```

## Analytics integration example

Here's a complete example of integrating SDK events with an analytics service:

```typescript theme={null}
import {
  initializeAiChatSdk,
  AiChatSdkEventType,
  type AiChatSdkEvent,
} from '@sleek/ai-chat-sdk';

// Track session durations
const sessionTimers = new Map<string, number>();

// Initialize SDK with event listener
initializeAiChatSdk('your-api-key', {
  // ... config
}, [
  (event: AiChatSdkEvent) => {
    const baseProperties = {
      sessionId: event.data.chatSessionId,
      timestamp: Date.now(),
    };

    switch (event.type) {
      // Badge events
      case AiChatSdkEventType.BADGE_SHOWN:
        analytics.track('ai_badge_shown', {
          ...baseProperties,
          promptCount: event.data.prompts.length,
        });
        break;

      case AiChatSdkEventType.BADGE_CLICKED:
        analytics.track('ai_badge_clicked', baseProperties);
        break;

      case AiChatSdkEventType.BADGE_PROMPT_CLICKED:
        analytics.track('ai_badge_prompt_clicked', {
          ...baseProperties,
          prompt: event.data.prompt,
        });
        break;

      // Inline events
      case AiChatSdkEventType.INLINE_SHOWN:
        analytics.track('ai_inline_shown', {
          ...baseProperties,
          promptCount: event.data.prompts.length,
        });
        break;

      case AiChatSdkEventType.INLINE_PROMPT_CLICKED:
        analytics.track('ai_inline_prompt_clicked', {
          ...baseProperties,
          prompt: event.data.prompt,
        });
        break;

      // Chat events
      case AiChatSdkEventType.CHAT_SHOWN:
        sessionTimers.set(event.data.chatSessionId, Date.now());
        analytics.track('ai_chat_opened', {
          ...baseProperties,
          hasInitialMessage: !!event.data.initialMessage,
        });
        break;

      case AiChatSdkEventType.CHAT_CLOSED:
        const startTime = sessionTimers.get(event.data.chatSessionId);
        const duration = startTime ? Date.now() - startTime : 0;
        analytics.track('ai_chat_closed', {
          ...baseProperties,
          sessionDurationMs: duration,
        });
        sessionTimers.delete(event.data.chatSessionId);
        break;

      case AiChatSdkEventType.CHAT_MESSAGE_SENT:
        analytics.track('ai_chat_message_sent', baseProperties);
        break;

      case AiChatSdkEventType.CHAT_LINK_CLICKED:
        analytics.track('ai_chat_link_clicked', {
          ...baseProperties,
          url: event.data.url,
          merchantName: event.data.merchantName,
        });
        break;

      case AiChatSdkEventType.CHAT_TOP_MERCHANTS_CLICKED:
        analytics.track('ai_merchant_clicked', {
          ...baseProperties,
          url: event.data.url,
          merchantName: event.data.merchantName,
        });
        break;

      case AiChatSdkEventType.CHAT_PRODUCTS_CLICKED:
        analytics.track('ai_product_clicked', {
          ...baseProperties,
          url: event.data.url,
          merchantName: event.data.merchantName,
        });
        break;

      case AiChatSdkEventType.CHAT_ERROR_SHOWN:
        analytics.track('ai_chat_error', baseProperties);
        break;
    }
  }
]);
```

## Debugging events

Enable debug mode to see all events logged to the console:

```typescript theme={null}
initializeAiChatSdk('your-api-key', {
  enableDebug: true,  // Enable debug logging
  // ... other options
});
```

You can also add a simple debug listener:

```typescript theme={null}
initializeAiChatSdk('your-api-key', {
  // ... config
}, [
  (event) => {
    console.group(`SDK Event: ${event.type}`);
    console.log('Data:', event.data);
    console.log('Session ID:', event.data.chatSessionId);
    console.groupEnd();
  }
]);
```

## Best practices

### 1. Track meaningful metrics

Focus on events that provide business value:

* **Entry point engagement**: `BADGE_SHOWN` → `BADGE_CLICKED` → `CHAT_SHOWN`
* **Conversion funnel**: `CHAT_PROMPTS_SHOWN` → `CHAT_PROMPT_CLICKED` → `CHAT_PRODUCTS_CLICKED`
* **Session duration**: Time between `CHAT_SHOWN` and `CHAT_CLOSED`
* **Error monitoring**: `CHAT_ERROR_SHOWN` frequency

### 2. Handle errors gracefully

Wrap event handlers in try-catch to prevent one handler from breaking others:

```typescript theme={null}
initializeAiChatSdk('your-api-key', {}, [
  (event) => {
    try {
      handleEvent(event);
    } catch (error) {
      console.error('Error handling SDK event:', error);
    }
  }
]);
```

### 3. Avoid blocking operations

Event handlers should be fast and non-blocking:

```typescript theme={null}
initializeAiChatSdk('your-api-key', {}, [
  (event) => {
    // Good: Fire and forget
    analytics.track(event.type, event.data);

    // Avoid: Blocking async operation
    // await someSlowOperation();
  }
]);
```

### 4. Clean up resources

Use events to manage resources like timers:

```typescript theme={null}
case AiChatSdkEventType.CHAT_CLOSED:
  sessionTimers.delete(event.data.chatSessionId);
  sessionData.delete(event.data.chatSessionId);
  break;
```

### 5. Respect user privacy

Be mindful of what data you collect:

```typescript theme={null}
case AiChatSdkEventType.CHAT_MESSAGE_SENT:
  // Good: Track that a message was sent
  analytics.track('message_sent', {
    sessionId: event.data.chatSessionId,
  });

  // Note: Message content is not included in the event payload
  // This protects user privacy by default
  break;
```
