All files classifier.ts

94.37% Statements 151/160
82.58% Branches 166/201
100% Functions 32/32
96.05% Lines 146/152

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 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563          10x                                                       36x 2x       34x 4x       30x 3x       27x 4x       23x 3x       20x 3x       17x 3x       14x   1x 1x         13x 4x       9x 1x       8x 6x     2x 2x                                 36x 36x     36x       36x     36x       5x           36x                   34x     34x     34x 34x   34x 41x 34x       34x       34x                   13x       13x         13x   13x         13x                   27x 27x   27x               27x 162x       27x         27x   48x           27x                   23x 23x   23x 23x 86x   23x 23x   44x     42x   23x                           20x 20x   20x                   20x 156x     20x       20x   40x             20x                   17x 17x   17x                     17x 135x     17x     17x   35x           17x                   14x 14x   14x 14x 53x     14x     14x   29x         14x                   9x 9x 9x   9x                 63x   9x       9x   17x         9x                   30x 30x 30x     30x 30x   30x   8x 30x             30x 3x     30x                               13x   1x   1x   1x   2x     3x     1x   1x     2x   2x   1x   1x   1x   1x                         1x   1x 1x   1x                         1x                       1x 3x 33x 2x     3x 27x       1x                               7x   1x   1x             1x   2x   1x   1x      
import type { DependencyNode, FileClassification } from './types';
 
/**
 * Constants for file classifications to avoid magic strings
 */
export const Classification = {
  BARREL: 'barrel-export' as const,
  TYPE_DEFINITION: 'type-definition' as const,
  NEXTJS_PAGE: 'nextjs-page' as const,
  LAMBDA_HANDLER: 'lambda-handler' as const,
  SERVICE: 'service-file' as const,
  EMAIL_TEMPLATE: 'email-template' as const,
  PARSER: 'parser-file' as const,
  COHESIVE_MODULE: 'cohesive-module' as const,
  UTILITY_MODULE: 'utility-module' as const,
  MIXED_CONCERNS: 'mixed-concerns' as const,
  UNKNOWN: 'unknown' as const,
};
 
/**
 * Classify a file into a specific type for better analysis context
 *
 * @param node The dependency node representing the file
 * @param cohesionScore The calculated cohesion score for the file
 * @param domains The detected domains/concerns for the file
 * @returns The determined file classification
 */
export function classifyFile(
  node: DependencyNode,
  cohesionScore: number = 1,
  domains: string[] = []
): FileClassification {
  // 1. Detect barrel exports (primarily re-exports)
  if (isBarrelExport(node)) {
    return Classification.BARREL;
  }
 
  // 2. Detect type definition files
  if (isTypeDefinition(node)) {
    return Classification.TYPE_DEFINITION;
  }
 
  // 3. Detect Next.js App Router pages
  if (isNextJsPage(node)) {
    return Classification.NEXTJS_PAGE;
  }
 
  // 4. Detect Lambda handlers
  if (isLambdaHandler(node)) {
    return Classification.LAMBDA_HANDLER;
  }
 
  // 5. Detect Service files
  if (isServiceFile(node)) {
    return Classification.SERVICE;
  }
 
  // 6. Detect Email templates
  if (isEmailTemplate(node)) {
    return Classification.EMAIL_TEMPLATE;
  }
 
  // 7. Detect Parser/Transformer files
  if (isParserFile(node)) {
    return Classification.PARSER;
  }
 
  // 8. Detect Session/State management files
  if (isSessionFile(node)) {
    // If it has high cohesion, it's a cohesive module
    Eif (cohesionScore >= 0.25 && domains.length <= 1)
      return Classification.COHESIVE_MODULE;
    return Classification.UTILITY_MODULE; // Group with utility for now
  }
 
  // 9. Detect Utility modules (multi-domain but functional purpose)
  if (isUtilityModule(node)) {
    return Classification.UTILITY_MODULE;
  }
 
  // 10. Detect Config/Schema files
  if (isConfigFile(node)) {
    return Classification.COHESIVE_MODULE;
  }
 
  // Cohesion and Domain heuristics
  if (domains.length <= 1 && domains[0] !== 'unknown') {
    return Classification.COHESIVE_MODULE;
  }
 
  Eif (domains.length > 1 && cohesionScore < 0.4) {
    return Classification.MIXED_CONCERNS;
  }
 
  if (cohesionScore >= 0.7) {
    return Classification.COHESIVE_MODULE;
  }
 
  return Classification.UNKNOWN;
}
 
/**
 * Detect if a file is a barrel export (index.ts)
 *
 * @param node The dependency node to check
 * @returns True if the file appears to be a barrel export
 */
