npm package: @ocx-inc/credits
Description: API client for Credits Management
Latest version: 0.0.0

# @ocx-inc/credits

TypeScript client for the Credits Management API with separate client and server implementations.

## Installation

```bash
pnpm add @ocx-inc/credits
```

## Package Exports

This package uses package.json exports to provide separate entry points:

- `@ocx-inc/credits/client` - Client-side API (frontend/browser)
- `@ocx-inc/credits/server` - Server-side API (backend/admin)

Each entry point exports only the relevant code, enabling better tree-shaking and clearer separation of concerns.

## Usage

### Server-Side (Backend/Admin)

Use `ServerClient` for backend operations with API key authentication. This client has full access to all operations including creating transactions and managing users.

```typescript
import { ServerClient } from '@ocx-inc/credits/server';

const serverClient = new ServerClient({
  baseUrl: 'https://your-api-url.com',
  apiKey: 'your-api-key',
});

// Create a user (idempotent)
await serverClient.createUser('app-id', 'user-id');

// Grant credits
await serverClient.createTransaction('app-id', 'user-id', {
  delta: 100,
  reason: 'grant',
});

// Consume credits
await serverClient.createTransaction('app-id', 'user-id', {
  delta: -10,
  reason: 'consume',
});

// List all users (admin only)
const users = await serverClient.listUsers('app-id');

// Get any user's balance
const balance = await serverClient.getBalance('app-id', 'user-id');
```

### Client-Side (Frontend/End-User)

Use `UserClient` for frontend operations with JWT authentication. This client can only access the authenticated user's own data (read-only).

```typescript
import { UserClient } from '@ocx-inc/credits/client';

const client = new UserClient({
  baseUrl: 'https://your-api-url.com',
  applicationId: 'app-id',
  bearerToken: userJwtToken, // From your auth provider (Clerk, Auth0, etc.)
});

// Get own balance
const balance = await client.getBalance('user-id');
console.log(`Balance: ${balance.balance} credits`);

// List own transaction history
const transactions = await client.listTransactions('user-id');

// Get own user info
const user = await client.getUser('user-id');
```

## API Reference

### `ServerClient`

Server-side client for backend/admin operations. Requires API key authentication.

**Constructor Options:**
- `baseUrl` (string): The base URL of the API
- `apiKey` (string): API key for authentication
- `fetch` (function, optional): Custom fetch implementation

**Methods:**

#### User Management
- `createUser(applicationId, userId)`: Create or update a user (idempotent)
- `getUser(applicationId, userId)`: Get user information
- `listUsers(applicationId, cursor?)`: List all users in the application

#### Credits Management
- `getBalance(applicationId, userId)`: Get user's credit balance
- `createTransaction(applicationId, userId, transaction)`: Create a credit transaction (grant/consume/refund)
- `listTransactions(applicationId, userId, cursor?)`: List user's transaction history

---

### `UserClient`

Client-side client for end-user operations. Requires JWT bearer token authentication.

**Constructor Options:**
- `baseUrl` (string): The base URL of the API
- `applicationId` (string): The application ID
- `bearerToken` (string): JWT token from your auth provider
- `fetch` (function, optional): Custom fetch implementation

**Methods:**

- `getUser(userId)`: Get authenticated user's information
- `getBalance(userId)`: Get authenticated user's credit balance
- `listTransactions(userId, cursor?)`: List authenticated user's transaction history

**Note:** Client-side users cannot create transactions. All credit modifications must be done through the server using `ServerClient`.

## Type Definitions

Types are automatically exported from each entry point:

```typescript
// Import from the client module
import type {
  UserClient,
  UserClientOptions,
  GetBalanceResponse,
  ListTransactionsResponse,
  CreditTransactionReason
} from '@ocx-inc/credits/client';

// Import from the server module
import type {
  ServerClient,
  ServerClientOptions,
  CreateTransactionRequest,
  CreateTransactionResponse,
  CreditTransactionReason
} from '@ocx-inc/credits/server';
```

**Available Types:**

```typescript
export type CreditTransactionReason = "grant" | "consume" | "refund";

export type CreateTransactionRequest = {
  delta: number;
  reason: CreditTransactionReason;
};

export type GetBalanceResponse = {
  balance: number;
};

export type ListTransactionsResponse = {
  transactions: Array<{
    delta: number;
    reason: CreditTransactionReason;
    createdAt: Date;
  }>;
  nextCursor?: string;
};
```

## Security

- **Server Client**: Full access with API key authentication. Keep your API key secret and only use it server-side.
- **Client Client**: Read-only access with JWT authentication. Safe to use in frontend applications.
- The API validates JWT tokens and ensures users can only access their own data.