npm package: @panoptic-it-solutions/cloudcockpit-client
Description: Type-safe API client for CloudCockpit CSP API
Author: Panoptic IT Solutions
Latest version: 1.0.0

# CloudCockpit API Client

Type-safe TypeScript client for the [CloudCockpit](https://cloudcockpit.com) CSP API.

## Installation

```bash
npm install @panoptic-it-solutions/cloudcockpit-client
```

## Quick Start

```typescript
import { createCloudCockpitClient } from '@panoptic-it-solutions/cloudcockpit-client';

const client = createCloudCockpitClient({
  tenant: 'cloud.mwh.ie',
  auth: {
    clientId: process.env.CLOUDCOCKPIT_CLIENT_ID!,
    clientSecret: process.env.CLOUDCOCKPIT_CLIENT_SECRET!,
  },
});

// List customers
const { items, totalCount } = await client.customers.list({ pageSize: 50 });

// Get all customers with auto-pagination
const allCustomers = await client.customers.listAll();

// Iterate efficiently over large datasets
for await (const customer of client.customers.iterate()) {
  console.log(customer.company?.name);
}
```

## Authentication

### OAuth Credentials (Recommended)

The client handles token management automatically when you provide OAuth credentials:

```typescript
const client = createCloudCockpitClient({
  tenant: 'cloud.mwh.ie',
  auth: {
    clientId: process.env.CLOUDCOCKPIT_CLIENT_ID!,
    clientSecret: process.env.CLOUDCOCKPIT_CLIENT_SECRET!,
  },
});
```

Tokens are cached and automatically refreshed 60 seconds before expiry.

### Direct JWT Token

You can also provide a JWT token directly:

```typescript
const client = createCloudCockpitClient({
  tenant: 'cloud.mwh.ie',
  token: 'your-jwt-token',
});
```

Or use a dynamic token function:

```typescript
const client = createCloudCockpitClient({
  tenant: 'cloud.mwh.ie',
  token: async () => fetchTokenFromSomewhere(),
});
```

## Resources

The client provides access to all CloudCockpit API resources:

- `client.auditLogs` - Audit log queries
- `client.customers` - Customer management (includes users, licenses, domains, MCA, GDAP)
- `client.invoices` - Invoice retrieval with line items
- `client.offers` - Available offers and pricing
- `client.orders` - Order creation
- `client.providers` - Provider instances
- `client.resellers` - Reseller management (includes margins)
- `client.subscriptions` - Subscription management (suspend, reactivate, transitions)
- `client.users` - User management

## Pagination

Each paginated resource supports three access patterns:

```typescript
// Single page
const { items, totalCount } = await client.customers.list({ pageSize: 50 });

// All pages to array
const allCustomers = await client.customers.listAll();

// Memory-efficient streaming
for await (const customer of client.customers.iterate()) {
  console.log(customer);
}
```

## Error Handling

```typescript
import {
  isCloudCockpitError,
  isAuthError,
  isNotFoundError,
  isValidationError,
  isRateLimitError,
} from '@panoptic-it-solutions/cloudcockpit-client';

try {
  await client.customers.get('invalid-id');
} catch (error) {
  if (isNotFoundError(error)) {
    console.log('Customer not found');
  } else if (isAuthError(error)) {
    console.log('Authentication failed');
  } else if (isValidationError(error)) {
    console.log('Validation error:', error.details);
  } else if (isRateLimitError(error)) {
    console.log('Rate limited, retry after:', error.retryAfter);
  }
}
```

## Rate Limiting

Configure rate limiting to stay within API limits:

```typescript
const client = createCloudCockpitClient({
  tenant: 'cloud.mwh.ie',
  auth: { ... },
  rateLimiter: {
    maxConcurrent: 10,      // Max concurrent requests
    minTime: 100,           // Min ms between requests
    reservoir: 100,         // Max requests per interval
    reservoirRefreshInterval: 60000,  // Refresh interval (1 minute)
  },
});
```

## Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `tenant` | `string` | required | Your CloudCockpit tenant domain |
| `auth` | `OAuthCredentials` | - | OAuth client credentials |
| `token` | `string \| () => Promise<string>` | - | JWT token (alternative to auth) |
| `baseUrl` | `string` | `https://api.cloudcockpit.com` | API base URL |
| `defaultPageSize` | `number` | `100` | Default page size for list operations |
| `correlationId` | `string \| () => string` | - | Request correlation ID |
| `rateLimiter` | `RateLimiterConfig` | - | Rate limiting configuration |
| `fetch` | `typeof fetch` | - | Custom fetch implementation |

## Raw Client Access

For advanced usage, access the underlying openapi-fetch client:

```typescript
const response = await client.raw.GET('/v1/Customers/{customerId}', {
  params: { path: { customerId: '123' } },
});
```

## TypeScript

Full TypeScript support with generated types from the OpenAPI spec:

```typescript
import type { components } from '@panoptic-it-solutions/cloudcockpit-client/types';

type Customer = components['schemas']['CustomerCompanyViewModel'];
```

## License

MIT