# Initra CLI

A comprehensive NPX tool for project setup and management.

## Key Features

- **Project Initialization**: Create new projects with various frameworks and configurations
- **Automatic Dependency Installation**: Installs all dependencies using npm or yarn automatically
- **Feature Management**: Add, remove, or update features in your project
- **Code Generation**: Generate components, models, tests, utilities, and configs
- **Project Analysis**: Analyze your project for security, performance, and code quality
- **Deployment**: Deploy your project to various platforms
- **Updates**: Keep your project dependencies and features up to date

## Quick Start

```bash
npx initra init
```

Or install globally:

```bash
npm install -g initra-cli
initra init
```

## How It Works

### For New Projects

1. Run `initra init`
2. Follow the interactive setup wizard
3. Choose your project structure, framework, and features
4. The CLI will create your project with all selected features
5. Dependencies are automatically installed using npm or yarn
6. Get a detailed installation summary with dependency counts

### For Existing Projects

1. Run `initra features` to add or remove features
2. Use `initra generate` to create new code
3. Run `initra analyze` to check your project quality

## Main Commands

- `initra init`: Initialize a new project
- `initra features`: Manage project features
- `initra status`: Check project status
- `initra generate`: Generate code
- `initra deploy`: Deploy your project
- `initra analyze`: Analyze your project
- `initra update`: Update your project

## Code Generation

Generate various code elements:

```bash
# Generate a component
initra generate component MyComponent

# Generate a model
initra generate model User

# Generate a test
initra generate test MyComponent

# Generate a utility
initra generate util StringHelper

# Generate a config
initra generate config Database
```

### Available Generation Types

- **component/c**: Components with TypeScript support
- **model/m**: Data models with validation and serialization
- **test/t**: Jest test files with proper structure
- **util/u**: Utility functions with common patterns
- **config**: Configuration files with environment support

## Environment Configuration

The CLI automatically creates a `.env` file with all necessary environment variables:

- **Common Variables**: `NODE_ENV`, `PORT`
- **Database Variables**: Based on your selected database (MongoDB, PostgreSQL, MySQL)
- **Authentication Variables**: Based on your selected authentication method
- **Setup Instructions**: Clear instructions for OAuth provider configuration

### Generated Environment Variables

#### JWT Authentication
```bash
JWT_SECRET=your-secret-key
```

#### OAuth Authentication
```bash
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret
FACEBOOK_APP_ID=your_facebook_app_id
FACEBOOK_APP_SECRET=your_facebook_app_secret
SESSION_SECRET=your-session-secret
```

#### Session Authentication
```bash
SESSION_SECRET=your-session-secret
```

#### Database Variables
- **MongoDB**: `MONGODB_URI`
- **PostgreSQL**: `PGUSER`, `PGPASSWORD`, `PGDATABASE`, `PGHOST`, `PGPORT`
- **MySQL**: `DB_NAME`, `DB_USER`, `DB_PASSWORD`, `DB_HOST`, `DB_PORT`

## Dependency Installation

The CLI automatically handles dependency installation:

- **Package Manager Detection**: Automatically detects and uses npm or yarn
- **Real Installation**: Actually installs dependencies, not just simulation
- **Progress Tracking**: Shows real-time installation progress
- **Error Handling**: Provides helpful error messages and fallback instructions
- **Installation Summary**: Shows dependency counts and installation time
- **Smart Detection**: Skips installation if node_modules already exists

## OAuth Authentication Setup

When you select OAuth authentication, the CLI automatically:

- **Installs Dependencies**: Passport.js and OAuth provider strategies
- **Generates OAuth Configuration**: Complete OAuth setup with multiple providers
- **Creates Routes**: Authentication routes for Google, GitHub, and Facebook
- **Provides Middleware**: Authentication and logout middleware
- **TypeScript Support**: Full TypeScript support with proper type definitions

### Supported OAuth Providers

- **Google OAuth**: Uses Google+ API for authentication
- **GitHub OAuth**: Uses GitHub API for authentication  
- **Facebook OAuth**: Uses Facebook Graph API for authentication

### Environment Variables Required

```bash
# Google OAuth
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret

# GitHub OAuth
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret

# Facebook OAuth
FACEBOOK_APP_ID=your_facebook_app_id
FACEBOOK_APP_SECRET=your_facebook_app_secret
```

### Generated Routes

- `GET /auth/google` - Initiate Google OAuth
- `GET /auth/google/callback` - Google OAuth callback
- `GET /auth/github` - Initiate GitHub OAuth
- `GET /auth/github/callback` - GitHub OAuth callback
- `GET /auth/facebook` - Initiate Facebook OAuth
- `GET /auth/facebook/callback` - Facebook OAuth callback
- `GET /auth/logout` - Logout user

## TypeScript Support

When you select TypeScript, the CLI automatically:

- **Generates** `tsconfig.json` with optimal settings
- **Installs** core TypeScript dependencies (`typescript`, `ts-node`, `@types/node`)
- **Adds** framework-specific type definitions:
  - Express: `@types/express`, `@types/cors`, `@types/morgan`
  - Koa: `@types/koa`, `@types/koa__cors`
  - Hapi: `@types/hapi__hapi`
