All files / src/core/file-system scan-api-dir.ts

68.75% Statements 44/64
45.71% Branches 16/35
60% Functions 6/10
67.74% Lines 42/62

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                                                                                                                                                    19x 19x 24x 24x 21x 21x         17x 17x 9x 6x 6x               14x 14x 14x   14x 1x       14x   14x 29x   29x 1x 28x   28x                   28x 1x 1x 1x   1x       27x 9x 9x 9x             13x   13x 13x 13x   13x 13x 13x       13x             13x           13x      
/**
 * API directory scanner
 * Core logic - uses Node.js fs but abstracted to be testable
 */
 
import * as fs from 'fs';
import * as path from 'path';
import {
  ROUTE_FILE_PATTERN,
  MIDDLEWARE_FILE_PATTERN,
  SOCKET_FILE_PATTERN,
  PARAM_PATTERN,
} from '../../shared/constants.js';
import type { ParsedRoute } from '../routing/route-parser.js';
import { parseRouteFile } from '../routing/route-parser.js';
import type { ParsedSocket } from '../routing/socket-parser.js';
import { parseSocketFile } from '../routing/socket-parser.js';
 
/**
 * Information about a found middleware
 */
export interface MiddlewareInfo {
  /** Absolute path of the middleware file */
  path: string;
  /** Base pattern calculated from the path (e.g., "posts", "posts/:id", "" for global) */
  basePattern: string;
}
 
/**
 * Result of API directory scan
 */
export interface ScanResult {
  routes: ParsedRoute[];
  middlewares: MiddlewareInfo[];
  sockets: ParsedSocket[];
}
 
/**
 * Calculates the base pattern of a middleware based on the path relative to apiDir
 * Example:
 * - src/api/middleware.ts -> "" (global)
 * - src/api/posts/middleware.ts -> "posts"
 * - src/api/posts/[id]/middleware.ts -> "posts/:id"
 */
function calculateMiddlewareBasePattern(middlewarePath: string, apiDir: string): string {
  // Get the directory where the middleware is located
  const middlewareDir = path.dirname(middlewarePath);
  
  // Calculate relative path from middleware directory to apiDir
  const relativePath = path.relative(apiDir, middlewareDir);
  
  // If it's at the root (apiDir), it's a global middleware
  if (!relativePath || relativePath === '.' || relativePath === '') {
    return '';
  }
  
  // Normalize separators
  let pattern = relativePath.replace(/\\/g, '/');
  
  // Remove leading/trailing slashes
  pattern = pattern.replace(/^\/+|\/+$/g, '');
  
  // Convert [id] to :id and [...ids] to *ids
  pattern = pattern.replace(PARAM_PATTERN, (match, isCatchAll, paramName) => {
    if (isCatchAll) {
      return `*${paramName}`;
    }
    return `:${paramName}`;
  });
  
  return pattern;
}
 
export function deduplicateParsedRoutes(routes: ParsedRoute[]): ParsedRoute[] {
  const seen = new Set<string>();
  return routes.filter((r) => {
    const key = `${r.method}:${r.pattern}`;
    if (seen.has(key)) return false;
    seen.add(key);
    return true;
  });
}
 
export function deduplicateParsedSockets(sockets: ParsedSocket[]): ParsedSocket[] {
  const seen = new Set<string>();
  return sockets.filter((s) => {
    if (seen.has(s.pattern)) return false;
    seen.add(s.pattern);
    return true;
  });
}
 
/**
 * Recursively scans a directory looking for route files and middlewares
 */
export function scanApiDirectory(apiDir: string): ScanResult {
  const routes: ParsedRoute[] = [];
  const middlewares: MiddlewareInfo[] = [];
  const sockets: ParsedSocket[] = [];
 
  if (!fs.existsSync(apiDir)) {
    return { routes, middlewares, sockets };
  }
  
  function scanDir(currentDir: string): void {
    const entries = fs.readdirSync(currentDir, { withFileTypes: true });
    
    for (const entry of entries) {
      const fullPath = path.join(currentDir, entry.name);
      
      if (entry.isDirectory()) {
        scanDir(fullPath);
      E} else if (entry.isFile()) {
        // Check if it's a middleware file
        Iif (MIDDLEWARE_FILE_PATTERN.test(entry.name)) {
          const basePattern = calculateMiddlewareBasePattern(fullPath, apiDir);
          middlewares.push({
            path: fullPath,
            basePattern,
          });
          continue;
        }
        
        // Check if it's a socket file
        if (SOCKET_FILE_PATTERN.test(entry.name)) {
          const parsed = parseSocketFile(fullPath, apiDir);
          Eif (parsed) {
            sockets.push(parsed);
          }
          continue;
        }
 
        // Check if it's a route file
        if (ROUTE_FILE_PATTERN.test(entry.name)) {
          const parsed = parseRouteFile(fullPath, apiDir);
          Eif (parsed) {
            routes.push(parsed);
          }
        }
      }
    }
  }
  
  scanDir(apiDir);
 
  const dedupedRoutes = deduplicateParsedRoutes(routes);
  routes.length = 0;
  routes.push(...dedupedRoutes);
 
  const dedupedSockets = deduplicateParsedSockets(sockets);
  sockets.length = 0;
  sockets.push(...dedupedSockets);
 
  // Sort middlewares by depth (most generic first, most specific last)
  // This ensures that when composing, global middlewares come before specific ones
  middlewares.sort((a, b) => {
    const aDepth = a.basePattern ? a.basePattern.split('/').length : 0;
    const bDepth = b.basePattern ? b.basePattern.split('/').length : 0;
    return aDepth - bDepth;
  });
 
  // Sort sockets by depth for match priority
  sockets.sort((a, b) => {
    const aDepth = a.pattern ? a.pattern.split('/').length : 0;
    const bDepth = b.pattern ? b.pattern.split('/').length : 0;
    return aDepth - bDepth;
  });
 
  return { routes, middlewares, sockets };
}