All files / src/utils configValidator.ts

98.57% Statements 69/70
85% Branches 34/40
100% Functions 18/18
98.46% Lines 64/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244                                            3x                                               3x 33x   33x 1x                 32x 35x   35x 25x                   7x   4x 1x               3x     2x 1x               1x     5x                   3x 4x   4x 12x     4x           3x 11x           3x 4x   8x 8x   4x 2x 2x 3x       4x 2x 2x 5x       4x 2x 2x 3x 3x 3x     2x     4x           3x 3x 2x 2x   1x       1x     1x     1x                                     1x                 1x           3x           2x 2x 2x 2x   2x 6x 5x 5x             2x              
import { Provider } from '../types/index.js';
 
/**
 * Configuration validation results
 */
export interface ConfigValidationResult {
  provider: Provider;
  status: 'configured' | 'missing-token' | 'missing-project' | 'invalid-config' | 'skipped';
  reason?: string;
  isValid: boolean;
}
 
/**
 * Provider configuration requirements
 */
interface ProviderRequirements {
  requiredEnvVars: string[];
  optionalEnvVars: string[];
  requiredConfigFields: string[];
  description: string;
}
 
const PROVIDER_REQUIREMENTS: Record<string, ProviderRequirements | undefined> = {
  github: {
    requiredEnvVars: ['GITHUB_TOKEN'],
    optionalEnvVars: ['GITHUB_ORG'],
    requiredConfigFields: [],
    description: 'GitHub requires GITHUB_TOKEN environment variable',
  },
  gitlab: {
    requiredEnvVars: ['GITLAB_TOKEN'],
    optionalEnvVars: ['GITLAB_URL', 'GITLAB_GROUP'],
    requiredConfigFields: [],
    description: 'GitLab requires GITLAB_TOKEN environment variable',
  },
  azure: {
    requiredEnvVars: ['AZURE_TOKEN', 'AZURE_ORG'],
    optionalEnvVars: ['AZURE_PROJECT'],
    requiredConfigFields: [],
    description: 'Azure DevOps requires AZURE_TOKEN and AZURE_ORG environment variables',
  },
};
 
/**
 * Validates configuration for a specific provider
 */
export function validateProviderConfig(provider: string): ConfigValidationResult {
  const requirements = PROVIDER_REQUIREMENTS[provider];
 
  if (!requirements) {
    return {
      provider: provider as Provider,
      status: 'invalid-config',
      reason: `Unknown provider: ${provider}`,
      isValid: false,
    };
  }
 
  // Check for required environment variables
  for (const envVar of requirements.requiredEnvVars) {
    const value = process.env[envVar];
 
    if (!value || value === 'test_token' || value === 'your_token_here' || value.length < 5) {
      return {
        provider: provider as Provider,
        status: 'missing-token',
        reason: `Missing or invalid ${envVar}. ${requirements.description}`,
        isValid: false,
      };
    }
  }
 
  // Additional provider-specific validation
  switch (provider) {
    case 'github':
      if (!process.env.GITHUB_ORG && !hasGitHubProjectMapping()) {
        return {
          provider: provider as Provider,
          status: 'missing-project',
          reason:
            'GitHub requires either GITHUB_ORG environment variable or project mappings in .mcp.json',
          isValid: false,
        };
      }
      break;
 
    case 'azure':
      if (!process.env.AZURE_PROJECT && !hasAzureProjectMapping()) {
        return {
          provider: provider as Provider,
          status: 'missing-project',
          reason:
            'Azure DevOps requires either AZURE_PROJECT environment variable or project mappings in .mcp.json',
          isValid: false,
        };
      }
      break;
  }
 
  return {
    provider: provider as Provider,
    status: 'configured',
    isValid: true,
  };
}
 
/**
 * Validates all supported providers
 */
export function validateAllProviderConfigs(): ConfigValidationResult[] {
  const results: ConfigValidationResult[] = [];
 
  for (const provider of Object.keys(PROVIDER_REQUIREMENTS) as Provider[]) {
    results.push(validateProviderConfig(provider));
  }
 
  return results;
}
 
/**
 * Filters results to only include properly configured providers
 */
export function getConfiguredProviders(results: ConfigValidationResult[]): Provider[] {
  return results.filter((result) => result.isValid).map((result) => result.provider);
}
 
/**
 * Logs configuration validation results in a user-friendly format
 */
export function logConfigurationStatus(results: ConfigValidationResult[]): void {
  console.log('\n=== Provider Configuration Status ===');
 
  const configured = results.filter((r) => r.isValid);
  const missing = results.filter((r) => !r.isValid);
 
  if (configured.length > 0) {
    console.log('\n✅ Configured providers:');
    configured.forEach((result) => {
      console.log(`   ${result.provider}: Ready`);
    });
  }
 
  if (missing.length > 0) {
    console.log('\n⚠️  Skipped providers (missing configuration):');
    missing.forEach((result) => {
      console.log(`   ${result.provider}: ${result.reason}`);
    });
  }
 
  if (missing.length === results.length) {
    console.log('\n🔧 To enable providers, set the required environment variables:');
    missing.forEach((result) => {
      const req = PROVIDER_REQUIREMENTS[result.provider];
      Eif (req) {
        console.log(`   ${result.provider}: ${req.description}`);
      }
    });
    console.log('\n   Example: export GITHUB_TOKEN=ghp_your_token_here');
  }
 
  console.log('=====================================\n');
}
 
/**
 * Creates help text for provider configuration
 */
export function getConfigurationHelp(provider?: string): string {
  if (provider) {
    const req = PROVIDER_REQUIREMENTS[provider];
    if (!req) return `Unknown provider: ${provider}`;
 
    return `${provider.toUpperCase()} Configuration:
${req.description}
 
Required environment variables:
${req.requiredEnvVars.map((env) => `  - ${env}`).join('\n')}
 
Optional environment variables:
${req.optionalEnvVars.map((env) => `  - ${env}`).join('\n')}`;
  }
 
  return `Provider Configuration Help:
 
Available providers: ${Object.keys(PROVIDER_REQUIREMENTS).join(', ')}
 
Use --help <provider> for specific configuration requirements.
 
Quick setup examples:
  export GITHUB_TOKEN=ghp_your_token_here
  export GITLAB_TOKEN=glpat_your_token_here  
  export AZURE_TOKEN=your_pat_here
  export AZURE_ORG=your_org_name`;
}
 
/**
 * Check if GitHub project mapping exists in config
 */
function hasGitHubProjectMapping(): boolean {
  // In a real implementation, this would check .mcp.json for project mappings
  // For now, return false to require explicit org configuration
  return false;
}
 
/**
 * Check if Azure project mapping exists in config
 */
function hasAzureProjectMapping(): boolean {
  // In a real implementation, this would check .mcp.json for project mappings
  // For now, return false to require explicit project configuration
  return false;
}
 
/**
 * Validates configuration and provides helpful error messages for CLI usage
 */
export function validateConfigurationForCLI(): {
  isValid: boolean;
  configuredProviders: Provider[];
  errors: string[];
  warnings: string[];
} {
  const results = validateAllProviderConfigs();
  const configured = getConfiguredProviders(results);
  const errors: string[] = [];
  const warnings: string[] = [];
 
  results.forEach((result) => {
    if (!result.isValid) {
      if (result.status === 'missing-token' || result.status === 'invalid-config') {
        errors.push(result.reason ?? 'Configuration error');
      } else E{
        warnings.push(result.reason ?? 'Configuration warning');
      }
    }
  });
 
  return {
    isValid: configured.length > 0,
    configuredProviders: configured,
    errors,
    warnings,
  };
}