All files utils.ts

77.41% Statements 72/93
73.52% Branches 25/34
100% Functions 1/1
80.23% Lines 69/86

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                          2x   1x       4x     3x         13x           18x         4x   11x   1x     2x   1x   56x         7x   6x   81x 81x     6x 6x 6x 6x                           795x 795x 795x                 276x 276x   276x 276x               64x 64x       1x 1x   211x   211x 247x 243x   243x       211x                                                                         11x 11x 11x 11x   5x   11x       3x   3x 3x   3x       4560x             4x       3x         217x   251x       26x       19x 19x 19x 19x 19x               2x 2x   1x   2x 2x         119x     119x           5x     14x       6x 6x    
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
 
import * as ts from 'typescript';
 
import { IMPORT_RESOLVE_EXTS } from './types.js';
 
import type { NodeBudget, NodeTree, SyntaxNode } from './types.js';
 
export function canonicalScriptKind(ext: string): ts.ScriptKind {
  switch (ext) {
    case '.tsx':
      return ts.ScriptKind.TSX;
    case '.jsx':
      return ts.ScriptKind.JSX;
    case '.js':
    case '.mjs':
    case '.cjs':
      return ts.ScriptKind.JS;
    case '.ts':
    default:
      return ts.ScriptKind.TS;
  }
}
 
export function hashString(value: string): string {
  return crypto.createHash('sha1').update(value).digest('hex').slice(0, 16);
}
 
export function normalizeNodeKind(kind: ts.SyntaxKind): string {
  switch (kind) {
    case ts.SyntaxKind.Identifier:
      return 'ID';
    case ts.SyntaxKind.StringLiteral:
    case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
    case ts.SyntaxKind.TemplateMiddle:
    case ts.SyntaxKind.TemplateHead:
      return 'STR';
    case ts.SyntaxKind.NumericLiteral:
      return 'NUM';
    case ts.SyntaxKind.BigIntLiteral:
      return 'BIGINT';
    case ts.SyntaxKind.TrueKeyword:
    case ts.SyntaxKind.FalseKeyword:
      return 'BOOL';
    case ts.SyntaxKind.NullKeyword:
      return 'NULL';
    default:
      return ts.SyntaxKind[kind] || 'UNKNOWN';
  }
}
 
export function makeFingerprint(node: ts.Node, seen: WeakMap<ts.Node, string> = new WeakMap()): string {
  if (seen.has(node)) return seen.get(node)!;
 
  const tokens: string[] = [];
  const visit = (current: ts.Node): void => {
    tokens.push(normalizeNodeKind(current.kind));
    ts.forEachChild(current, visit);
  };
 
  visit(node);
  const hash = hashString(tokens.join('|'));
  seen.set(node, hash);
  return hash;
}
 
export function makeTreeSitterFingerprint(node: SyntaxNode): string {
  const tokens: string[] = [];
  const visit = (current: SyntaxNode): void => {
    tokens.push(current.type);
    for (const child of current.children) visit(child);
  };
  visit(node);
  return hashString(tokens.join('|'));
}
 
export function getLineAndCharacter(sourceFile: ts.SourceFile, node: ts.Node): { lineStart: number; lineEnd: number; columnStart: number; columnEnd: number } {
  const start = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
  const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
  return {
    lineStart: start.line + 1,
    lineEnd: end.line + 1,
    columnStart: start.character + 1,
    columnEnd: end.character + 1,
  };
}
 
export function buildNodeTree(node: ts.Node, sourceFile: ts.SourceFile, depth: number, maxNodes: NodeBudget, seen: WeakSet<ts.Node> = new WeakSet()): NodeTree | null {
  Iif (!node || maxNodes.size <= 0) return null;
  maxNodes.size -= 1;
 
  const loc = getLineAndCharacter(sourceFile, node);
  const base: NodeTree = {
    kind: ts.SyntaxKind[node.kind] || 'UNKNOWN',
    startLine: loc.lineStart,
    endLine: loc.lineEnd,
    children: [],
  };
 
  if (depth <= 0) {
    base.truncated = true;
    return base;
  }
 
  if (seen.has(node)) {
    base.truncated = true;
    return base;
  }
  seen.add(node);
 
  ts.forEachChild(node, (child) => {
    if (maxNodes.size <= 0) return;
    const childTree = buildNodeTree(child, sourceFile, depth - 1, maxNodes, seen);
    if (childTree) {
      base.children.push(childTree);
    }
  });
 
  return base;
}
 