export function isBarrelExport(node: DependencyNode): boolean {
  const { file, exports } = node;
  const fileName = file.split('/').pop()?.toLowerCase();
 
  // Barrel files are typically named index.ts or index.js
  const isIndexFile = fileName === 'index.ts' || fileName === 'index.js';
 
  // Small file with many exports is likely a barrel
  const isSmallAndManyExports =
    node.tokenCost < 1000 && (exports || []).length > 5;
 
  // RE-EXPORT HEURISTIC for non-index files
  const isReexportPattern =
    (exports || []).length >= 5 &&
    (exports || []).every(
      (e) =>
        e.type === 'const' ||
        e.type === 'function' ||
        e.type === 'type' ||
        e.type === 'interface'
    );
 
  return !!isIndexFile || !!isSmallAndManyExports || !!isReexportPattern;
}
 
/**
 * Detect if a file is primarily type definitions
 *
 * @param node The dependency node to check
 * @returns True if the file appears to be primarily types
 */
export function isTypeDefinition(node: DependencyNode): boolean {
  const { file } = node;
 
  // Check file extension
  Iif (file.endsWith('.d.ts')) return true;
 
  // Check if all exports are types or interfaces
  const nodeExports = node.exports || [];
  const hasExports = nodeExports.length > 0;
  const areAllTypes =
    hasExports &&
    nodeExports.every((e) => e.type === 'type' || e.type === 'interface');
  const allTypes: boolean = !!areAllTypes;
 
  // Check if path includes 'types' or 'interfaces'
  const isTypePath =
    file.toLowerCase().includes('/types/') ||
    file.toLowerCase().includes('/interfaces/') ||
    file.toLowerCase().includes('/models/');
 
  return allTypes || (isTypePath && hasExports);
}
 
/**
 * Detect if a file is a utility module
 *
 * @param node The dependency node to check
 * @returns True if the file appears to be a utility module
 */
export function isUtilityModule(node: DependencyNode): boolean {
  const { file } = node;
 
  // Check if path includes 'utils', 'helpers', etc.
  const isUtilPath =
    file.toLowerCase().includes('/utils/') ||
    file.toLowerCase().includes('/helpers/') ||
    file.toLowerCase().includes('/util/') ||
    file.toLowerCase().includes('/helper/');
 
  const fileName = file.split('/').pop()?.toLowerCase();
  const isUtilName =
    fileName?.includes('utils.') ||
    fileName?.includes('helpers.') ||
    fileName?.includes('util.') ||
    fileName?.includes('helper.');
 
  return !!isUtilPath || !!isUtilName;
}
 
/**
 * Detect if a file is a Lambda/API handler
 *
 * @param node The dependency node to check
 * @returns True if the file appears to be a Lambda handler
 */
export function isLambdaHandler(node: DependencyNode): boolean {
  const { file, exports } = node;
  const fileName = file.split('/').pop()?.toLowerCase();
 
  const handlerPatterns = [
    'handler',
    '.handler.',
    '-handler.',
    'lambda',
    '.lambda.',
    '-lambda.',
  ];
  const isHandlerName = handlerPatterns.some((pattern) =>
    fileName?.includes(pattern)
  );
 
  const isHandlerPath =
    file.toLowerCase().includes('/handlers/') ||
    file.toLowerCase().includes('/lambdas/') ||
    file.toLowerCase().includes('/lambda/') ||
    file.toLowerCase().includes('/functions/');
 
  const hasHandlerExport = (exports || []).some(
    (e) =>
      e.name.toLowerCase() === 'handler' ||
      e.name.toLowerCase() === 'main' ||
      e.name.toLowerCase() === 'lambdahandler' ||
      e.name.toLowerCase().endsWith('handler')
  );
 
  return !!isHandlerName || !!isHandlerPath || !!hasHandlerExport;
}
 
/**
 * Detect if a file is a service file
 *
 * @param node The dependency node to check
 * @returns True if the file appears to be a service file
 */
export function isServiceFile(node: DependencyNode): boolean {
  const { file, exports } = node;
  const fileName = file.split('/').pop()?.toLowerCase();
 
  const servicePatterns = ['service', '.service.', '-service.', '_service.'];
  const isServiceName = servicePatterns.some((pattern) =>
    fileName?.includes(pattern)
  );
  const isServicePath = file.toLowerCase().includes('/services/');
  const hasServiceNamedExport = (exports || []).some(
    (e) =>
      e.name.toLowerCase().includes('service') ||
      e.name.toLowerCase().endsWith('service')
  );
  const hasClassExport = (exports || []).some((e) => e.type === 'class');
 
  return (
    !!isServiceName ||
    !!isServicePath ||
    (!!hasServiceNamedExport && !!hasClassExport)
  );
}
 
