# Electron Build Patterns

**Author**: Matthew Raymer
**Date**: 2025-01-27
**Status**: 🎯 **ACTIVE** - Current Implementation

## Overview

TimeSafari's Electron build system provides comprehensive packaging and
distribution capabilities across Windows, macOS, and Linux platforms. The
system supports multiple build modes, environment configurations, and
package formats for different deployment scenarios.

## Build Architecture

### Multi-Stage Build Process

```
1. Web Build (Vite) → 2. Capacitor Sync → 3. TypeScript Compile → 4. Package
```

**Stage 1: Web Build**
- Vite builds web assets with Electron-specific configuration
- Environment variables loaded based on build mode
- Assets optimized for desktop application

**Stage 2: Capacitor Sync**
- Copies web assets to Electron app directory
- Syncs Capacitor configuration and plugins
- Prepares native module bindings

**Stage 3: TypeScript Compile**
- Compiles Electron main process TypeScript
- Rebuilds native modules for target platform
- Generates production-ready JavaScript

**Stage 4: Package Creation**
- Creates platform-specific installers
- Generates distribution packages
- Signs applications (when configured)

## Build Modes

### Development Mode (--mode development)

**Purpose**: Local development and testing
**Configuration**: Development environment variables
**Output**: Unpacked application for testing

```bash
# Development build (runs app)
npm run build:electron:dev

# Development build with explicit mode
npm run build:electron -- --mode development
```

**Features**:
- Hot reload enabled
- Debug tools available
- Development logging
- Unoptimized assets

### Testing Mode (--mode test)

**Purpose**: Staging and testing environments
**Configuration**: Test environment variables
**Output**: Packaged application for testing

```bash
# Test build
npm run build:electron -- --mode test

# Test build with specific platform
npm run build:electron:windows -- --mode test
npm run build:electron:mac -- --mode test
npm run build:electron:linux -- --mode test
```

**Features**:
- Test API endpoints
- Staging configurations
- Optimized for testing
- Debug information available

### Production Mode (--mode production)

**Purpose**: Production deployment
**Configuration**: Production environment variables
**Output**: Optimized distribution packages

```bash
# Production build
npm run build:electron -- --mode production

# Production build with specific platform
npm run build:electron:windows -- --mode production
npm run build:electron:mac -- --mode production
npm run build:electron:linux -- --mode production
```

**Features**:
- Production optimizations
- Code minification
- Security hardening
- Performance optimizations

## Platform-Specific Builds

### Windows Builds

**Target Platforms**: Windows 10/11 (x64)
**Package Formats**: NSIS installer, portable executable

```bash
# Windows development build
npm run build:electron:windows -- --mode development

# Windows test build
npm run build:electron:windows -- --mode test

# Windows production build
npm run build:electron:windows -- --mode production
```

**Configuration**:
- NSIS installer with custom options
- Desktop and Start Menu shortcuts
- Elevation permissions for installation
- Custom installation directory support

### macOS Builds

**Target Platforms**: macOS 10.15+ (x64, arm64)
**Package Formats**: DMG installer, app bundle

```bash
# macOS development build
npm run build:electron:mac -- --mode development

# macOS test build
npm run build:electron:mac -- --mode test

# macOS production build
npm run build:electron:mac -- --mode production
```

**Configuration**:
- Universal binary (x64 + arm64)
- DMG installer with custom branding
- App Store compliance (when configured)
- Code signing support

### Linux Builds

**Target Platforms**: Ubuntu 18.04+, Debian 10+, Arch Linux
**Package Formats**: AppImage, DEB, RPM

```bash
# Linux development build
npm run build:electron:linux -- --mode development

# Linux test build
npm run build:electron:linux -- --mode test

# Linux production build
npm run build:electron:linux -- --mode production
```

**Configuration**:
- AppImage for universal distribution
- DEB package for Debian-based systems
- RPM package for Red Hat-based systems
- Desktop integration

## Package-Specific Builds

### AppImage Package

**Format**: Self-contained Linux executable
**Distribution**: Universal Linux distribution

```bash
# AppImage development build
npm run build:electron:appimage -- --mode development

# AppImage test build
npm run build:electron:appimage -- --mode test

# AppImage production build
npm run build:electron:appimage -- --mode production
```

**Features**:
- Single file distribution
- No installation required
- Portable across Linux distributions
- Automatic updates support

