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

claude-pricing

v0.1.0

Published

Calculate and track Claude API costs from token usage. Bundled pricing table + custom override. Zero dependencies.

Readme

claude-pricing

Calculate and track Claude API costs from token usage. Bundled pricing table + custom overrides. Zero dependencies.

import { calculateCost, formatUSD, CostTracker } from "claude-pricing";

// One-shot cost calculation
const cost = calculateCost("claude-opus-4-7", {
  input_tokens: 1500,
  output_tokens: 800,
  cache_read_input_tokens: 5000,
});
console.log(formatUSD(cost.total));  // "$0.0900"

// Session tracker with budget alert
const tracker = new CostTracker({
  budgetUSD: 1.0,
  onBudgetExceeded: (total, budget) =>
    alert(`Budget blown: ${formatUSD(total)} > ${formatUSD(budget)}`),
});

tracker.add("claude-opus-4-7", usage, { label: "planning" });
tracker.add("claude-sonnet-4-6", usage, { label: "draft" });

console.log(formatUSD(tracker.total().total));
console.log(tracker.byModel());

Why this exists

You're running Claude API in production. You want to know:

  • What did this one call cost? The SDK returns usage but doesn't tell you the dollars.
  • Did this session blow my budget? You want a running total across an agent loop.
  • Where's my money going? Per-model breakdown for cost optimization.
  • What about cache and batch? The pricing math is non-obvious (1.25× input for cache write, 50% off for batch).

This package is ~180 lines of TypeScript. Zero deps. Bundled with up-to-date Anthropic pricing, but everything is overridable because list prices change and you may have a custom contract.

Install

npm install claude-pricing

API

calculateCost(model, usage, options?)

function calculateCost(
  model: string,
  usage: TokenUsage,
  options?: { pricing?: ModelPricing | Record<string, ModelPricing>; batch?: boolean }
): CostBreakdown;

Returns { input, output, cacheWrite, cacheRead, total } — all in USD.

CostTracker

const tracker = new CostTracker({
  pricing?: customTable,
  budgetUSD?: 5.00,
  onBudgetExceeded?: (total, budget) => ...,
});

tracker.add(model, usage, { label?: 'step-1', batch?: true });
tracker.total();      // { input, output, cacheWrite, cacheRead, total }
tracker.byModel();    // { 'claude-opus-4-7': { calls, usage, breakdown }, ... }
tracker.reset();
tracker.getEntries(); // readonly array of { model, usage, breakdown, timestamp, label }

formatUSD(amount)

Smart-precision formatter:

  • $1.23 for amounts ≥ $1
  • $0.0123 for amounts ≥ $0.01
  • $0.000123 for sub-cent

ANTHROPIC_PRICING

The bundled default table (USD per million tokens):

| Model | Input | Output | Cache write | Cache read | |---|---|---|---|---| | claude-opus-4-7 | $15 | $75 | $18.75 | $1.50 | | claude-sonnet-4-6 | $3 | $15 | $3.75 | $0.30 | | claude-haiku-4-5 | $0.80 | $4 | $1.00 | $0.08 |

⚠️ Snapshot taken 2026-05. Verify against Anthropic pricing for production. Pass your own table via options.pricing for current rates.

Recipes

Override pricing for current rates

const myPricing = {
  "claude-opus-4-7": { input: 14, output: 70 },  // discounted contract
};
const cost = calculateCost(model, usage, { pricing: myPricing });

Use for any custom/fine-tuned model

const cost = calculateCost(
  "my-fine-tune",
  usage,
  { pricing: { input: 8, output: 24 } }  // single ModelPricing
);

Pair with claude-stream-collector

import { collectStream } from "claude-stream-collector";
import { calculateCost, formatUSD } from "claude-pricing";

const result = await collectStream(stream);
const cost = calculateCost(result.model, result.usage);
console.log(formatUSD(cost.total));

The TokenUsage shape is compatible — pass result.usage directly.

Track an agent loop with budget cap

const tracker = new CostTracker({
  budgetUSD: 0.10,
  onBudgetExceeded: () => { throw new Error("Cost limit reached"); }
});

for (const step of agent.run()) {
  tracker.add(step.model, step.usage, { label: step.name });
  // throws automatically when total > $0.10
}

console.log(tracker.byModel());

Batch API (50% off)

calculateCost(model, usage, { batch: true });
// Or per add():
tracker.add(model, usage, { batch: true });

Tests & build

npm install
npm test       # vitest run
npm run build  # tsc

License

MIT — © 2026 xiangnuans

Part of a series

The 3rd package in small, focused Claude SDK helpers built in public.

  • claude-stream-collector — Consume streaming events into typed result
  • claude-retry — Smart retry with backoff
  • claude-pricing — Cost calculation + session tracker (this package)
  • 🚧 claude-prompt-toolkit — Prompt templating, versioning

Follow the journey: ship-log-2026.