npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@earnlayer/ai-ads-sdk

v1.0.0

Published

Integrate contextual advertising with any AI model using production-ready React components

Readme

@earnlayer/ai-ads-sdk

npm version License: MIT

Integrate contextual advertising with any AI model using production-ready React components. Battle-tested from the EarnLayer platform.

Features

  • 🤖 AI Model Support: Works with Gemini, OpenAI, Claude, and custom models
  • ⚛️ React Components: Pre-built ad components for easy integration
  • 🎯 Contextual Ads: AI-powered ad selection based on conversation context
  • 📊 Analytics: Built-in tracking and analytics for ad performance
  • 🔗 MCP Integration: Model Context Protocol for advanced ad management
  • 📱 Responsive: Mobile-first design with touch-friendly interactions
  • 🎨 Customizable: Full control over ad appearance and behavior
  • ⚡ Performance: Optimized for production with minimal bundle impact

Installation

npm install @earnlayer/ai-ads-sdk
# or
yarn add @earnlayer/ai-ads-sdk
# or
pnpm add @earnlayer/ai-ads-sdk

Quick Start

1. Basic Setup

import { EarnLayerSDK, GeminiAdapter, AdStateProvider } from '@earnlayer/ai-ads-sdk';

// Initialize SDK
const sdk = new EarnLayerSDK({
  creatorId: 'your-creator-id',
  aiModel: new GeminiAdapter('your-gemini-api-key')
});

// Wrap your app with AdStateProvider
function App() {
  return (
    <AdStateProvider>
      <YourChatInterface />
    </AdStateProvider>
  );
}

2. Add Ad Components

import { 
  ManagedBannerAd, 
  ManagedPopupAd, 
  ManagedThinkingAd 
} from '@earnlayer/ai-ads-sdk';

function ChatInterface() {
  return (
    <div className="chat-container">
      {/* Your chat messages */}
      <div className="messages">
        {/* Chat content */}
      </div>
      
      {/* SDK Ad Components */}
      <ManagedBannerAd className="my-4" />
      <ManagedPopupAd />
      <ManagedThinkingAd />
    </div>
  );
}

3. Handle User Interactions

import { useAdState } from '@earnlayer/ai-ads-sdk';

function AdController() {
  const { state, actions } = useAdState();
  
  const handleAdClick = (ad: any) => {
    console.log('Ad clicked:', ad);
    // Track the click
  };
  
  return (
    <ManagedBannerAd onAdClick={handleAdClick} />
  );
}

AI Model Support

Gemini (Google)

import { EarnLayerSDK, GeminiAdapter } from '@earnlayer/ai-ads-sdk';

const sdk = new EarnLayerSDK({
  creatorId: 'your-creator-id',
  aiModel: new GeminiAdapter('your-gemini-api-key', 'gemini-1.5-pro')
});

OpenAI

import { EarnLayerSDK, OpenAIAdapter } from '@earnlayer/ai-ads-sdk';

const sdk = new EarnLayerSDK({
  creatorId: 'your-creator-id',
  aiModel: new OpenAIAdapter('your-openai-api-key', 'gpt-4')
});

Claude (Anthropic)

import { EarnLayerSDK, ClaudeAdapter } from '@earnlayer/ai-ads-sdk';

const sdk = new EarnLayerSDK({
  creatorId: 'your-creator-id',
  aiModel: new ClaudeAdapter('your-claude-api-key', 'claude-3-sonnet')
});

Custom Models

import { EarnLayerSDK, BaseAIModelAdapter } from '@earnlayer/ai-ads-sdk';

class CustomAdapter extends BaseAIModelAdapter {
  async generateResponse(messages: any[], options: any) {
    // Your custom AI model implementation
    return {
      content: 'Response from your custom model',
      usage: { tokens: 100 }
    };
  }
}

const sdk = new EarnLayerSDK({
  creatorId: 'your-creator-id',
  aiModel: new CustomAdapter()
});

Ad Components

Banner Ads

import { ManagedBannerAd } from '@earnlayer/ai-ads-sdk';

<ManagedBannerAd 
  className="my-4"
  onAdClick={(ad) => console.log('Banner clicked:', ad)}
/>

Popup Ads

import { ManagedPopupAd } from '@earnlayer/ai-ads-sdk';

<ManagedPopupAd 
  onAdClick={(ad) => console.log('Popup clicked:', ad)}
/>

Thinking Ads

import { ManagedThinkingAd } from '@earnlayer/ai-ads-sdk';

<ManagedThinkingAd />

Video Ads

import { ManagedVideoAd } from '@earnlayer/ai-ads-sdk';

<ManagedVideoAd 
  onAdClick={(ad) => console.log('Video clicked:', ad)}
/>

State Management

Ad State Context

import { useAdState } from '@earnlayer/ai-ads-sdk';

