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

# Debug Plugin

> Development logging, event validation, and dry-run mode

## Overview

The DebugPlugin helps during development by logging events, validating parameters, and optionally preventing events from being sent.

## Installation

```typescript theme={null}
import { Refine, DebugPlugin } from '@refine-ai/sdk';

const refine = new Refine({
  apiKey: process.env.REFINE_API_KEY,
  organizationId: 'org_abc123',
  catalogId: 'cat_xyz789'
});

refine.use(new DebugPlugin({
  logEvents: true,
  validateEvents: true,
  dryRun: false
}));
```

## Options

<ParamField body="logEvents" type="boolean" default="true">
  Log all events to the browser console with formatted output.
</ParamField>

<ParamField body="validateEvents" type="boolean" default="true">
  Validate event parameters and warn about potential issues.
</ParamField>

<ParamField body="dryRun" type="boolean" default="false">
  Prevent events from being sent to the server. Useful for testing.
</ParamField>

## Console Output

With `logEvents: true`, you'll see detailed logs:

```
[Refine] trackSearch
  query: "summer dress"
  surface: "search_results"
  itemCount: 24
  totalResults: 847

[Refine] trackClick
  itemId: "sku_001"
  position: 3
  serveId: "srv_abc123"

[Refine] trackPurchase
  orderId: "order_789"
  value: 149.99
  currency: "USD"
  items: 2
```

## Validation Warnings

With `validateEvents: true`, the plugin warns about common issues:

```
[Refine Warning] trackClick called with position > 100. 
  This may indicate incorrect position tracking.
  Position: 247

[Refine Warning] trackPurchase item "sku_unknown" not found in recent serves.
  This item may not be attributable to a search/recommendation.

[Refine Warning] trackView called before trackItemsServed.
  Ensure items are served before tracking views.
```

## Dry Run Mode

With `dryRun: true`, events are processed but not sent:

```typescript theme={null}
refine.use(new DebugPlugin({
  logEvents: true,
  dryRun: true  // Events won't reach the server
}));

// This will be logged but not sent
refine.events.trackPurchase({
  orderId: 'test_order',
  value: 99.99,
  currency: 'USD',
  items: [{ itemId: 'test_sku', quantity: 1, unitPrice: 99.99 }]
});

// Console shows:
// [Refine] trackPurchase (DRY RUN - not sent)
//   orderId: "test_order"
//   ...
```

## Development vs Production

Only enable in development:

```typescript theme={null}
import { Refine, DebugPlugin } from '@refine-ai/sdk';

const refine = new Refine({
  apiKey: process.env.REFINE_API_KEY,
  organizationId: 'org_abc123',
  catalogId: 'cat_xyz789'
});

if (process.env.NODE_ENV === 'development') {
  refine.use(new DebugPlugin({
    logEvents: true,
    validateEvents: true,
    dryRun: false
  }));
}
```

## Debugging Specific Issues

### Missing Event Attribution

```typescript theme={null}
// Enable verbose logging
refine.use(new DebugPlugin({
  logEvents: true,
  validateEvents: true
}));

// Search
const results = await refine.search.text({ query: 'shoes', topK: 20 });
const context = refine.events.trackSearch('shoes', results.results, { 
  surface: 'search_results',
  totalResults: results.totalResults 
});

// Click - if position is wrong, you'll see a warning
context.trackClick('sku_001', 3);
// [Refine] trackClick
//   itemId: "sku_001"
//   position: 3
//   serveId: "srv_abc123"
```

### Event Queue Issues

```typescript theme={null}
// Check queue status
const metrics = refine.events.getMetrics();
console.log(metrics);
// { queued: 5, sent: 142, failed: 2, retrying: 1 }

// Force flush to debug sending issues
await refine.events.flush();
```

### Identity Verification

```typescript theme={null}
// Log current identity state
console.log('Visitor:', refine.getVisitorId());
console.log('Session:', refine.getSessionId());
console.log('User:', refine.getUserId());
```

## Testing Integration

Use dry run mode for automated tests:

```typescript theme={null}
// test/search.test.ts
import { Refine, DebugPlugin } from '@refine-ai/sdk';

describe('Search tracking', () => {
  let refine: Refine;
  let debugPlugin: DebugPlugin;

  beforeEach(() => {
    refine = new Refine({
      apiKey: 'test-key',
      organizationId: 'test-org',
      catalogId: 'test-catalog'
    });

    debugPlugin = new DebugPlugin({
      logEvents: false,  // Quiet in tests
      validateEvents: true,
      dryRun: true       // Don't send real events
    });

    refine.use(debugPlugin);
  });

  it('should track search events', async () => {
    const context = refine.events.trackSearch(
      'test query',
      [{ productId: 'sku_001' }],
      { surface: 'search_results', totalResults: 1 }
    );

    // Event is validated but not sent
    expect(context).toBeDefined();
  });
});
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Consent Plugin" icon="shield-check" href="/sdk/plugins/consent-plugin">
    Privacy compliance
  </Card>

  <Card title="Auto Track Plugin" icon="wand-magic-sparkles" href="/sdk/plugins/auto-track-plugin">
    Automatic tracking
  </Card>
</CardGroup>
