# Code Cleanup and Pruning Workflow
## Overview
This workflow provides a systematic approach to cleaning up, simplifying, and reducing code duplication across the CoAP router codebase. The goal is to identify unused code, consolidate duplicated functionality, and improve overall code maintainability.
**Note**: Documentation files (\*.md) should be excluded from all code cleanup and analysis operations as they are not executable code.
## Phase 1: Discovery and Analysis
### 1.1 Identify Unused Code
**Dead Code Detection**
- [ ] Scan for unused imports across all TypeScript/JavaScript files
- [ ] Identify unreferenced functions, variables, and components
- [ ] Check for unused Rust functions and modules
- [ ] Find unused CSS classes and Tailwind utilities
- [ ] Locate orphaned files with no references
- [ ] Search for and remove legacy code (see Legacy Code Detection below)
- [ ] **Note**: Documentation files (\*.md) should be excluded from unused code analysis
**Legacy Code Detection**
- [ ] Search for code marked with "legacy", "deprecated", or "TODO: remove"
- [ ] Identify code kept for backward compatibility that's no longer needed
- [ ] Find commented-out code blocks that were kept "just in case"
- [ ] Locate old implementation alternatives marked as fallbacks
- [ ] Check for outdated workarounds that may no longer be necessary
**Tools to Use:**
```bash
# TypeScript/JavaScript unused exports
npx ts-unused-exports tsconfig.json
# Find unused files (excluding .md documentation files)
find static/js -name "*.ts" -o -name "*.tsx" -o -name "*.js" | xargs grep -L "import\|require"
# Rust unused code (built-in warnings)
grep -r -i "legacy\|deprecated\|todo.*remove\|fixme.*remove" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.rs" .
grep -r "//.*TODO\|#.*TODO\|//.*FIXME\|#.*FIXME" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.rs" .
grep -r -E "^[[:space:]]*//.*" --include="*.ts" --include="*.tsx" --include="*.js" . | head -20
```
### 1.2 Duplication Analysis
**Comprehensive Code Review for DRY Principle**
- [ ] Conduct full repository review to identify areas where DRY (Don't Repeat Yourself) principle can be better implemented
- [ ] Analyze codebase for patterns that could be abstracted into reusable components or utilities
**WASM vs JavaScript Duplication**
- [ ] Compare WASM API client functions with frontend JS implementations
- [ ] Identify overlapping functionality between `/wasm-api-client/` and `/static/js/preact/`
- [ ] Check for duplicated type definitions between Rust and TypeScript
- [ ] Look for redundant API call patterns
**Component and Utility Duplication**
- [ ] Scan for similar React/Preact components that could be consolidated
- [ ] Identify duplicated utility functions across different modules
- [ ] Check for redundant context providers or state management
- [ ] Find duplicated styling patterns
**Database and Model Duplication**
- [ ] Review Rust models vs WASM types vs TypeScript types
- [ ] Check for redundant database queries or similar operations
- [ ] Identify overlapping validation logic
### 1.3 Complexity Analysis
**Overly Complex Files**
- [ ] Identify files with high cyclomatic complexity
- [ ] Find functions that exceed 50 lines or have too many parameters
- [ ] Locate deeply nested code structures
- [ ] Check for overly complex conditionals
**Architecture Inconsistencies**
- [ ] Find components not following established patterns
- [ ] Identify inconsistent error handling approaches
- [ ] Check for mixed architectural patterns within modules
## Phase 2: Cleanup Strategy Planning
### 2.1 Priority Assessment
**High Priority (Safety Critical)**
- [ ] Remove unused authentication/security code
- [ ] Clean up database migration code
- [ ] Remove orphaned API endpoints
**Medium Priority (Performance Impact)**
- [ ] Consolidate WASM/JS duplication
- [ ] Remove unused React components
- [ ] Clean up unused CSS/Tailwind classes
**Low Priority (Maintenance)**
- [ ] Remove unused utility functions
- [ ] Clean up dead imports
- [ ] Consolidate similar styling patterns
### 2.2 Consolidation Plan
**WASM Integration Opportunities**
- [ ] Identify JS functions that should use WASM instead
- [ ] Plan migration of duplicated API calls to WASM-only
- [ ] Consolidate type definitions to single source of truth
**Component Consolidation**
- [ ] Merge similar modal components
- [ ] Consolidate form components with shared patterns
- [ ] Create reusable UI primitives from duplicated code
**Utility Consolidation**
- [ ] Merge similar helper functions
- [ ] Create shared validation utilities
- [ ] Consolidate API response handling
## Phase 3: Implementation
### 3.1 Safe Removal Process
**Pre-Removal Validation**
- [ ] Run full test suite: `cargo test`
- [ ] Build frontend: `npm run build:all`
- [ ] Check for dynamic imports or runtime references
- [ ] Verify no external dependencies on code to be removed
**Removal Order**
1. [ ] Remove unused imports first
2. [ ] Remove legacy/deprecated code and TODO items marked for removal
3. [ ] Remove unused utility functions
4. [ ] Remove unused components
5. [ ] Remove unused API endpoints
6. [ ] Remove unused database code
### 3.2 Consolidation Implementation
**WASM-First Approach**
- [ ] Move duplicated API logic to WASM client
- [ ] Update TypeScript to use WASM functions exclusively
- [ ] Remove redundant JavaScript API implementations
- [ ] Update imports across codebase
**Component Refactoring**
- [ ] Extract common patterns into shared components
- [ ] Create reusable hooks for duplicated logic
- [ ] Consolidate styling into shared utilities
- [ ] Update all consumers of refactored components
### 3.3 Type System Cleanup
**Single Source of Truth**
- [ ] Consolidate Rust types in `shared-types/`
- [ ] Generate TypeScript types from Rust using `typeshare`
- [ ] Remove manually maintained TypeScript type duplicates
- [ ] Update WASM bindings to use shared types
## Phase 4: Validation and Testing
### 4.1 Automated Validation
**Build Verification**
```bash
# Frontend build
npm run build:all
# Backend build
cargo build --release --features embedded-assets
# WASM build
npm run build:wasm
# Test suite
cargo test
```
**Linting and Formatting**
```bash
# Format check
npm run format:check
# TypeScript check
npx tsc --noEmit
# Rust formatting
cargo fmt --check
```
### 4.2 Functionality Testing
**Manual Testing Checklist**
- [ ] Authentication flow works correctly
- [ ] Map functionality unchanged
- [ ] CRUD operations for all entities work
- [ ] Import/export functionality intact
- [ ] Offline functionality preserved
- [ ] Service worker functionality maintained
**Performance Validation**
- [ ] Bundle size reduction measured
- [ ] Page load times maintained or improved
- [ ] Memory usage not increased
- [ ] WASM performance not degraded
## Phase 5: Documentation and Maintenance
### 5.1 Update Documentation
**Code Documentation**
- [ ] Update component documentation for consolidated components
- [ ] Document new shared utilities and their usage
- [ ] Update API documentation for removed endpoints
- [ ] Update WASM client documentation
**Architecture Documentation**
- [ ] Update `CLAUDE.md` with architectural changes
- [ ] Document new patterns established during cleanup
- [ ] Update migration guides if needed
### 5.2 Monitoring and Maintenance
**Ongoing Cleanup**
- [ ] Set up automated unused code detection in CI
- [ ] Add linting rules to prevent future duplication
- [ ] Establish code review checklist for new features
- [ ] Schedule regular cleanup reviews
## Tools and Scripts
### Useful Commands
```bash
# Find unused code in Rust
find . -name "*.rs" -not -name "*.md" | xargs wc -l | sort -nr | head -20
# Find potential duplicated handler patterns
grep -r "impl.*Handler" src/ | cut -d: -f2 | sort | uniq -d
# Check binary size
cargo build --release && ls -la target/release/
# Find unused dependencies
cargo machete
# Run benchmarks to check performance
cargo bench
```
### Cleanup Script Template
```bash
#!/bin/bash
# cleanup-unused.sh
echo "Starting code cleanup process..."
# Step 1: Check for unused code
echo "Checking for unused code..."
echo "Running clippy..."
cargo clippy --all-features
# Step 3: Check dependencies
echo "Checking for unused dependencies..."
cargo machete
# Step 4: Run tests before cleanup
echo "Running tests before cleanup..."
cargo test
# Step 5: Build verification
echo "Verifying build..."
cargo build --release
echo "Cleanup validation complete. Review results before proceeding with removal."
```
## Success Criteria
- [ ] Reduced binary size by at least 10%
- [ ] No functionality regression
- [ ] All tests passing
- [ ] Improved build times
- [ ] Reduced code duplication by at least 25%
- [ ] Consolidated handler/extractor patterns
- [ ] Improved router performance benchmarks
## Risk Mitigation
- **Backup**: Create feature branch before starting cleanup
- **Incremental**: Make small, focused changes rather than large sweeping changes
- **Testing**: Run full test suite after each cleanup step
- **Rollback Plan**: Maintain ability to quickly revert changes
- **Code Review**: Have all cleanup changes reviewed by team