UNPKG

ruch

Version:

Revolutionary React TypeScript CLI with hexagonal architecture & AI-powered development assistance. Create maintainable, scalable applications with domain-driven design and integrated AI tooling.

733 lines (536 loc) โ€ข 19.8 kB
# ๐Ÿ Ruch CLI > **Revolutionary React Development with Hexagonal Architecture & AI-Powered Assistance** [![npm version](https://badge.fury.io/js/ruch.svg)](https://badge.fury.io/js/ruch) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![TypeScript](https://img.shields.io/badge/TypeScript-4.9+-blue.svg)](https://www.typescriptlang.org/) [![Bun](https://img.shields.io/badge/Bun-1.0+-orange.svg)](https://bun.sh/) **Ruch CLI** is a revolutionary command-line tool that transforms React TypeScript development by implementing clean hexagonal architecture principles while providing unprecedented AI-powered assistance for consistent, maintainable code generation. ## โœจ Key Features ### ๐Ÿ—๏ธ **Hexagonal Architecture Made Simple** - **Complete domain structure** generation with entities, ports, services, adapters, hooks, and UI - **Dependency inversion** patterns built-in - **Domain isolation** with clear boundaries - **Co-located testing** strategy ### ๐Ÿค– **AI-Powered Development (Flagship Feature)** - **Revolutionary guide-ai** command that teaches AI assistants your architecture - **Tool-specific configurations** for Cursor, GitHub Copilot, Windsurf, and Juni - **Consistent code generation** that respects hexagonal boundaries - **Architecture-aware suggestions** from AI tools ### ๐Ÿงช **Advanced Testing with MSW** - **Realistic API simulation** with Mock Service Worker - **Automatic handler generation** for all domains - **Domain-isolated testing** strategies - **Co-located test patterns** ### ๐Ÿ“Š **Project Visualization** - **Interactive dependency graphs** with circular dependency detection - **Architecture health insights** and metrics - **Real-time visualization** of domain relationships ## ๐Ÿš€ Quick Start ### Installation **Using npx (Recommended)** ```bash npx ruch create user ``` **Global Installation** ```bash # Using Bun (Recommended) bun install -g ruch # Using npm npm install -g ruch # Using yarn yarn global add ruch # Using pnpm pnpm install -g ruch ``` ### 5-Minute Setup ```bash # 1. Create your first domain npx ruch create user # 2. Generate service context with dependency injection npx ruch context generate # 3. Set up realistic testing with MSW npx ruch msw init npx ruch msw handlers npx ruch msw mocks # 4. Enable AI-powered development (FLAGSHIP) npx ruch guide-ai # 5. Visualize your architecture npx ruch visualize ``` **Result:** Complete React application with hexagonal architecture, comprehensive testing setup, and AI documentation ready for development. ## ๐Ÿ“š Core Concepts ### ๐Ÿ›๏ธ Hexagonal Architecture Layers Ruch CLI implements a simplified hexagonal architecture specifically designed for React applications: ```mermaid graph TD A[UI Components] --> B[Hooks] B --> C[Services] C --> D[Ports] D --> E[Adapters] E --> F[External APIs] G[Entities] --> C H[Tests] --> C H --> E ``` | Layer | Description | Location | Responsibilities | | --------------- | ----------------- | ----------- | -------------------------------------------------- | | **๐Ÿ›๏ธ Entities** | Business models | `entities/` | Data structures, domain types, validation rules | | **โš™๏ธ Services** | Business logic | `services/` | Pure business logic, domain operations, validation | | **๐Ÿ”Œ Ports** | Abstractions | `ports/` | Interfaces for external dependencies | | **๐Ÿ”ง Adapters** | Implementations | `adapters/` | API calls, external service implementations | | **โš›๏ธ Hooks** | React integration | `hooks/` | React Query hooks, state management | | **๐ŸŽจ UI** | Presentation | `ui/` | React components, user interactions | ### ๐ŸŽฏ Architecture Principles 1. **Business Logic Isolation** - ALL business logic MUST be in domain services 2. **No Direct Service Imports** - Components ALWAYS use domain hooks 3. **Cross-Domain Communication** - Only via ports/adapters patterns 4. **Co-Located Tests** - Tests alongside implementation files 5. **Dependency Inversion** - High-level modules don't depend on low-level modules ## ๐Ÿ› ๏ธ CLI Commands Reference ### ๐Ÿ—๏ธ Domain Management #### `create <domain>` - Create New Domain ```bash # Create complete domain with hexagonal structure npx ruch create user # Create domain without UI components npx ruch create analytics --without-ui # Create API-only domain npx ruch create notification --without-ui --without-store ``` #### `list` - List All Domains ```bash npx ruch list # or npx ruch ls ``` #### `delete <domain>` - Delete Domain ```bash # Safe delete with confirmation npx ruch delete user # Force delete without confirmation npx ruch delete user --force ``` ### โš™๏ธ Service Context Management #### `context generate` - Generate Service Context ```bash # Generate complete service context with dependency injection npx ruch context generate ``` Creates `src/context/ServiceContext.tsx` with: - Service instantiation for all domains - React Context Provider - `useServices` hook - TypeScript interfaces - Complete test coverage #### `context update` - Update Context ```bash # Add missing domains to existing context npx ruch context update ``` ### ๐Ÿงช Mock Service Worker (MSW) #### `msw init` - Initialize MSW ```bash npx ruch msw init ``` Creates: - `src/mocks/browser.ts` - Browser MSW setup - `src/mocks/server.ts` - Node.js MSW setup - `src/setupTests.ts` - Test configuration - `public/mockServiceWorker.js` - Service worker #### `msw handlers` - Generate Handlers ```bash # Generate MSW handlers for all domains npx ruch msw handlers ``` #### `msw mocks` - Generate Mock Data ```bash # Generate realistic mock data templates npx ruch msw mocks ``` #### `msw update` - Update MSW Configuration ```bash # Update MSW for new domains npx ruch msw update # Update specific domain npx ruch msw update user ``` ### ๐Ÿค– AI-Powered Development #### `guide-ai` - Generate AI Documentation โญ **FLAGSHIP FEATURE** Transform your development workflow by teaching AI assistants to understand and respect your hexagonal architecture. ```bash # Generate complete AI documentation npx ruch guide-ai # Configure specific AI tools npx ruch guide-ai --tools cursor,copilot,windsurf,juni # Configure single tool npx ruch guide-ai --tools cursor ``` **What guide-ai Creates:** | File | Purpose | AI Tool | | ------------------- | ----------------------------- | --------- | | `ruch-guide.json` | Complete project mapping | All tools | | `GUIDE.md` | Human-readable documentation | All tools | | `.cursorrules` | Cursor-specific configuration | Cursor | | `.windsurfrules` | Windsurf configuration | Windsurf | | `.juni/config.json` | Juni integration | Juni | **Before guide-ai:** ```typescript // AI generates this (WRONG) import { UserService } from '../domains/user/services'; function MyComponent() { const userService = new UserService(); // โŒ Direct instantiation const users = userService.getUsers(); // โŒ Blocking call return <div>{users.map(...)}</div>; } ``` **After guide-ai:** ```typescript // AI generates this (CORRECT) import { useUsers } from '../domains/user/hooks'; function MyComponent() { const { data: users, isLoading, error } = useUsers(); // โœ… Proper hook usage if (isLoading) return <LoadingSpinner />; if (error) return <ErrorMessage error={error} />; return <div>{users?.map(...)}</div>; } ``` ### ๐Ÿ“Š Visualization & Analysis #### `visualize` - Interactive Dependency Visualization ```bash # Launch interactive visualization app npx ruch visualize # Custom port npx ruch visualize --port 4000 # Export to JSON npx ruch visualize --format json --output architecture.json # Console output npx ruch visualize --format console # Don't auto-open browser npx ruch visualize --no-open ``` #### `http-client` - Generate HTTP Client ```bash # Generate configured HTTP client with interceptors npx ruch http-client ``` ## ๐Ÿ—๏ธ Generated Project Structure When you create a domain, Ruch generates a complete hexagonal structure: ``` src/domains/user/ โ”œโ”€โ”€ entities/ โ”‚ โ”œโ”€โ”€ User.ts # Business models and types โ”‚ โ”œโ”€โ”€ UserProfile.ts # Related entities โ”‚ โ”œโ”€โ”€ index.ts # Barrel exports โ”‚ โ””โ”€โ”€ User.test.ts # Entity tests โ”œโ”€โ”€ ports/ โ”‚ โ”œโ”€โ”€ UserRepository.ts # Abstraction interfaces โ”‚ โ”œโ”€โ”€ index.ts # Port exports โ”‚ โ””โ”€โ”€ UserRepository.test.ts โ”œโ”€โ”€ services/ โ”‚ โ”œโ”€โ”€ UserService.ts # Pure business logic โ”‚ โ”œโ”€โ”€ index.ts # Service exports โ”‚ โ””โ”€โ”€ UserService.test.ts # Service tests (with mocked ports) โ”œโ”€โ”€ adapters/ โ”‚ โ”œโ”€โ”€ UserApiAdapter.ts # API implementation โ”‚ โ”œโ”€โ”€ index.ts # Adapter exports โ”‚ โ””โ”€โ”€ UserApiAdapter.test.ts # Adapter tests (with MSW) โ”œโ”€โ”€ hooks/ โ”‚ โ”œโ”€โ”€ useUsers.ts # React Query hooks โ”‚ โ”œโ”€โ”€ useCreateUser.ts # Mutation hooks โ”‚ โ”œโ”€โ”€ index.ts # Hook exports โ”‚ โ””โ”€โ”€ useUsers.test.ts # Hook tests (with MSW) โ”œโ”€โ”€ ui/ โ”‚ โ”œโ”€โ”€ UserList.tsx # Domain components โ”‚ โ”œโ”€โ”€ UserCard.tsx # Related components โ”‚ โ”œโ”€โ”€ index.ts # UI exports โ”‚ โ””โ”€โ”€ UserList.test.tsx # Component tests (integration) โ””โ”€โ”€ index.ts # Domain entry point ``` ## ๐ŸŽฏ Usage Workflows ### ๐Ÿš€ New Project Setup ```bash # 1. Create core domains npx ruch create user npx ruch create product npx ruch create order # 2. Generate service context with dependency injection npx ruch context generate # 3. Set up comprehensive testing npx ruch msw init npx ruch msw handlers npx ruch msw mocks # 4. Enable AI-powered development (FLAGSHIP) npx ruch guide-ai # 5. Visualize architecture npx ruch visualize ``` ### ๐Ÿ”„ Incremental Development ```bash # Add new domain npx ruch create payment # Update existing configurations npx ruch context update npx ruch msw update # Refresh AI documentation npx ruch guide-ai # Verify architecture npx ruch visualize ``` ### ๐Ÿข Enterprise Development Workflow ```bash # Create multiple business domains npx ruch create user npx ruch create product npx ruch create inventory npx ruch create order npx ruch create payment npx ruch create notification # Generate complete infrastructure npx ruch context generate npx ruch msw init npx ruch msw handlers npx ruch msw mocks npx ruch http-client # Enable AI assistance for team development npx ruch guide-ai --tools cursor,copilot,windsurf,juni # Monitor architecture health npx ruch visualize --format console ``` ## ๐Ÿงช Testing Strategy Ruch CLI implements a comprehensive testing strategy across all architectural layers: ### ๐Ÿ›๏ธ Entity Testing (Pure) ```typescript describe('User Entity', () => { it('should create valid user', () => { const user = User.create({ email: 'john@example.com', name: 'John Doe', }); expect(user.id).toBeDefined(); expect(user.email).toBe('john@example.com'); }); }); ``` ### โš™๏ธ Service Testing (With Mock Ports) ```typescript describe('UserService', () => { it('should create user with valid data', async () => { const mockRepository = createMockUserRepository(); const userService = new UserService(mockRepository); const result = await userService.createUser(userData); expect(result.email).toBe(userData.email); expect(mockRepository.save).toHaveBeenCalled(); }); }); ``` ### ๐Ÿ”ง Adapter Testing (With MSW) ```typescript describe('UserApiAdapter', () => { it('should save user via API', async () => { server.use( http.post('/api/users', () => { return HttpResponse.json(mockUser); }) ); const result = await adapter.save(userData); expect(result.id).toBe('generated-id'); }); }); ``` ### โš›๏ธ Hook Testing (With MSW) ```typescript describe('useUsers', () => { it('should fetch users successfully', async () => { const { result } = renderHook(() => useUsers(), { wrapper: createTestWrapper(), }); await waitFor(() => { expect(result.current.isSuccess).toBe(true); }); }); }); ``` ### ๐ŸŽจ Component Testing (Integration) ```typescript describe('UserList', () => { it('should display list of users', async () => { render(<UserList />, { wrapper: createTestWrapper() }); await waitFor(() => { expect(screen.getByText('Users')).toBeInTheDocument(); }); }); }); ``` ## ๐Ÿ› ๏ธ Development ### System Requirements - **Node.js**: 18.0 or higher - **Package Manager**: Bun (recommended), npm, yarn, or pnpm - **Operating System**: Windows, macOS, or Linux - **TypeScript**: 4.9 or higher ### Local Development Setup ```bash # Clone the repository git clone https://github.com/yourusername/ruch.git cd ruch # Install dependencies with Bun (recommended) bun install # Build the project bun run build # Make executable for local testing chmod +x dist/index.js # Test local installation ./dist/index.js --version ``` ### Available Scripts ```bash # Build the project bun run build # Run comprehensive test suite bun test # Run tests in watch mode bun test --watch # Lint code with ESLint bun run lint # Format code with Prettier bun run format # Type checking bun run type-check # Run all quality checks bun run quality ``` ### Project Structure ``` ruch/ โ”œโ”€โ”€ src/ โ”‚ โ”œโ”€โ”€ commands/ # CLI command implementations โ”‚ โ”‚ โ”œโ”€โ”€ create.ts # Domain creation โ”‚ โ”‚ โ”œโ”€โ”€ context.ts # Service context management โ”‚ โ”‚ โ”œโ”€โ”€ msw.ts # MSW configuration โ”‚ โ”‚ โ”œโ”€โ”€ guide-ai.ts # AI documentation (flagship) โ”‚ โ”‚ โ””โ”€โ”€ visualize.ts # Architecture visualization โ”‚ โ”œโ”€โ”€ services/ # Internal CLI services โ”‚ โ”œโ”€โ”€ templates/ # Code generation templates โ”‚ โ”œโ”€โ”€ utils/ # Shared utilities โ”‚ โ””โ”€โ”€ index.ts # CLI entry point โ”œโ”€โ”€ tests/ # Comprehensive test suite โ”œโ”€โ”€ templates/ # Domain templates โ””โ”€โ”€ docs/ # Additional documentation ``` ## ๐ŸŽฏ Best Practices ### ๐Ÿ—๏ธ Domain Design - **Keep domains focused** and cohesive around business capabilities - **Avoid domain dependencies** - use events for cross-domain communication - **Define clear boundaries** - each domain should be independently deployable - **Use consistent naming** - follow established conventions across domains ### ๐Ÿ”ง Code Organization - **Co-locate tests** with implementation files - **Use barrel exports** (`index.ts`) for clean imports - **Follow naming conventions** - consistent across all domains - **Separate concerns** between architectural layers ### ๐Ÿงช Testing Philosophy - **Test each layer in isolation** with appropriate mocking strategies - **Use MSW for realistic API testing** instead of basic mocks - **Write integration tests** for complete user flows - **Mock external dependencies** at the adapter layer ### ๐Ÿค– AI Development Workflow - **Always regenerate guide-ai** after creating new domains - **Keep AI documentation current** with architectural changes - **Use consistent patterns** that AI can learn and replicate - **Leverage AI for boilerplate** generation while maintaining quality ## ๐ŸŒŸ Real-World Examples ### E-Commerce Application ```bash # Create complete e-commerce domain structure npx ruch create user # User authentication & management npx ruch create product # Product catalog & inventory npx ruch create cart # Shopping cart functionality npx ruch create order # Order processing & tracking npx ruch create payment # Payment processing npx ruch create notification # Email & SMS notifications # Generate infrastructure npx ruch context generate npx ruch msw init npx ruch msw handlers npx ruch msw mocks # Enable AI-powered development for team npx ruch guide-ai --tools cursor,copilot,windsurf,juni # Verify architecture integrity npx ruch visualize ``` ### SaaS Platform ```bash # Create multi-tenant SaaS domains npx ruch create tenant # Multi-tenancy management npx ruch create user # User & role management npx ruch create subscription # Billing & subscriptions npx ruch create analytics # Usage analytics npx ruch create support # Customer support npx ruch create integration # Third-party integrations # Full setup npx ruch context generate npx ruch msw init && npx ruch msw handlers && npx ruch msw mocks npx ruch guide-ai npx ruch visualize --format console ``` ## ๐Ÿ”ง Advanced Configuration ### Custom Templates (Coming Soon) ```bash # Use custom domain templates npx ruch create user --template enterprise # Generate with custom configurations npx ruch create product --config ./ruch.config.js ``` ### CI/CD Integration ```yaml # .github/workflows/architecture-check.yml name: Architecture Health Check on: [push, pull_request] jobs: architecture-check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v1 - run: bun install -g ruch - run: ruch visualize --format console - run: ruch guide-ai --tools cursor # Keep AI docs updated ``` ## ๐Ÿšจ Important Considerations ### MSW Customization Required **โš ๏ธ CRITICAL:** All generated MSW handlers and mock data are **templates** and **MUST** be customized for your specific API and business logic. **Recommended MSW Workflow:** 1. **Initialize**: `npx ruch msw init` 2. **Generate templates**: `npx ruch msw handlers && npx ruch msw mocks` 3. **๐Ÿ”ฅ CUSTOMIZE**: Adapt endpoints, authentication, validation, business data 4. **Test thoroughly**: Verify MSW setup with your application 5. **Maintain**: Use `npx ruch msw update` when domains change ### Architecture Rules (Enforced by guide-ai) 1. **Business Logic Isolation**: ALL business logic MUST be in domain services 2. **No Direct Service Imports**: Components ALWAYS use domain hooks 3. **Cross-Domain Communication**: Only via ports/adapters or events 4. **Co-Located Tests**: Tests MUST be alongside implementation files 5. **Dependency Direction**: Inner layers never depend on outer layers ## ๐Ÿค Contributing We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details. ### Development Workflow 1. **Fork & Clone**: Fork the repository and clone your fork 2. **Create Branch**: `git checkout -b feature/your-feature-name` 3. **Develop**: Make your changes with tests 4. **Test**: `bun test` - ensure all tests pass 5. **Quality Check**: `bun run quality` - linting, formatting, type checking 6. **Commit**: Use conventional commits 7. **Push & PR**: Push to your fork and create a pull request ### Reporting Issues - **Bug Reports**: Use the bug report template - **Feature Requests**: Use the feature request template - **Security Issues**: Email security@ruch.dev ## ๐Ÿ“„ License MIT License - see [LICENSE](LICENSE) for details. ## ๐Ÿ† Recognition Built with โค๏ธ for the React community by developers who believe in clean architecture and AI-assisted development. **Star โญ this repository if you find it helpful!** --- <div align="center"> ### ๐Ÿš€ Transform Your React Development Today [Get Started](#-quick-start) โ€ข [Documentation](https://docs.ruch.dev) โ€ข [Examples](https://github.com/ruch-cli/examples) โ€ข [Community](https://discord.gg/ruch) </div>