npm package: @rivtor/local
Description: Offline-first development environment with SQLite adapter and mock services
Author: Rivtor
Latest version: 1.1.0

# @rivtor/local

**Production-ready offline-first development environment with SQLite adapter and mock services**

## Features

- **SQLite Adapter**: Seamless swap for Postgres in local development
- **Mock Services**: Built-in mocks for JWT, Stripe, email, and more
- **Local Mode Detection**: Automatically detects when running locally
- **Production Checklist**: Validates your app is ready for deployment
- **Email Logging**: View all sent emails in development
- **CLI Tool**: Simple command-line interface for local development

## Installation

```bash
npm install @rivtor/local
# or
yarn add @rivtor/local
# or
pnpm add @rivtor/local
```

## Quick Start

### 1. Start Local Development Server

```bash
# Start local development server
npx rivtor dev start

# Start with custom database path
npx rivtor dev start --db-path ./local.db

# Start with email logging enabled
npx rivtor dev start --email-logs

# Start with custom port
npx rivtor dev start --port 3001
```

### 2. Validate Production Readiness

```bash
# Check if your app is ready for production
npx rivtor dev validate

# Check with specific environment
npx rivtor dev validate --env staging

# Check specific checks only
npx rivtor dev validate --checks env-vars,database
```

### 3. View Mock Email Logs

```bash
# View all sent emails
npx rivtor dev email-logs

# View last 10 emails
npx rivtor dev email-logs --limit 10

# View email by ID
npx rivtor dev email-logs --id email-123

# Watch for new emails
npx rivtor dev email-logs --watch
```

### 4. Enable Local Mode

```typescript
import { isLocalMode, setupLocalMode } from '@rivtor/local/server';

// Check if running in local mode
if (isLocalMode()) {
  const cleanup = await setupLocalMode({
    database: {
      type: 'sqlite',
      path: './local.db'
    },
    mocks: {
      jwt: true,
      email: true,
      stripe: true
    }
  });

  // Later: cleanup();
}
```

### 5. Use SQLite Adapter

```typescript
import { createSQLiteAdapter } from '@rivtor/local/server';

// Create SQLite adapter
const adapter = createSQLiteAdapter({
  type: 'sqlite',
  path: './local.db'
});

// Query data
const users = await adapter.query('SELECT * FROM users');

// Execute command
await adapter.execute('INSERT INTO users (email) VALUES (?)', ['user@example.com']);
```

## API Reference

### CLI Commands

```bash
# Start local development
npx rivtor dev start [options]

# Validate production readiness
npx rivtor dev validate [options]

# View email logs
npx rivtor dev email-logs [options]

# Reset local database
npx rivtor dev reset-db

# Options:
#   --db-path <path>        Path to SQLite database
#   --email-logs            Enable email logging
#   --port <port>           Port for dev server
#   --env <environment>     Environment to validate
#   --checks <checks>       Comma-separated list of checks
#   --limit <number>        Limit number of results
#   --id <id>               Specific ID to view
#   --watch                 Watch for changes
```

### Server Functions

```typescript
import {
  isLocalMode,
  setupLocalMode,
  createSQLiteAdapter,
  validateProductionReadiness,
  getEmailLogs
} from '@rivtor/local/server';

// Check if running in local mode
isLocalMode(): boolean;

// Setup local mode
await setupLocalMode(config: {
  database?: {
    type: 'sqlite';
    path: string;
  };
  mocks?: {
    jwt?: boolean;
    email?: boolean;
    stripe?: boolean;
  };
}): Promise<() => void>; // Returns cleanup function

// Create SQLite adapter
createSQLiteAdapter(config: {
  type: 'sqlite';
  path: string;
}): SQLiteAdapter;

// Validate production readiness
await validateProductionReadiness(options?: {
  env?: string;
  checks?: string[];
}): Promise<{
  readyForProduction: boolean;
  passed: string[];
  failed: string[];
  warnings: string[];
}>;

// Get email logs
await getEmailLogs(options?: {
  limit?: number;
  since?: Date;
}): Promise<EmailLog[]>;
```

### SQLite Adapter

