This commit is contained in:
NotII
2025-04-07 19:25:24 +01:00
parent 7f7dd78818
commit 2f48ee38c2
102 changed files with 1825 additions and 761 deletions

View File

@@ -0,0 +1,80 @@
/**
* Main script to clean up the codebase by finding deprecated imports and files
* Run with: node scripts/cleanup-codebase.js
*/
const { execSync } = require('child_process');
const path = require('path');
// Print a separator for readability
function printSeparator() {
console.log('\n' + '='.repeat(80) + '\n');
}
// Run a script and print its output
function runScript(scriptPath) {
try {
console.log(`Running ${path.basename(scriptPath)}...\n`);
const output = execSync(`node ${scriptPath}`, { encoding: 'utf8' });
console.log(output);
} catch (error) {
console.error(`Error running ${scriptPath}:`, error.message);
console.error(error.stdout);
}
}
// Main function to run all cleanup scripts
function main() {
console.log(`
✨ Ember Market Frontend Cleanup Utility ✨
This script will help you clean up your codebase by:
1. Finding deprecated imports that should be updated
2. Identifying files that can be safely removed
3. Organizing the lib folder into a proper structure
`);
// First, find deprecated imports
printSeparator();
console.log('STEP 1: FINDING DEPRECATED IMPORTS');
printSeparator();
runScript(path.join(__dirname, 'find-deprecated-imports.js'));
// Then, identify files that can be removed
printSeparator();
console.log('STEP 2: IDENTIFYING DEPRECATED FILES');
printSeparator();
runScript(path.join(__dirname, 'cleanup-deprecated-files.js'));
// Finally, organize the lib folder
printSeparator();
console.log('STEP 3: ORGANIZING LIB FOLDER');
printSeparator();
runScript(path.join(__dirname, 'organize-lib-folder.js'));
// Final instructions
printSeparator();
console.log(`
NEXT STEPS:
1. Review the lib directory to ensure files are properly organized
2. Verify that existing code still imports everything correctly
3. Run tests to ensure everything still works correctly
The new structure is:
- lib/api.ts - Main API entry point that exports all API functions
- lib/utils/ - Contains utility functions organized by purpose
- lib/types/ - Contains TypeScript type definitions
- lib/services/ - Contains service implementations
For ongoing maintenance:
- Always import from @/lib/api for API functionality
- Use @/lib/utils for utility functions
- Add new types to the appropriate types file
- Add new services to the services directory
`);
}
// Run the main function
main();

View File

