ts-analyser
v2.0.1
Published
A comprehensive TypeScript library for analyzing and transforming TypeScript code, including imports/exports analysis, function complexity metrics, side effect detection, and automated refactoring
Downloads
264
Maintainers
Readme
ts-analyser
A comprehensive, secure TypeScript library for analyzing and transforming TypeScript code. Features advanced function analysis, side effect detection, complexity metrics, and automated refactoring capabilities with built-in security protections.
Installation
npm install ts-analyserSecurity
This library implements multiple security protections:
- Input Validation: All file paths are validated and sanitized
- Type Safety: Strict TypeScript typing prevents runtime type errors
- Memory Protection: AST traversal depth limits prevent stack overflow attacks
- Error Sanitization: Error messages don't leak sensitive file system information
- Path Security: Directory traversal protection for file operations
For security-sensitive applications, consider additional sandboxing and input validation.
Usage
import { analyze } from 'ts-analyser';
const result = analyze('/path/to/file.ts');
console.log(JSON.stringify(result, null, 2));API
Core Analysis
analyze(filename: string): AnalysisResult
Analyzes the given TypeScript file and returns an object containing imports and exports information.
ImportInfo
originalPath:string- The import path as written in the coderesolvedPath:string- The resolved absolute path of the imported moduleentities:ImportEntity[]- List of imported entities
ImportEntity
name:string- The name of the imported entityalias?:string- The alias if the import is renamed
ExportInfo
name:string- The name of the exported entitytype:string- The JavaScript type ('function', 'variable', 'class', 'interface', 'type', 'enum', 'const', 'let', 'var')signature:string- The full TypeScript signature of the export
Advanced Analysis (for Power Users)
FunctionAnalyzer
Main analyzer class providing access to all function analysis capabilities.
const analyzer = new FunctionAnalyzer(sourceCode, 'file.ts');
// Find functions
const func = analyzer.getFunctionByName('myFunction');
// Analyze complexity
const complexity = analyzer.calculateComplexity(func);
// Detect side effects
const sideEffects = analyzer.detectSideEffects(func);
// Find split opportunities
const splits = analyzer.detectSplitOpportunities(func);
// Purify function (make it pure)
const purified = analyzer.purifyFunction(func);SplitAnalyzer
Specialized analyzer for detecting function splitting opportunities.
const splitAnalyzer = new SplitAnalyzer(sourceFile);
const candidates = splitAnalyzer.detectSplitOpportunities(funcNode);
// Each candidate includes:
// - Benefit score (higher is better)
// - Input/output variables
// - Complexity metrics before/after
// - Whether it's recommendedSideEffectAnalyzer
Detects side effects and closure references in functions.
const sideEffectAnalyzer = new SideEffectAnalyzer(sourceFile);
const effects = sideEffectAnalyzer.detectSideEffects(funcNode);
// Detects:
// - Closure reads/writes
// - Parameter mutations
// - Global variable access
// - Console operations
// - DOM operations
// - Async operationsComplexityAnalyzer
Calculates various complexity metrics for functions.
const complexityAnalyzer = new ComplexityAnalyzer(sourceFile);
const metrics = complexityAnalyzer.calculateComplexity(funcNode);
// Metrics include:
// - Cyclomatic complexity
// - Lines of code
// - Maximum nesting depth
// - Parameter count
// - Variable count
// - Cognitive complexityFunctionPurifier
Transforms functions to eliminate side effects and make them pure.
const purifier = new FunctionPurifier(sourceFile);
const result = purifier.purifyFunction(funcNode);
// Result includes:
// - Transformed pure function code
// - Added parameters for closures
// - Return properties for modified variables
// - Remaining side effects that couldn't be eliminatedExample
Given a TypeScript file example.ts:
export function greet(name: string): string {
return `Hello, ${name}!`;
}
export const PI = 3.14159;
export class Calculator {
add(a: number, b: number): number {
return a + b;
}
}
import { log } from 'console';
import * as fs from 'fs';
import React from 'react';Running analyze('example.ts') returns:
{
"imports": [
{
"originalPath": "console",
"resolvedPath": "/path/to/node_modules/console/index.d.ts",
"entities": [
{
"name": "log"
}
]
},
{
"originalPath": "fs",
"resolvedPath": "/path/to/node_modules/@types/node/fs.d.ts",
"entities": [
{
"name": "*",
"alias": "fs"
}
]
},
{
"originalPath": "react",
"resolvedPath": "/path/to/node_modules/react/index.d.ts",
"entities": [
{
"name": "React"
}
]
}
],
"exports": [
{
"name": "greet",
"type": "function",
"signature": "export function greet(name: string): string {\n return `Hello, ${name}!`;\n}"
},
{
"name": "PI",
"type": "const",
"signature": "PI: 3.14159"
},
{
"name": "Calculator",
"type": "class",
"signature": "export class Calculator {\n add(a: number, b: number): number {\n return a + b;\n }\n}"
}
]
}Contributing
Contributions are welcome! Please ensure all tests pass before submitting a pull request.
License
MIT