```typescript
import { createSQLiteAdapter } from '@rivtor/local/server';

const adapter = createSQLiteAdapter({ type: 'sqlite', path: './local.db' });

// Query data
const users = await adapter.query('SELECT * FROM users WHERE active = ?', [true]);

// Execute command
await adapter.execute('INSERT INTO users (email, name) VALUES (?, ?)', [
  'user@example.com',
  'John Doe'
]);

// Execute transaction
await adapter.transaction(async (db) => {
  await db.execute('INSERT INTO users (email) VALUES (?)', ['user@example.com']);
  await db.execute('INSERT INTO profiles (user_id) VALUES (?)', [userId]);
});

// Get schema
const schema = await adapter.getSchema();
// Returns: { tables: [...], columns: [...] }
```

### Mock Services

```typescript
import { setupMocks } from '@rivtor/local/server';

await setupMocks({
  // Mock JWT service
  jwt: {
    enabled: true,
    secret: 'local-secret',
    expiresIn: '7d'
  },

  // Mock email service
  email: {
    enabled: true,
    logToConsole: true,
    storeLogs: true
  },

  // Mock Stripe service
  stripe: {
    enabled: true,
    testMode: true
  }
});
```

### Production Validation

```typescript
import { validateProductionReadiness } from '@rivtor/local/server';

const result = await validateProductionReadiness();

if (!result.readyForProduction) {
  console.error('Not ready for production:');
  result.failed.forEach(check => {
    console.error(`  - ${check}`);
  });
  result.warnings.forEach(warning => {
    console.warn(`  - ${warning}`);
  });
}

// Example output:
// {
//   readyForProduction: false,
//   passed: ['node-version', 'typescript'],
//   failed: ['env-vars', 'database-connection'],
//   warnings: ['cors-configuration']
// }
```

### Environment Variables

```bash
# Enable local mode
RIVTOR_LOCAL=true

# SQLite database path
RIVTOR_DB_PATH=./local.db

# Email logging
RIVTOR_EMAIL_LOGS=true

# Mock services
RIVTOR_MOCK_JWT=true
RIVTOR_MOCK_EMAIL=true
RIVTOR_MOCK_STRIPE=true
```

## Configuration

```typescript
import { configureLocal } from '@rivtor/local/server';

configureLocal({
  // Database configuration
  database: {
    type: 'sqlite',
    path: './local.db',
    migrationsPath: './migrations',
    seedsPath: './seeds'
  },

  // Mock services
  mocks: {
    jwt: {
      enabled: true,
      secret: 'local-dev-secret',
      expiresIn: '7d',
      algorithm: 'HS256'
    },
    email: {
      enabled: true,
      logToConsole: true,
      storeLogs: true,
      retentionDays: 7
    },
    stripe: {
      enabled: true,
      testMode: true,
      mockCustomers: true,
      mockPayments: true
    }
  },

  // Production checks
  checks: {
    requiredEnvVars: [
      'DATABASE_URL',
      'JWT_SECRET',
      'STRIPE_SECRET_KEY'
    ],
    requiredNodeVersion: '>=18.0.0',
    requiredDependencies: [
      'next',
      'react',
      '@rivtor/analytics'
    ]
  },

  // Dev server
  server: {
    port: 3000,
    host: 'localhost',
    hotReload: true
  }
});
```

## Production Readiness Checks

The following checks are performed when validating production readiness:

| Check | Description |
|-------|-------------|
| node-version | Validates Node.js version |
| env-vars | Checks required environment variables |
| database-connection | Verifies database connectivity |
| cors-configuration | Validates CORS settings |
| dependencies | Checks for missing dependencies |
| build | Verifies app builds successfully |
| types | Validates TypeScript compilation |

## Best Practices

1. **Use Local Mode**: Always use local mode for development and testing
2. **Validate Before Deploy**: Run production validation before every deployment
3. **Mock External Services**: Use mocks to avoid external API calls in development
4. **Keep Database in Git**: Commit your local SQLite database for reproducible tests
5. **Monitor Email Logs**: Regularly check email logs to ensure emails are sent correctly

## License

MIT

---

Made with ❤️ by [Rivtor](https://rivtor.com)