# FreshRoute Server

A comprehensive development server and CLI tool that provides API response mocking, Chrome extension management, and extended functionality for the FreshRoute Chrome extension.

## 🚀 Quick Start

### Installation
```bash
# Install globally for CLI access
npm install -g freshroute-server

# Or install locally
npm install freshroute-server
```

### Complete Setup
```bash
# One command setup: builds extension + starts server
freshroute setup

# Or step by step:
freshroute install-extension    # Install Chrome extension
freshroute start               # Start the server
```

## 🛠️ CLI Commands

The `freshroute-server` package provides a comprehensive CLI tool:

### Server Commands
```bash
freshroute start                    # Start the server
freshroute start --dev              # Start with auto-restart
freshroute start -p 4000 -w 4001   # Custom ports
freshroute dashboard               # Open server dashboard
```

### Extension Commands
```bash
freshroute install-extension       # Install Chrome extension
freshroute open-chrome             # Open Chrome with extension & CORS disabled
freshroute extension-info          # Show extension information
freshroute setup                   # Complete setup process
```

### Help
```bash
freshroute --help                  # Show all commands
freshroute start --help            # Show start command options
```

## 🎯 What's Included

When you install `freshroute-server`, you get:

1. **Mock API Server** - Local development server with WebSocket support
2. **Chrome Extension** - Built and ready-to-install FreshRoute extension
3. **CLI Tool** - Command-line interface for easy management
4. **Example Rules** - Pre-configured mock rules to get started

## 📦 Package Contents

```
freshroute-server/
├── server.js              # Main server application
├── bin/
│   └── freshroute-cli.js   # CLI tool
├── scripts/
│   ├── build-extension.js  # Extension build script
│   ├── install-extension.js # Extension installer
│   └── postinstall.js     # Post-install setup
├── extension/              # Built Chrome extension
├── responses/              # Mock response files
├── default-rules.json      # Example mock rules
└── README.md              # This file
```

## 🌐 Server Features

### HTTP Server (Port 3001)
- **Main Proxy**: `http://localhost:3001/proxy/*`
- **Health Check**: `http://localhost:3001/health`
- **API Rules**: `http://localhost:3001/api/rules`

### WebSocket Server (Port 3002)
- **Extension Communication**: `ws://localhost:3002`
- Real-time sync between extension and server

## 🎭 API Mocking

Create sophisticated mock rules with:

```json
{
  "id": "user-api-mock",
  "name": "Users API Mock",
  "enabled": true,
  "method": "GET",
  "urlPattern": "https://api.example.com/users/.*",
  "responseType": "json",
  "statusCode": 200,
  "delay": 500,
  "responseHeaders": {
    "Content-Type": "application/json",
    "X-Mock": "true"
  },
  "responseBody": {
    "users": [
      {"id": 1, "name": "John Doe"},
      {"id": 2, "name": "Jane Smith"}
    ]
  }
}
```

### Mock Features
- **URL Pattern Matching** - Regex or string matching
- **HTTP Method Filtering** - GET, POST, PUT, DELETE, or ANY
- **Response Types** - JSON, text, or file-based responses
- **Custom Headers** - Add any response headers
- **Simulated Delays** - Test slow network conditions
- **Status Codes** - Return any HTTP status code

## 🔧 Chrome Extension Integration

The package includes a complete Chrome extension build:

### Installation Process
1. Run `freshroute install-extension`
2. Open Chrome: `chrome://extensions/`
3. Enable "Developer mode"
4. Click "Load unpacked"
5. Select the extension folder (shown in CLI output)

### Extension Features
- **URL Rewriting** - Redirect requests to mock server
- **Header Modification** - Modify request/response headers
- **Real-time Sync** - Live updates with server
- **Rule Management** - Add/edit/delete mock rules via UI

## 🌐 Chrome Development Mode

The `freshroute open-chrome` command launches Chrome with special development settings:

### Development Features
- **CORS Disabled** - No cross-origin restrictions for API testing
- **Extension Auto-loaded** - FreshRoute extension automatically enabled
- **Separate Profile** - Uses isolated Chrome profile for development
- **Background Throttling Disabled** - Better performance for development
- **Security Restrictions Relaxed** - Allows testing with local/insecure content