function AdController() {
  const { state, actions } = useAdState();
  
  // Access ad state
  console.log('Banner ad:', state.banner.ad);
  console.log('Popup ad:', state.popup.ad);
  
  // Control ads programmatically
  const showCustomAd = () => {
    actions.setAd('banner', {
      ad_id: 'custom-1',
      title: 'Custom Ad',
      description: 'Your custom advertisement',
      url: 'https://example.com',
      ad_type: 'banner',
      placement: 'inline',
      source: 'contextual'
    });
  };
  
  const clearAds = () => {
    actions.clearAd('banner');
    actions.clearAd('popup');
  };
  
  return (
    <div>
      <button onClick={showCustomAd}>Show Custom Ad</button>
      <button onClick={clearAds}>Clear All Ads</button>
    </div>
  );
}

MCP Integration

Model Context Protocol

import { useMCP, ConversationProvider } from '@earnlayer/ai-ads-sdk';

function ChatCore() {
  const {
    loading,
    error,
    hasActiveConversation,
    initializeConversation,
    getHyperlinkAds
  } = useMCP();

  const handleStart = async () => {
    await initializeConversation('creator_123');
  };

  const handleGetAds = async () => {
    const ads = await getHyperlinkAds({
      queries: ['user message'],
      user_message: 'user message',
      include_demo_ads: true
    });
  };

  return (
    <div>
      {!hasActiveConversation && (
        <button onClick={handleStart}>Start Conversation</button>
      )}
      {hasActiveConversation && (
        <button onClick={handleGetAds}>Get Ads</button>
      )}
    </div>
  );
}

// Wrap with ConversationProvider
function App() {
  return (
    <ConversationProvider>
      <ChatCore />
    </ConversationProvider>
  );
}

Analytics & Tracking

Automatic Tracking

The SDK automatically tracks:

  • Ad impressions and views
  • Click-through rates
  • User engagement metrics
  • Revenue attribution

Custom Events

import { DisplayAdAnalyticsService } from '@earnlayer/ai-ads-sdk';

const analytics = new DisplayAdAnalyticsService();

// Track custom events
analytics.trackEvent('custom_interaction', {
  ad_id: 'banner-1',
  user_id: 'user-123',
  metadata: { custom_data: 'value' }
});

Configuration

SDK Configuration

import { EarnLayerSDK, GeminiAdapter } from '@earnlayer/ai-ads-sdk';

const sdk = new EarnLayerSDK({
  creatorId: 'your-creator-id',
  aiModel: new GeminiAdapter('your-api-key'),
  earnLayerConfig: {
    adTypes: ['banner', 'popup', 'thinking'],
    frequency: 'normal',
    revenueVsRelevance: 0.5,
    displayAdSimilarityThreshold: 0.7,
    minSecondsBetweenDisplayAds: 30
  },
  debug: true
});

Ad Preferences

const adPreferences = {
  adTypes: ['banner', 'popup'],
  frequency: 'normal',
  categories: ['technology', 'business'],
  revenueVsRelevance: 0.5,
  displayAdSimilarityThreshold: 0.7
};

Examples

Complete Chat Integration

See our complete example based on the EarnLayer chat page implementation.

Multi-Model Setup

import { 
  EarnLayerSDK, 
  GeminiAdapter, 
  OpenAIAdapter, 
  ClaudeAdapter 
} from '@earnlayer/ai-ads-sdk';

// Switch between models
const models = {
  gemini: new GeminiAdapter('gemini-key'),
  openai: new OpenAIAdapter('openai-key'),
  claude: new ClaudeAdapter('claude-key')
};

const sdk = new EarnLayerSDK({
  creatorId: 'your-creator-id',
  aiModel: models.gemini // Start with Gemini
});

// Switch models dynamically
sdk.setConfig({ aiModel: models.openai });

API Reference

Core SDK

  • EarnLayerSDK - Main SDK class
  • MCPCore - Model Context Protocol core
  • BaseAIModelAdapter - Base class for custom adapters

React Components

  • ManagedAdComponent - Generic ad component
  • ManagedBannerAd - Banner ad component
  • ManagedPopupAd - Popup ad component
  • ManagedThinkingAd - Thinking ad component
  • ManagedVideoAd - Video ad component

Context Providers

  • AdStateProvider - Ad state management
  • ConversationProvider - Conversation management

Hooks

  • useAdState() - Access ad state and actions
  • useAdSlot(adType) - Get specific ad slot
  • useMCP() - MCP conversation management
  • useChatWithAds() - Chat with ads integration
  • useGsapAnimation() - GSAP animation utilities

Services

  • ClickTrackingService - Click tracking
  • DisplayAdAnalyticsService - Analytics service
  • MCPService - MCP service
  • ConversationService - Conversation service

Requirements

  • Node.js: 18.0.0 or higher
  • React: 18.0.0 or higher
  • TypeScript: 4.5.0 or higher (optional but recommended)

Browser Support

  • Chrome 90+
  • Firefox 88+
  • Safari 14+
  • Edge 90+

Contributing

We welcome contributions! Please see our Contributing Guide for details.

License

MIT License - see LICENSE for details.

Support

Changelog

See CHANGELOG.md for a list of changes.


Made with ❤️ by the EarnLayer team