### DEB Package

**Format**: Debian package installer
**Distribution**: Debian-based Linux systems

```bash
# DEB development build
npm run build:electron:deb -- --mode development

# DEB test build
npm run build:electron:deb -- --mode test

# DEB production build
npm run build:electron:deb -- --mode production
```

**Features**:
- Native package management
- Dependency resolution
- System integration
- Easy installation/uninstallation

### DMG Package

**Format**: macOS disk image
**Distribution**: macOS systems

```bash
# DMG development build
npm run build:electron:dmg -- --mode development

# DMG test build
npm run build:electron:dmg -- --mode test

# DMG production build
npm run build:electron:dmg -- --mode production
```

**Features**:
- Native macOS installer
- Custom branding and layout
- Drag-and-drop installation
- Code signing support

## Environment Configuration

### Environment Variables

**Development Environment**:
```bash
VITE_API_URL=http://localhost:3000
VITE_DEBUG=true
VITE_LOG_LEVEL=debug
VITE_ENABLE_DEV_TOOLS=true
```

**Testing Environment**:
```bash
VITE_API_URL=https://test-api.timesafari.com
VITE_DEBUG=false
VITE_LOG_LEVEL=info
VITE_ENABLE_DEV_TOOLS=false
```

**Production Environment**:
```bash
VITE_API_URL=https://api.timesafari.com
VITE_DEBUG=false
VITE_LOG_LEVEL=warn
VITE_ENABLE_DEV_TOOLS=false
```

### Build Configuration

**Vite Configuration** (`vite.config.electron.mts`):
```typescript
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  
  return {
    mode,
    build: {
      outDir: 'dist',
      emptyOutDir: true,
      sourcemap: mode === 'development',
      minify: mode === 'production'
    },
    define: {
      __DEV__: mode === 'development',
      __TEST__: mode === 'test',
      __PROD__: mode === 'production'
    }
  };
});
```

**Electron Builder Configuration** (`electron-builder.config.json`):
```json
{
  "appId": "app.timesafari.desktop",
  "productName": "TimeSafari",
  "directories": {
    "buildResources": "resources",
    "output": "dist"
  },
  "files": [
    "assets/**/*",
    "build/**/*",
    "capacitor.config.*",
    "app/**/*"
  ]
}
```

## Build Scripts Reference

### Main Build Scripts

```bash
# Development builds
npm run build:electron:dev              # Development build and run
npm run build:electron --dev            # Development build only

# Testing builds
npm run build:electron:test             # Test environment build

# Production builds
npm run build:electron:prod             # Production environment build
```

### Platform-Specific Scripts

```bash
# Windows builds
npm run build:electron:windows          # Windows production build
npm run build:electron:windows:dev      # Windows development build
npm run build:electron:windows:test     # Windows test build
npm run build:electron:windows:prod     # Windows production build

# macOS builds
npm run build:electron:mac              # macOS production build
npm run build:electron:mac:dev          # macOS development build
npm run build:electron:mac:test         # macOS test build
npm run build:electron:mac:prod         # macOS production build

# Linux builds
npm run build:electron:linux            # Linux production build
npm run build:electron:linux:dev        # Linux development build
npm run build:electron:linux:test       # Linux test build
npm run build:electron:linux:prod       # Linux production build
```

### Package-Specific Scripts

```bash
# AppImage builds
npm run build:electron:appimage         # Linux AppImage production build
npm run build:electron:appimage:dev     # AppImage development build
npm run build:electron:appimage:test    # AppImage test build
npm run build:electron:appimage:prod    # AppImage production build

# DEB builds
npm run build:electron:deb              # Debian package production build
npm run build:electron:deb:dev          # DEB development build
npm run build:electron:deb:test         # DEB test build
npm run build:electron:deb:prod         # DEB production build

# DMG builds
npm run build:electron:dmg              # macOS DMG production build
npm run build:electron:dmg:dev          # DMG development build
npm run build:electron:dmg:test         # DMG test build
npm run build:electron:dmg:prod         # DMG production build
```

### Direct Script Usage

All npm scripts use the underlying `./scripts/build-electron.sh` script:

