All files / src graph-builder.ts

85.71% Statements 66/77
70.58% Branches 24/34
91.66% Functions 11/12
89.85% Lines 62/69

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                                                29x   11x                                               11x 4x     18x 18x     18x     18x 18x 27x 27x       3x 12x 12x     3x                   22x   22x 38x 38x                                         38x 80x 80x         12x         22x                           23x 23x     23x   39x   23x   39x     39x 29x 29x   39x     39x             39x 39x   39x             39x     23x 23x 23x   23x 23x   23x 39x 57x               57x 57x           23x                                   10x                               14x                           7x 7x   7x 7x   7x 2x 2x 2x       7x                   8x    
import { estimateTokens, parseFileExports, FileContent } from '@aiready/core';
import { singularize } from './utils/string-utils';
import {
  calculateImportDepthFromEdges,
  detectGraphCycles,
  getTransitiveDependenciesFromEdges,
} from './utils/dependency-graph-utils';
import type { DependencyGraph, DependencyNode } from './types';
import { buildCoUsageMatrix } from './semantic/co-usage';
import { buildTypeGraph } from './semantic/type-graph';
import { inferDomainFromSemantics } from './semantic/domain-inference';
import { extractExportsWithAST } from './ast-utils';
import { join, dirname, normalize } from 'path';
 
/**
 * Resolve an import source to its absolute path considering the importing file's location
 */
function resolveImport(
  source: string,
  importingFile: string,
  allFiles: Set<string>
): string | null {
  // If it's not a relative import, we treat it as an external dependency for now
  // (unless it's an absolute path that exists in our set)
  if (!source.startsWith('.') && !source.startsWith('/')) {
    // Handle monorepo package imports (@aiready/*)
    Iif (source.startsWith('@aiready/')) {
      const pkgName = source.split('/')[1];
      const possiblePaths = [
        // Standard src/index.ts entry point for our packages
        join('packages', pkgName, 'src', 'index.ts'),
        join('packages', pkgName, 'src', 'index.tsx'),
        // Support for sub-exports if needed (e.g. @aiready/core/client)
        join(
          'packages',
          pkgName,
          'src',
          `${source.split('/').slice(2).join('/') || 'index'}.ts`
        ),
      ];
 
      for (const p of possiblePaths) {
        // Find the absolute path that ends with this relative path
        const absolutePkgPath = Array.from(allFiles).find((f) =>
          f.endsWith(normalize(p))
        );
        if (absolutePkgPath) return absolutePkgPath;
      }
    }
 
    if (allFiles.has(source)) return source;
    return null;
  }
 
  const dir = dirname(importingFile);
  const absolutePath = normalize(join(dir, source));
 
  // Try exact match
  Iif (allFiles.has(absolutePath)) return absolutePath;
 
  // Try common extensions
  const extensions = ['.ts', '.tsx', '.js', '.jsx'];
  for (const ext of extensions) {
    const withExt = absolutePath + ext;
    if (allFiles.has(withExt)) return withExt;
  }
 
  // Try directory index
  for (const ext of extensions) {
    const indexFile = normalize(join(absolutePath, `index${ext}`));
    Iif (allFiles.has(indexFile)) return indexFile;
  }
 
  return null;
}
 
/**
 * Auto-detect domain keywords from workspace folder structure.
 *
 * @param files - Array of file contents to analyze for folder patterns.
 * @returns Array of singularized domain keywords.
 */
export function extractDomainKeywordsFromPaths(files: FileContent[]): string[] {
  const folderNames = new Set<string>();
 
  for (const { file } of files) {
    const segments = file.split('/');
    const skipFolders = new Set([
      'src',
      'lib',
      'dist',
      'build',
      'node_modules',
      'test',
      'tests',
      '__tests__',
      'spec',
      'e2e',
      'scripts',
      'components',
      'utils',
      'helpers',
      'util',
      'helper',
      'api',
      'apis',
    ]);
 
    for (const segment of segments) {
      const normalized = segment.toLowerCase();
      if (
        normalized &&
        !skipFolders.has(normalized) &&
        !normalized.includes('.')
      ) {
        folderNames.add(singularize(normalized));
      }
    }
  }
 
  return Array.from(folderNames);
}
 