@@ -0,0 +1,159 @@
/**
* Script to help clean up deprecated files in the codebase
* Run with: node scripts/cleanup-deprecated-files.js
*/
const fs = require('fs');
const path = require('path');
// List of files that are now deprecated and can be removed/archived
const DEPRECATED_FILES = [
// API Client files that are now merged into api-client.ts
'lib/client-utils.ts',
'lib/client-service.ts',
'lib/data-service.ts',
// Service files that are now in the services directory
'lib/productData.ts',
'lib/shippingHelper.ts',
'lib/stats-service.ts',
'lib/storeHelper.ts',
// Server API files now in server-api.ts
'lib/server-service.ts',
// Files that may contain functionality already migrated
'lib/api-utils.ts',
];
// Create backup directory if it doesn't exist
const BACKUP_DIR = path.join(__dirname, '../lib/deprecated-backup');
if (!fs.existsSync(BACKUP_DIR)) {
fs.mkdirSync(BACKUP_DIR, { recursive: true });
console.log(`Created backup directory: ${BACKUP_DIR}`);
}
// Process each deprecated file
function processDeprecatedFiles() {
console.log('Analyzing deprecated files...\n');
const results = {
safe: [],
notFound: [],
mayNeedMigration: []
};
DEPRECATED_FILES.forEach(filePath => {
const fullPath = path.join(__dirname, '..', filePath);
if (!fs.existsSync(fullPath)) {
results.notFound.push(filePath);
return;
}
// Check if this file is safe to remove (has been migrated)
const isSafeToRemove = checkIfSafeToRemove(filePath);
if (isSafeToRemove) {
results.safe.push(filePath);
} else {
results.mayNeedMigration.push(filePath);
}
});
return results;
}
// Check if a file's functionality has been migrated
function checkIfSafeToRemove(filePath) {
// Simple heuristic - files that we're confident have been fully migrated
const definitelyMigrated = [
'lib/client-utils.ts',
'lib/client-service.ts',
'lib/data-service.ts',
'lib/productData.ts',
'lib/shippingHelper.ts',
'lib/stats-service.ts',
'lib/server-service.ts',
];
return definitelyMigrated.includes(filePath);
}
// Create a backup of a file before removing it
function backupFile(filePath) {
const fullPath = path.join(__dirname, '..', filePath);
const backupPath = path.join(BACKUP_DIR, path.basename(filePath));
try {
const content = fs.readFileSync(fullPath, 'utf8');
fs.writeFileSync(backupPath, content);
console.log(`✅ Backed up: ${filePath} to ${path.basename(backupPath)}`);
return true;
} catch (error) {
console.error(`❌ Failed to backup ${filePath}:`, error.message);
return false;
}
}
// Remove a file from the codebase
function removeFile(filePath) {
const fullPath = path.join(__dirname, '..', filePath);
try {
fs.unlinkSync(fullPath);
console.log(`🗑️ Removed: ${filePath}`);
return true;
} catch (error) {
console.error(`❌ Failed to remove ${filePath}:`, error.message);
return false;
}
}
// Main execution function
function main() {
const results = processDeprecatedFiles();
console.log('\n=== ANALYSIS RESULTS ===\n');
if (results.notFound.length > 0) {
console.log('📂 Files not found:');
results.notFound.forEach(f => console.log(` - ${f}`));
console.log('');
}
if (results.mayNeedMigration.length > 0) {
console.log('⚠️ Files that may need migration:');
results.mayNeedMigration.forEach(f => console.log(` - ${f}`));
console.log('\nCheck these files manually to ensure all functionality has been migrated.\n');
}
if (results.safe.length > 0) {
console.log('✅ Files safe to remove (already migrated):');
results.safe.forEach(f => console.log(` - ${f}`));
console.log('\nWhat would you like to do with these files?');
console.log('1. Back up and remove now');
console.log('2. Just back up');
console.log('3. Do nothing for now');
// In a real script, you'd get user input here
// For now, just demonstrate with a backup
console.log('\nDemo mode: backing up files...\n');
results.safe.forEach(filePath => {
if (backupFile(filePath)) {
console.log(`To remove ${filePath}, run: rm "${path.join(__dirname, '..', filePath)}"`);
}
});
}
console.log('\n=== MANUAL CLEANUP INSTRUCTIONS ===\n');
console.log('After verifying imports have been updated with find-deprecated-imports.js:');
console.log('1. Remove the backed up files using the commands above');
console.log('2. Check any remaining files in the lib/ directory to see if they should be organized');
console.log('3. Update imports in files using the main API module');
}
// Run the script
main();

View File

