codetraverse-bridge
v0.8.0
Published
Node.js bridge for CodeTraverse Python static analysis tool
Downloads
24
Maintainers
Readme
CodeTraverse Bridge
A self-contained Node.js bridge for CodeTraverse static analysis. This package bundles everything needed - just install and go!
Installation
npm install codetraverse-bridgePrerequisites:
- Python 3.8+ (the bridge auto-installs Python dependencies)
- Node.js 14+
What's Included:
✅ Complete CodeTraverse Python codebase
✅ Automatic dependency installation
✅ TypeScript interfaces
✅ Cross-platform support
Quick Start
import { CodeTraverseBridge } from '@codetraverse/bridge';
const bridge = new CodeTraverseBridge();
// Analyze a single file
const components = await bridge.analyzeFile('./src/utils.ts', 'typescript');
console.log(`Found ${components.length} components`);
// Analyze entire workspace
const graphData = await bridge.analyzeWorkspace('./src', {
language: 'typescript'
});
console.log(`Graph has ${graphData.nodes.length} nodes, ${graphData.edges.length} edges`);API Reference
CodeTraverseBridge
Main class providing the bridge functionality.
Constructor
new CodeTraverseBridge(config?: BridgeConfig)Configuration options:
interface BridgeConfig {
pythonPath?: string; // Path to Python executable (default: 'python')
codetraversePath?: string; // Path to CodeTraverse module (default: 'codetraverse')
timeout?: number; // Process timeout in ms (default: 60000)
workingDirectory?: string; // Working directory (default: process.cwd())
}Methods
analyzeFile(filePath: string, language: Language): Promise<Component[]>
Analyze a single source code file and return extracted components.
Parameters:
filePath: Absolute path to the source filelanguage: Programming language ('typescript','python','rust','golang','haskell','rescript')
Returns: Array of extracted components (functions, classes, types, etc.)
Example:
const components = await bridge.analyzeFile('./src/utils.ts', 'typescript');
components.forEach(comp => {
console.log(`${comp.kind}: ${comp.name} at lines ${comp.start_line}-${comp.end_line}`);
});analyzeWorkspace(rootPath: string, options: AnalysisOptions): Promise<GraphData>
Analyze an entire workspace and return the dependency graph.
Parameters:
rootPath: Root directory of the projectoptions: Analysis configuration
interface AnalysisOptions {
language: Language;
outputBase?: string; // Output directory for component files (default: 'fdep')
graphDir?: string; // Output directory for graph files (default: 'graph')
force?: boolean; // Force reanalysis if output exists
}Returns: Graph data with nodes and edges
Example:
const graph = await bridge.analyzeWorkspace('./my-project', {
language: 'typescript',
outputBase: 'analysis',
graphDir: 'graphs'
});
console.log(`Found ${graph.nodes.length} components`);
console.log(`Found ${graph.edges.length} relationships`);analyzeWorkspaceComponents(rootPath: string, options: AnalysisOptions): Promise<Component[]>
Like analyzeWorkspace but returns raw components instead of graph structure.
findPath(graphPath: string, fromComponent: string, toComponent: string): Promise<PathResult>
Find the shortest path between two components in a dependency graph.
Parameters:
graphPath: Path to GraphML file (generated by workspace analysis)fromComponent: Fully-qualified source component IDtoComponent: Fully-qualified target component ID
Example:
const result = await bridge.findPath(
'graphs/repo_function_calls.graphml',
'src/utils::helper',
'src/main::main'
);
if (result.found) {
console.log('Path:', result.path?.join(' → '));
}getNeighbors(graphPath: string, component: string): Promise<NeighborResult>
Get direct neighbors (incoming and outgoing edges) for a component.
validateSetup(): Promise<void>
Validate that Python and CodeTraverse are properly installed and accessible.
getSupportedLanguages(): Language[]
Get list of supported programming languages.
isLanguageSupported(language: string): boolean
Check if a language is supported.
Component Types
The bridge provides strongly-typed interfaces for all component types:
// Base component interface
interface BaseComponent {
kind: ComponentKind;
name: string;
module: string;
start_line: number;
end_line: number;
full_component_path: string;
jsdoc?: string;
}
// Specific component types
interface FunctionComponent extends BaseComponent {
kind: 'function';
parameters: Parameter[];
type_signature: string | null;
function_calls: FunctionCall[];
}
interface ClassComponent extends BaseComponent {
kind: 'class';
function_calls: FunctionCall[];
bases?: string[];
implements?: string[];
}
// ... other component typesGraph Data Structure
interface GraphData {
nodes: GraphNode[];
edges: GraphEdge[];
}
interface GraphNode {
id: string;
category: string;
location: ComponentLocation;
// ... other properties
}
interface GraphEdge {
from: string;
to: string;
relation: string; // 'calls', 'extends', 'implements', etc.
}Error Handling
The bridge provides specific error types for different scenarios:
try {
await bridge.analyzeFile('./nonexistent.ts', 'typescript');
} catch (error) {
if (error instanceof FileNotFoundError) {
console.log('File not found:', error.filePath);
} else if (error instanceof PythonProcessError) {
console.log('Python error:', error.stderr);
} else if (error instanceof InvalidLanguageError) {
console.log('Unsupported language:', error.language);
}
}VSCode Extension Integration
This bridge is designed for easy integration with VSCode extensions:
// In your VSCode extension
import * as vscode from 'vscode';
import { CodeTraverseBridge } from '@codetraverse/bridge';
export function activate(context: vscode.ExtensionContext) {
const bridge = new CodeTraverseBridge();
// Register command to analyze current file
const analyzeCommand = vscode.commands.registerCommand(
'extension.analyzeCurrentFile',
async () => {
const editor = vscode.window.activeTextEditor;
if (!editor) return;
const filePath = editor.document.fileName;
const language = getLanguageFromExtension(filePath);
try {
const components = await bridge.analyzeFile(filePath, language);
// Display results in UI
showComponentsInTreeView(components);
} catch (error) {
vscode.window.showErrorMessage(`Analysis failed: ${error.message}`);
}
}
);
context.subscriptions.push(analyzeCommand);
}Examples
See the examples directory for complete usage examples:
basic-usage.js- Basic API usage- More examples coming soon...
Supported Languages
- TypeScript (
.ts) - Python (
.py) - Rust (
.rs) - Go (
.go) - Haskell (
.hs) - ReScript (
.res)
Performance Notes
- Single file analysis is fast (typically < 1 second)
- Workspace analysis time scales with project size
- Results are cached by the Python backend for faster subsequent runs
- Use
force: trueoption to ignore cache and reanalyze
Troubleshooting
"Python process failed" errors
- Ensure Python is in your PATH:
python --version - Ensure CodeTraverse is installed:
python -m codetraverse --help - Check that required Tree-sitter parsers are installed
Timeout errors
Increase timeout for large projects:
const bridge = new CodeTraverseBridge({
timeout: 300000 // 5 minutes
});Path resolution issues
Use absolute paths when possible:
import * as path from 'path';
const absolutePath = path.resolve('./my-project');
await bridge.analyzeWorkspace(absolutePath, options);Contributing
This bridge is part of the CodeTraverse project. See the main README for contribution guidelines.
License
MIT License - see LICENSE file.
