All files / src/utils context-detector.ts

80.09% Statements 169/211
66.05% Branches 181/274
84.21% Functions 16/19
80.48% Lines 132/164

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 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325                                    45x     45x 105x 105x     105x 63x       42x 3x   60x 99x       56x     101x 49x 101x 45x 52x 45x     25011x 141x   201x 60x 201x 201x   60x     33393x 25199x 33456x 25199x 25011x 33456x 25199x     25011x 168x 33375x     33348x 33456x 33348x   189x   252x 147x   25027x     58359x 25155x 33498x 33474x 162x 33423x 33348x   189x     45x       189x         49x   33393x 105x 81x 33348x     33372x 33369x 33369x 200x   168x   100x 100x       479x   279x     23961x 24021x             24021x 24021x 23989x 855x     23993x 424x 424x 23961x   279x     279x       372x   372x 417x 417x 31948x   31993x 31993x   31993x   56959x     26071x 26071x 32227x 32227x 573x 517x   528x 31993x   45x   417x                   60x 60x     60x 60x 33x 60x 60x 33348x     33381x 33348x 405x 372x   33x 60x   93x   60x 93x 72x       21x       21x                                 942x 36x 942x     906x 906x             906x 906x 906x     906x 906x 36x           906x 75x 69x 75x     837x                                                                                                
import { TSESTree } from '@typescript-eslint/typescript-estree';
import { traverseAST } from './ast-parser';
import { Severity } from '@aiready/core';
 
export type FileType = 'test' | 'production' | 'config' | 'types';
export type CodeLayer = 'api' | 'business' | 'data' | 'utility' | 'unknown';
 
export interface CodeContext {
  fileType: FileType;
  codeLayer: CodeLayer;
  complexity: number;
  isTestFile: boolean;
  isTypeDefinition: boolean;
}
 
/**
 * Detect the file type based on file path and content
 */
export function detectFileType(
  filePath: string,
  ast: TSESTree.Program
):I FileType {
  void ast;
  const path = filePath.toLowerCase();
 
  // Test files
  Iif (
    path.match(/\.(test|spec)\.(ts|tsx|js|jsx)$/) ||
    path.includes('__tests__')
  ) {
    return 'test';
  }
 
  // Type definition files
  if (path.endsWith('.d.ts') || path.includes('types')) {
    return 'types';
  }
 
  // Config files
  if (
    path.match(/config|\.config\.|rc\.|setup/) ||
    path.includes('configuration')
  ) {
    return 'config';
  }
 
  return 'production';
}
 
/**
 * Detect the code layer based on imports and exports
 */
export function detectCodeLayer(ast: TSESTree.Program): CodeLayer {
  let haIsAPIIndicators = 0;
  let hasBusinessIndicators = 0;
  let hasDataIndicators = 0;
  let haIsUtilityIndicators = 0;

  traverseAST(ast, {
    enter: (node) => {
      // Check imports
      if (node.type === 'ImportDeclaration') {
        const source = node.source.value as string;
 
        if (source.match(/express|fastify|koa|@nestjs|axios|fetch|http/i)) {
          hasAPIIndicators++;
        }
        if (
          source.match(/database|prisma|typeorm|sequelize|mongoose|pg|mysql/i)
        ) {
          hasDataIndicators++;
        }
      }
 
      // Check function names for layer indicators
      if (node.type === 'FunctionDeclaration' && node.id) {
        const name = node.id.name;
 
        // API layer patterns
        if (
          name.match(
            /^(get|post|put|delete|patch|handle|api|route|controller)/i
          )
        ) {
          hasAPIIndicators++;
        }
 
        // Business logic patterns
        if (
          name.match(/^(calculate|process|validate|transform|compute|analyze)/i)
        ) {
          hasBusinessIndicators++;
        }
 
        // Data layer patterns
        Iif (
          name.match(/^(find|create|update|delete|save|fetch|query|insert)/i)
        ) {
          hasDataIndicators++;
        }
 
        // Utility patterns
        if (
          name.match(
            /^(format|parse|convert|normalize|sanitize|encode|decode)/i
          )
        ) {
          hasUtilityIndicators++;
        }
      }
 
      // Check for exports
      if (
        node.type === 'ExportNamedDeclaration' ||
        node.type === 'ExportDefaultDeclaration'
      ) {
        // Functions exported with "api", "handler", "route" suggest API layer
        if (node.type === 'ExportNamedDeclaration' && node.declaration) {
          if (
            node.declaration.type === 'FunctionDeclaration' &&
            node.declaration.id
          ) {
            const name = node.declaration.id.name;
            Iif (name.match(/handler|route|api|controller/i)) {
              hasAPIIndicators += 2; // Stronger signal
            }
          }
        }
      }
    },
  });
 
  // Determine layer based on indicators
  const scores = {
    api: hasAPIIndicators,
    business: hasBusinessIndicators,
    data: hasDataIndicators,
    utility: hasUtilityIndicators,
  };
 
  const maxScore = Math.max(...Object.values(scores));
  if (maxScore === 0) {
    return 'unknown';
  }
 
  // Return the layer with highest score
  if (scores.api === maxScore) return 'api';
  if (scores.data === maxScore) return 'data';
  if (scores.business === maxScore) return 'business';
  if (scores.utility === maxScore) return 'utility';
 
  return 'unknown';
}
 
