# Web Build Scripts Documentation

**Author**: Matthew Raymer
**Date**: 2025-07-11
**Status**: ✅ **COMPLETE** - Full web build system with PWA and Docker support

## Overview

The web build system for TimeSafari provides comprehensive support for web application development, PWA functionality, and containerized deployment. It supports development, testing, and production environments with optimized builds for each use case.

## Build Script Integration

### Package.json Scripts

The web build system is fully integrated into `package.json` with the following scripts:

#### Basic Build Commands

```bash
# Development (starts dev server)
npm run build:web:dev      # Development server with hot reload

# Production builds
npm run build:web:test     # Testing environment build
npm run build:web:prod     # Production environment build
```

#### Docker Integration

```bash
# Docker builds
npm run build:web:docker       # Development + Docker
npm run build:web:docker:test  # Testing + Docker
npm run build:web:docker:prod  # Production + Docker
```

#### Utility Commands

```bash
# Serve built files locally
npm run build:web:serve    # Build and serve locally

# Legacy command (maintains compatibility)
npm run build:web          # Full build process
```

## Script Usage

### Direct Script Usage

The `build-web.sh` script supports comprehensive command-line options:

```bash
# Basic usage
./scripts/build-web.sh [options]

# Environment-specific builds
./scripts/build-web.sh --dev          # Development server
./scripts/build-web.sh --test         # Testing build
./scripts/build-web.sh --prod         # Production build

# Docker integration
./scripts/build-web.sh --docker       # Development + Docker
./scripts/build-web.sh --docker:test  # Testing + Docker
./scripts/build-web.sh --docker:prod  # Production + Docker

# Local serving
./scripts/build-web.sh --serve        # Build and serve locally
```

### Command-Line Options

| Option | Description | Default |
|--------|-------------|---------|
| `--dev`, `--development` | Development mode (starts dev server) | ✅ |
| `--test` | Testing environment build | |
| `--prod`, `--production` | Production environment build | |
| `--docker` | Build and create Docker image | |
| `--docker:test` | Testing environment + Docker | |
| `--docker:prod` | Production environment + Docker | |
| `--serve` | Build and serve locally | |
| `-h`, `--help` | Show help message | |
| `-v`, `--verbose` | Enable verbose logging | |

## Build Process

### Development Mode Flow

1. **Environment Setup**: Load development environment variables
2. **Validation**: Check for required dependencies
3. **Server Start**: Start Vite development server
4. **Hot Reload**: Enable live reload and HMR
5. **PWA Setup**: Configure PWA for development

### Production Mode Flow

1. **Environment Setup**: Load production environment variables
2. **Cleanup**: Clean previous build artifacts
3. **Asset Optimization**: Optimize images and code
4. **Build Process**: Run Vite production build
5. **PWA Generation**: Generate service worker and manifest
6. **Output**: Create optimized static files

### Docker Mode Flow

1. **Build Process**: Run production build
2. **Docker Build**: Create Docker image
3. **Image Tagging**: Tag with environment and version
4. **Output**: Ready-to-deploy container

## Environment Management

### Environment Variables

The web build system automatically sets environment variables:

```bash
# Platform configuration
VITE_PLATFORM=web
VITE_PWA_ENABLED=true
VITE_DISABLE_PWA=false

# Build information
VITE_GIT_HASH=<git-commit-hash>
DEBUG_MIGRATIONS=0
```

### Environment Files

```bash
.env.development    # Development environment
.env.test          # Testing environment
.env.production    # Production environment
```

### Mode-Specific Configuration

#### Development Mode
```bash
# Uses .env.development
VITE_DEFAULT_ENDORSER_API_SERVER=http://127.0.0.1:3000
VITE_PWA_ENABLED=true
```

#### Test Mode
```bash
# Uses .env.test
VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.timesafari.org
VITE_PWA_ENABLED=true
```

