npm package: @kethub/sdk
Description: Official TypeScript SDK for Kethub API Gateway
Author: Kethub Team
Latest version: 1.0.1

# Kethub SDK

The official TypeScript SDK for the Kethub API Gateway - your all-in-one solution for integrating email, social media, and storage functionality into your applications.

## Installation

```bash
npm install @kethub/sdk
```

## Quick Start

```typescript
import Kethub from '@kethub/sdk';

const client = new Kethub({
  apiKey: 'ik_your_api_key_here',
  // baseUrl: 'https://api.kethub.dev', // Optional: defaults to production
});

// Send an email
await client.email.send({
  to: 'user@example.com',
  subject: 'Welcome!',
  html: '<h1>Hello from Kethub!</h1>',
});

// Post a tweet
await client.twitter.postText('Hello from Kethub! 🚀');

// Upload a file
const file = new File(['Hello World'], 'hello.txt', { type: 'text/plain' });
const uploadResult = await client.storage.uploadFile(file);
```

## Configuration

```typescript
const client = new Kethub({
  apiKey: 'ik_your_api_key_here',    // Required: Your Kethub API key
  baseUrl: 'https://api.kethub.dev', // Optional: API base URL
  timeout: 30000,                     // Optional: Request timeout in ms (default: 30000)
  retries: 3,                        // Optional: Number of retries (default: 3)
});
```

## Email Module

Send emails with ease using various providers.

### Send a single email

```typescript
const result = await client.email.send({
  to: 'recipient@example.com',
  from: 'sender@yourcompany.com', // Optional: uses default if not provided
  subject: 'Hello from Kethub!',
  html: '<h1>Welcome!</h1><p>Thanks for signing up.</p>',
  // text: 'Welcome! Thanks for signing up.', // Optional: plain text version
  // cc: ['cc@example.com'],                  // Optional: CC recipients
  // bcc: ['bcc@example.com'],               // Optional: BCC recipients
});

console.log('Email sent:', result.messageId);
```

### Send batch emails

```typescript
const emails = [
  {
    to: 'user1@example.com',
    subject: 'Welcome User 1!',
    html: '<h1>Hello User 1!</h1>',
  },
  {
    to: 'user2@example.com',
    subject: 'Welcome User 2!',
    html: '<h1>Hello User 2!</h1>',
  },
];

const batchResult = await client.email.sendBatch(emails);
console.log(`Sent ${batchResult.results.length} emails`);
```

### Email with attachments

```typescript
await client.email.send({
  to: 'recipient@example.com',
  subject: 'Document attached',
  html: '<p>Please find the document attached.</p>',
  attachments: [
    {
      filename: 'document.pdf',
      content: 'base64-encoded-content-here',
      contentType: 'application/pdf',
    },
  ],
});
```

## Twitter Module

Manage your Twitter presence programmatically.

### Post tweets

```typescript
// Simple text tweet
const tweet = await client.twitter.postText('Hello from Kethub! 🚀');
console.log('Tweet posted:', tweet.id);

// Reply to a tweet
await client.twitter.reply('Thanks for sharing!', 'original_tweet_id');

// Quote tweet
await client.twitter.quote('This is interesting!', 'tweet_to_quote_id');
```

### Get user information

```typescript
const profile = await client.twitter.getProfile('username');
console.log(`${profile.name} has ${profile.followers_count} followers`);
```

### Search tweets

```typescript
const tweets = await client.twitter.searchSimple('Kethub', 10);
console.log(`Found ${tweets.length} tweets about Kethub`);
```

### Get user timeline

```typescript
const recentTweets = await client.twitter.getRecentTweets('username', 5);
recentTweets.forEach(tweet => {
  console.log(`${tweet.created_at}: ${tweet.text}`);
});
```

## Storage Module

Upload, manage, and serve files effortlessly.

### Upload files

```typescript
// From a File object (browser)
const file = new File(['Hello World'], 'hello.txt', { type: 'text/plain' });
const uploadResult = await client.storage.uploadFile(file, {
  folder: 'documents',
  public: true,
});

console.log('File uploaded:', uploadResult.url);

// From a Buffer (Node.js)
const buffer = Buffer.from('Hello World', 'utf8');
const result = await client.storage.uploadBuffer(
  buffer,
  'hello.txt',
  'text/plain',
  { folder: 'documents' }
);
```

### Manage files

```typescript
// Get file information
const fileInfo = await client.storage.getFile('file_id');
console.log('File size:', fileInfo.size);

// Download file
const { content, contentType, filename } = await client.storage.downloadFile('file_id');

// Delete file
await client.storage.deleteFile('file_id');
```

### List files

```typescript
// List all files
const filesList = await client.storage.listFiles({
  page: 1,
  limit: 20,
});

// List files in a specific folder
const folderFiles = await client.storage.listFolder('documents');
```

## Health Checks

Check the status of modules and services:

```typescript
// Check all modules
const healthStatus = await client.healthCheck();
console.log('Email module status:', healthStatus.email.status);
console.log('Twitter module status:', healthStatus.twitter.status);
console.log('Storage module status:', healthStatus.storage.status);

// Check individual module
const emailHealth = await client.email.health();
if (emailHealth.status === 'healthy') {
  console.log('Email service is operational');
}
```

## Error Handling

The SDK provides specific error types for different scenarios:

```typescript
import {
  KethubError,
  ValidationError,
  RateLimitError,
  AuthenticationError
} from '@kethub/sdk';

try {
  await client.email.send(emailData);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Validation failed:', error.message);
  } else if (error instanceof RateLimitError) {
    console.error('Rate limit exceeded, please try again later');
  } else if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof KethubError) {
    console.error('Kethub API error:', error.message, error.statusCode);
  } else {
    console.error('Unexpected error:', error);
  }
}
```

## TypeScript Support

The SDK is written in TypeScript and includes comprehensive type definitions:

```typescript
import {
  SendEmailRequest,
  TweetResponse,
  UploadFileResponse
} from '@kethub/sdk';

const emailData: SendEmailRequest = {
  to: 'user@example.com',
  subject: 'Test',
  html: '<p>Hello!</p>',
};

const tweet: TweetResponse = await client.twitter.postText('Hello!');
// TypeScript knows tweet has properties: id, text, created_at, etc.
```

## Configuration Updates

Update configuration at runtime:

```typescript
// Update API key
client.updateApiKey('ik_new_api_key');

// Update base URL (useful for switching between environments)
client.updateBaseUrl('https://staging-api.kethub.dev');

// Get current configuration
const config = client.getConfig();
console.log('Current API key:', config.apiKey);
```

## Environment Variables

For security, store your API key in environment variables:

```bash
# .env
KETHUB_API_KEY=ik_your_api_key_here
```

```typescript
const client = new Kethub({
  apiKey: process.env.KETHUB_API_KEY!,
});
```

## Rate Limiting

The SDK automatically handles rate limiting with exponential backoff. Different endpoints have different rate limits:

- Email sending: 50 requests/minute per endpoint
- Twitter posting: 25 requests/minute
- Storage uploads: 50 requests/minute
- General API calls: 1000 requests/minute

## Support

- 📚 [Documentation](https://docs.kethub.dev)
- 💬 [Discord Community](https://discord.gg/kethub)
- 🐛 [Report Issues](https://github.com/kethub/sdk/issues)
- 📧 [Contact Support](mailto:support@kethub.dev)

## License

MIT License. See [LICENSE](LICENSE) for details.