/**
 * Detect if a file is an email template/layout
 *
 * @param node The dependency node to check
 * @returns True if the file appears to be an email template
 */
export function isEmailTemplate(node: DependencyNode): boolean {
  const { file, exports } = node;
  const fileName = file.split('/').pop()?.toLowerCase();
 
  const emailTemplatePatterns = [
    '-email-',
    '.email.',
    '_email_',
    '-template',
    '.template.',
    '_template',
    '-mail.',
    '.mail.',
  ];
  const isEmailTemplateName = emailTemplatePatterns.some((pattern) =>
    fileName?.includes(pattern)
  );
  const isEmailPath =
    file.toLowerCase().includes('/emails/') ||
    file.toLowerCase().includes('/mail/') ||
    file.toLowerCase().includes('/notifications/');
 
  const hasTemplateFunction = (exports || []).some(
    (e) =>
      e.type === 'function' &&
      (e.name.toLowerCase().startsWith('render') ||
        e.name.toLowerCase().startsWith('generate') ||
        (e.name.toLowerCase().includes('template') &&
          e.name.toLowerCase().includes('email')))
  );
 
  return !!isEmailPath || !!isEmailTemplateName || !!hasTemplateFunction;
}
 
/**
 * Detect if a file is a parser/transformer
 *
 * @param node The dependency node to check
 * @returns True if the file appears to be a parser
 */
export function isParserFile(node: DependencyNode): boolean {
  const { file, exports } = node;
  const fileName = file.split('/').pop()?.toLowerCase();
 
  const parserPatterns = [
    'parser',
    '.parser.',
    '-parser.',
    '_parser.',
    'transform',
    '.transform.',
    'converter',
    'mapper',
    'serializer',
  ];
  const isParserName = parserPatterns.some((pattern) =>
    fileName?.includes(pattern)
  );
  const isParserPath =
    file.toLowerCase().includes('/parsers/') ||
    file.toLowerCase().includes('/transformers/');
 
  const hasParseFunction = (exports || []).some(
    (e) =>
      e.type === 'function' &&
      (e.name.toLowerCase().startsWith('parse') ||
        e.name.toLowerCase().startsWith('transform') ||
        e.name.toLowerCase().startsWith('extract'))
  );
 
  return !!isParserName || !!isParserPath || !!hasParseFunction;
}
 
/**
 * Detect if a file is a session/state management file
 *
 * @param node The dependency node to check
 * @returns True if the file appears to be a session/state file
 */
export function isSessionFile(node: DependencyNode): boolean {
  const { file, exports } = node;
  const fileName = file.split('/').pop()?.toLowerCase();
 
  const sessionPatterns = ['session', 'state', 'context', 'store'];
  const isSessionName = sessionPatterns.some((pattern) =>
    fileName?.includes(pattern)
  );
  const isSessionPath =
    file.toLowerCase().includes('/sessions/') ||
    file.toLowerCase().includes('/state/');
 
  const hasSessionExport = (exports || []).some(
    (e) =>
      e.name.toLowerCase().includes('session') ||
      e.name.toLowerCase().includes('state') ||
      e.name.toLowerCase().includes('store')
  );
 
  return !!isSessionName || !!isSessionPath || !!hasSessionExport;
}
 
/**
 * Detect if a file is a configuration or schema file
 *
 * @param node The dependency node to check
 * @returns True if the file appears to be a config file
 */
export function isConfigFile(node: DependencyNode): boolean {
  const { file, exports } = node;
  const lowerPath = file.toLowerCase();
  const fileName = file.split('/').pop()?.toLowerCase();
 
  const configPatterns = [
    '.config.',
    'tsconfig',
    'jest.config',
    'package.json',
    'aiready.json',
    'next.config',
    'sst.config',
  ];
  const isConfigName = configPatterns.some((p) => fileName?.includes(p));
  const isConfigPath =
    lowerPath.includes('/config/') ||
    lowerPath.includes('/settings/') ||
    lowerPath.includes('/schemas/');
 
  const hasSchemaExports = (exports || []).some(
    (e) =>
      e.name.toLowerCase().includes('schema') ||
      e.name.toLowerCase().includes('config') ||
      e.name.toLowerCase().includes('setting')
  );
 
  return !!isConfigName || !!isConfigPath || !!hasSchemaExports;
}
 
/**
 * Detect if a file is a Next.js App Router page
 *
 * @param node The dependency node to check
 * @returns True if the file appears to be a Next.js page
 */
