npm package: @sed-sh/sdk
Description: Official Node.js SDK for sed.sh API - URL shortening, malware scanning, disposable email, mock APIs, and PDF reports
Author: sed.sh
Latest version: 0.1.0

# @sed-sh/sdk

Official Node.js SDK for [sed.sh](https://www.sed.sh) API - URL shortening, malware scanning, disposable email, mock APIs, and PDF reports.

[![npm version](https://img.shields.io/npm/v/@sed-sh/sdk.svg)](https://www.npmjs.com/package/@sed-sh/sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

## Features

- 🔗 **Links** - URL shortening with optional password protection
- 🛡️ **Malware** - File scanning powered by AWS GuardDuty
- 📧 **Inbox** - Disposable email addresses for testing
- 🚦 **Routes** - Mock API endpoints for development
- 📄 **Reports** - PDF generation from HTML templates
- 🔒 **Type-safe** - Full TypeScript support
- 🚀 **Promise-based** - Modern async/await API
- 📦 **Zero config** - Works out of the box

## Installation

```bash
npm install @sed-sh/sdk

# or

yarn add @sed-sh/sdk

# or

pnpm add @sed-sh/sdk
```

## Quick Start

```typescript
import { SedSH } from '@sed-sh/sdk';

// Initialize client
const client = new SedSH({ apiKey: 'your-api-key' });

// Shorten a URL
const link = await client.links.create('https://example.com');
console.log(link.shortUrl); // https://sed.sh/abc123

// Create a disposable inbox
const inbox = await client.inbox.create();
console.log(inbox.email); // random@sed.sh

// Scan a file for malware
const scan = await client.malware.scanFile('/path/to/file.pdf');
console.log(scan.scanId);
```

## Authentication

API key can be provided in three ways (in order of priority):

### 1. Constructor parameter (recommended)

```typescript
const client = new SedSH({ apiKey: 'your-api-key' });
```

### 2. Environment variable

```bash
export SEDSH_API_KEY='your-api-key'
```

```typescript
const client = new SedSH(); // Reads from env
```

### 3. Config file

Create `~/.sedsh/config.json`:

```json
{
  "api_key": "your-api-key"
}
```

```typescript
const client = new SedSH(); // Reads from config file
```

Get your API key from: https://www.sed.sh/settings

## Usage

### Links Service

```typescript
// Create a short URL
const link = await client.links.create('https://github.com/anthropics/claude-code');
console.log(link.shortUrl); // https://sed.sh/abc123
console.log(link.code);     // abc123

// Create with password protection
const protectedLink = await client.links.create('https://example.com', {
  password: 'secret123'
});

// List all links
const { links } = await client.links.list();
for (const link of links) {
  console.log(`${link.code}: ${link.targetUrl} (${link.clicks} clicks)`);
}

// Delete a link
await client.links.delete('abc123');
```

### Malware Service

```typescript
// Scan a file
const scan = await client.malware.scanFile('/path/to/document.pdf');
console.log(`Scan ID: ${scan.scanId}`);
console.log(`Status: ${scan.status}`);
// You'll receive an email when the scan completes (typically 1-2 minutes)

// Supported file types: Any file up to 150 GB
// Detection: Powered by AWS GuardDuty Malware Protection
```

### Inbox Service

```typescript
// Create a disposable inbox
const inbox = await client.inbox.create();
console.log(`Email: ${inbox.email}`);
console.log(`Code: ${inbox.code}`);

// List all inboxes
const { inboxes } = await client.inbox.list();

// Get messages
const { messages } = await client.inbox.getMessages('inbox_123');
for (const msg of messages) {
  console.log(`From: ${msg.from}, Subject: ${msg.subject}`);
}

// Get message details
const message = await client.inbox.getMessage('inbox_123', 'msg_456');
console.log(message.body);

// Delete a message
await client.inbox.deleteMessage('inbox_123', 'msg_456');

// Delete an inbox
await client.inbox.delete('inbox_123');
```

### Routes Service (Mock APIs)

```typescript
// Create a mock endpoint
const endpoint = await client.routes.createEndpoint({
  name: 'User API',
  method: 'GET',
  path: '/api/users',
  responseStatus: 200,
  responseBody: JSON.stringify({ users: [] }),
  responseHeaders: { 'Content-Type': 'application/json' }
});
console.log(endpoint.url); // Your mock API URL

// Create with delay
const slowEndpoint = await client.routes.createEndpoint({
  name: 'Slow API',
  method: 'POST',
  path: '/api/slow',
  responseStatus: 200,
  responseDelay: 2000, // 2 second delay
  responseBody: JSON.stringify({ message: 'This took 2 seconds' })
});

// Forward mode (proxy)
const proxy = await client.routes.createEndpoint({
  name: 'GitHub Proxy',
  method: 'GET',
  path: '/api/github',
  forwardMode: true,
  forwardUrl: 'https://api.github.com/users/github'
});

// List all endpoints
const { endpoints } = await client.routes.listEndpoints();

// Update an endpoint
await client.routes.updateEndpoint('ep_123', {
  responseStatus: 201,
  responseBody: JSON.stringify({ updated: true })
});

// Toggle endpoint on/off
await client.routes.toggleEndpoint('ep_123', false); // Disable
await client.routes.toggleEndpoint('ep_123', true);  // Enable

// View request logs
const { requests } = await client.routes.getRequests();
for (const req of requests) {
  console.log(`${req.method} ${req.path} from ${req.sourceIp}`);
}

// Get request details
const request = await client.routes.getRequest('req_123');
console.log(request.headers);
console.log(request.body);

// Delete endpoint
await client.routes.deleteEndpoint('ep_123');
```

### Reports Service (PDF Generation)

```typescript
// Create a template
const template = await client.reports.createTemplate({
  name: 'Invoice Template',
  html: `
    <html>
      <head><style>body { font-family: Arial; }</style></head>
      <body>
        <h1>Invoice #{{invoiceNumber}}</h1>
        <p>Customer: {{customerName}}</p>
        <ul>
          {{#each items}}
          <li>{{this.name}} - ${{this.price}}</li>
          {{/each}}
        </ul>
        <h3>Total: ${{total}}</h3>
      </body>
    </html>
  `,
  expiryHours: 24
});
console.log(template.templateId);
console.log(template.endpoint); // Public PDF generation endpoint

// Generate a PDF
const pdf = await client.reports.generatePDF(template.templateId, {
  invoiceNumber: '12345',
  customerName: 'John Doe',
  items: [
    { name: 'Widget', price: '9.99' },
    { name: 'Gadget', price: '19.99' }
  ],
  total: '29.98'
});
console.log(pdf.downloadUrl); // Download the PDF (expires in 24 hours)
console.log(`PDF size: ${pdf.sizeBytes} bytes`);
console.log(`Generated in: ${pdf.computeTimeSeconds}s`);

// List templates
const { templates } = await client.reports.listTemplates();

// Get template with HTML
const templateDetail = await client.reports.getTemplate('tpl_123');
console.log(templateDetail.html);

// List recent generations
const { generations } = await client.reports.listGenerations();

// Delete template
await client.reports.deleteTemplate('tpl_123');
```

## CLI Usage

The SDK includes a command-line tool:

```bash
# Set API key
export SEDSH_API_KEY='your-api-key'

# Links
sedsh links create https://example.com
sedsh links create https://example.com --password secret
sedsh links list
sedsh links delete abc123

# Malware
sedsh malware scan /path/to/file.pdf

# Inbox
sedsh inbox create
sedsh inbox list
sedsh inbox messages inbox_123
sedsh inbox message inbox_123 msg_456
sedsh inbox delete inbox_123

# Routes
sedsh routes create --name "API" --method GET --path /test --status 200 --body '{"ok":true}'
sedsh routes list
sedsh routes delete ep_123
sedsh routes requests
sedsh routes request req_123

# Reports
sedsh reports create-template --name "Invoice" --html template.html
sedsh reports list-templates
sedsh reports generate tpl_123 --data data.json
sedsh reports list-generations
sedsh reports delete-template tpl_123

# Help
sedsh --help
sedsh links --help
```

## Error Handling

All errors inherit from `SedSHError`:

```typescript
import { SedSH, SedSHError, AuthenticationError, ResourceNotFoundError } from '@sed-sh/sdk';

try {
  const link = await client.links.delete('nonexistent');
} catch (error) {
  if (error instanceof ResourceNotFoundError) {
    console.log('Link not found:', error.message);
    console.log('Status code:', error.statusCode);
  } else if (error instanceof AuthenticationError) {
    console.log('Invalid API key');
  } else if (error instanceof SedSHError) {
    console.log('API error:', error.message);
  } else {
    console.log('Unknown error:', error);
  }
}
```

### Exception Types

- `SedSHError` - Base error class
- `AuthenticationError` - Invalid API key (HTTP 401)
- `PaymentRequiredError` - Payment required (HTTP 402)
- `ResourceNotFoundError` - Resource not found (HTTP 404)
- `InvalidRequestError` - Invalid request (HTTP 400, 422)
- `RateLimitError` - Rate limit exceeded (HTTP 429)
- `ServerError` - Server error (HTTP 500-599)
- `NetworkError` - Network/connection errors

## TypeScript Support

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

```typescript
import type {
  Link,
  Inbox,
  Endpoint,
  Template,
  MalwareScan
} from '@sed-sh/sdk';

const link: Link = await client.links.create('https://example.com');
const inbox: Inbox = await client.inbox.create();
```

## Important Notes

⚠️ **No automatic retries** - The SDK does not automatically retry failed requests. Implement retry logic in your application if needed.

⚠️ **No client-side validation** - The SDK passes data directly to the API without validation. The API will return clear error messages for invalid inputs.

⚠️ **Rate limits** - Respect API rate limits. The SDK will throw `RateLimitError` when limits are exceeded.

## Examples

See the [examples](./examples) directory for more usage examples:

- `links.js` - URL shortening examples
- `malware.js` - File scanning examples
- `inbox.js` - Disposable email examples
- `routes.js` - Mock API examples
- `reports.js` - PDF generation examples

## Requirements

- Node.js >= 14.0.0
- npm, yarn, or pnpm

## Documentation

- **API Documentation**: https://www.sed.sh/docs
- **Links**: https://www.sed.sh/docs/links
- **Malware**: https://www.sed.sh/docs/malware
- **Inbox**: https://www.sed.sh/docs/inbox
- **Routes**: https://www.sed.sh/docs/routes
- **Reports**: https://www.sed.sh/docs/reports

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Support

- **Issues**: https://github.com/triellocom/sed-sh-sdk/issues
- **Website**: https://www.sed.sh
- **Email**: support@sed.sh

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.