/**
 * Build a dependency graph from file contents, resolving imports and extracting metadata.
 *
 * @param files - Array of file contents to process.
 * @param options - Optional configuration for domain detection.
 * @returns Complete dependency graph with nodes, edges, and semantic matrices.
 */
export async function buildDependencyGraph(
  files: FileContent[],
  options?: { domainKeywords?: string[] }
): Promise<DependencyGraph> {
  const nodes = new Map<string, DependencyNode>();
  const edges = new Map<string, Set<string>>();
 
  const autoDetectedKeywords =
    options?.domainKeywords ?? extractDomainKeywordsFromPaths(files);
 
  const allFilePaths = new Set(files.map((f) => f.file));
 
  for (const { file, content } of files) {
    // 1. Get high-fidelity AST-based imports & exports
    const { imports: astImports } = await parseFileExports(content, file);
 
    // 2. Resolve imports to absolute paths in the graph
    const resolvedImports = astImports
      .map((i) => resolveImport(i.source, file, allFilePaths))
      .filter((path): path is string => path !== null);
 
    const importSources = astImports.map((i) => i.source);
 
    // 3. Wrap with platform-specific metadata (v0.11+)
    const exports = await extractExportsWithAST(
      content,
      file,
      { domainKeywords: autoDetectedKeywords },
      importSources
    );
 
    const tokenCost = estimateTokens(content);
    const linesOfCode = content.split('\n').length;
 
    nodes.set(file, {
      file,
      imports: importSources,
      exports,
      tokenCost,
      linesOfCode,
    });
    edges.set(file, new Set(resolvedImports));
  }
 
  const graph: DependencyGraph = { nodes, edges };
  const coUsageMatrix = buildCoUsageMatrix(graph);
  const typeGraph = buildTypeGraph(graph);
 
  graph.coUsageMatrix = coUsageMatrix;
  graph.typeGraph = typeGraph;
 
  for (const [file, node] of nodes) {
    for (const exp of node.exports) {
      const semanticAssignments = inferDomainFromSemantics(
        file,
        exp.name,
        graph,
        coUsageMatrix,
        typeGraph,
        exp.typeReferences
      );
      exp.domains = semanticAssignments;
      Iif (semanticAssignments.length > 0) {
        exp.inferredDomain = semanticAssignments[0].domain;
      }
    }
  }
 
  return graph;
}
 
/**
 * Calculate the maximum depth of the import tree for a specific file.
 *
 * @param file - File path to start depth calculation from.
 * @param graph - The dependency graph.
 * @param visited - Optional set to track visited nodes during traversal.
 * @param depth - Current recursion depth.
 * @returns Maximum depth of the import chain.
 */
export function calculateImportDepth(
  file: string,
  graph: DependencyGraph,
  visited = new Set<string>(),
  depth = 0
): number {
  return calculateImportDepthFromEdges(file, graph.edges, visited, depth);
}
 
/**
 * Retrieve all transitive dependencies for a specific file.
 *
 * @param file - File path to analyze.
 * @param graph - The dependency graph.
 * @param visited - Optional set to track visited nodes.
 * @returns Array of all reachable file paths.
 */
export function getTransitiveDependencies(
  file: string,
  graph: DependencyGraph,
  visited = new Set<string>()
): string[] {
  return getTransitiveDependenciesFromEdges(file, graph.edges, visited);
}
 
/**
 * Calculate total context budget (tokens needed to understand this file and its dependencies).
 *
 * @param file - File path to calculate budget for.
 * @param graph - The dependency graph.
 * @returns Total token count including recursive dependencies.
 */
export function calculateContextBudget(
  file: string,
  graph: DependencyGraph
): number {
  const node = graph.nodes.get(file);
  Iif (!node) return 0;
 
  let totalTokens = node.tokenCost;
  const deps = getTransitiveDependencies(file, graph);
 
  for (const dep of deps) {
    const depNode = graph.nodes.get(dep);
    Eif (depNode) {
      totalTokens += depNode.tokenCost;
    }
  }
 
  return totalTokens;
}
 
/**
 * Detect circular dependencies (cycles) within the dependency graph.
 *
 * @param graph - The dependency graph to scan.
 * @returns Array of dependency cycles (each cycle is an array of file paths).
 */
export function detectCircularDependencies(graph: DependencyGraph): string[][] {
  return detectGraphCycles(graph.edges);
}