npm package: @sig-ai-aeo/sdk
Description: Sig AI AEO SDK - Make your app AI-discoverable with one line of code
Author: Sig AI Health
Latest version: 1.2.0

# @sig-ai-aeo/sdk

> Make your app AI-discoverable with one line of code

[![npm version](https://img.shields.io/npm/v/@sig-ai-aeo/sdk.svg)](https://www.npmjs.com/package/@sig-ai-aeo/sdk)
[![Bundle Size](https://img.shields.io/bundlephobia/minzip/@sig-ai-aeo/sdk)](https://bundlephobia.com/package/@sig-ai-aeo/sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

The Sig AI AEO (AI Engine Optimization) SDK is a lightweight JavaScript library that helps you optimize your web application for AI discovery, track AI-driven traffic, and improve your content's visibility across AI platforms like ChatGPT, Gemini, Perplexity, Grok, and Claude.

## Features

- 🚀 **One-line Integration** - Get started in seconds
- 🤖 **AI Traffic Attribution** - Automatically detect and track AI-referred visitors (94%+ accuracy)
- ⚡ **Content Optimization** - Server-side AI-powered content analysis
- 📊 **Analytics Dashboard** - Real-time AI traffic insights
- 🎯 **Event Tracking** - Custom events, conversions, and page views
- 📦 **Tiny Bundle** - <12KB minified + gzipped
- 🔒 **Privacy-First** - GDPR/CCPA compliant
- 🎨 **Framework Agnostic** - Works with React, Vue, Angular, or vanilla JS

## Quick Start

### Getting Your API Key

Before using the SDK, you'll need an API key from your Sig AI AEO account:

1. **Create a free account** at [aeo.sig.ai](https://aeo.sig.ai)
2. Navigate to **Dashboard → Account Settings**
3. Click on the **"API Keys"** tab
4. Click **"Create New API Key"** button
5. Give your key a descriptive name and **copy it securely**

> ⚠️ **Important:** Store your API key securely - it won't be shown again after creation!

**Free Tier:** 10,000 API calls per month
**Need more?** [View pricing plans](https://aeo.sig.ai/pricing)

### Installation

#### Option 1: CDN (Recommended for Quick Start)

```html
<!-- Core SDK (7.97 KB gzipped) - Recommended for most apps -->
<script src="https://cdn.sig.ai/sdk/web/core/latest.js"
        integrity="sha384-0Ra58W8gPhmD1h3CYL3VkYWiD1P2ilYsYGO7cWEsktUZAMmwNVlYp/aN2AF+QW6L"
        crossorigin="anonymous"></script>

<!-- Full SDK with React/Vue (32.07 KB gzipped) -->
<script src="https://cdn.sig.ai/sdk/web/full/latest.js"
        integrity="sha384-klXvU3E3Dp1NhvggReR2VIHu4TQd8pWQgxjq1Z6R3Dvkih/dtku6wToYdXLksVUc"
        crossorigin="anonymous"></script>
```

**Benefits:**
- ✅ No build step required
- ✅ Instant global CDN delivery (300+ edge locations)
- ✅ Automatic browser caching
- ✅ Subresource Integrity (SRI) for security

**Version-specific URLs** (recommended for production):
```html
<!-- Core SDK v1.1.3 (immutable, cached for 1 year) -->
<script src="https://cdn.sig.ai/sdk/web/core/v1.1.3.js"></script>

<!-- Or use major version (auto-updates to latest v1.x) -->
<script src="https://cdn.sig.ai/sdk/web/core/v1.js"></script>
```

#### Option 2: npm/yarn

```bash
npm install @sig-ai-aeo/sdk
# or
yarn add @sig-ai-aeo/sdk
```

### Import Paths

The SDK provides modular imports for tree-shaking:

```javascript
// Core SDK only (minimal bundle)
import { AIVisibility } from '@sig-ai-aeo/sdk/core';

// React bindings only
import { AIVisibilityProvider, useAIVisibility } from '@sig-ai-aeo/sdk/react';

// Vue bindings only
import { provideAIVisibility, useAIVisibility } from '@sig-ai-aeo/sdk/vue';

// Everything (default import)
import { AIVisibility } from '@sig-ai-aeo/sdk';
```

### Basic Usage

#### With CDN (HTML)

```html
<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.sig.ai/sdk/web/core/latest.js"></script>
</head>
<body>
  <script>
    // Initialize the SDK
    AIVisibility.init({
      apiKey: 'your-api-key-here',
      autoTrack: true  // Automatically track page views
    });
  </script>
</body>
</html>
```

#### With npm/yarn (JavaScript)

```javascript
import { AIVisibility } from '@sig-ai-aeo/sdk';

// Initialize the SDK
AIVisibility.init({
  apiKey: 'your-api-key-here',
  autoTrack: true  // Automatically track page views
});
```

That's it! The SDK will now:
- ✅ Automatically track page views
- ✅ Detect AI-referred traffic
- ✅ Send analytics to your dashboard

## Usage Examples

### Tracking Custom Events

```javascript
// Track a custom event
AIVisibility.track('button_clicked', {
  button_id: 'signup',
  location: 'header'
});

// Track conversions
AIVisibility.trackConversion(99.99, {
  product_id: 'premium-plan',
  currency: 'USD'
});
```

### Content Optimization

```javascript
// Optimize content for AI discovery
const result = await AIVisibility.optimize(document.body.innerText, {
  content_type: 'article',
  include_structured_data: true,
  include_recommendations: true
});

console.log('Optimization Score:', result.optimization_score);
console.log('Suggestions:', result.suggestions);
console.log('Structured Data:', result.structured_data);
```

### AI Attribution Detection

```javascript
// Get current visitor's AI attribution
const attribution = AIVisibility.getAttribution();

if (attribution.source) {
  console.log(`Visitor from ${attribution.source} with ${attribution.confidence * 100}% confidence`);
  // Example output: "Visitor from chatgpt with 95% confidence"
}
```

### React Integration

#### Using React Hooks (Recommended)

```jsx
import {
  AIVisibilityProvider,
  useAIVisibility,
  usePageTracking,
  useEventTracker,
  useConversionTracker,
  AIAttributionBadge
} from '@sig-ai-aeo/sdk';

// Wrap your app with the provider
function App() {
  return (
    <AIVisibilityProvider
      config={{
        apiKey: process.env.REACT_APP_SIG_AI_AEO_API_KEY,
        autoTrack: true,
        debug: process.env.NODE_ENV === 'development'
      }}
    >
      <Dashboard />
    </AIVisibilityProvider>
  );
}

// Use hooks in your components
function Dashboard() {
  // Auto-track this page view
  usePageTracking({ page: 'dashboard' });

  // Get event and conversion trackers
  const trackEvent = useEventTracker();
  const trackConversion = useConversionTracker();

  const handleClick = () => {
    trackEvent('button_clicked', { button_id: 'signup' });
  };

  const handlePurchase = () => {
    trackConversion(99.99, { plan: 'pro' });
  };

  return (
    <div>
      <AIAttributionBadge showConfidence />
      <button onClick={handleClick}>Sign Up</button>
      <button onClick={handlePurchase}>Purchase</button>
    </div>
  );
}
```

#### All Available React Hooks

```jsx
import {
  useAIVisibility,        // Access SDK methods
  usePageTracking,        // Auto-track page views
  useAIAttribution,       // Get AI attribution
  useEventTracker,        // Track custom events
  useConversionTracker,   // Track conversions
  useAnalytics,           // Get analytics data
  useContentOptimization, // Optimize content
  useRateLimitInfo        // Get rate limit status
} from '@sig-ai-aeo/sdk';

// Example: Analytics hook with loading states
function AnalyticsDashboard() {
  const { data, loading, error, refetch } = useAnalytics({
    startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
    endDate: new Date()
  });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h2>Total Events: {data.metrics.total_events}</h2>
      <h2>AI Traffic: {data.metrics.ai_traffic}</h2>
      <button onClick={refetch}>Refresh</button>
    </div>
  );
}
```

#### Using Components

```jsx
import { AIAttributionBadge, PageTracker } from '@sig-ai-aeo/sdk';

function MyComponent() {
  return (
    <div>
      {/* Auto-track page view */}
      <PageTracker metadata={{ section: 'landing' }} />

      {/* Display AI attribution badge */}
      <AIAttributionBadge showConfidence />
    </div>
  );
}
```

#### Vanilla React (without hooks)

```jsx
import { useEffect } from 'react';
import { AIVisibility } from '@sig-ai-aeo/sdk';

function App() {
  useEffect(() => {
    AIVisibility.init({
      apiKey: process.env.REACT_APP_SIG_AI_AEO_API_KEY,
      autoTrack: true
    });
  }, []);

  const handleSignup = async () => {
    await AIVisibility.track('signup_completed', { plan: 'pro' });
  };

  return <button onClick={handleSignup}>Sign Up</button>;
}
```

### Vue Integration

```vue
<script setup>
import { onMounted } from 'vue';
import { AIVisibility } from '@sig-ai-aeo/sdk';

onMounted(() => {
  AIVisibility.init({
    apiKey: import.meta.env.VITE_SIG_AI_AEO_API_KEY,
    autoTrack: true
  });
});

const handleSignup = async () => {
  await AIVisibility.trackConversion(99.99, {
    plan: 'premium'
  });
};
</script>

<template>
  <button @click="handleSignup">Sign Up</button>
</template>
```

### Next.js Integration

```typescript
// app/providers.tsx
'use client';

import { useEffect } from 'react';
import { AIVisibility } from '@sig-ai-aeo/sdk';

export function AIVisibilityProvider({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    AIVisibility.init({
      apiKey: process.env.NEXT_PUBLIC_SIG_AI_AEO_API_KEY!,
      autoTrack: true
    });
  }, []);

  return <>{children}</>;
}

// app/layout.tsx
import { AIVisibilityProvider } from './providers';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <AIVisibilityProvider>
          {children}
        </AIVisibilityProvider>
      </body>
    </html>
  );
}
```

## Configuration Options

```typescript
AIVisibility.init({
  apiKey: string;                    // Required: Your API key
  apiEndpoint?: string;              // Optional: API endpoint (default: https://rankapi.sig.ai)
  debug?: boolean;                   // Optional: Enable debug logging
  autoTrack?: boolean;               // Optional: Auto-track page views (default: true)
  batchEvents?: boolean;             // Optional: Batch events for performance (default: true)
  batchSize?: number;                // Optional: Events per batch (default: 20)
  batchInterval?: number;            // Optional: Batch flush interval in ms (default: 5000)
  sessionTimeout?: number;           // Optional: Session timeout in minutes (default: 30)
  cookieDomain?: string;             // Optional: Cookie domain for cross-subdomain tracking
  headers?: Record<string, string>;  // Optional: Custom headers for API requests
  onError?: (error: SDKError) => void;      // Optional: Error callback
  onSuccess?: (event: TrackedEvent) => void; // Optional: Success callback
});
```

## API Reference

### Core Methods

#### `init(config: SDKConfig): void`
Initialize the SDK with your configuration.

#### `track(eventName: string, data?: Record<string, any>): Promise<TrackedEvent>`
Track a custom event.

#### `trackPageView(url?: string, metadata?: Record<string, any>): Promise<TrackedEvent>`
Track a page view.

#### `trackConversion(value: number, metadata?: Record<string, any>): Promise<TrackedEvent>`
Track a conversion event.

### Content Optimization

#### `optimize(content: string, options?: OptimizationRequest): Promise<OptimizationResult>`
Optimize content for AI discovery.

**Options:**
- `url?: string` - URL of the content
- `content_type?: 'product' | 'article' | 'landing_page' | 'documentation'`
- `include_structured_data?: boolean` - Generate JSON-LD structured data
- `include_recommendations?: boolean` - Include optimization recommendations

### Analytics

#### `getAnalytics(startDate?: Date, endDate?: Date, metrics?: string[]): Promise<AnalyticsData>`
Get analytics data for the specified period.

#### `getAttribution(): AIAttribution`
Get current visitor's AI attribution.

### Session Management

#### `getSessionId(): string`
Get current session ID.

#### `resetSession(): void`
Reset the current session.

#### `setUserProperties(properties: Record<string, any>): void`
Set user properties for tracking.

### Utility

#### `flush(): Promise<void>`
Manually flush the event queue.

#### `healthCheck(): Promise<boolean>`
Check API health.

#### `getRateLimitInfo(): RateLimitInfo | null`
Get current rate limit information.

#### `renderWidget(container: HTMLElement | string, config: WidgetConfig): Promise<void>`
Render an embeddable analytics widget.

**Widget Types:**
- `traffic_summary` - Display AI traffic metrics
- `top_pages` - Show most visited pages from AI
- `optimization_score` - Display average optimization score
- `realtime_activity` - Live feed of AI traffic events

**Options:**
- `widget_type` (required) - Type of widget to render
- `theme?: 'light' | 'dark' | 'auto'` - Widget theme
- `accent_color?: string` - Primary color (hex)
- `show_upgrade_prompts?: boolean` - Show upgrade CTAs
- `embed_mode?: boolean` - Use iframe for isolation (recommended)

**Example:**
```javascript
await AIVisibility.renderWidget('#widget-container', {
  widget_type: 'traffic_summary',
  theme: 'light',
  accent_color: '#4169E1',
  show_upgrade_prompts: true,
  embed_mode: true
});
```

#### `destroy(): void`
Destroy the SDK instance and clean up.

## AI Attribution Methods

The SDK uses multiple methods to detect AI-referred traffic:

1. **User-Agent Detection** (95% confidence)
   - Detects AI bot user agents (GPTBot, PerplexityBot, etc.)

2. **Referrer Analysis** (90% confidence)
   - Detects referrers from AI platforms (chat.openai.com, perplexity.ai, etc.)

3. **Query Parameter Tracking** (85% confidence)
   - Detects UTM parameters (utm_source=chatgpt, ref=perplexity, etc.)

4. **Cookie Persistence** (70% confidence)
   - Persists attribution across sessions

## Performance

- **Bundle Size:** <12KB minified + gzipped
- **Load Time:** <100ms on 3G connection
- **Memory:** <2MB footprint
- **Network:** Events batched to minimize requests

## Browser Support

- Chrome/Edge: Latest 2 versions
- Firefox: Latest 2 versions
- Safari: Latest 2 versions
- iOS Safari: iOS 13+
- Android Chrome: Android 5.0+

## TypeScript Support

The SDK is written in TypeScript and includes full type definitions.

```typescript
import { AIVisibility, TrackedEvent, AIAttribution } from '@sig-ai-aeo/sdk';

const event: TrackedEvent = await AIVisibility.track('click', { button: 'signup' });
const attribution: AIAttribution = AIVisibility.getAttribution();
```

## Privacy & Security

### Security Hardening (v1.0.1)

The SDK has undergone comprehensive security hardening with all critical vulnerabilities addressed:

- ✅ **XSS Protection** - All user-provided data is properly escaped in widgets
- ✅ **PostMessage Security** - Origin verification with configurable allowlists
- ✅ **Session Security** - Crypto-secure IDs, automatic expiry, sessionStorage
- ✅ **Input Validation** - Comprehensive validation of all user inputs (50KB limit)
- ✅ **Memory Safety** - Bounded queues, proper cleanup, no memory leaks
- ✅ **Data Integrity** - No data loss during navigation (sendBeacon API)

### Privacy & Compliance

- ✅ **GDPR/CCPA Compliant** - IP addresses are hashed
- ✅ **No PII Collection** - No personal data stored without consent
- ✅ **Secure** - All requests use HTTPS/TLS 1.3
- ✅ **Transparent** - Open source and auditable

For detailed security information, see:
- [SECURITY-ASSESSMENT-FINAL.md](./SECURITY-ASSESSMENT-FINAL.md) - Production readiness assessment
- [SECURITY-FIXES.md](./SECURITY-FIXES.md) - Detailed security improvements
- [CHANGELOG.md](./CHANGELOG.md) - Complete change history

## Pricing

- **Free Tier:** Unlimited events for 1 domain
- **Pro Tier:** $99/month - Multiple domains + advanced features
- **Enterprise:** Custom pricing - White-label + SLA

[View full pricing →](https://aeo.sig.ai/pricing)

## Support

- 📚 [Documentation](https://aeo.sig.ai/docs)
- 📧 [Email Support](mailto:support@sig.ai)
- 🐛 [Report Issues](https://github.com/sigaihealth/sig-ai-aeo-sdk/issues)

## Examples

Check out example integrations:
- [React Example](./examples/react-app) - Complete React demo
- [Widget Demo](./examples/widget-demo.html) - Embeddable widgets
- [Vue Example](./examples/vue) - Vue 3 integration
- [Next.js Example](./examples/nextjs) - Next.js App Router

## SDK Status

### Production Ready ✅ (v1.1.3 - October 28, 2025)

**Client:**
- ✅ 33 unit tests passing (100% success rate)
- ✅ Zero critical vulnerabilities
- ✅ Security grade: A+ (96/100)
- ✅ Bundle size: 7.1KB (core), 32KB (full) gzipped
- ✅ Published to NPM: `@sig-ai-aeo/sdk@1.1.3`
- ✅ CDN: `https://cdn.sig.ai/sdk/web/full/latest.js`

**Backend Integration:**
- ✅ Health check: PASSED (production backend operational)
- ✅ Single event endpoint: OPERATIONAL (`/api/sdk/v1/track`)
- ✅ Batch event endpoint: OPERATIONAL (`/api/sdk/v1/track/batch`)
- ✅ Authentication: Properly enforced (401 for invalid keys)
- ✅ Backend URL: https://rankapi.sig.ai

**Test Coverage:**
- Unit tests: 33/33 passing (mocked fetch calls)
- Integration tests: Backend connectivity verified (October 28, 2025)
- See [TEST-REPORT.md](./TEST-REPORT.md) for detailed results

**Documentation:**
- [CHANGELOG.md](./CHANGELOG.md) - Version history
- [SECURITY-ASSESSMENT-FINAL.md](./SECURITY-ASSESSMENT-FINAL.md) - Security audit
- [TEST-REPORT.md](./TEST-REPORT.md) - Test results and coverage

## License

MIT © Sig AI Health

---

Made with ❤️ by the Sig AI team