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

@hardlydifficult/usage-tracker

v1.0.66

Published

Numeric usage tracking with session/cumulative dual-tracking, persistence, and spend limits.

Readme

@hardlydifficult/usage-tracker

Numeric usage tracking with session/cumulative dual-tracking, persistence, and spend limits.

Installation

npm install @hardlydifficult/usage-tracker

Quick Start

import { UsageTracker } from "@hardlydifficult/usage-tracker";

const defaults = {
  api: { requests: 0, tokens: 0, costUsd: 0 },
  audio: { requests: 0, durationSeconds: 0 },
};

const tracker = await UsageTracker.create({
  key: "my-app",
  default: defaults,
  stateDirectory: "./state",
});

// Record usage for a session
tracker.record({ api: { requests: 1, tokens: 500, costUsd: 0.01 } });

// Access metrics
console.log(tracker.session.api.requests); // 1
console.log(tracker.cumulative.api.requests); // 1

// Save state to disk
await tracker.save();

Core Concepts

Usage Tracking

Tracks numeric metrics across two timeframes: session (since last create()) and cumulative (all-time). Both are updated atomically on every record() call.

// Record a partial delta — only specify the fields you're incrementing
tracker.record({ api: { requests: 1, tokens: 100 } });

// Unspecified fields remain unchanged
expect(tracker.session.api.costUsd).toBe(0); // unchanged

Cost Tracking

Any leaf field ending in CostUsd (case-insensitive) is automatically detected and recorded in a time-series for spend monitoring.

const defaults = {
  anthropic: { estimatedCostUsd: 0, requests: 0 },
  openai: { costUsd: 0, tokens: 0 },
};

const tracker = await UsageTracker.create({ key: "cost-test", default: defaults });
tracker.record({ anthropic: { estimatedCostUsd: 0.05 }, openai: { costUsd: 0.01 } });

expect(tracker.costInWindow(60_000)).toBeCloseTo(0.06);

Spend Limits

Define trailing-window spend limits and optionally handle violations via a callback or exception.

const tracker = await UsageTracker.create({
  key: "limits-test",
  default: { api: { estimatedCostUsd: 0 } },
  spendLimits: [{ windowMs: 60_000, maxSpendUsd: 5, label: "1 minute" }],
  onSpendLimitExceeded: (status) => {
    console.warn(`Limit exceeded! Resumes at ${status.resumesAt}`);
  },
});

tracker.record({ api: { estimatedCostUsd: 6 } });

// Throws SpendLimitExceededError
tracker.assertWithinSpendLimits();

State Persistence

State is persisted to disk and restored across restarts. Sessions reset automatically, but cumulative totals are preserved.

// First run
const tracker1 = await UsageTracker.create({ key: "persist", default: { a: 0 } });
tracker1.record({ a: 5 });
await tracker1.save();

// Second run (cumulative preserved, session reset)
const tracker2 = await UsageTracker.create({ key: "persist", default: { a: 0 } });
expect(tracker2.cumulative.a).toBe(5);
expect(tracker2.session.a).toBe(0);

API Reference

UsageTracker

Tracks usage metrics and cost (USD) with session/cumulative tracking, spend limits, and persistence.

Static Methods

| Method | Description | |--------|-------------| | UsageTracker.create(options) | Initialize tracker, load persisted state, and start a new session |

Properties

| Property | Type | Description | |----------|------|-------------| | session | Readonly<T> | Current session metrics | | cumulative | Readonly<T> | All-time cumulative metrics | | sessionStartedAt | string | ISO timestamp for session start | | trackingSince | string | ISO timestamp for when tracking began | | isPersistent | boolean | Whether state is persisted to disk |

Methods

| Method | Description | |--------|-------------| | record(values: DeepPartial<T>) | Increment session and cumulative metrics | | costInWindow(windowMs: number) | Get total cost (USD) in a trailing window | | spendStatus() | Get status for all configured spend limits | | assertWithinSpendLimits() | Throw if any limit is exceeded | | save() | Force-save current state to disk |

SpendLimitExceededError

Custom error thrown when a spend limit is exceeded.

try {
  tracker.assertWithinSpendLimits();
} catch (err) {
  if (err instanceof SpendLimitExceededError) {
    console.log(err.status.spentUsd, err.status.remainingUsd);
  }
}

Utility Functions

| Function | Description | |----------|-------------| | findCostFieldPaths(obj) | Extract dot-separated paths for all *CostUsd fields | | extractCostFromDelta(delta, paths) | Sum cost values from a partial delta | | deepAdd(target, source) | Recursively add numeric values (mutates target) |

Types

| Type | Description | |------|-------------| | NumericRecord | Nested object with only number leaves | | DeepPartial<T> | Recursive partial — omit unchanged nested fields | | SpendLimit | Trailing-window limit: { windowMs, maxSpendUsd, label } | | SpendStatus | Current status: { limit, spentUsd, remainingUsd, exceeded, resumesAt } | | SpendEntry | Timestamped spend entry: { timestamp, amountUsd } | | UsageTrackerOptions<T> | Configuration passed to create() |

Options

interface UsageTrackerOptions<T extends NumericRecord> {
  key: string; // Unique persistence key (alphanumeric, hyphens, underscores)
  default: T; // Default metrics shape (all leaves must be 0)
  stateDirectory?: string; // Directory for state persistence
  autoSaveMs?: number; // Auto-save interval in ms (passed to StateTracker)
  onEvent?: (event: StateTrackerEvent) => void; // Logging callback
  spendLimits?: readonly SpendLimit[]; // Trailing-window spend limits
  onSpendLimitExceeded?: (status: SpendStatus) => void; // Exceeded callback
}