npm package: @makebell/platform-sdk
Description: A universal SDK for client and server applications with Vite-based build system
Author: Makebell
Latest version: 1.0.0

# Makebell Platform SDK

A universal TypeScript/JavaScript SDK for client and server applications, built with Vite for optimal performance and compatibility across different frameworks.

## Features

- 🚀 **Universal Compatibility**: Works with Next.js, React, Express.js, NestJS, and any JavaScript/TypeScript application
- 📦 **Dual Architecture**: Separate client and server SDKs with optimized functionality for each environment
- 🔧 **Vite-based Build**: Fast builds with tree-shaking and modern JavaScript output
- 📊 **Built-in Analytics**: Client-side analytics and event tracking
- 🛡️ **Error Reporting**: Comprehensive error reporting and logging
- 📈 **Metrics & Monitoring**: Server-side metrics collection and performance monitoring
- 🚦 **Rate Limiting**: Built-in rate limiting for server applications
- 🔍 **TypeScript Support**: Full TypeScript support with comprehensive type definitions
- 🎯 **Demo Functionality**: Ready-to-use demo features for quick integration

## Installation

```bash
npm install @makebell/platform-sdk
```

## Quick Start

### Client SDK (Frontend)

```typescript
import { createClient, ClientConfig } from '@makebell/platform-sdk/client'

const config: ClientConfig = {
  appId: 'your-app-id',
  baseUrl: 'https://api.makebell.com',
  apiKey: 'your-api-key',
  enableAnalytics: true,
  enableErrorReporting: true,
  debug: true
}

const client = createClient(config)

// Get current user
const user = await client.getCurrentUser()

// Track analytics events
client.analytics.track('button_clicked', { buttonId: 'signup' })

// Check feature flags
const isEnabled = await client.getFeatureFlag('new-dashboard')

// Send notifications
await client.sendNotification(user.id, 'Welcome!', 'info')
```

### Server SDK (Backend)

```typescript
import { createServer, ServerConfig } from '@makebell/platform-sdk/server'

const config: ServerConfig = {
  appId: 'your-app-id',
  baseUrl: 'https://api.makebell.com',
  apiKey: 'your-api-key',
  enableLogging: true,
  enableMetrics: true,
  rateLimitPerMinute: 100,
  debug: true
}

const server = createServer(config)

// User management
const user = await server.getUser('user-id')
const newUser = await server.createUser({ email: 'user@example.com', name: 'John Doe' })

// Batch operations
const users = await server.batchCreateUsers([
  { email: 'user1@example.com', name: 'User 1' },
  { email: 'user2@example.com', name: 'User 2' }
])

// Export data
const csvData = await server.exportUsers('csv')
```

## Configuration

### Client Configuration

```typescript
interface ClientConfig {
  appId: string                    // Your application ID
  baseUrl: string                  // API base URL
  apiKey?: string                  // API key for authentication
  timeout?: number                 // Request timeout (default: 10000ms)
  retries?: number                 // Number of retries (default: 0)
  debug?: boolean                  // Enable debug logging
  enableAnalytics?: boolean        // Enable analytics tracking
  enableErrorReporting?: boolean   // Enable error reporting
  userAgent?: string              // Custom user agent
}
```

### Server Configuration

```typescript
interface ServerConfig {
  appId: string                    // Your application ID
  baseUrl: string                  // API base URL
  apiKey?: string                  // API key for authentication
  timeout?: number                 // Request timeout (default: 10000ms)
  retries?: number                 // Number of retries (default: 0)
  debug?: boolean                  // Enable debug logging
  enableLogging?: boolean          // Enable request/response logging
  enableMetrics?: boolean          // Enable metrics collection
  rateLimitPerMinute?: number      // Rate limit per minute (default: 100)
}
```

## Framework Examples

### Next.js

```typescript
// pages/index.tsx
import { createClient } from '@makebell/platform-sdk/client'

const client = createClient({
  appId: 'your-app-id',
  baseUrl: 'https://api.makebell.com',
  apiKey: 'your-api-key'
})

export default function HomePage() {
  useEffect(() => {
    client.analytics.page('Home Page')
  }, [])

  return <div>Your Next.js app with Makebell SDK</div>
}
```

### Express.js