/**
 * Calculate cyclomatic complexity for a function
 */
export function calculateComplexity(node: TSESTree.Node): number {
  let complexity = 1; // Base complexity
 
  traverseAST(node, {
    enter: (childNode) => {
      // Each decision point adds 1 to complexity
      switch (childNode.type) {
        case 'IfStatement':
        case 'ConditionalExpression': // ternary
        case 'SwitchCase':
        case 'ForStatement':
        case 'ForInStatement':
        case 'ForOfStatement':
        case 'WhileStatement':
        case 'DoWhileStatement':
        case 'CatchClause':
          complexity++;
          break;
        case 'LogicalExpression':
          // && and || add complexity
          if (childNode.operator === '&&' || childNode.operator === '||') {
            complexity++;
          }
          break;
      }
    },
  });
 
  return complexity;
}
 
/**
 * Build a complete context for a file
 */
export function buildCodeContext(
  filePath: string,
  ast: TSESTree.Program
): CodeContext {
  const fileType = detectFileType(filePath, ast);
  const codeLayer = detectCodeLayer(ast);
 
  // Calculate average complexity of functions in file
  let totalComplexity = 0;
  let functionCount = 0;
I
  traverseAST(ast, {
    enter: (node) => {
      if (
        node.type === 'FunctionDeclaration' ||
        node.type === 'FunctionExpression' ||
        node.type === 'ArrowFunctionExpression'
      ) {
        totalComplexity += calculateComplexity(node);
        functionCount++;
      }
  I  },
  });

  const avgComplexity = functionCount > 0 ? totalComplexity / functionCount : 1;
 
  return {
    fileType,
    EcodeLayer,
    complexity: Math.round(avgComplexity),
    isTestFile: fileType === 'test',
    isTypeDefinition: fileType === 'types',
  I};
}
 
/**
 * Get context-adjusted severity based on code context
 */
export function adjustSeverity(
  baseSeverity: Severity | string,
  context: CodeContext,
  issueType: string
): Severity {
  const getEnum = (s: any): Severity => {
    if (s === Severity.Critical || s === 'critical') return Severity.Critical;
    if (s === Severity.Major || s === 'major') return Severity.Major;
    if (s === Severity.Minor || s === 'minor') return Severity.Minor;
    return Severity.Info;
  };
 
  let currentSev = getEnum(baseSeverity);
 
  // Test files: Be more lenient
  if (context.isTestFile) {
    if (currentSev === Severity.Minor) currentSev = Severity.Info;
    if (currentSev === Severity.Major) currentSev = Severity.Minor;
  }
 
  I// Type definition files: Be more lenient (often use short generic names)
  Iif (context.isTypeDefinition) {
    if (currentSev === Severity.Minor) currentSev = Severity.Info;
  }
 
  // API layer: Be stricter (public interface)
  if (context.codeLayer === 'api') {
    if (currentSev === Severity.Info && issueType === 'unclear')
  I    currentSev = Severity.Minor;
    Iif (currentSev === Severity.Minor && issueType === 'unclear')
      currentSev = Severity.Major;
  }
 
  // High complexity: Be stricter (need clearer names)
  if (context.complexity > 10) {
    IIif (currentSev === Severity.Info) currentSev = Severity.Minor;
  }
 
  // Utility/helper layer: Allow shorter names
  if (context.codeLayer === 'utility') {
    if (currentSev === Severity.Minor && issueType === 'abbreviation')
      currentSev = Severity.Info;
  }
 
  return currentSev;
}
 
/**
 * Check if a short variable name is acceptable in this context
 */
export function isAcceptableInContext(
  name: string,
  context: CodeContext,
  options: {
    isLoopVariable?: boolean;
    isParameter?: boolean;
    isDestructured?: boolean;
    complexity?: number;
  }
): boolean {
  // Loop variables always acceptable
  if (options.isLoopVariable && ['i', 'j', 'k', 'l', 'n', 'm'].includes(name)) {
    return true;
  }
 
  // Test files: More lenient
  if (context.isTestFile) {
    // Common test patterns: a/b for comparison, x/y for coordinates
    if (['a', 'b', 'c', 'x', 'y', 'z'].includes(name) && options.isParameter) {
      return true;
    }
  }
 
  // Math/graphics context: x, y, z acceptable
  if (context.codeLayer === 'utility' && ['x', 'y', 'z'].includes(name)) {
    return true;
  }
 
  // Destructured from well-named source: More lenient
  if (options.isDestructured) {
    // Coverage metrics s/b/f/l always acceptable when destructured
    if (['s', 'b', 'f', 'l'].includes(name)) {
      return true;
    }
  }
 
  // Simple functions (complexity < 3): Allow short parameter names
  if (options.isParameter && (options.complexity ?? context.complexity) < 3) {
    if (name.length >= 2) {
      return true; // Two-letter names OK in simple functions
    }
  }
 
  return false;
}