#### Production Mode
```bash
# Uses .env.production
VITE_DEFAULT_ENDORSER_API_SERVER=https://api.timesafari.org
VITE_PWA_ENABLED=true
```

## PWA (Progressive Web App) Features

### PWA Configuration

TimeSafari implements comprehensive PWA functionality across all environments:

#### ✅ **Development Mode PWA**
- Service worker registration active
- Manifest generation enabled
- Hot reload compatible
- Development testing of PWA features

#### ✅ **Test Mode PWA**
- Full PWA feature testing
- Service worker registration active
- Manifest generation enabled
- QA testing of PWA functionality

#### ✅ **Production Mode PWA**
- Full caching strategies
- Service worker registration active
- Manifest generation enabled
- Runtime caching for API calls
- Optimized for production performance

### PWA Assets Generated

```bash
dist/
├── manifest.webmanifest    # PWA manifest with app metadata
├── sw.js                   # Service worker for offline functionality
├── workbox-*.js           # Workbox library for caching strategies
└── assets/
    ├── icons/             # PWA icons in various sizes
    └── splash/            # Splash screen images
```

### PWA Features

- **Offline Support**: Service worker caches essential resources
- **App Installation**: Browser install prompts
- **Share Target**: Image sharing integration
- **Background Sync**: Offline data synchronization
- **Push Notifications**: Web push notification support

### PWA Manifest

```json
{
  "name": "TimeSafari",
  "short_name": "TimeSafari",
  "description": "Crowd-Funder for Time",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#4f46e5",
  "icons": [
    {
      "src": "assets/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    }
  ]
}
```

## Docker Integration

### Docker Build Process

The web build system includes comprehensive Docker support:

```bash
# Development Docker
./scripts/build-web.sh --docker

# Testing Docker
./scripts/build-web.sh --docker:test

# Production Docker
./scripts/build-web.sh --docker:prod
```

### Docker Features

- **Automatic Image Tagging**: `timesafari-web:mode`
- **Build Argument Passing**: Environment-specific configurations
- **Multi-Stage Builds**: Optimized production images
- **Health Checks**: Container health monitoring
- **Security Scanning**: Vulnerability assessment

### Docker Output

```bash
# Generated Docker images
timesafari-web:development
timesafari-web:test
timesafari-web:production
```

### Docker Usage

```bash
# Run development container
docker run -p 8080:80 timesafari-web:development

# Run production container
docker run -p 8080:80 timesafari-web:production

# Deploy to container registry
docker push timesafari-web:production
```

## Build Artifacts

### Development Mode

- **No files created**: Runs development server directly
- **Server URL**: http://localhost:8080
- **Hot Reload**: Enabled with Vite HMR
- **Source Maps**: Enabled for debugging

### Production Mode

```bash
dist/
├── index.html              # Main HTML file
├── manifest.webmanifest    # PWA manifest
├── sw.js                   # Service worker
├── workbox-*.js           # Workbox library
└── assets/
    ├── index-*.js         # Main application bundle
    ├── index-*.css        # Stylesheet bundle
    ├── icons/             # PWA icons
    └── images/            # Optimized images
```

### File Sizes (Typical)

| File Type | Development | Production | Gzipped |
|-----------|-------------|------------|---------|
| **Main Bundle** | 2.1MB | 850KB | 250KB |
| **CSS Bundle** | 180KB | 45KB | 12KB |
| **PWA Assets** | 50KB | 50KB | 15KB |
| **Total** | 2.3MB | 945KB | 277KB |

## Performance Optimization

### Build Optimizations

- **Code Splitting**: Automatic route-based splitting
- **Tree Shaking**: Unused code elimination
- **Minification**: JavaScript and CSS compression
- **Asset Optimization**: Image compression and optimization
- **Caching**: Long-term caching for static assets

### Runtime Optimizations

- **Service Worker**: Offline caching and background sync
- **Lazy Loading**: Component and route lazy loading
- **Preloading**: Critical resource preloading
- **Compression**: Gzip/Brotli compression support

