npm package: @rivtor/meter
Description: Production-ready usage tracking and limits for B2B SaaS
Author: Rivtor
Latest version: 1.0.1

# @rivtor/meter

[![npm version](https://badge.fury.io/js/%40rivtor%2Fmeter.svg)](https://www.npmjs.com/package/@rivtor/meter)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Production-ready usage tracking and limits for B2B SaaS.

## Overview

`@rivtor/meter` is the "Meter" module that makes usage-based pricing simple. Track usage, enforce limits, and display beautiful progress bars—all with a single function call.

**Key Features:**
- 📊 **Usage Tracking** - Track any metric (API calls, PDFs, storage, etc.)
- 🎯 **Limit Enforcement** - Automatic 402 errors when limits exceeded
- 🔄 **Auto Reset** - Monthly/daily/weekly reset periods
- 📈 **Usage UI** - Pre-built progress bar component
- ⚡ **High Performance** - Built on Supabase with row-level security

## Installation

```bash
npm install @rivtor/meter
```

## Quick Start

### Server-Side

```typescript
import { meter } from '@rivtor/meter';

// Increment usage
export async function POST(request: Request) {
  const user = await auth.requireUser(request);
  
  // Check limit before generating
  await meter.checkLimit(user.id, 'pdf_generated');
  
  // Generate PDF
  const pdf = await generatePDF(data);
  
  // Increment counter
  await meter.increment(user.id, 'pdf_generated', 1);
  
  return Response.json({ pdf });
}

// Get current usage
export async function GET(request: Request) {
  const user = await auth.requireUser(request);
  const usage = await meter.getUsage(user.id, 'pdf_generated');
  
  return Response.json({
    used: usage.current,
    limit: usage.limit,
    percentage: (usage.current / usage.limit) * 100,
  });
}
```

### Client-Side (React)

```tsx
import { RivtorUsageBar } from '@rivtor/meter/react';

export default function Dashboard() {
  return (
    <div>
      <h1>Dashboard</h1>
      
      <RivtorUsageBar 
        metric="pdf_generated" 
        label="PDFs Generated This Month"
      />
      
      <RivtorUsageBar 
        metric="api_calls" 
        label="API Calls"
        color="blue"
      />
    </div>
  );
}
```

## API Reference

### Server Methods

- `increment(userId, metric, amount)` - Increment usage counter
- `checkLimit(userId, metric)` - Check if within limit (throws 402 if exceeded)
- `getUsage(userId, metric)` - Get current usage statistics
- `resetUsage(userId, metric)` - Reset usage counter
- `setLimit(userId, metric, limit)` - Update user's limit

### React Components

- `<RivtorUsageBar metric="name" label="Label" />` - Usage progress bar

## Configuration Example

```typescript
// rivtor.config.ts
export const config = {
  limits: {
    pdf_generated: { 
      free: 10, 
      pro: 100, 
      enterprise: 1000 
    },
    api_calls: { 
      free: 1000, 
      pro: 10000, 
      enterprise: 100000 
    },
  },
  resetPeriod: 'monthly', // 'daily', 'weekly', 'monthly'
};
```

## Environment Variables

```bash
# Supabase (Required)
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key
```

## Database Schema

```sql
CREATE TABLE usage_metrics (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
  metric TEXT NOT NULL,
  current_usage INTEGER DEFAULT 0,
  limit_value INTEGER NOT NULL,
  reset_at TIMESTAMPTZ NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(user_id, metric)
);
```

## License

MIT © Rivtor

## Support

- Email: legal@rivtor.com
- Documentation: [GitHub Wiki](https://github.com/rivtor/rivtor-meter/wiki)

---

**Built with care by [Rivtor](https://rivtor.com)**