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

@supernal/api-usage-tracker

v0.1.0

Published

API usage tracking, cost calculation, and billing utilities

Readme

@supernal/api-usage-tracker

A comprehensive API usage tracking, cost calculation, and billing utilities package for the Supernal platform. This package provides dynamic pricing calculations, secure API key management, and detailed usage tracking with support for both platform-managed and user-provided (BYOK) API keys.

Features

  • 🔢 Dynamic Cost Calculation - Real-time pricing based on actual provider rates
  • 🔐 Secure API Key Vault - AES-256-GCM encryption for user API keys
  • 📊 Usage Tracking - Detailed usage metrics with cost attribution
  • 💰 Multi-Provider Pricing - Support for OpenAI, Cartesia, Azure, ElevenLabs, Google
  • 🔄 BYOK Support - Let users bring their own API keys with zero platform fees
  • 📈 Tiered Pricing - Handle volume-based pricing tiers automatically

Installation

npm install @supernal/api-usage-tracker
# or
pnpm add @supernal/api-usage-tracker

Quick Start

1. Initialize the Package

import { ApiKeyVault } from '@supernal/api-usage-tracker'

// Initialize the API key vault with your encryption secret
ApiKeyVault.initialize(process.env.API_KEY_ENCRYPTION_SECRET)

2. Track API Usage

import { UsageTracker } from '@supernal/api-usage-tracker'

// Track platform key usage
const event = await UsageTracker.trackTTSUsage({
  userId: 'user123',
  provider: 'openai',
  model: 'tts-1',
  characters: 1000,
  cached: false,
  keyType: 'platform'
})

console.log(`Cost: $${event.cost.toFixed(4)}`)

3. Calculate Costs

import { TTSPricingCalculator } from '@supernal/api-usage-tracker'

// Calculate cost for specific usage
const { cost, perCharacter } = TTSPricingCalculator.calculateCost(
  'openai',
  'tts-1',
  100000  // 100k characters
)

// Compare providers
const comparison = TTSPricingCalculator.compareProviders(100000, [
  { provider: 'openai', model: 'tts-1' },
  { provider: 'cartesia', model: 'sonic' },
  { provider: 'azure', model: 'neural' }
])

API Reference

TTSPricingCalculator

calculateCost(provider, model, characters, monthlyUsage?)

Calculate the cost for TTS synthesis.

const { cost, perCharacter } = TTSPricingCalculator.calculateCost(
  'openai',
  'tts-1',
  50000,
  1000000  // Optional: monthly usage for tier calculation
)

calculateWithMarkup(baseCost, markupPercent?)

Add platform markup to base cost.

const { total, markup, base } = TTSPricingCalculator.calculateWithMarkup(
  new Decimal(10),
  20  // 20% markup
)

estimateMonthlyCost(provider, model, monthlyCharacters, cacheHitRate?)

Estimate monthly costs with caching benefits.

const estimate = TTSPricingCalculator.estimateMonthlyCost(
  'openai',
  'tts-1',
  1000000,  // 1M chars/month
  0.7       // 70% cache hit rate
)

compareProviders(characters, providers)

Compare costs across multiple providers.

const comparison = TTSPricingCalculator.compareProviders(100000, [
  { provider: 'openai', model: 'tts-1' },
  { provider: 'openai', model: 'tts-1-hd' },
  { provider: 'cartesia', model: 'sonic' }
])
// Returns sorted by cost (cheapest first)

UsageTracker

trackTTSUsage(params)

Track a TTS usage event.

const event = await UsageTracker.trackTTSUsage({
  userId: 'user123',
  provider: 'openai',
  model: 'tts-1',
  characters: 1000,
  cached: false,
  keyType: 'platform',  // or 'user' for BYOK
  userApiKeyId: 'uak_123'  // For BYOK
})

getUserSummary(userId, startDate, endDate)

Get usage summary for a user.

const summary = await UsageTracker.getUserSummary(
  'user123',
  new Date('2024-01-01'),
  new Date('2024-01-31')
)

estimateCost(params)

Estimate cost before synthesis.

const estimate = UsageTracker.estimateCost({
  provider: 'openai',
  model: 'tts-1',
  text: 'Hello world',
  keyType: 'platform'
})

ApiKeyVault

initialize(encryptionKey)

Initialize the vault with an encryption key.

ApiKeyVault.initialize('your-32-character-encryption-key')

storeUserKey(params)

Store a user's API key securely.

const userKey = await ApiKeyVault.storeUserKey({
  userId: 'user123',
  name: 'Production OpenAI Key',
  provider: 'openai',
  keyType: 'openai',
  key: 'sk-...',
  metadata: {
    model: 'tts-1',
    rateLimit: 100
  }
})

getUserKey(userId, keyId)

Retrieve and decrypt a user's API key.

const decryptedKey = await ApiKeyVault.getUserKey('user123', 'uak_123')

validateKey(provider, keyType, key)

Validate an API key with its provider.

const { valid, error } = await ApiKeyVault.validateKey(
  'openai',
  'openai',
  'sk-...'
)

Pricing Data

The package includes real-world pricing for major TTS providers:

| Provider | Model | Price per Million Characters | |----------|-------|------------------------------| | OpenAI | tts-1 | $15.00 | | OpenAI | tts-1-hd | $30.00 | | Cartesia | sonic | $2.50 | | Azure | neural | $4.00 - $16.00 (tiered) | | ElevenLabs | multilingual_v2 | $180.00 - $330.00 (tiered) | | Google | wavenet | $16.00 |

Security

  • Encryption: All API keys encrypted using AES-256-GCM
  • Key Derivation: Uses scrypt for key derivation
  • Unique IVs: Each encryption uses a unique initialization vector
  • Hash Storage: Stores SHA256 hash for duplicate detection

Usage Examples

Complete BYOK Flow

// 1. Store user's API key
const storedKey = await ApiKeyVault.storeUserKey({
  userId: 'user123',
  name: 'My OpenAI Key',
  provider: 'openai',
  keyType: 'openai',
  key: 'sk-...'
})

// 2. Use the key for TTS
const audio = await ttsService.synthesize(
  'Hello world',
  {
    provider: 'openai',
    voice: 'alloy',
    useUserKey: true,
    userApiKeyId: storedKey.id
  },
  'user123'
)

// 3. Track usage (automatically done, but zero cost)
// Cost will be 0 for user keys

Cost Optimization Analysis

// Analyze potential savings
const monthlyUsage = 5000000  // 5M characters

// Without caching
const fullCost = TTSPricingCalculator.calculateCost(
  'openai', 'tts-1', monthlyUsage
)

// With caching
const estimate = TTSPricingCalculator.estimateMonthlyCost(
  'openai', 'tts-1', monthlyUsage, 0.7
)

console.log(`Monthly cost without cache: $${fullCost.cost.toFixed(2)}`)
console.log(`Monthly cost with cache: $${estimate.withCache.toFixed(2)}`)
console.log(`Monthly savings: $${estimate.savings.toFixed(2)}`)

Testing

# Run tests
pnpm test

# Run tests with coverage
pnpm test -- --coverage

# Run tests in watch mode
pnpm test:watch

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This package is part of the Supernal platform and is subject to the Supernal license agreement.