npm package: @super-resume/foundry
Description: 🔨 CLI tool for generating production-ready NestJS microservices in monorepo environments
Author: Super Resume
Latest version: 1.1.2

# Foundry

<!-- Quality Gate & AI Assurance -->
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=Super-Resume_foundry&metric=alert_status&token=8cac9596183f78c288848f9e3893cbec45be4b64)](https://sonarcloud.io/summary/new_code?id=Super-Resume_foundry)
[![AI Code Assurance](https://sonarcloud.io/api/project_badges/ai_code_assurance?project=Super-Resume_foundry&token=8cac9596183f78c288848f9e3893cbec45be4b64)](https://sonarcloud.io/summary/new_code?id=Super-Resume_foundry)
[![Build Status](https://github.com/Super-Resume/foundry/actions/workflows/ci.yml/badge.svg)](https://github.com/Super-Resume/foundry/actions/workflows/ci.yml)

<!-- Code Quality Metrics -->
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=Super-Resume_foundry&metric=coverage&token=8cac9596183f78c288848f9e3893cbec45be4b64)](https://sonarcloud.io/summary/new_code?id=Super-Resume_foundry)
[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=Super-Resume_foundry&metric=bugs&token=8cac9596183f78c288848f9e3893cbec45be4b64)](https://sonarcloud.io/summary/new_code?id=Super-Resume_foundry)
[![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=Super-Resume_foundry&metric=code_smells&token=8cac9596183f78c288848f9e3893cbec45be4b64)](https://sonarcloud.io/summary/new_code?id=Super-Resume_foundry)
[![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=Super-Resume_foundry&metric=duplicated_lines_density&token=8cac9596183f78c288848f9e3893cbec45be4b64)](https://sonarcloud.io/summary/new_code?id=Super-Resume_foundry)

<!-- Security & Reliability -->
[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=Super-Resume_foundry&metric=security_rating&token=8cac9596183f78c288848f9e3893cbec45be4b64)](https://sonarcloud.io/summary/new_code?id=Super-Resume_foundry)
[![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=Super-Resume_foundry&metric=vulnerabilities&token=8cac9596183f78c288848f9e3893cbec45be4b64)](https://sonarcloud.io/summary/new_code?id=Super-Resume_foundry)
[![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=Super-Resume_foundry&metric=reliability_rating&token=8cac9596183f78c288848f9e3893cbec45be4b64)](https://sonarcloud.io/summary/new_code?id=Super-Resume_foundry)

<!-- Maintainability & Technical Debt -->
[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=Super-Resume_foundry&metric=sqale_rating&token=8cac9596183f78c288848f9e3893cbec45be4b64)](https://sonarcloud.io/summary/new_code?id=Super-Resume_foundry)
[![Technical Debt](https://sonarcloud.io/api/project_badges/measure?project=Super-Resume_foundry&metric=sqale_index&token=8cac9596183f78c288848f9e3893cbec45be4b64)](https://sonarcloud.io/summary/new_code?id=Super-Resume_foundry)

<!-- Package & Distribution -->
[![NPM Version](https://img.shields.io/npm/v/@super-resume/foundry?style=flat-square&color=blue&logo=npm)](https://www.npmjs.com/package/@super-resume/foundry)
[![NPM Downloads](https://img.shields.io/npm/dm/@super-resume/foundry?style=flat-square&color=green&logo=npm)](https://www.npmjs.com/package/@super-resume/foundry)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT)

<!-- Technology Stack -->
[![TypeScript](https://img.shields.io/badge/TypeScript-007ACC?style=flat-square&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
[![NestJS](https://img.shields.io/badge/NestJS-E0234E?style=flat-square&logo=nestjs&logoColor=white)](https://nestjs.com/)
[![Node.js](https://img.shields.io/badge/Node.js-43853D?style=flat-square&logo=node.js&logoColor=white)](https://nodejs.org/)

<!-- Community & Development -->
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)

## TLDR
```bash
npm install -g @super-resume/foundry
foundry generate    # Interactive mode (recommended)
```

A powerful CLI tool for generating NestJS microservice templates with **Domain-Driven Design (DDD)** and **Clean Architecture** patterns. Creates production-ready services with optional database, serverless, Docker, and Kubernetes support.

## 📝 A Note from the Maintainers

This tool was originally designed as an internal package for generating our microservice templates at JobTopGun. However, we decided to open-source it as it addresses common challenges developers face when setting up NestJS microservices - including the notorious "Prisma client not found" issue that many encounter!

While initially built for our specific needs, we believe Foundry can be valuable for the broader community. It encapsulates our battle-tested patterns and solutions for building scalable, maintainable microservices.

**⚠️ Important Note for v1.1.0+**: Starting from version 1.1.0, some generated templates with authentication features may have dependencies on internal packages (`@jobtopgun/auth`, `@jobtopgun/common`) that are part of our private architecture. While we cannot share the complete implementation due to proprietary considerations, you'll need to create your own adapters for these dependencies. 

- 📖 **Detailed Guide**: See our comprehensive [Adapter Implementation Guide](ADAPTER_GUIDE.md)
- 🚀 **Quick Fix**: Generate without auth using `--no-authentication` flag
- 🤝 **Community**: Share your adapter implementations with others!

**🔒 Security Notice**: If you discover any security vulnerabilities in these templates, please contact us immediately. We take security seriously and appreciate responsible disclosure.

**🤝 Contributions Welcome**: Feel free to adapt these templates to your needs, and we welcome contributions to make Foundry even better for everyone!

## 🎯 Quick Start - Interactive Mode

The easiest way to get started is with the **interactive mode**, which guides you through the configuration step-by-step:

```bash
foundry generate
```

This will prompt you to:
1. 📝 Enter your service name
2. 🎨 Choose a service type (Basic, Authenticated, BFF, or Custom)
3. ⚙️ Configure features based on your needs
4. 📦 Select S3 bucket configurations (if applicable)
5. 🏢 Enter your organization name (for package scope and Docker registry)
6. 🔍 Review and confirm your configuration

### Service Types

- **🚀 Basic Service** - Simple REST API with database and standard features
- **🔐 Authenticated Service** - Includes JWT authentication and authorization
- **🎯 BFF Service** - Backend for Frontend with full feature set
- **⚙️ Custom** - Choose exactly which features you need

### Quick Commands

For experienced users, we provide quick commands for common service types:

```bash
# Create a basic service
foundry create-basic user-service

# Create a BFF service with authentication and all features
foundry create-bff bff-service

# Use flags for non-interactive mode
foundry generate api-service --authentication --s3 --non-interactive
```

## Features

### Core Features
- 🚀 **NestJS Framework**: Full NestJS service template with modular architecture
- 🏛️ **DDD/Clean Architecture**: Domain-driven design with clear separation of concerns
- 🎯 **Interactive CLI**: User-friendly prompts for service configuration (like create-next-app)
- 🏗️ **Monorepo Structure**: Generates services in `services/` directory
- ✅ **Production Ready**: Built-in validation, health checks, and monitoring
- 🛠️ **Auto Setup**: One-command service setup with `npm run setup`

### Infrastructure Features
- 🗄️ **Database Support**: Optional Prisma ORM with PostgreSQL configuration
- 🐳 **Docker Ready**: Optional Dockerfile and container support
- ☁️ **Serverless**: Optional AWS Lambda configuration with Serverless Framework
- ⚓ **Kubernetes**: Optional K8s deployment and service manifests
- 🔄 **CI/CD Ready**: GitHub Actions workflow with testing, building, and deployment

### Advanced Features (New!)
- 🔐 **JWT Authentication**: Built-in JWT authentication with global guards
- 🔑 **Public Endpoints**: `@Public()` decorator for unprotected endpoints
- ☁️ **AWS S3 Storage**: Configurable S3 buckets for file storage
- 📡 **EventBridge Integration**: Event-driven architecture support
- ⚡ **Redis Cache**: Optional Redis caching layer
- 🔗 **Service Communication**: Inter-service endpoint configuration
- 🌉 **AWS Bridge**: Seamless development-to-production AWS integration
- 📊 **Health Monitoring**: Advanced health checks with memory and dependency monitoring
- 📚 **API Documentation**: Optional Swagger/OpenAPI documentation with auth support

## Generated Service Structure

```
services/your-service/
├── src/
│   ├── main.ts                           # Application entry point
│   ├── lambda.ts                         # Lambda handler (if serverless enabled)
│   ├── config/
│   │   ├── service.config.ts             # Service configuration
│   │   ├── environment.config.ts         # Environment variables
│   │   └── aws-bridge.config.ts          # AWS integration bridge
│   ├── domain/                           # Domain Layer (Business Logic)
│   │   ├── entities/
│   │   │   └── user.entity.ts           # Domain entities
│   │   ├── value-objects/
│   │   │   └── email.value-object.ts    # Value objects
│   │   └── repositories/
│   │       └── user.repository.ts       # Repository interfaces
│   ├── application/                      # Application Layer (Use Cases)
│   │   ├── services/
│   │   │   └── user.service.ts          # Application services
│   │   └── use-cases/
│   │       ├── create-user.use-case.ts  # Business use cases
│   │       └── get-user.use-case.ts
│   ├── infrastructure/                   # Infrastructure Layer
│   │   ├── database/                     # Database configuration (if enabled)
│   │   ├── filters/                      # Global exception filters
│   │   ├── repositories/
│   │   │   └── prisma-user.repository.ts # Repository implementations
│   │   └── infrastructure.module.ts
│   ├── modules/
│   │   └── your-module/                  # Module name (strips -service suffix)
│   │       ├── your-module.module.ts     # Main service module
│   │       └── controller/
│   │           └── v1/
│   │               ├── health.controller.ts # Enhanced health/readiness/liveness checks
│   │               └── user.controller.ts   # User API endpoints
│   └── swagger/                          # Swagger setup (if enabled)
├── scripts/
│   └── setup.ts                          # Automated service setup script
├── test/                                 # Test configuration
├── k8s/                                  # Kubernetes manifests (if enabled)
├── .github/
│   └── workflows/
│       └── service-ci.yml                # CI/CD pipeline with testing & deployment
├── .vscode/
│   └── settings.json                     # VS Code configuration
├── package.json                          # Enhanced scripts and dependencies
├── Dockerfile                            # Docker configuration (if enabled)
├── serverless.yml                        # Serverless config (if enabled)
├── .env.example                          # Environment variables template
└── README.md                             # Service documentation
```

## Installation

### Global Installation
```bash
npm install -g @super-resume/foundry
```

### Local Development
```bash
git clone git@github.com:Super-Resume/foundry.git
cd foundry
npm install
npm run build
```

## 🚀 Setup Autocomplete

Enable tab completion for the foundry command:

### Bash
```bash
foundry completion --shell bash >> ~/.bashrc
source ~/.bashrc
```

### Zsh
```bash
foundry completion --shell zsh >> ~/.zshrc
source ~/.zshrc
```

### Fish
```bash
foundry completion --shell fish > ~/.config/fish/completions/foundry.fish
```

## Usage

### Interactive Mode (Recommended)
The interactive mode guides you through service configuration with user-friendly prompts:

```bash
# Start interactive generation
foundry generate

# Or provide service name upfront
foundry generate user-service
```

The interactive mode will:
- ✅ Validate inputs automatically
- 📋 Show configuration summary before generation
- 🎨 Offer preset configurations (Basic, Authenticated, BFF)
- ⚙️ Allow custom feature selection

### Quick Commands
Pre-configured commands for common service types:

```bash
# Create a basic service with standard features
foundry create-basic user-service

# Create a BFF service with full authentication and features
foundry create-bff bff-service --port 3001
```

### Non-Interactive Mode (CI/CD)
Use flags for automated environments:

```bash
# Basic service (traditional mode)
foundry generate user-service --non-interactive

# Service with authentication
foundry generate api-service \
  --authentication \
  --non-interactive

# Full-featured BFF service
foundry generate bff-service \
  --authentication \
  --s3 \
  --s3-buckets jobApplication,company \
  --events \
  --redis \
  --service-endpoints \
  --non-interactive

# Disable specific features
foundry generate simple-api \
  --no-database \
  --no-docker \
  --non-interactive
```

### Examples with New Features

```bash
# Service with custom organization
foundry generate api-service --organization acme-corp --non-interactive

# Service with JWT authentication
foundry generate secure-api --authentication --non-interactive

# Service with S3 file storage
foundry generate file-service --s3 --s3-buckets jobApplication,company --non-interactive

# Service with event-driven architecture
foundry generate event-service --events --non-interactive

# Service with Redis caching
foundry generate cached-api --redis --non-interactive

# Complete BFF service with all features
foundry generate bff-service \
  --authentication \
  --s3 \
  --s3-buckets jobApplication,company,iam \
  --events \
  --redis \
  --service-endpoints \
  --port 3001 \
  --output ./services \
  --non-interactive
```

## CLI Options

### Core Options
| Option | Description | Default | Example |
|--------|-------------|---------|---------|
| `--port <port>` | Service port number | 3000 | `--port 3001` |
| `--output <path>` | Output directory | Current directory | `--output ./backend` |
| `--organization <name>` | Organization name | jobtopgun | `--organization acme-corp` |
| `--non-interactive` | Skip interactive prompts | Interactive mode | `--non-interactive` |

### Feature Flags (Enable)
| Option | Description | Default | Example |
|--------|-------------|---------|---------|
| `--authentication` | Enable JWT authentication | false | `--authentication` |
| `--s3` | Enable S3 file storage | false | `--s3` |
| `--s3-buckets <list>` | S3 bucket types | None | `--s3-buckets jobApplication,company` |
| `--events` | Enable EventBridge | false | `--events` |
| `--redis` | Enable Redis cache | false | `--redis` |
| `--service-endpoints` | Enable service communication | false | `--service-endpoints` |

### Feature Flags (Disable)
| Option | Description | Default | Example |
|--------|-------------|---------|---------|
| `--no-database` | Disable database support | Enabled | `--no-database` |
| `--no-swagger` | Disable Swagger docs | Enabled | `--no-swagger` |
| `--no-docker` | Disable Docker support | Enabled | `--no-docker` |
| `--no-serverless` | Disable serverless support | Enabled | `--no-serverless` |
| `--no-kubernetes` | Disable Kubernetes support | Enabled | `--no-kubernetes` |

## Service Naming Convention

- Service names must be in **kebab-case** (e.g., `user-service`, `payment-gateway`)
- Module folder names automatically strip the `-service` suffix (e.g., `user-service` → `modules/user/`)
- Service names will be converted to appropriate cases for different files:
  - **PascalCase** for class names (`UserService`)
  - **camelCase** for variables (`userService`)
  - **snake_case** for database names (`user_service_db`)

## Architecture & Design Patterns

### Domain-Driven Design (DDD)

The generated services follow DDD principles with clear separation of concerns:

**Domain Layer** (`src/domain/`)
- **Entities**: Core business objects with identity (`user.entity.ts`)
- **Value Objects**: Immutable objects that describe characteristics (`email.value-object.ts`)
- **Repository Interfaces**: Contracts for data access (`user.repository.ts`)

**Application Layer** (`src/application/`)
- **Services**: Orchestrate business logic and coordinate between layers (`user.service.ts`)
- **Use Cases**: Specific business operations (`create-user.use-case.ts`, `get-user.use-case.ts`)

**Infrastructure Layer** (`src/infrastructure/`)
- **Repository Implementations**: Concrete data access implementations (`prisma-user.repository.ts`)
- **Database Configuration**: Prisma setup and database connections
- **External Services**: Third-party integrations

**Presentation Layer** (`src/modules/*/controller/`)
- **Controllers**: HTTP request handling (`health.controller.ts`, `user.controller.ts`)
- **DTOs**: Data transfer objects for API boundaries

### Benefits

- **Maintainability**: Clear separation makes code easier to understand and modify
- **Testability**: Each layer can be tested independently with proper mocking
- **Scalability**: Well-defined boundaries support growing team collaboration
- **Domain Focus**: Business logic is isolated from technical concerns

## Generated Features

### Database Integration (Prisma ORM)
When database support is enabled:
- Prisma schema configuration
- Database connection service
- Migration scripts
- Repository pattern implementation
- AWS Secrets Manager integration for production

### API Documentation (Swagger)
When Swagger is enabled:
- Automatic API documentation
- Interactive Swagger UI
- OpenAPI specification

### Docker Support
When Docker is enabled:
- Multi-stage Dockerfile
- Optimized for production
- Health check configuration

### Serverless Support
When serverless is enabled:
- AWS Lambda handler
- Serverless Framework configuration
- API Gateway integration

### Kubernetes Support
When Kubernetes is enabled:
- Deployment manifest
- Service manifest
- Configurable replicas and resources

## Post-Generation Steps

After generating a service, you have two options:

### Option 1: Automated Setup (Recommended)

1. **Navigate to the service directory:**
   ```bash
   cd ./services/your-service
   ```

2. **Run automated setup:**
   ```bash
   npm run setup
   ```

   This will automatically:
   - Install dependencies
   - Create and validate `.env` file
   - Generate Prisma client (if database enabled)
   - Run TypeScript type checking
   - Test build process
   - Set up development tools

3. **Start the service:**
   ```bash
   npm run start:dev
   ```

### Option 2: Manual Setup

1. **Navigate to the service directory:**
   ```bash
   cd ./services/your-service
   ```

2. **Install dependencies:**
   ```bash
   npm install
   ```
   
   **Note:** If you encounter peer dependency conflicts (common in monorepo environments), try:
   ```bash
   npm install --legacy-peer-deps
   ```

3. **Configure environment (if database enabled):**
   ```bash
   cp .env.example .env
   # Edit .env with your database configuration
   ```

4. **Run database migrations (if database enabled):**
   ```bash
   npm run prisma:migrate
   ```

5. **Start the service:**
   ```bash
   npm run start:dev
   ```

### Additional Commands

- **Validate service:** `npm run validate`
- **Health check:** `npm run health-check`
- **Start local database:** `npm run docker:db` (if database enabled)
- **AWS connectivity check:** `npm run aws:check`
- **Setup with verbose output:** `npm run setup:verbose`

## Environment Variables

The generated `.env.example` includes:

- **Server Configuration**: `NODE_ENV`, `PORT`, `LOG_LEVEL`
- **Database Configuration**: `DATABASE_URL`, `DB_HOST`, `DB_PORT`, etc.
- **Security**: `JWT_SECRET`, `CORS_ORIGIN`
- **AWS Configuration**: `AWS_REGION`, `DB_SECRET_NAME`
- **Monitoring**: `METRICS_ENABLED`, `TRACING_ENABLED`

## Development

### Local Development
```bash
# Development mode
npm run dev

# Build project
npm run build

# Run tests
npm test
```

### Testing the Enhanced Generator

#### 1. Build the Generator
```bash
npm run build
```

#### 2. Test Basic Generation
```bash
# Create test directory
mkdir test-output

# Generate a basic service
node dist/index.js generate test-basic-service --output ./test-output

# Test the generated service
cd test-output/services/test-basic-service
npm run setup
npm run start:dev
```

#### 3. Test Full-Featured Service
```bash
# Generate service with all features
node dist/index.js generate test-full-service \
  --port 3001 \
  --output ./test-output

# Test the generated service
cd test-output/services/test-full-service
npm run setup:verbose
npm run validate
npm run health-check
```

#### 4. Test Different Configurations
```bash
# Minimal service
node dist/index.js generate test-minimal-service \
  --no-database \
  --no-swagger \
  --no-docker \
  --no-serverless \
  --no-kubernetes \
  --output ./test-output

# Database-only service
node dist/index.js generate test-db-service \
  --no-swagger \
  --no-docker \
  --no-serverless \
  --no-kubernetes \
  --port 3002 \
  --output ./test-output
```

#### 5. Run Integration Tests
```bash
# Run the enhanced integration tests
npm test -- --testNamePattern="integration"

# Run with integration tests enabled
RUN_INTEGRATION_TESTS=true npm test
```

#### 6. Test Using the Generation Script
```bash
# Use the existing test script
chmod +x scripts/test-generation.sh
./scripts/test-generation.sh
```

#### 7. Test Service Validation
```bash
# Test individual service validation
cd test-output/services/test-basic-service
npm run setup --skip-deps  # Skip dependencies for faster testing
npm run validate
```

### Testing New Features

#### Health Checks
```bash
# Start a generated service
npm run start:dev

# In another terminal, test health endpoints
curl http://localhost:3000/test-service/health
curl http://localhost:3000/test-service/health/readiness
curl http://localhost:3000/test-service/health/liveness
```

#### AWS Bridge Configuration
```bash
# Test with AWS credentials configured
aws configure  # Set up AWS credentials
npm run aws:check  # Test AWS connectivity

# Test without AWS (should gracefully degrade)
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY
npm run start:dev  # Should still work in development
```

#### CI/CD Pipeline
```bash
# Test the generated GitHub Actions workflow
cd test-output/services/test-service
git init
git add .
git commit -m "Initial commit"

# The .github/workflows/service-ci.yml will run on push to GitHub
```

### Manual Testing Checklist

- [ ] Service generation completes without errors
- [ ] Generated service has all expected files and directories
- [ ] `npm run setup` works correctly
- [ ] TypeScript compilation passes
- [ ] Service starts successfully
- [ ] Health endpoints respond correctly
- [ ] Database integration works (if enabled)
- [ ] Docker build succeeds (if enabled)
- [ ] AWS integration works in production mode
- [ ] CI/CD pipeline validates correctly

### Performance Testing
```bash
# Test generation performance
time node dist/index.js generate perf-test-service --output ./test-output

# Test setup performance
cd test-output/services/perf-test-service
time npm run setup
```

## New Features

### Service Validation
Generated services include comprehensive validation:
- **TypeScript Compilation**: Ensures code compiles without errors
- **Dependency Compatibility**: Checks for package conflicts and security issues
- **AWS Connectivity**: Verifies AWS credentials and service access
- **File Structure**: Validates required files and directories exist
- **Environment Configuration**: Ensures required environment variables are set

### AWS Bridge Configuration
Seamless integration between development and production:
- **Development Mode**: Uses local `.env` files
- **Production Mode**: Automatically loads from AWS Secrets Manager
- **Fallback Support**: Graceful degradation if AWS services are unavailable
- **Service-specific Secrets**: Organized by service name in AWS Secrets Manager

### Enhanced Health Checks
Production-ready monitoring endpoints:
- **Health (`/health`)**: Overall service health with database, AWS, and memory checks
- **Readiness (`/health/readiness`)**: Kubernetes readiness probe with dependency checks
- **Liveness (`/health/liveness`)**: Simple liveness probe for basic availability
- **Response Time Monitoring**: Database query performance tracking
- **Memory Usage Tracking**: Heap memory monitoring with configurable limits

### CI/CD Pipeline
Complete GitHub Actions workflow:
- **Testing**: Unit tests, integration tests, and TypeScript validation
- **Building**: Docker images with multi-stage builds
- **Security**: Dependency scanning and Docker image vulnerability checks
- **Deployment**: Automated staging and production deployment
- **Performance**: Load testing with Apache Bench
- **Monitoring**: Service startup and health endpoint validation

### Automated Setup
One-command service initialization:
- **Dependency Installation**: Automatic npm install with timeout handling
- **Environment Setup**: Creates `.env` from template with validation
- **Database Setup**: Prisma client generation and migration support
- **Build Validation**: Ensures service compiles and starts correctly
- **Development Tools**: VS Code configuration and tool availability checks

## Architecture

The generator uses a modular architecture:

- **CLI Layer**: Command parsing and validation
- **Generator Layer**: Service generation logic with validation
- **Template Engine**: EJS template processing
- **File Writer**: File system operations
- **Service Validator**: Post-generation validation and health checks

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make changes and add tests
4. Submit a pull request

## License

MIT License - see LICENSE file for details.

## Adapter Implementation

### Required Adapters for v1.1.0+

If you're using authentication features, you'll need to implement adapters for the following internal packages:

#### 1. `@jobtopgun/auth` Package

This package provides JWT authentication functionality. You'll need to implement:

```typescript
// Create your own auth module with these components:

// jwt-auth.module.ts
@Module({
  imports: [JwtModule, PassportModule],
  providers: [JwtStrategy, JwtAuthGuard, JwtTokenService],
  exports: [JwtAuthGuard, JwtTokenService],
})
export class JwtAuthModule {}

// jwt-auth.guard.ts
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  // Implement your JWT validation logic
}

// jwt-token.service.ts
@Injectable()
export class JwtTokenService {
  // Implement token generation and validation
}

// types.ts
export interface AuthenticatedRequest extends Request {
  user: {
    sub: string;
    email?: string;
    // Add your user properties
  };
}
```

#### 2. `@jobtopgun/common` Package

This package provides common utilities and middleware. Key components to implement:

```typescript
// service-context.middleware.ts
export class ServiceContextMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    // Add correlation ID and request tracking
    req['correlationId'] = req.headers['x-correlation-id'] || generateId();
    next();
  }
}
```

### Implementation Options

You have several options for handling these dependencies:

1. **Create Local Modules**: Implement the required functionality directly in your project
2. **Build Your Own Package**: Create your own npm packages with equivalent functionality
3. **Use Alternative Libraries**: Replace with community packages like:
   - `@nestjs/passport` and `passport-jwt` for authentication
   - Custom middleware for service context
4. **Remove Dependencies**: If you don't need authentication, remove these imports from the generated code

### Quick Start Without Authentication

If you want to use Foundry without authentication features:

```bash
# Generate service without authentication
foundry generate my-service --no-authentication --non-interactive
```

This will generate templates without any `@jobtopgun/*` dependencies.

### Community Adapters

We encourage the community to share their adapter implementations. If you've created adapters for these packages, please consider:
- Sharing them as open-source packages
- Contributing examples to our documentation
- Creating a pull request with adapter templates

## Troubleshooting

### Common Issues and Solutions

#### Service Generation Fails
```bash
# Check if templates directory exists
ls -la templates/

# Ensure you're in the project root
pwd  # Should show /path/to/foundry

# Try with verbose output
node dist/index.js generate test-service --output ./test-output --verbose
```

#### Setup Script Fails
```bash
# Run setup with verbose output
npm run setup:verbose

# Check individual steps
npm install  # Install dependencies
npm run build  # Test build
npx tsc --noEmit  # Type check
```

#### Dependency Installation Issues (npm install failures)
```bash
# Common issue in monorepo environments with NestJS 11
# Try installing with legacy peer dependency resolution
npm install --legacy-peer-deps

# Alternative: force installation
npm install --force

# Clear cache and try again
npm cache clean --force
rm -rf node_modules package-lock.json
npm install --legacy-peer-deps

# For specific peer dependency conflicts, use npm overrides in package.json:
# "overrides": {
#   "@nestjs/mapped-types": "^2.1.0",
#   "@nestjs/swagger": "^11.2.0"
# }
```

#### Health Endpoints Don't Work
```bash
# Check service is running
curl http://localhost:3000/service-name/health

# Check correct service name and port
grep -r "serviceNameKebab" src/
grep -r "port" .env
```

#### Database Connection Issues
```bash
# Check DATABASE_URL in .env
cat .env | grep DATABASE_URL

# Test database connection
npm run prisma:studio  # Should open Prisma Studio

# For local development, start database
npm run docker:db
```

#### AWS Integration Problems
```bash
# Check AWS credentials
aws sts get-caller-identity

# Test AWS connectivity
npm run aws:check

# Check AWS region configuration
echo $AWS_REGION
```

#### TypeScript Compilation Errors
```bash
# Check TypeScript configuration
npx tsc --noEmit --listFiles

# Clear cache and reinstall
rm -rf node_modules package-lock.json
npm install
```

#### Integration Tests Fail
```bash
# Enable integration tests
RUN_INTEGRATION_TESTS=true npm test

# Test specific integration
npm test -- --testNamePattern="should generate a service that starts successfully"

# Check timeout issues
npm test -- --testTimeout=300000
```

### Debug Mode

Enable debug output for troubleshooting:
```bash
# Set debug environment variable
export DEBUG=foundry:*

# Run with debug output
node dist/index.js generate debug-service --output ./test-output
```

### Performance Issues

If generation is slow:
```bash
# Check system resources
top  # Monitor CPU and memory usage

# Skip heavy operations during testing
npm run setup --skip-deps --skip-build

# Use local cache
npm ci --cache ~/.npm
```

### File Permission Issues

On Unix systems:
```bash
# Fix script permissions
chmod +x scripts/test-generation.sh
chmod +x scripts/setup.ts

# Fix directory permissions
chmod -R 755 templates/
```

## Support & Contact

### 📬 General Support
For issues and questions:
- Create an issue on [GitHub](https://github.com/Super-Resume/foundry/issues) with detailed error messages
- Check existing documentation and troubleshooting guide
- Review generated service examples in the `test-output` directory
- Use `npm run setup:verbose` for detailed setup information

### 🔒 Security Issues
For security vulnerabilities:
- **DO NOT** create public issues for security vulnerabilities
- Email us directly at: varis@topgunthailand.com
- We aim to respond within 48 hours
- We appreciate responsible disclosure and will credit reporters (if desired)
- See our [Security Policy](SECURITY.md) for more details

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

---

**Happy coding! 🚀**