Package Exports
- structure-validation
- structure-validation/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (structure-validation) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Structure Validation
A Node.js CLI tool for validating and maintaining consistent codebase folder and file structure using declarative configuration. Now with automatic import updates! 🚀
Why Structure Validation?
Maintaining a clean, consistent file structure across your codebase is crucial for:
- Team Productivity - Developers can quickly locate files
- Code Quality - Enforced patterns prevent structural debt
- Scalability - Consistent structure scales with your project
- Onboarding - New team members understand the codebase faster
Features
- 🔍 Declarative Configuration - Define your structure rules in TypeScript
- 🚀 Fast Validation - Built with performance in mind for large codebases
- 🛠️ Auto-fix Mode - Automatically move files to correct locations
- 📦 Git Integration - Validate staged, changed, or all files
- 🎯 Pattern Matching - Support for glob patterns and variable placeholders
- 🔧 Husky Integration - Pre-commit hooks for consistent validation
- 📊 Detailed Reporting - Clear error messages and suggestions
- 🔄 Automatic Import Updates - NEW! Automatically update import statements when files are moved or renamed
- 📁 Smart File Operations - Comprehensive file operations with import management
- 🛡️ Enhanced Error Handling - Better user experience with detailed error reporting
- ⚡ Batch Operations - Efficient handling of multiple file operations
Quick Start
Installation
npm install structure-validationBasic Usage
- Create Configuration
Create structure-validation.config.json in your project root:
{
"root": ".",
"structure": {
"components": ["*.tsx"],
"services": ["*.service.ts"],
"hooks": ["use*.ts", "use*.tsx"],
"utils": ["*.util.ts"],
"{a}": ["{a}.ts", "{a}.tsx", "{a}.*.ts", "{a}.*.tsx"],
"{root}": ["*.config.json", "package.json", "README.md", "tsconfig.json"],
"**": ["*.test.ts", "*.test.tsx", "index.ts", "index.tsx", "page.tsx", "route.ts", "not-found.tsx"]
}
}- Run Validation
# Validate staged files (default)
npx structure-validation
# Validate all files
npx structure-validation --scope all
# Auto-fix issues with automatic import updates
npx structure-validation --fix
# Validate with root folder verification
npx structure-validation --verify-rootCLI Options
npx structure-validation [options]
Options:
--scope <scope> all, staged, or changes (default: staged)
--files <files> Specific files to validate
--config <path> Config file path (default: structure-validation.config.json)
--fix Auto-fix file structure issues with import updates
--dry-run Preview changes without applying
--backup Create backup before fixing (default: true)
--verify-root Enable root folder validation
--skip-error Skip interactive mode and continue on errors
-h, --help Show help
-v, --version Show versionAutomatic Import Updates
NEW FEATURE! Structure Validation now automatically updates import statements when files are moved, renamed, or deleted. This ensures your code continues to work after file operations.
How It Works
When you move or rename files, the tool:
- Detects all import statements that reference the moved/renamed files
- Calculates new relative paths based on the new file location
- Updates all import statements automatically
- Validates the changes to ensure code functionality is maintained
Example
# Move a file and automatically update all imports
npx structure-validation --fix
# The tool will:
# 1. Move src/utils/helper.ts → shared/utils/helper.ts
# 2. Update all imports from './utils/helper' to '../../shared/utils/helper'
# 3. Validate that all imports are correctly updatedSupported Import Types
- Named imports:
import { name } from './module' - Default imports:
import defaultExport from './module' - Namespace imports:
import * as namespace from './module' - Type imports:
import type { Type } from './module' - Mixed imports:
import defaultExport, { named } from './module'
For detailed information about automatic import updates, see AUTOMATIC_IMPORT_UPDATES.md.
Pattern Examples
Basic Patterns
*.tsx- Files ending with .tsxuse*.ts- Files starting with "use" and ending with .ts*.service.ts- Files ending with .service.ts
Variable Placeholders
{a}.ts- Matchesuser.tsinuser/folder{a}.*.ts- Matchesuser.profile.tsinuser/folder{root}- Root folder patterns (use with--verify-root)
Global Patterns
**- Applies to all folders (e.g.,*.test.ts,index.ts)
Examples
Validate All Files
npx structure-validation --scope allAuto-fix with Import Updates
npx structure-validation --scope all --fixPreview Changes
npx structure-validation --scope all --dry-runValidate Root Folder
npx structure-validation --verify-rootInteractive Mode
# Start interactive mode for fixing validation errors
npx structure-validation
# Skip interactive mode and continue on errors
npx structure-validation --skip-errorIn interactive mode, you'll be prompted for each file with validation errors:
- 1 - Move to subfolder (automatically uses suggested folder name)
- 2 - Rename file (keep extension)
- 3 - Move to upper folder (creates folder with suggested name if needed)
- 4 - Delete file
- 5 - Add file to structure-validation.config.json (modifies config and restarts)
- 6 - Add file pattern to structure-validation.config.json (modifies config and restarts)
- 7 - Skip this file (adds to structure-validation.skip.json)
The subfolder suggestions are based on your structure-validation.config.json file:
- File patterns in the config determine the suggested folder
- Matches are found by comparing filename against configured patterns
- Special patterns like {root}, {a}, and ** are excluded from suggestions
Skip functionality:
- Skipped files are stored in
structure-validation.skip.json - Skipped files are automatically excluded from future validation runs
- The skip file persists across sessions
Husky Integration
Structure Validation integrates seamlessly with Husky to verify folder structure before commits, ensuring code quality and consistency across your team.
🚀 Quick Setup
# Install Husky and structure-validation
npm install --save-dev husky structure-validation
# Initialize Husky
npx husky init
# Add pre-commit hook
npx husky add .husky/pre-commit "npx structure-validation --scope staged --verify-root"📋 Recommended Configuration
Add these scripts to your package.json for comprehensive validation:
{
"scripts": {
"validate:staged": "structure-validation --scope staged --verify-root",
"validate:all": "structure-validation --scope all --verify-root",
"validate:fix": "structure-validation --scope staged --fix --verify-root",
"validate:preview": "structure-validation --scope staged --dry-run",
"validate:interactive": "structure-validation --scope staged"
},
"husky": {
"hooks": {
"pre-commit": "npm run validate:staged"
}
}
}🔧 Advanced Husky Setup
For more control over the validation process:
# Create a custom pre-commit script
cat > .husky/pre-commit << 'EOF'
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
# Validate staged files
echo "🔍 Validating file structure..."
npx structure-validation --scope staged --verify-root
# If validation fails, show helpful message
if [ $? -ne 0 ]; then
echo ""
echo "❌ File structure validation failed!"
echo "💡 Run 'npm run validate:interactive' to fix issues interactively"
echo "💡 Run 'npm run validate:fix' to auto-fix issues"
echo "💡 Run 'npm run validate:preview' to preview changes"
exit 1
fi
echo "✅ File structure validation passed!"
EOF
# Make the script executable
chmod +x .husky/pre-commit🎯 Validation Strategies
1. Staged Files Only (Recommended for pre-commit)
# Validates only files that are staged for commit
npx structure-validation --scope staged --verify-root2. All Files (Use for CI/CD or manual validation)
# Validates all files in the repository
npx structure-validation --scope all --verify-root3. Auto-fix Mode (Use with caution)
# Automatically fixes structure issues with import updates
npx structure-validation --scope staged --fix --verify-root4. Interactive Mode (Best for manual fixes)
# Interactive mode for fixing validation errors
npx structure-validation --scope staged🛠️ Team Workflow Integration
For Development Teams
Initial Setup:
# Install dependencies npm install --save-dev husky structure-validation # Setup Husky npx husky init # Add pre-commit hook npx husky add .husky/pre-commit "npm run validate:staged"
Configuration File: Create
structure-validation.config.jsonin your project root:{ "root": ".", "structure": { "components": ["*.tsx"], "services": ["*.service.ts"], "hooks": ["use*.ts", "use*.tsx"], "utils": ["*.util.ts"], "{root}": ["*.config.json", "package.json", "README.md"], "**": ["*.test.ts", "index.ts"] } }
Team Guidelines:
- Commit frequently to catch issues early
- Use
npm run validate:interactivefor complex fixes - Use
npm run validate:previewto preview changes - Run
npm run validate:allbefore major releases
For CI/CD Pipelines
Add to your GitHub Actions workflow:
name: Structure Validation
on: [push, pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Validate structure
run: npx structure-validation --scope changes --verify-root
- name: Auto-fix if needed
run: npx structure-validation --scope changes --fix --verify-root
continue-on-error: true🔍 Troubleshooting Husky Integration
Common Issues
Pre-commit hook not running:
# Check if Husky is properly installed ls -la .husky/ # Reinstall Husky if needed npm uninstall husky npm install --save-dev husky npx husky init
Validation taking too long:
# Use staged files only for faster validation npx structure-validation --scope staged # Or validate specific files npx structure-validation --files src/components/
False positives:
# Add files to skip list npx structure-validation --scope staged # Choose option 7 to skip problematic files
Import update conflicts:
# Use dry-run to preview changes npx structure-validation --scope staged --dry-run # Or use interactive mode for manual control npx structure-validation --scope staged
Performance Tips
- Use staged files only for pre-commit hooks
- Exclude large directories in your config
- Use specific file patterns instead of broad globs
- Run full validation only in CI/CD
📊 Monitoring and Reporting
Git Hooks Logging
Add logging to your pre-commit hook:
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
echo "🔍 Validating file structure..."
npx structure-validation --scope staged --verify-root 2>&1 | tee .validation.log
if [ $? -ne 0 ]; then
echo "❌ Validation failed. Check .validation.log for details"
exit 1
fi
echo "✅ Validation passed!"Team Notifications
For team environments, consider adding Slack/Discord notifications:
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
echo "🔍 Validating file structure..."
npx structure-validation --scope staged --verify-root
if [ $? -ne 0 ]; then
# Send notification to team channel
curl -X POST -H 'Content-type: application/json' \
--data '{"text":"❌ File structure validation failed in $(pwd)"}' \
$SLACK_WEBHOOK_URL
exit 1
fi🎯 Best Practices
- Start Small: Begin with basic validation, then add complexity
- Team Training: Educate team on structure-validation commands
- Gradual Rollout: Start with warnings, then enforce strictly
- Documentation: Keep team guidelines updated
- Regular Reviews: Periodically review and update validation rules
Configuration
Configuration Examples
Basic Configuration
{
"root": ".",
"structure": {
"components": ["*.tsx"],
"services": ["*.service.ts"],
"utils": ["*.util.ts"],
"{a}": ["{a}.ts", "{a}.*.ts"],
"{root}": ["*.config.json", "package.json"],
"**": ["*.test.ts", "index.ts"]
}
}Advanced Configuration with Import Updates
{
"root": ".",
"structure": {
"components": ["*.tsx"],
"services": ["*.service.ts"],
"utils": ["*.util.ts"],
"hooks": ["use*.ts", "use*.tsx"],
"types": ["*.type.ts", "*.interface.ts", "*.d.ts"],
"{a}": ["{a}.ts", "{a}.*.ts"],
"{root}": ["*.config.json", "package.json"],
"**": ["*.test.ts", "index.ts"]
}
}File Operations with Import Updates
The tool provides comprehensive file operations that automatically handle import updates:
Moving Files
import { FileOperationService } from 'structure-validation';
const fileOperationService = new FileOperationService();
// Move a file and automatically update all imports
const result = await fileOperationService.moveFile(
'src/utils/helper.ts',
'shared/utils/helper.ts'
);Renaming Files
// Rename a file and automatically update all imports
const result = await fileOperationService.renameFile(
'src/services/OldService.ts',
'NewService.ts'
);Batch Operations
// Move multiple files and update all imports in a single operation
const moves = [
{ sourcePath: 'src/components/Button.tsx', targetPath: 'ui/components/Button.tsx' },
{ sourcePath: 'src/components/Input.tsx', targetPath: 'ui/components/Input.tsx' }
];
const results = await fileOperationService.batchMoveFiles(moves);Troubleshooting
Configuration Not Found
Create structure-validation.config.json in your project root.
Git Repository Required
Initialize git repository or run without --scope flag.
Auto-fix Errors
- Check if target files already exist
- Verify write permissions
- Check disk space for backups
- Ensure TypeScript configuration is correct for import updates
Import Update Issues
- Verify that import paths are relative (not absolute)
- Check that files actually import the moved/renamed files
- Use
--dry-runto preview changes before applying - Check the validation report for import update errors
Contributing
We welcome contributions! Please see our Contributing Guide for details.
License
This project is licensed under the MIT License - see the LICENSE file for details.