```bash
# Direct script usage examples
./scripts/build-electron.sh --dev                    # Development build
./scripts/build-electron.sh --test                   # Test build
./scripts/build-electron.sh --prod                   # Production build
./scripts/build-electron.sh --prod --windows         # Windows production
./scripts/build-electron.sh --test --appimage        # Linux AppImage test
./scripts/build-electron.sh --dev --mac              # macOS development
./scripts/build-electron.sh --prod --dmg             # macOS DMG production
```

### Utility Scripts

```bash
# Cleanup scripts
npm run clean:electron                  # Clean Electron build artifacts

# Development scripts
npm run electron:dev                    # Start development server
npm run electron:dev-full              # Full development workflow
```

## Build Output Structure

### Development Build

```
electron/
├── app/                    # Web assets
├── build/                  # Compiled TypeScript
├── dist/                   # Build artifacts (empty in dev)
└── node_modules/           # Dependencies
```

### Production Build

```
electron/
├── app/                    # Web assets
├── build/                  # Compiled TypeScript
├── dist/                   # Distribution packages
│   ├── TimeSafari.exe     # Windows executable
│   ├── TimeSafari.dmg     # macOS installer
│   ├── TimeSafari.AppImage # Linux AppImage
│   └── TimeSafari.deb     # Debian package
└── node_modules/           # Dependencies
```

## Troubleshooting

### Common Build Issues

**TypeScript Compilation Errors**:
```bash
# Clean and rebuild
npm run clean:electron
cd electron && npm run build
```

**Native Module Issues**:
```bash
# Rebuild native modules
cd electron && npm run build
```

**Asset Copy Issues**:
```bash
# Verify Capacitor sync
npx cap sync electron
```

**Package Creation Failures**:
```bash
# Check electron-builder configuration
# Verify platform-specific requirements
# Check signing certificates (macOS/Windows)
```

### Platform-Specific Issues

**Windows**:
- Ensure Windows Build Tools installed
- Check NSIS installation
- Verify code signing certificates

**macOS**:
- Install Xcode Command Line Tools
- Configure code signing certificates
- Check app notarization requirements

**Linux**:
- Install required packages (rpm-tools, etc.)
- Check AppImage dependencies
- Verify desktop integration

## Performance Optimization

### Build Performance

**Parallel Builds**:
- Use concurrent TypeScript compilation
- Optimize asset copying
- Minimize file system operations

**Caching Strategies**:
- Cache node_modules between builds
- Cache compiled TypeScript
- Cache web assets when unchanged

### Runtime Performance

**Application Startup**:
- Optimize main process initialization
- Minimize startup dependencies
- Use lazy loading for features

**Memory Management**:
- Monitor memory usage
- Implement proper cleanup
- Optimize asset loading

## Security Considerations

### Code Signing

**Windows**:
- Authenticode code signing
- EV certificate for SmartScreen
- Timestamp server configuration

**macOS**:
- Developer ID code signing
- App notarization
- Hardened runtime

**Linux**:
- GPG signing for packages
- AppImage signing
- Package verification

### Security Hardening

**Production Builds**:
- Disable developer tools
- Remove debug information
- Enable security policies
- Implement sandboxing

**Update Security**:
- Secure update channels
- Package integrity verification
- Rollback capabilities

## CI/CD Integration

### GitHub Actions

```yaml
# Example workflow for Electron builds
- name: Build Electron
  run: |
    npm run build:electron -- --mode production
    npm run build:electron:windows -- --mode production
    npm run build:electron:mac -- --mode production
    npm run build:electron:linux -- --mode production
```

### Automated Testing

```yaml
# Test Electron builds
- name: Test Electron
  run: |
    npm run build:electron -- --mode test
    # Run automated tests
```

### Release Management

```yaml
# Create releases with assets
- name: Create Release
  run: |
    # Upload built packages
    # Create GitHub release
    # Publish to distribution channels
```

## Best Practices

### Development Workflow

1. **Use development mode for local testing**
2. **Test builds in all environments**
3. **Validate packages before distribution**
4. **Maintain consistent versioning**

### Build Optimization

1. **Minimize build dependencies**
2. **Use efficient asset processing**
3. **Implement proper caching**
4. **Optimize for target platforms**

### Quality Assurance

1. **Test on all target platforms**
2. **Validate installation processes**
3. **Check update mechanisms**
4. **Verify security configurations**

---

**Status**: Active implementation
**Last Updated**: 2025-01-27
**Version**: 1.0
**Maintainer**: Matthew Raymer 