export function isNextJsPage(node: DependencyNode): boolean {
  const { file, exports } = node;
  const lowerPath = file.toLowerCase();
  const fileName = file.split('/').pop()?.toLowerCase();
 
  const isInAppDir =
    lowerPath.includes('/app/') || lowerPath.startsWith('app/');
  const isPageFile = fileName === 'page.tsx' || fileName === 'page.ts';
 
  if (!isInAppDir || !isPageFile) return false;
 
  const hasDefaultExport = (exports || []).some((e) => e.type === 'default');
  const nextJsExports = [
    'metadata',
    'generatemetadata',
    'faqjsonld',
    'jsonld',
    'icon',
  ];
  const hasNextJsExports = (exports || []).some((e) =>
    nextJsExports.includes(e.name.toLowerCase())
  );
 
  return !!hasDefaultExport || !!hasNextJsExports;
}
 
/**
 * Adjust cohesion score based on file classification
 *
 * @param baseCohesion The initial cohesion score
 * @param classification The file classification
 * @param node Optional dependency node for further context
 * @returns The adjusted cohesion score
 */
export function adjustCohesionForClassification(
  baseCohesion: number,
  classification: FileClassification,
  node?: DependencyNode
): number {
  switch (classification) {
    case Classification.BARREL:
      return 1;
    case Classification.TYPE_DEFINITION:
      return 1;
    case Classification.NEXTJS_PAGE:
      return 1;
    case Classification.UTILITY_MODULE: {
      if (
        node &&
        hasRelatedExportNames(
          (node.exports || []).map((e) => e.name.toLowerCase())
        )
      ) {
        return Math.max(0.8, Math.min(1, baseCohesion + 0.45));
      }
      return Math.max(0.75, Math.min(1, baseCohesion + 0.35));
    }
    case Classification.SERVICE:
      return Math.max(0.72, Math.min(1, baseCohesion + 0.3));
    case Classification.LAMBDA_HANDLER:
      return Math.max(0.75, Math.min(1, baseCohesion + 0.35));
    case Classification.EMAIL_TEMPLATE:
      return Math.max(0.72, Math.min(1, baseCohesion + 0.3));
    case Classification.PARSER:
      return Math.max(0.7, Math.min(1, baseCohesion + 0.3));
    case Classification.COHESIVE_MODULE:
      return Math.max(baseCohesion, 0.7);
    case Classification.MIXED_CONCERNS:
      return baseCohesion;
    default:
      return Math.min(1, baseCohesion + 0.1);
  }
}
 
/**
 * Check if export names suggest related functionality
 *
 * @param exportNames List of exported names
 * @returns True if names appear related
 */
function hasRelatedExportNames(exportNames: string[]): boolean {
  Iif (exportNames.length < 2) return true;
 
  const stems = new Set<string>();
  const domains = new Set<string>();
 
  const verbs = [
    'get',
    'set',
    'create',
    'update',
    'delete',
    'fetch',
    'save',
    'load',
    'parse',
    'format',
    'validate',
  ];
  const domainPatterns = [
    'user',
    'order',
    'product',
    'session',
    'email',
    'file',
    'db',
    'api',
    'config',
  ];
 
  for (const name of exportNames) {
    for (const verb of verbs) {
      if (name.startsWith(verb) && name.length > verb.length) {
        stems.add(name.slice(verb.length).toLowerCase());
      }
    }
    for (const domain of domainPatterns) {
      Iif (name.includes(domain)) domains.add(domain);
    }
  }
 
  Eif (stems.size === 1 || domains.size === 1) return true;
 
  return false;
}
 
/**
 * Adjust fragmentation score based on file classification
 *
 * @param baseFragmentation The initial fragmentation score
 * @param classification The file classification
 * @returns The adjusted fragmentation score
 */
export function adjustFragmentationForClassification(
  baseFragmentation: number,
  classification: FileClassification
): number {
  switch (classification) {
    case Classification.BARREL:
      return 0;
    case Classification.TYPE_DEFINITION:
      return 0;
    case Classification.UTILITY_MODULE:
    case Classification.SERVICE:
    case Classification.LAMBDA_HANDLER:
    case Classification.EMAIL_TEMPLATE:
    case Classification.PARSER:
    case Classification.NEXTJS_PAGE:
      return baseFragmentation * 0.2;
    case Classification.COHESIVE_MODULE:
      return baseFragmentation * 0.3;
    case Classification.MIXED_CONCERNS:
      return baseFragmentation;
    default:
      return baseFragmentation * 0.7;
  }
}