npm package: @rivtor/codegen
Description: TypeScript Schema Generator with Postgres introspection and watch mode
Author: Rivtor
Latest version: 1.1.0

# @rivtor/codegen

**Production-ready TypeScript schema generator with Postgres introspection and watch mode**

## Features

- **Postgres Introspection**: Automatically scans information_schema and pg_catalog for complete type generation
- **Enum Generation**: Auto-generate TypeScript types from Postgres enums
- **RLS Policy Awareness**: Includes JSDoc comments for Row Level Security policies
- **Watch Mode**: Auto-regenerate types on schema changes
- **CLI Tool**: Simple command-line interface for type generation
- **CamelCase Support**: Optional camelCase conversion for field names

## Installation

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

## Quick Start

### 1. Generate Types via CLI

```bash
# Generate types from your Postgres database
npx rivtor-codegen generate --schema public --output ./types/database.ts

# Watch for changes and auto-regenerate
npx rivtor-codegen watch --schema public --output ./types/database.ts

# Include specific tables only
npx rivtor-codegen generate --include users,projects,subscriptions --output ./types/database.ts

# Exclude specific tables
npx rivtor-codegen generate --exclude logs,audit_events --output ./types/database.ts

# Use camelCase for field names
npx rivtor-codegen generate --camel-case --output ./types/database.ts
```

### 2. Generate Types Programmatically

```typescript
import { generateTypes } from '@rivtor/codegen/server';

// Generate types with custom options
await generateTypes({
  schema: 'public',
  outputFile: './types/database.ts',
  includeTables: ['users', 'projects', 'subscriptions'],
  excludeTables: ['logs', 'audit_events'],
  camelCase: true,
  includeJSDoc: true
});
```

### 3. Use Generated Types in Your Code

```typescript
import { User, UserInsert, UserUpdate } from './types/database';

// Insert new user
const newUser: UserInsert = {
  email: 'user@example.com',
  name: 'John Doe',
  created_at: new Date().toISOString()
};

// Update existing user
const updates: UserUpdate = {
  id: 'user-123',
  name: 'Jane Doe'
};

// Query result type
function getUserById(id: string): Promise<User | null> {
  // Your database query here
}
```

### 4. Enable Watch Mode for Development

```typescript
import { watchSchema } from '@rivtor/codegen/server';

// Watch for schema changes and auto-regenerate
const watcher = await watchSchema({
  schema: 'public',
  outputFile: './types/database.ts',
  onChange: (tables) => {
    console.log(`Regenerated types for ${tables.length} tables`);
  }
});

// Later: stop watching
await watcher.stop();
```

## API Reference

### CLI Commands

```bash
# Generate types
npx rivtor-codegen generate [options]

# Watch mode
npx rivtor-codegen watch [options]

# Options:
#   --schema <name>        Postgres schema name (default: public)
#   --output <path>        Output file path (default: ./types/database.ts)
#   --include <tables>     Comma-separated list of tables to include
#   --exclude <tables>     Comma-separated list of tables to exclude
#   --camel-case           Convert field names to camelCase
#   --no-jsdoc             Exclude JSDoc comments
#   --watch                Enable watch mode
```

### Server Functions

```typescript
import { generateTypes, watchSchema, inspectDatabase } from '@rivtor/codegen/server';

// Generate TypeScript types
await generateTypes({
  schema: 'public',                    // Postgres schema name
  outputFile: './types/database.ts',    // Output file path
  includeTables?: string[],             // Tables to include (optional)
  excludeTables?: string[],             // Tables to exclude (optional)
  camelCase?: boolean,                  // Use camelCase for fields
  includeJSDoc?: boolean,               // Include JSDoc comments
  dbUrl?: string                        // Database URL (optional, uses DATABASE_URL)
});

// Watch schema for changes
await watchSchema({
  schema: 'public',
  outputFile: './types/database.ts',
  onChange?: (tables: TableInfo[]) => void,  // Callback on changes
  pollInterval?: number                       // Poll interval in ms (default: 5000)
});

// Inspect database without generating types
const schema = await inspectDatabase({
  schema: 'public',
  includeTables: ['users', 'projects']
});
// Returns: { tables, enums, views }
```

## Configuration

```typescript
interface CodegenConfig {
  // Postgres schema to scan
  schema: string;

  // Output file path
  outputFile: string;

  // Include only specific tables
  includeTables?: string[];

  // Exclude specific tables
  excludeTables?: string[];

  // Convert field names to camelCase
  camelCase?: boolean;

  // Include JSDoc comments with RLS policy info
  includeJSDoc?: boolean;

  // Database connection URL (optional)
  dbUrl?: string;

  // Custom type mappings
  typeMappings?: Record<string, string>;
}
```

## Generated Output

The package generates TypeScript types with:

- **Table interfaces**: Full type definitions for each table
- **Insert types**: Types for creating new records (excluding auto-generated fields)
- **Update types**: Types for updating records (all fields optional)
- **Enum types**: TypeScript enums from Postgres enums
- **JSDoc comments**: Documentation including RLS policy information

```typescript
// Auto-generated by @rivtor/codegen

export interface User {
  id: string;
  email: string;
  name?: string | null;
  role: 'admin' | 'user' | 'guest';
  created_at: string;
  updated_at: string;
  /** @rls Users can only read their own records */
}

export type UserInsert = {
  email: string;
  name?: string | null;
  role?: 'admin' | 'user' | 'guest';
  created_at?: string;
  updated_at?: string;
};

export type UserUpdate = {
  id?: string;
  email?: string;
  name?: string | null;
  role?: 'admin' | 'user' | 'guest';
  created_at?: string;
  updated_at?: string;
};

export enum UserRole {
  Admin = 'admin',
  User = 'user',
  Guest = 'guest'
}
```

## Best Practices

1. **Commit Generated Types**: Commit the generated types to version control
2. **Use Watch Mode**: Enable watch mode during development for automatic updates
3. **Custom Type Mappings**: Define custom mappings for domain-specific types
4. **Include JSDoc**: Keep JSDoc comments enabled for better IDE support

## License

MIT

---

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