@@ -0,0 +1,89 @@
/**
* Script to find deprecated imports in the codebase
* Run with: node scripts/find-deprecated-imports.js
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
// Deprecated patterns to search for
const DEPRECATED_PATTERNS = [
"from '@/lib/client-utils'",
"from '@/lib/client-service'",
"from '@/lib/data-service'",
"from '@/lib/server-service'",
"from '@/lib/productData'",
"from '@/lib/shippingHelper'",
"from '@/lib/storeHelper'",
"from '@/lib/stats-service'",
// Add other deprecated import patterns here
];
// Run grep to find deprecated imports
function findDeprecatedImports() {
console.log('Searching for deprecated imports...\n');
DEPRECATED_PATTERNS.forEach(pattern => {
try {
// Using grep to find the pattern in all TypeScript/JavaScript files
const result = execSync(`grep -r "${pattern}" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" .`, { encoding: 'utf8' });
if (result) {
console.log(`\n== Found deprecated imports: ${pattern} ==`);
console.log(result);
console.log(`\n== Suggested replacement: ==`);
suggestReplacement(pattern);
}
} catch (error) {
// grep returns non-zero exit code if no matches found
if (error.status !== 1) {
console.error(`Error searching for ${pattern}:`, error.message);
}
}
});
}
function suggestReplacement(pattern) {
// Extract the import path
const match = pattern.match(/from '([^']+)'/);
if (!match) return;
const oldPath = match[1];
let replacement = '';
// Generate replacement suggestions based on deprecated path
switch (oldPath) {
case '@/lib/client-utils':
case '@/lib/client-service':
case '@/lib/data-service':
replacement = "import { clientFetch, fetchClient } from '@/lib/api';";
break;
case '@/lib/server-service':
replacement = "import { fetchServer } from '@/lib/api'; // Only use in Server Components";
break;
case '@/lib/productData':
replacement = "import { getProducts, createProduct, updateProduct, deleteProduct } from '@/lib/api';";
break;
case '@/lib/shippingHelper':
replacement = "import { getShippingOptions, createShippingOption, updateShippingOption, deleteShippingOption } from '@/lib/api';";
break;
case '@/lib/storeHelper':
replacement = "import { clientFetch } from '@/lib/api';";
break;
case '@/lib/stats-service':
replacement = "import { getPlatformStats } from '@/lib/api';";
break;
default:
replacement = "import from '@/lib/api';";
}
console.log(replacement);
console.log("\nReplace the specific imports with the corresponding ones from @/lib/api");
}
// Run the search
findDeprecatedImports();
// Uncomment the following line to run the remove-old-files.js script
// node scripts/remove-old-files.js

View File

@@ -0,0 +1,268 @@
/**
* Script to organize the lib folder by moving files into appropriate directories
* Run with: node scripts/organize-lib-folder.js
*/
const fs = require('fs');
const path = require('path');
// File organization plan
const ORGANIZATION_PLAN = {
// Files to move to utils folder
'utils': [
{ source: 'lib/utils.ts', destination: 'lib/utils/general.ts' },
{ source: 'lib/auth-utils.ts', destination: 'lib/utils/auth.ts' },
{ source: 'lib/git-utils.ts', destination: 'lib/utils/git.ts' },
{ source: 'lib/styles.ts', destination: 'lib/utils/styles.ts' }
],
// Files to move to types folder
'types': [
{ source: 'lib/types.ts', destination: 'lib/types/index.ts' }
],
// Files to keep in lib root (core API files)
'keep': [
'lib/api.ts',
'lib/api-client.ts',
'lib/server-api.ts',
'lib/README.md'
],
// Files to remove (already migrated to services or consolidated)
'remove': [
'lib/client-utils.ts',
'lib/client-service.ts',
'lib/data-service.ts',
'lib/productData.ts',
'lib/shippingHelper.ts',
'lib/stats-service.ts',
'lib/storeHelper.ts',
'lib/server-service.ts',
'lib/api-utils.ts'
]
};
// Create backup directory
const BACKUP_DIR = path.join(__dirname, '../lib/deprecated-backup');
if (!fs.existsSync(BACKUP_DIR)) {
fs.mkdirSync(BACKUP_DIR, { recursive: true });
console.log(`Created backup directory: ${BACKUP_DIR}`);
}
// Make sure target directories exist
function createDirectories() {
const directories = ['lib/utils', 'lib/types', 'lib/services'];
directories.forEach(dir => {
const fullPath = path.join(__dirname, '..', dir);
if (!fs.existsSync(fullPath)) {
fs.mkdirSync(fullPath, { recursive: true });
console.log(`Created directory: ${dir}`);
}
});
}
// Backup a file before moving or removing it
function backupFile(filePath) {
const fullPath = path.join(__dirname, '..', filePath);
if (!fs.existsSync(fullPath)) {
console.log(`⚠️ ${filePath} doesn't exist, skipping backup`);
return false;
}
try {
const backupPath = path.join(BACKUP_DIR, path.basename(filePath));
fs.copyFileSync(fullPath, backupPath);
console.log(`✅ Backed up: ${filePath} to backup folder`);
return true;
} catch (error) {
console.error(`❌ Failed to backup ${filePath}:`, error.message);
return false;
}
}
// Move a file to its new location
function moveFile(source, destination) {
const sourcePath = path.join(__dirname, '..', source);
const destPath = path.join(__dirname, '..', destination);
if (!fs.existsSync(sourcePath)) {
console.log(`⚠️ Source file ${source} doesn't exist, skipping`);
return false;
}
try {
// Ensure the destination directory exists
const destDir = path.dirname(destPath);
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir, { recursive: true });
}
// Read content from source
const content = fs.readFileSync(sourcePath, 'utf8');
// Write to destination
fs.writeFileSync(destPath, content);
console.log(`✅ Moved: ${source}${destination}`);
// Remove the source file
fs.unlinkSync(sourcePath);
return true;
} catch (error) {
console.error(`❌ Error moving ${source} to ${destination}:`, error.message);
return false;
}
}
// Remove a file
function removeFile(filePath) {
const fullPath = path.join(__dirname, '..', filePath);
if (!fs.existsSync(fullPath)) {
console.log(`⚠️ ${filePath} doesn't exist, skipping removal`);
return false;
}
try {
fs.unlinkSync(fullPath);
console.log(`🗑️ Removed: ${filePath}`);
return true;
} catch (error) {
console.error(`❌ Failed to remove ${filePath}:`, error.message);
return false;
}
}
// Update imports in the utils/index.ts file
function updateUtilsIndex() {
const indexPath = path.join(__dirname, '..', 'lib/utils/index.ts');
try {
const content = `/**
* Main utilities index file
* Re-exports all utility functions from their respective modules
*/
// Re-export general utils
export * from './general';
// Re-export auth utils
export * from './auth';
// Re-export git utils
export * from './git';
// Re-export style utils
export * from './styles';
`;
fs.writeFileSync(indexPath, content);
console.log(`✅ Updated lib/utils/index.ts with proper exports`);
return true;
} catch (error) {
console.error(`❌ Failed to update utils index:`, error.message);
return false;
}
}
// Main function to organize files
function organizeLibFolder() {
console.log('Starting lib folder organization...\n');
// Create necessary directories
createDirectories();
// Stats to track progress
const stats = {
backed_up: 0,
moved: 0,
removed: 0,
errors: 0
};
// First, back up all files we'll be modifying
const allFiles = [
...ORGANIZATION_PLAN.utils.map(item => item.source),
...ORGANIZATION_PLAN.types.map(item => item.source),
...ORGANIZATION_PLAN.remove
];
allFiles.forEach(file => {
if (backupFile(file)) {
stats.backed_up++;
} else {
stats.errors++;
}
});
// Move files to utils folder
ORGANIZATION_PLAN.utils.forEach(item => {
if (moveFile(item.source, item.destination)) {
stats.moved++;
} else {
stats.errors++;
}
});
// Move files to types folder
ORGANIZATION_PLAN.types.forEach(item => {
if (moveFile(item.source, item.destination)) {
stats.moved++;
} else {
stats.errors++;
}
});
// Remove deprecated files
ORGANIZATION_PLAN.remove.forEach(file => {
if (removeFile(file)) {
stats.removed++;
} else {
stats.errors++;
}
});
// Update the utils index file
updateUtilsIndex();
// Summary
console.log(`\nOrganization complete!`);
console.log(`${stats.backed_up} files backed up`);
console.log(`${stats.moved} files moved to appropriate folders`);
console.log(`${stats.removed} deprecated files removed`);
if (stats.errors > 0) {
console.log(`${stats.errors} errors encountered (see above)`);
}
console.log(`\nBackups are located in: lib/deprecated-backup`);
console.log(`You can delete this directory when you are confident the migration is complete.`);
}
// Show confirmation before proceeding
console.log(`
✨ Lib Folder Organization Tool ✨
This script will organize your lib folder as follows:
1. Move utility files to lib/utils/
${ORGANIZATION_PLAN.utils.map(f => `\n - ${f.source}${f.destination}`).join('')}
2. Move type files to lib/types/
${ORGANIZATION_PLAN.types.map(f => `\n - ${f.source}${f.destination}`).join('')}
3. Keep core API files in the lib root
${ORGANIZATION_PLAN.keep.map(f => `\n - ${f}`).join('')}
4. Remove deprecated files
${ORGANIZATION_PLAN.remove.map(f => `\n - ${f}`).join('')}
All files will be backed up to lib/deprecated-backup before any changes.
To proceed, edit this script and uncomment the organizeLibFolder() call at the bottom.
`);
// Uncomment this line to actually organize the folder
organizeLibFolder();