### Command Options
```bash
freshroute open-chrome                    # Basic usage
freshroute open-chrome --profile mydev   # Custom profile name
freshroute open-chrome --url http://localhost:8080  # Custom start URL
freshroute open-chrome --port 4000       # Connect to server on different port
```

### Platform Support
- **macOS** - Uses `/Applications/Google Chrome.app/`
- **Windows** - Searches `Program Files` and `Program Files (x86)`
- **Linux** - Uses `google-chrome` command

### Chrome Profile Location
Development profiles are created in:
- **macOS/Linux**: `/tmp/chrome-freshroute-dev/`
- **Windows**: `%TEMP%\chrome-freshroute-dev\`

## 📊 Use Cases

### 1. API Development
Mock new APIs before they're built:
```bash
freshroute start
# Configure mock rules via extension UI
# Test frontend against mock responses
```

### 2. Error Testing
Simulate server errors:
```json
{
  "name": "Server Error Test",
  "method": "GET",
  "urlPattern": "https://api.example.com/users",
  "statusCode": 500,
  "delay": 2000
}
```

### 3. Performance Testing
Test slow network conditions:
```json
{
  "name": "Slow Network Test",
  "delay": 5000,
  "responseBody": {"message": "This was slow!"}
}
```

## 🚦 Development Workflow

### Typical Usage
```bash
# 1. Install the package
npm install -g freshroute-server

# 2. Set up everything
freshroute setup

# 3. Start development server
freshroute start --dev

# 4. Open Chrome with extension & CORS disabled
freshroute open-chrome

# 5. Configure mocks via Chrome extension
# 6. Test your application with mocked APIs
```

### Project Integration
```json
{
  "scripts": {
    "dev": "freshroute start --dev",
    "dev:chrome": "freshroute open-chrome",
    "mock:setup": "freshroute setup",
    "mock:install": "freshroute install-extension"
  }
}
```

## 🔗 Extension-Server Communication

The extension and server communicate via WebSocket for:

- **Real-time Rule Updates** - Changes sync immediately
- **Connection Status** - Monitor server connectivity
- **Rule Validation** - Server validates rule syntax
- **Request Logging** - View intercepted requests

## 📁 File Locations

After installation:
- **Extension**: `~/.freshroute/extension/`
- **Install Info**: `~/.freshroute/install-info.json`
- **Server Config**: Where you run the commands

## 🛡️ Security Notes

- **Local Development Only** - Not for production use
- **CORS Enabled** - Allows all origins for development
- **No Authentication** - Don't expose to public networks
- **Developer Mode** - Chrome extension runs in developer mode

## 🐛 Troubleshooting

### Server Issues
- **Port conflicts**: Use `-p` and `-w` flags for custom ports
- **Permission errors**: Run with appropriate permissions
- **Module errors**: Ensure Node.js >= 18.0.0

### Extension Issues
- **Not loading**: Check Chrome developer mode is enabled
- **No connection**: Verify server is running on correct ports
- **Rules not working**: Check URL pattern matching in server logs

### Common Solutions
```bash
# Check if ports are available
lsof -i :3001
lsof -i :3002

# Reinstall extension
freshroute install-extension

# Check extension info
freshroute extension-info

# View server status
freshroute dashboard
```

## 📝 Publishing

This package is designed for npm publishing with:

- **Pre-publish builds** - Extension built automatically
- **CLI distribution** - Global command availability
- **File filtering** - Only necessary files included
- **Version management** - Semantic versioning support

### Build Process
```bash
npm run build:extension    # Build Chrome extension manually
npm run validate           # Validate package before publish
npm run publish:dry        # Test what will be published
npm run publish:patch      # Version bump (patch) and publish
npm run publish:minor      # Version bump (minor) and publish
npm run publish:major      # Version bump (major) and publish
```

### Publishing Workflow
```bash
# Option 1: Manual version management
npm version patch          # or minor/major
npm publish               # Automatic validation + extension build

# Option 2: One-command publishing
npm run publish:patch     # Version bump + publish
npm run publish:minor     # Version bump + publish
npm run publish:major     # Version bump + publish

# Option 3: Test before publishing
npm run publish:dry       # See what will be included
```

## 🤝 Contributing

This package is part of the FreshRoute project ecosystem:
- **Server**: API mocking and development server
- **Extension**: Chrome extension for URL rewriting
- **CLI**: Command-line tools for easy management

## 📜 License

MIT License - See main FreshRoute project for details. 