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 🙏

© 2026 – Pkg Stats / Ryan Hefner

search-collector-js

v1.1.1

Published

JavaScript library for search collection that works in both browser and Node.js environments

Readme

search-collector-js

Features

  • Singleton API - Simple, plug-and-play interface
  • Fully Injectable - All components can be replaced with custom implementations
  • TypeScript - Full type safety and IDE support
  • UMD Build - Works in browser and Node.js
  • Batching - Automatic event batching with configurable intervals
  • Search Trail Tracking - Query-centric tracking model

Installation

npm install search-collector-js

Quick Start

Basic Usage

import {
    configure,
    initialize,
    trackSearch,
    trackProductClick,
} from 'search-collector-js';

// Configure with defaults
configure({
    endpoint: 'https://your-endpoint-url',
    channel: 'de',
});

// Initialize (sends browser event)
initialize();

// Track events
trackSearch({keywords: 'jacket', count: 42});
trackProductClick({productId: 'prod-123', position: 1, keywords: 'jacket'});

Browser (UMD)


<script src="node_modules/search-collector-js/dist/search-collector-js.js"></script>
<script>
    SearchCollector.configure({
        endpoint: 'https://your-endpoint-url',
        channel: 'de',
    });

    SearchCollector.initialize();
    SearchCollector.trackSearch({keywords: 'shoes', count: 100});
</script>

Architecture

The library is built on a modular architecture with injectable dependencies:

SearchCollectorCore
├── Transport          → Handles event transmission
├── SessionStore       → Manages session IDs (48h sliding window)
├── TrailStore         → Tracks search trails (current/previous query)
├── EventQueue         → Batches events (respects 10KB/10 events limits)
├── ContextProvider    → Provides URL, referrer, user agent, etc.
└── TimestampProvider  → Provides timestamps

Custom Implementations

All components can be replaced with custom implementations:

import {
    configure,
    SimpleBatchQueue,
    InMemoryTrailStore,
    ManualContextProvider,
    SingleSessionStore,
} from 'search-collector-js';

const customSession = new SingleSessionStore();
const customTrailStore = new InMemoryTrailStore();
const customContext = new ManualContextProvider(
    'https://example.com',
    'https://google.com',
    'Custom User Agent',
    false,
    'de-DE'
);

configure({
    endpoint: 'https://your-endpoint-url',
    channel: 'de',
    overrides: {
        sessionStore: customSession,
        trailStore: customTrailStore,
        contextProvider: customContext,
        eventQueue: new SimpleBatchQueue(20),
    },
});

Available Implementations

Transport

  • ShSqsTransport - AWS SQS transport for searchHub

SessionStore

  • CookieSessionStore - Browser cookies (default in browser runtime)
  • LocalStorageSessionStore - Browser localStorage
  • SingleSessionStore - Memory-based session store (default in non-browser runtime)

TrailStore

  • BrowserTrailStore - localStorage/sessionStorage-backed (default in browser runtime)
  • InMemoryTrailStore - memory-backed (default in non-browser runtime)

EventQueue

  • SimpleBatchQueue - Batches events with 10KB/10 events limits (in-memory)
  • LocalStorageEventQueue - Persists events in localStorage, survives page reloads

ContextProvider

  • BrowserContextProvider - Auto-detects browser context (default)
  • ManualContextProvider - Manual context for Node.js

TimestampProvider

  • SystemTimestampProvider - Uses Date.now()

Event Persistence

The LocalStorageEventQueue provides automatic event persistence in the browser. Events are stored in localStorage and survive page reloads, browser crashes, or network issues.

Using LocalStorageEventQueue

import {
    configure,
    LocalStorageEventQueue,
} from 'search-collector-js';

const eventQueue = new LocalStorageEventQueue(undefined, 10);

configure({
    endpoint: 'https://my-queue-url',
    channel: 'de',
    overrides: {eventQueue},
});

Benefits

  • Reliability: Events are not lost if the page is closed before sending
  • Offline Support: Events accumulate in localStorage when offline
  • Automatic Recovery: On next page load, queued events are automatically sent
  • Storage Key: Events are stored under search-collector-queue (or search-collector-queue-<id>)

How It Works

  1. Events are immediately written to localStorage on enqueue()
  2. Events are batched and sent during flush() (manual or auto)
  3. After successful transmission, events are removed from localStorage
  4. If sending fails, events remain in localStorage for retry
  5. On page load, any existing events are loaded and queued for sending

Event Tracking API

Session Events

initialize()  // Sends browser event with user agent, touch, language

Search Events

trackInstantSearch({keywords: string})
trackFiredSearch({keywords: string})
trackSuggestClick({keywords: string, prefix: string, position: number})
trackSuggestProductClick({keywords: string, prefix: string, position: number, productId: string})
trackSearch({keywords: string, count: number, action? : SearchAction})
trackRedirect({keywords: string, resultCount: number})

Product Events

trackImpression({products: Array < {id: string; position: number} >})
trackProductClick({productId: string, position: number, keywords: string})
trackAssociatedProductClick({productId: string, position: number, keywords: string})

Conversion Events

trackBasket({productId: string, price: number})
trackCheckout({products: Array < {id: string; price: number; quantity: number} >})

Utility Functions

flush()                        // Force-send queued events
registerTrail({key: string, query: string | Query, trailType? : TrailType})
copyTrail({fromProductId: string, toProductId: string})  // Copy trail to variant
reset()                        // Reset singleton instance

Configuration Options

interface SearchCollectorConfig {
    endpoint: string;              // Required: Transport endpoint
    channel: string;               // Required: Channel identifier (e.g., 'de', 'en')
    logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent';
    logger?: Logger;
    queueSettings?: {
        batchInterval?: number;      // Optional: Auto-flush interval in ms (default: 5000)
        maxBatchSize?: number;       // Optional: Max events per batch (default: 10)
    };

    // Injectable dependencies
    overrides?: {
        transport?: Transport;
        sessionStore?: SessionStore;
        trailStore?: TrailStore;
        eventQueue?: EventQueue;
        contextProvider?: ContextProvider;
        timestampProvider?: TimestampProvider;
    };
}

Creating Custom Implementations

Custom Transport

import {Transport, SearchCollectorEvent} from 'search-collector-js';

class MyCustomTransport implements Transport {
    async send(events: SearchCollectorEvent[]): Promise<void> {
        // Implement your custom transport logic
        await fetch('https://my-api.com/events', {
            method: 'POST',
            body: JSON.stringify(events)
        });
    }
}

Custom SessionStore

import {SessionStore} from 'search-collector-js';

class MyCustomSessionStore implements SessionStore {
    getOrCreateSessionId(): string {
        // Return or create session ID
    }

    touch(): void {
        // Update last activity timestamp
    }
}

Development

Install dependencies

npm install

Build

npm run build

Run example

npm run example

Lint

npm run lint

License

MIT