Files
mcp-tool/fix-syntax-preserve-parameters.js
nasir@endelospay.com 8c74b0e23f first
2025-07-11 20:22:12 +05:00

282 lines
8.1 KiB
JavaScript

/**
* @fileoverview Fix syntax issues while preserving all parameters
* This script fixes structural issues but keeps all parameter definitions
*/
import fs from 'fs';
import path from 'path';
/**
* Fix syntax while preserving all parameters
*/
function fixSyntaxPreserveParameters() {
try {
console.log('=== FIXING SYNTAX WHILE PRESERVING ALL PARAMETERS ===');
console.log('');
const endpointsPath = path.join(process.cwd(), 'src/config/endpoints.js');
let content = fs.readFileSync(endpointsPath, 'utf8');
console.log('📁 Reading endpoints.js...');
console.log(`📊 Original file size: ${content.length} characters`);
// Create backup
const backupPath = path.join(process.cwd(), `endpoints_syntax_preserve_backup_${Date.now()}.js`);
fs.writeFileSync(backupPath, content);
console.log(`💾 Backup created: ${backupPath}`);
// Fix syntax issues step by step
console.log('🔧 Step 1: Fix bracket notation in parameter names...');
content = fixBracketNotation(content);
console.log('🔧 Step 2: Fix malformed parameter structures...');
content = fixMalformedParameters(content);
console.log('🔧 Step 3: Fix excessive closing braces...');
content = fixExcessiveBraces(content);
console.log('🔧 Step 4: Fix missing commas...');
content = fixMissingCommas(content);
console.log('🔧 Step 5: Fix multi-line descriptions...');
content = fixMultiLineDescriptions(content);
console.log('🔧 Step 6: Add missing helper functions...');
content = addMissingHelperFunctions(content);
// Write the fixed content
fs.writeFileSync(endpointsPath, content);
console.log(`📊 Fixed file size: ${content.length} characters`);
console.log('');
console.log('✅ Syntax fixed while preserving all parameters!');
return {
backupPath: backupPath,
success: true
};
} catch (error) {
console.error('❌ Error fixing syntax:', error);
throw error;
}
}
/**
* Fix bracket notation in parameter names
*/
function fixBracketNotation(content) {
// Fix parameter names with brackets - need to quote them
content = content.replace(/(\s+)([a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\](?:\[[^\]]+\])?)(\s*:\s*\{)/g, '$1"$2"$3');
return content;
}
/**
* Fix malformed parameter structures
*/
function fixMalformedParameters(content) {
// Fix parameter definitions that are missing closing braces
content = content.replace(
/(\w+:\s*\{\s*type:\s*"[^"]*",\s*required:\s*(?:true|false),\s*description:\s*"[^"]*")\s*,?\s*\n(\s*)(\w+:|"[^"]+":|\})/g,
(match, paramDef, indent, nextItem) => {
if (nextItem === '}') {
return `${paramDef} }\n${indent}${nextItem}`;
} else {
return `${paramDef} },\n${indent}${nextItem}`;
}
}
);
return content;
}
/**
* Fix excessive closing braces
*/
function fixExcessiveBraces(content) {
// Remove excessive closing braces
content = content.replace(/\}\s*\}\s*\}/g, '}');
content = content.replace(/\}\s*\}/g, '}');
return content;
}
/**
* Fix missing commas
*/
function fixMissingCommas(content) {
// Fix missing commas between parameters
content = content.replace(/(\}\s*)\n(\s+[a-zA-Z_"'])/g, '$1,\n$2');
// Fix trailing commas before closing braces
content = content.replace(/,(\s*\})/g, '$1');
return content;
}
/**
* Fix multi-line descriptions
*/
function fixMultiLineDescriptions(content) {
// Fix descriptions that are split across multiple lines
content = content.replace(
/description:\s*\n\s*"([^"]*)"([^}]*)/g,
'description: "$1"$2'
);
return content;
}
/**
* Add missing helper functions
*/
function addMissingHelperFunctions(content) {
// Check if helper functions already exist
if (content.includes('export function getEndpointsByAuthType')) {
return content;
}
// Add helper functions at the end
const helperFunctions = `
/**
* Helper function to get endpoints by authentication type
*/
export function getEndpointsByAuthType(authType) {
switch (authType) {
case AUTH_TYPES.PUBLIC:
return PUBLIC_ENDPOINTS;
case AUTH_TYPES.PROVIDER:
return PROVIDER_ENDPOINTS;
case AUTH_TYPES.PATIENT:
return PATIENT_ENDPOINTS;
case AUTH_TYPES.PARTNER:
return PARTNER_ENDPOINTS;
case AUTH_TYPES.AFFILIATE:
return AFFILIATE_ENDPOINTS;
case AUTH_TYPES.NETWORK:
return NETWORK_ENDPOINTS;
default:
return [];
}
}
/**
* Get all endpoints
*/
export function getAllEndpoints() {
return [
...PUBLIC_ENDPOINTS,
...PROVIDER_ENDPOINTS,
...PATIENT_ENDPOINTS,
...PARTNER_ENDPOINTS,
...AFFILIATE_ENDPOINTS,
...NETWORK_ENDPOINTS
];
}`;
return content + helperFunctions;
}
/**
* Validate the fixed file syntax
*/
async function validateSyntax() {
try {
console.log('🔍 Validating syntax...');
const endpointsPath = path.join(process.cwd(), 'src/config/endpoints.js');
// Use Node.js syntax check
const { spawn } = await import('child_process');
return new Promise((resolve) => {
const child = spawn('node', ['-c', endpointsPath], {
stdio: ['pipe', 'pipe', 'pipe']
});
let stderr = '';
child.stderr.on('data', (data) => {
stderr += data.toString();
});
child.on('close', (code) => {
if (code === 0) {
console.log('✅ Syntax validation passed');
resolve(true);
} else {
console.error('❌ Syntax errors found:');
console.error(stderr);
resolve(false);
}
});
});
} catch (error) {
console.error('❌ Error validating syntax:', error);
return false;
}
}
/**
* Count tools after fix
*/
function countTools() {
try {
console.log('📊 Counting tools...');
const endpointsPath = path.join(process.cwd(), 'src/config/endpoints.js');
const content = fs.readFileSync(endpointsPath, 'utf8');
const sections = ['PUBLIC_ENDPOINTS', 'PROVIDER_ENDPOINTS', 'PATIENT_ENDPOINTS', 'PARTNER_ENDPOINTS', 'AFFILIATE_ENDPOINTS', 'NETWORK_ENDPOINTS'];
let total = 0;
sections.forEach(section => {
const regex = new RegExp(`${section}\\s*=\\s*\\[([\\s\\S]*?)\\];`);
const match = content.match(regex);
if (match) {
const count = (match[1].match(/\{[\s\S]*?\}/g) || []).length;
console.log(` ${section.replace('_ENDPOINTS', '')}: ${count} tools`);
total += count;
}
});
console.log(` TOTAL: ${total} tools`);
return total;
} catch (error) {
console.error('❌ Error counting tools:', error);
return 0;
}
}
// Run the syntax fix
if (import.meta.url === `file://${process.argv[1]}`) {
(async () => {
try {
const result = fixSyntaxPreserveParameters();
console.log('');
console.log('=== VALIDATION ===');
const isValid = await validateSyntax();
const toolCount = countTools();
if (isValid) {
console.log('🎉 Syntax successfully fixed!');
console.log('✅ All parameters preserved');
console.log(`📊 Total tools: ${toolCount}`);
} else {
console.log('⚠️ Some syntax issues may remain');
}
console.log(`💾 Backup saved: ${result.backupPath}`);
} catch (error) {
console.error('❌ Failed to fix syntax:', error);
}
})();
}
export { fixSyntaxPreserveParameters };