102
scripts/remove-old-files.js Normal file
View File

@@ -0,0 +1,102 @@
/**
* Script to safely remove old files that have been migrated
* Run with: node scripts/remove-old-files.js
*
* This will backup and remove the files that are known to be safe to remove
* because they've been migrated to the new structure.
*/
const fs = require('fs');
const path = require('path');
// Files that are safe to remove because they've been completely migrated
const FILES_TO_REMOVE = [
// Client API files
'lib/client-utils.ts',
'lib/client-service.ts',
'lib/data-service.ts',
// Service files
'lib/productData.ts',
'lib/shippingHelper.ts',
'lib/stats-service.ts',
'lib/server-service.ts',
// API utility files
'lib/api-utils.ts'
];
// Create backup directory
const BACKUP_DIR = path.join(__dirname, '../lib/deprecated-backup');
if (!fs.existsSync(BACKUP_DIR)) {
fs.mkdirSync(BACKUP_DIR, { recursive: true });
console.log(`Created backup directory: ${BACKUP_DIR}`);
}
// Process a file - back it up and remove it
function processFile(filePath) {
const fullPath = path.join(__dirname, '..', filePath);
if (!fs.existsSync(fullPath)) {
console.log(`⚠️ ${filePath} doesn't exist, skipping`);
return;
}
try {
// 1. Create backup
const backupPath = path.join(BACKUP_DIR, path.basename(filePath));
fs.copyFileSync(fullPath, backupPath);
console.log(`✅ Backed up ${filePath} to ${path.relative(path.join(__dirname, '..'), backupPath)}`);
// 2. Remove the original file
fs.unlinkSync(fullPath);
console.log(`🗑️ Removed ${filePath}`);
return true;
} catch (error) {
console.error(`❌ Error processing ${filePath}:`, error.message);
return false;
}
}
// Process all files
function removeFiles() {
console.log('Starting cleanup of migrated files...\n');
let successCount = 0;
let errorCount = 0;
FILES_TO_REMOVE.forEach(filePath => {
const result = processFile(filePath);
if (result) {
successCount++;
} else {
errorCount++;
}
});
console.log(`\nCleanup complete. Processed ${successCount + errorCount} files:`);
console.log(`${successCount} files successfully backed up and removed`);
if (errorCount > 0) {
console.log(`${errorCount} files had errors (see above)`);
}
console.log(`\nBackups are located in: ${path.relative(path.join(__dirname, '..'), BACKUP_DIR)}`);
console.log('You can delete this directory when you are confident the migration is complete.');
}
// Add confirmation prompt
console.log(`
⚠️ WARNING: This script will remove ${FILES_TO_REMOVE.length} files from your codebase ⚠️
All files will be backed up to ${path.relative(path.join(__dirname, '..'), BACKUP_DIR)} before removal.
Files to remove:
${FILES_TO_REMOVE.map(f => `- ${f}`).join('\n')}
To proceed, edit this script and uncomment the removeFiles() call at the bottom.
`);
// Uncomment this line to actually remove the files
// removeFiles();