- **Includes** feature-specific types:
  - Testing: `@types/jest`, `ts-jest`
  - ESLint: `@typescript-eslint/eslint-plugin`, `@typescript-eslint/parser`
  - Database: `@types/mongoose`, `@types/pg`, `@types/sequelize`
  - Authentication: `@types/jsonwebtoken`, `@types/bcryptjs`
  - Logging: `@types/winston`
  - Security: `@types/helmet`, `@types/dotenv`
- **Configures** build scripts (`build`, `build:watch`)
- **Sets up** proper Jest configuration for TypeScript
- **Configures** ESLint for TypeScript linting

## Project Analysis

Analyze your project for various aspects:

```bash
# Run all analyses
initra analyze

# Run specific analyses
initra analyze --security --performance

# Run code quality analysis only
initra analyze --quality
```

### Analysis Types

- **Security**: npm audit, dependency vulnerabilities, security best practices
- **Performance**: Bundle analysis, optimization recommendations
- **Code Quality**: ESLint integration, test coverage, code standards
- **Dependencies**: Outdated packages, unused dependencies
- **Accessibility**: WCAG compliance, accessibility best practices
- **Best Practices**: Documentation, project structure, configuration

## Project Setup Wizard

The setup wizard guides you through:

1. Project name and description
2. Language (JavaScript/TypeScript)
3. Framework selection
4. Project structure
5. Database integration
6. Authentication
7. Testing framework
8. Code quality tools
9. DevOps and deployment options

## Project Structures

- **Basic**: Simple structure for small projects
- **MVC**: Model-View-Controller architecture
- **Microservices**: Distributed architecture
- **Library**: Structure for creating libraries
- **Full-Stack**: Combined frontend and backend

## Available Features

### Authentication
- **JWT Authentication**: JSON Web Token-based authentication with secure token generation and verification
- **OAuth Integration**: Complete OAuth 2.0 implementation with support for:
  - Google OAuth (Google+ API)
  - GitHub OAuth (GitHub API)
  - Facebook OAuth (Facebook Graph API)
  - Passport.js strategies for easy provider addition
- **Session-based Authentication**: Traditional session-based authentication with secure session management
- **Role-based Access Control**: Built-in middleware for role-based authorization

### Database Integration
- MongoDB
- PostgreSQL
- MySQL

### Testing
- Jest
- Mocha
- Cypress

### Code Quality
- ESLint
- Prettier
- TypeScript

### DevOps
- Docker
- CI/CD (GitHub Actions, GitLab CI)
- Automated documentation

### Deployment
- Vercel
- Netlify
- Heroku
- AWS
- Docker

### Monitoring
- Error tracking
- Performance monitoring
- Usage analytics

## Configuration

Initra CLI uses an `initra.json` file to store your project configuration:

```json
{
  "name": "my-project",
  "version": "1.0.0",
  "description": "My awesome project",
  "language": "typescript",
  "framework": "react",
  "structure": "basic",
  "features": {
    "authentication": "jwt",
    "database": "mongodb",
    "testing": "jest",
    "codeQuality": ["eslint", "prettier"],
    "devops": ["docker", "github-actions"],
    "deployment": "vercel"
  },
  "analysis": {
    "lastRun": "2024-01-01T00:00:00.000Z",
    "results": {
      "security": { "score": 85 },
      "performance": { "score": 80 },
      "codeQuality": { "score": 75 }
    }
  }
}
```

## Framework-Specific Features

### Express.js
- REST API generation
- Middleware setup (CORS, Helmet, Morgan)
- Database integration
- Authentication middleware

### Nest.js
- Decorator-based architecture
- Dependency injection
- Built-in validation
- Swagger documentation

### Fastify
- High-performance framework
- Plugin system
- Built-in validation
- TypeScript support

### Koa
- Lightweight middleware framework
- Async/await support
- Context-based middleware
- Modular architecture

### Hapi
- Enterprise-grade framework
- Built-in security features
- Plugin ecosystem
- Configuration-driven

### Vanilla Node.js
- Minimal setup
- Custom server implementation
- Full control over architecture

## Examples

### Generate an E-commerce Application

```bash
initra init --template e-commerce
```

### Generate a Blog

```bash
initra init --template blog
```

### Generate a REST API

```bash
initra init --template api
```

### Generate a Real-time Chat Application

```bash
initra init --template chat
```

## Environment Configuration

The CLI supports environment-specific configurations:

```bash
# Development
NODE_ENV=development initra analyze

# Production
NODE_ENV=production initra deploy
```

## Error Handling

The CLI includes comprehensive error handling:

- Graceful failure with helpful error messages
- Validation of user inputs
- Fallback options when tools are not available
- Detailed logging in verbose mode

## Testing

Test the CLI tool:

```bash
# Run the test suite
npm test

# Test CLI functionality
node test-cli.js
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## License

MIT License - see LICENSE file for details

## Support

- Documentation: [GitHub Wiki](https://github.com/initra-cli/initra-cli/wiki)
- Issues: [GitHub Issues](https://github.com/initra-cli/initra-cli/issues)
- Discussions: [GitHub Discussions](https://github.com/initra-cli/initra-cli/discussions)