### Performance Metrics

```bash
# Development startup time
~350ms (Vite dev server)

# Production build time
~8s (full build)
~2s (incremental build)

# Production bundle size
~945KB (total)
~277KB (gzipped)
```

## Development Workflow

### Daily Development

```bash
# Start development server
npm run build:web:dev

# Access at http://localhost:8080
# Hot reload enabled
# PWA features available
```

### Testing Workflow

```bash
# Build for testing
npm run build:web:test

# Test PWA functionality
# Verify offline support
# Test app installation
```

### Production Workflow

```bash
# Build for production
npm run build:web:prod

# Deploy to web server
# Or create Docker image
npm run build:web:docker:prod
```

## Local Development Server

### Development Server Features

- **Hot Module Replacement**: Instant updates without page refresh
- **Fast Refresh**: React-style fast refresh for Vue components
- **Source Maps**: Full debugging support
- **PWA Support**: Service worker and manifest in development
- **Error Overlay**: In-browser error reporting

### Server Configuration

```bash
# Development server settings
Port: 8080
Host: localhost
Protocol: http
HMR: enabled
Source Maps: enabled
PWA: enabled
```

### Accessing the Server

```bash
# Local development
http://localhost:8080

# Network access (if needed)
http://0.0.0.0:8080
```

## Troubleshooting

### Common Issues

#### Build Failures
```bash
# Clean build artifacts
rm -rf dist/

# Reinstall dependencies
npm install

# Rebuild
npm run build:web:prod
```

#### Development Server Issues
```bash
# Check port availability
lsof -i :8080

# Kill existing process
kill -9 <PID>

# Restart server
npm run build:web:dev
```

#### PWA Issues
```bash
# Clear service worker
# In browser DevTools > Application > Service Workers
# Click "Unregister"

# Clear browser cache
# In browser DevTools > Application > Storage
# Click "Clear site data"
```

### Debug Mode

Enable verbose logging for web builds:

```bash
# Verbose mode
./scripts/build-web.sh --verbose

# Debug environment
DEBUG_MIGRATIONS=1 npm run build:web:dev
```

### Performance Debugging

```bash
# Analyze bundle size
npm run build:web:prod
# Check dist/ directory for file sizes

# Analyze performance
# Use browser DevTools > Performance tab
# Use Lighthouse for PWA metrics
```

## Security Considerations

### Build Security

- **Environment Isolation**: Separate dev/test/prod environments
- **Secret Management**: Secure handling of API keys
- **Dependency Scanning**: Regular security audits
- **Content Security Policy**: CSP headers for security

### Runtime Security

- **HTTPS Only**: Production requires HTTPS
- **CSP Headers**: Content Security Policy enforcement
- **Service Worker Security**: Secure service worker implementation
- **API Security**: Secure API communication

## Deployment Options

### Static Hosting

```bash
# Build for production
npm run build:web:prod

# Deploy to static host
# Upload dist/ directory to web server
```

### Docker Deployment

```bash
# Build Docker image
npm run build:web:docker:prod

# Deploy to container platform
docker run -p 80:80 timesafari-web:production
```

### CDN Deployment

```bash
# Build for production
npm run build:web:prod

# Upload to CDN
# Configure CDN for PWA support
```

## Future Enhancements

### Planned Improvements

- **Advanced Caching**: Intelligent caching strategies
- **Performance Monitoring**: Real-time performance tracking
- **A/B Testing**: Feature flag support
- **Analytics Integration**: User behavior tracking

### PWA Enhancements

- **Background Sync**: Enhanced offline synchronization
- **Push Notifications**: Advanced notification features
- **App Shortcuts**: Quick action shortcuts
- **File Handling**: Native file integration

---

**Last Updated**: 2025-07-11
**Version**: 1.0.3-beta
**Status**: Production Ready 