115
scripts/update-imports.js Normal file
View File

@@ -0,0 +1,115 @@
/**
* Script to update imports after reorganizing the lib folder
* Run with: node scripts/update-imports.js
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
// Map of old imports to new imports
const importMap = {
'@/lib/styles': '@/lib/utils/styles',
'@/lib/utils': '@/lib/utils/general',
'@/lib/auth-utils': '@/lib/utils/auth',
'@/lib/git-utils': '@/lib/utils/git',
'@/lib/types': '@/lib/types',
'@/lib/data-service': '@/lib/api',
'@/lib/client-utils': '@/lib/api',
'@/lib/client-service': '@/lib/api',
'@/lib/productData': '@/lib/api',
'@/lib/shippingHelper': '@/lib/api',
'@/lib/stats-service': '@/lib/api',
'@/lib/storeHelper': '@/lib/api',
'@/lib/server-service': '@/lib/api',
'@/lib/api-utils': '@/lib/api',
};
// Function to find all TypeScript and JavaScript files
function findTsJsFiles(directory) {
let results = [];
const files = fs.readdirSync(directory, { withFileTypes: true });
for (const file of files) {
const fullPath = path.join(directory, file.name);
// Skip node_modules and .next directories
if (file.isDirectory()) {
if (file.name !== 'node_modules' && file.name !== '.next' && file.name !== '.git') {
results = results.concat(findTsJsFiles(fullPath));
}
} else if (file.name.endsWith('.ts') || file.name.endsWith('.tsx') || file.name.endsWith('.js') || file.name.endsWith('.jsx')) {
results.push(fullPath);
}
}
return results;
}
// Function to update imports in a file
function updateImportsInFile(filePath) {
console.log(`Checking ${filePath}`);
let fileContent = fs.readFileSync(filePath, 'utf8');
let originalContent = fileContent;
let hasChanges = false;
// Check for each old import and replace with new import
for (const [oldImport, newImport] of Object.entries(importMap)) {
// Create regex to match import statements for this module
// This handles different import formats:
// import X from 'oldImport'
// import { X } from 'oldImport'
// import * as X from 'oldImport'
const importRegex = new RegExp(`import\\s+(?:.+?)\\s+from\\s+['"]${oldImport.replace('/', '\\/')}['"]`, 'g');
if (importRegex.test(fileContent)) {
fileContent = fileContent.replace(importRegex, (match) => {
return match.replace(oldImport, newImport);
});
hasChanges = true;
}
}
// If any changes were made, write the file
if (hasChanges) {
fs.writeFileSync(filePath, fileContent, 'utf8');
console.log(`✅ Updated imports in ${filePath}`);
return true;
}
return false;
}
// Main function to update all imports
function updateAllImports() {
console.log('🔎 Finding TypeScript and JavaScript files...');
const projectRoot = path.resolve(__dirname, '..');
const files = findTsJsFiles(projectRoot);
console.log(`Found ${files.length} files to check.`);
console.log('🔄 Updating imports...');
let updatedCount = 0;
for (const file of files) {
if (updateImportsInFile(file)) {
updatedCount++;
}
}
console.log(`\n✅ Import update complete!`);
console.log(`- ${updatedCount} files were updated`);
console.log(`- ${files.length - updatedCount} files had no changes needed`);
// Run next build to check for any remaining errors
console.log('\n🔍 Running TypeScript check to find any remaining issues...');
try {
execSync('npx tsc --noEmit', { stdio: 'inherit' });
console.log('\n✅ TypeScript check passed!');
} catch (error) {
console.error('\n⚠ TypeScript check found some issues. Please fix them manually.');
}
}
// Run the script
updateAllImports();