export function buildTreeSitterTree(node: SyntaxNode, _sourceFileText: string, depth: number, maxNodes: NodeBudget, seen: WeakSet<SyntaxNode> = new WeakSet()): NodeTree | null {
  if (!node || maxNodes.size <= 0) return null;
  maxNodes.size -= 1;
 
  const base: NodeTree = {
    kind: node.type,
    startLine: node.startPosition.row + 1,
    endLine: node.endPosition.row + 1,
    children: [],
  };
 
  if (depth <= 0) {
    base.truncated = true;
    return base;
  }
 
  if (seen.has(node)) {
    base.truncated = true;
    return base;
  }
  seen.add(node);
 
  for (const child of node.children) {
    if (maxNodes.size <= 0) break;
    const childTree = buildTreeSitterTree(child, _sourceFileText, depth - 1, maxNodes, seen);
    if (childTree) {
      base.children.push(childTree);
    }
  }
 
  return base;
}
 
export function renderNodeText(node: NodeTree, indent: number = 0): string {
  const pad = '  '.repeat(indent);
  const span = node.startLine === node.endLine ? `${node.startLine}` : `${node.startLine}:${node.endLine}`;
  const trunc = node.truncated ? ' ...' : '';
  let line = `${pad}${node.kind}[${span}]${trunc}\n`;
  for (const child of node.children) {
    line += renderNodeText(child, indent + 1);
  }
  return line;
}
 
export function renderTreesText(entries: import('./types.js').TreeEntry[], generatedAt: string): string {
  const lines: string[] = [`# AST Trees — ${generatedAt}`, ''];
  for (const entry of entries) {
    lines.push(`## ${entry.package} — ${entry.file}`);
    lines.push(renderNodeText(entry.tree));
  }
  return lines.join('\n');
}
 
export function isTestFile(filePath: string): boolean {
  return (
    /(?:^|[\\/])(?:__tests__|__test__|tests)(?:[\\/]|$)/.test(filePath) ||
    /(?:\.test|_test|\.spec)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(filePath)
  );
}
 
export function toRepoPath(filePath: string, root: string): string {
  return path.relative(root, filePath).replace(/\\/g, '/');
}
 
export function normalizeDependencyValue(value: string): string {
  return path.normalize(value).replace(/\\/g, '/');
}
 
export function addToMapSet(map: Map<string, Set<string>>, key: string, value: string): void {
  if (!map.has(key)) {
    map.set(key, new Set());
  }
  map.get(key)!.add(value);
}
 
export function isRelativeImport(specifier: string): boolean {
  return specifier.startsWith('./') || specifier.startsWith('../') || specifier.startsWith('.\\') || specifier.startsWith('..\\');
}
 
export function resolveImportTarget(currentDirectory: string, specifier: string): string | null {
  const cleaned = specifier.replace(/[?#].*$/, '');
  const base = path.resolve(currentDirectory, cleaned);
  const candidates: string[] = [];
  const ext = path.extname(base);
  const jsToTsMap: Record<string, string[]> = {
    '.js': ['.ts', '.tsx'],
    '.jsx': ['.tsx'],
    '.mjs': ['.ts', '.tsx'],
    '.cjs': ['.ts', '.tsx'],
  };
 
  if (ext) {
    candidates.push(base);
    const altExts = jsToTsMap[ext];
    if (altExts) {
      const noExt = base.slice(0, -ext.length);
      for (const candidateExt of altExts) {
        const withTsExt = `${noExt}${candidateExt}`;
        candidates.push(withTsExt);
      }
    }
  } else {
    for (const ext of IMPORT_RESOLVE_EXTS) {
      candidates.push(`${base}${ext}`);
    }
    for (const ext of IMPORT_RESOLVE_EXTS) {
      candidates.push(path.join(base, `index${ext}`));
    }
  }
 
  for (const candidate of candidates) {
    if (fs.existsSync(candidate)) {
      return candidate;
    }
  }
  return null;
}
 
export function increment<T>(map: Map<string, T[]>, key: string, value: T): void {
  if (!map.has(key)) map.set(key, []);
  map.get(key)!.push(value);
}