```typescript
// app.js
import express from 'express'
import { createServer } from '@makebell/platform-sdk/server'

const app = express()
const makebellServer = createServer({
  appId: 'your-app-id',
  baseUrl: 'https://api.makebell.com',
  apiKey: 'your-api-key'
})

app.get('/users/:id', async (req, res) => {
  const user = await makebellServer.getUser(req.params.id)
  res.json(user)
})
```

### NestJS

```typescript
// users.service.ts
import { Injectable } from '@nestjs/common'
import { createServer } from '@makebell/platform-sdk/server'

@Injectable()
export class UsersService {
  private makebellServer = createServer({
    appId: process.env.MAKEBELL_APP_ID,
    baseUrl: process.env.MAKEBELL_BASE_URL,
    apiKey: process.env.MAKEBELL_API_KEY
  })

  async getUser(id: string) {
    return this.makebellServer.getUser(id)
  }
}
```

### React

```typescript
// App.tsx
import React, { useEffect } from 'react'
import { createClient } from '@makebell/platform-sdk/client'

const client = createClient({
  appId: 'your-app-id',
  baseUrl: 'https://api.makebell.com',
  apiKey: 'your-api-key'
})

function App() {
  useEffect(() => {
    client.analytics.page('React App')
  }, [])

  return <div>Your React app with Makebell SDK</div>
}
```

## API Reference

### Client SDK Methods

#### User Management
- `getCurrentUser()` - Get the current authenticated user
- `updateUser(userData)` - Update current user information

#### Analytics
- `analytics.track(event, properties, userId)` - Track custom events
- `analytics.identify(userId, traits)` - Identify users
- `analytics.page(name, properties)` - Track page views
- `analytics.on(event, callback)` - Listen to analytics events
- `analytics.getEvents()` - Get all tracked events

#### Feature Flags
- `getFeatureFlag(flagName)` - Check if a feature flag is enabled

#### Content Management
- `getContent(contentId)` - Fetch content by ID

#### Notifications
- `sendNotification(userId, message, type)` - Send notifications

#### Error Reporting
- `errorReporter.report(error, context)` - Report custom errors
- `errorReporter.onError(callback)` - Listen to error events

### Server SDK Methods

#### User Management
- `getUser(userId)` - Get user by ID
- `createUser(userData)` - Create a new user
- `updateUser(userId, userData)` - Update user information
- `deleteUser(userId)` - Delete a user
- `batchCreateUsers(users)` - Create multiple users at once

#### Data Export
- `exportUsers(format)` - Export users in JSON or CSV format

#### Logging
- `logger.info(message, data)` - Log info messages
- `logger.warn(message, data)` - Log warning messages
- `logger.error(message, data)` - Log error messages
- `logger.debug(message, data)` - Log debug messages

#### Metrics
- `metrics.record(endpoint, method, responseTime, statusCode)` - Record API metrics
- `metrics.getAverageResponseTime(endpoint)` - Get average response time
- `metrics.getSuccessRate(endpoint)` - Get success rate percentage

#### Rate Limiting
- `isRequestAllowed(identifier)` - Check if request is allowed
- `getRemainingRequests(identifier)` - Get remaining requests

## Development

### Building the SDK

```bash
# Install dependencies
npm install

# Build the SDK
npm run build

# Development mode with watch
npm run dev

# Type checking
npm run type-check
```

### Project Structure

```
src/
├── client/           # Client SDK implementation
│   ├── analytics.ts  # Analytics functionality
│   ├── error-reporter.ts # Error reporting
│   └── index.ts      # Client SDK main export
├── server/           # Server SDK implementation
│   ├── logger.ts     # Logging functionality
│   ├── metrics.ts    # Metrics collection
│   ├── rate-limiter.ts # Rate limiting
│   └── index.ts      # Server SDK main export
├── shared/           # Shared utilities
│   └── http-client.ts # HTTP client
├── types/            # TypeScript type definitions
│   └── index.ts
└── index.ts          # Main entry point
```

## Examples

Check the `examples/` directory for complete working examples:

- **Next.js**: `examples/nextjs/` - Full Next.js application
- **Express.js**: `examples/express/` - Express.js server with API routes
- **NestJS**: `examples/nestjs/` - NestJS application with modules
- **React**: `examples/react/` - React application with hooks

## Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Support

For support and questions, please open an issue on GitHub or contact us at support@makebell.com.