npm package: @mezzolla/prisma-diagram-core
Description: TypeScript library for generating diagrams from Prisma schemas
Author: Prisma Diagram Team
Latest version: 0.0.2

# @prisma-diagram/core

[![npm version](https://badge.fury.io/js/%40prisma-diagram%2Fcore.svg)](https://badge.fury.io/js/%40prisma-diagram%2Fcore)
[![TypeScript](https://img.shields.io/badge/TypeScript-007ACC?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
[![Jest](https://img.shields.io/badge/Jest-323330?logo=jest&logoColor=white)](https://jestjs.io/)
[![Rollup](https://img.shields.io/badge/Rollup-EC4A3F?logo=rollup.js&logoColor=white)](https://rollupjs.org/)

A powerful TypeScript library for generating visual diagrams from Prisma schemas. Transform your Prisma schema files into beautiful, interactive diagrams in multiple formats including DrawIO, SVG, and PNG.

## ✨ Features

- **🔍 Complete Prisma Schema Parsing**: Supports all Prisma constructs including models, enums, relations, generators, and datasources
- **🎨 Multiple Output Formats**: Generate diagrams in DrawIO (XML), SVG, and PNG formats
- **📐 Advanced Layout Engine**: 4 layout algorithms (hierarchical, force-directed, grid, circular) with automatic positioning
- **🎭 Theme System**: 4 built-in themes (default, dark, minimal, colorful) plus custom theme support
- **⚡ High Performance**: Parses complex schemas (900+ lines, 28+ models) in under 35ms
- **🔧 TypeScript First**: Full TypeScript support with comprehensive type definitions
- **🧪 Well Tested**: 59+ unit tests with 100% pass rate
- **📦 Zero Dependencies**: Lightweight with no external runtime dependencies

## 🚀 Quick Start

### Installation

```bash
npm install @prisma-diagram/core
# or
yarn add @prisma-diagram/core
# or
pnpm add @prisma-diagram/core
```

### Basic Usage

```typescript
import {PrismaDiagramGenerator} from '@prisma-diagram/core';

// Create generator from schema file
const generator = await PrismaDiagramGenerator.fromFile('./schema.prisma');

// Or create from schema content
const generator = PrismaDiagramGenerator.fromSchema(`
  model User {
    id    Int    @id @default(autoincrement())
    email String @unique
    name  String?
    posts Post[]
  }

  model Post {
    id       Int    @id @default(autoincrement())
    title    String
    content  String?
    authorId Int
    author   User   @relation(fields: [authorId], references: [id])
  }
`);

// Generate diagrams in different formats
const drawioXml = await generator.generateDrawIO();
const svgContent = await generator.generateSVG();
const pngBuffer = await generator.generatePNG();

// Save to files
import {writeFileSync} from 'fs';
writeFileSync('diagram.drawio', drawioXml);
writeFileSync('diagram.svg', svgContent);
writeFileSync('diagram.png', pngBuffer);
```

## 📖 API Reference

### PrismaDiagramGenerator

The main class for generating diagrams from Prisma schemas.

#### Static Methods

```typescript
// Create generator from file
static async fromFile(filePath: string): Promise<PrismaDiagramGenerator>

// Create generator from schema content
static fromSchema(schemaContent: string): PrismaDiagramGenerator
```

#### Instance Methods

```typescript
// Generate diagrams
async generateDrawIO(options?: ExportOptions): Promise<string>
async generateSVG(options?: ExportOptions): Promise<string>
async generatePNG(options?: ExportOptions): Promise<Buffer>

// Validation and information
validate(): ValidationResult
getModelsInfo(): ModelInfo[]
getRelationsInfo(): RelationInfo[]
getStats(): DiagramStats

// Configuration
setLayoutOptions(options: LayoutOptions): PrismaDiagramGenerator
setTheme(theme: ThemeOptions): PrismaDiagramGenerator
getAvailableFormats(): string[]
getGeneratorInfo(format: string): GeneratorInfo | null
```

### Layout Options

```typescript
interface LayoutOptions {
  algorithm: 'hierarchical' | 'force-directed' | 'grid' | 'circular';
  nodeSpacing?: number; // Default: 200
  levelSpacing?: number; // Default: 150
  direction?: 'top-to-bottom' | 'bottom-to-top' | 'left-to-right' | 'right-to-left';
  nodeWidth?: number; // Default: 200
  nodeHeight?: number; // Default: 100
  padding?: number; // Default: 20
  avoidOverlaps?: boolean; // Default: true
  centerGraph?: boolean; // Default: true
}
```

### Theme Options

```typescript
interface ThemeOptions {
  name?: 'default' | 'dark' | 'minimal' | 'colorful';
  customTheme?: Partial<Theme>;
}
```

## 🎨 Supported Formats

### DrawIO (XML)

- **Best for**: Interactive editing, collaboration, complex diagrams
- **Features**: Full Draw.io compatibility, editable elements, export to multiple formats
- **Use case**: When you need to edit or collaborate on diagrams

```typescript
const drawioXml = await generator.generateDrawIO();
// Opens directly in Draw.io or compatible editors
```

### SVG

- **Best for**: Web display, print, scalable graphics
- **Features**: Vector graphics, web-compatible, print-ready
- **Use case**: Web applications, documentation, high-quality prints

```typescript
const svgContent = await generator.generateSVG();
// Perfect for web applications and documentation
```

### PNG

- **Best for**: Sharing, universal compatibility, small file sizes
- **Features**: Raster images, universal support, optimized file size
- **Use case**: Social media, presentations, quick sharing

```typescript
const pngBuffer = await generator.generatePNG();
// Universal compatibility for sharing
```

## 🎯 Layout Algorithms

### Hierarchical Layout

- **Best for**: Database schemas with clear parent-child relationships
- **Features**: Top-down or left-right organization, clear hierarchy
- **Use case**: Traditional database diagrams, organizational charts

### Force-Directed Layout

- **Best for**: Complex schemas with many interconnections
- **Features**: Natural node distribution, minimizes edge crossings
- **Use case**: Complex relational databases, network diagrams

### Grid Layout

- **Best for**: Simple schemas, uniform organization
- **Features**: Regular grid pattern, predictable positioning
- **Use case**: Simple schemas, when you need consistent spacing

### Circular Layout

- **Best for**: Schemas with circular references, compact display
- **Features**: Circular arrangement, space-efficient
- **Use case**: Schemas with many circular references, compact views

## 🎨 Themes

### Default Theme

- Clean, professional appearance
- Light background with subtle colors
- Perfect for documentation and presentations

### Dark Theme

- Dark background with light text
- Modern, sleek appearance
- Great for dark mode applications

### Minimal Theme

- Ultra-clean design
- Minimal colors and styling
- Perfect for technical documentation

### Colorful Theme

- Vibrant colors and modern styling
- Eye-catching appearance
- Great for presentations and demos

## 📊 Performance

The library is optimized for performance and can handle complex schemas efficiently:

- **Simple schemas** (4 models): < 5ms parsing time
- **Complex schemas** (28 models, 909 lines): 35ms parsing time
- **Layout generation**: < 50ms for complex schemas
- **Memory efficient**: Optimized for enterprise schemas
- **Zero errors**: 100% parsing accuracy on production schemas

## 🧪 Testing

The library includes comprehensive test coverage:

```bash
# Run all tests
npm test

# Run specific test suites
npm test -- --testPathPattern=Parser
npm test -- --testPathPattern=Layout
npm test -- --testPathPattern=Generators

# Run with coverage
npm run test:coverage
```

## 🔧 Development

### Building the Library

```bash
# Install dependencies
npm install

# Build the library
npm run build

# Type checking
npm run type-check

# Linting
npm run lint
```

### Project Structure

```
src/
├── parser/           # Prisma schema parsing
│   ├── PrismaSchemaParser.ts
│   ├── ModelParser.ts
│   ├── RelationParser.ts
│   └── types.ts
├── layout/           # Layout engine and algorithms
│   ├── LayoutEngine.ts
│   ├── ConnectionRouter.ts
│   ├── ThemeManager.ts
│   └── types.ts
├── generators/       # Output format generators
│   ├── BaseGenerator.ts
│   ├── DrawIOGenerator.ts
│   ├── SVGGenerator.ts
│   ├── PNGGenerator.ts
│   ├── GeneratorFactory.ts
│   └── types.ts
└── index.ts         # Main entry point
```

## 📝 Examples

### Basic Schema

```typescript
const schema = `
  model User {
    id    Int    @id @default(autoincrement())
    email String @unique
    name  String?
    posts Post[]
  }

  model Post {
    id       Int    @id @default(autoincrement())
    title    String
    content  String?
    authorId Int
    author   User   @relation(fields: [authorId], references: [id])
  }
`;

const generator = PrismaDiagramGenerator.fromSchema(schema);
const svg = await generator.generateSVG();
```

### Complex Schema with Custom Options

```typescript
const generator = await PrismaDiagramGenerator.fromFile('./complex-schema.prisma');

// Custom layout
generator.setLayoutOptions({
  algorithm: 'force-directed',
  nodeSpacing: 300,
  levelSpacing: 200,
  direction: 'left-to-right',
});

// Custom theme
generator.setTheme({
  name: 'dark',
});

const diagram = await generator.generateDrawIO();
```

### Validation and Statistics

```typescript
const generator = PrismaDiagramGenerator.fromSchema(schema);

// Validate schema
const validation = generator.validate();
if (!validation.isValid) {
  console.error('Schema validation failed:', validation.errors);
}

// Get statistics
const stats = generator.getStats();
console.log(`Models: ${stats.models}, Relations: ${stats.relations}, Complexity: ${stats.complexity}`);

// Get detailed information
const modelsInfo = generator.getModelsInfo();
const relationsInfo = generator.getRelationsInfo();
```

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup

1. Fork the repository
2. Clone your fork
3. Install dependencies: `npm install`
4. Create a feature branch
5. Make your changes
6. Run tests: `npm test`
7. Submit a pull request

## 📄 License

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

## 🆘 Support

- **Documentation**: [Full API Documentation](https://github.com/PrismaDiagram/prisma-diagram-core)
- **Issues**: [GitHub Issues](https://github.com/PrismaDiagram/prisma-diagram-core/issues)
- **Discussions**: [GitHub Discussions](https://github.com/PrismaDiagram/prisma-diagram-core/discussions)
- **Email**: mezzolladev@gmail.com

## 🗺️ Roadmap

- [ ] **Phase 2**: Next.js Webapp with interactive diagram editor
- [ ] **Phase 3**: CLI tool for automation and CI/CD integration
- [ ] **Phase 4**: VS Code extension for real-time diagram generation
- [ ] **Phase 5**: Advanced features (collaboration, version control, etc.)

## 👨‍💻 Author

This project is developed by **[Luca Mezzolla](https://www.mezzolladev.com/)**, a Frontend Web Developer with over 4 years of experience in creating web applications. Currently working as Software Engineer at Intesa Sanpaolo, focusing on Frontend architectures. Luca is passionate about innovative technologies and committed to creating intuitive user interfaces and scalable systems.

For more information about his projects and skills, visit his [online portfolio](https://www.mezzolladev.com/).

## 🙏 Acknowledgments

- Built with [TypeScript](https://www.typescriptlang.org/)
- Tested with [Jest](https://jestjs.io/)
- Bundled with [Rollup](https://rollupjs.org/)
- Inspired by the Prisma ecosystem and diagramming tools

---

**Made with ❤️ by [Luca Mezzolla](https://www.mezzolladev.com/) for the Prisma community**