UNPKG

static-code-analyzer

Version:

Universal static code analysis tool for calculating API operation costs across multiple frameworks (NestJS, Express, Fastify)

283 lines (226 loc) • 7.12 kB
typescript // Detects parallel operations automatically const [user, profile, permissions] = await Promise.all([ prisma.user.findUnique({ where: { id } }), // Cost: 1 prisma.profile.findUnique({ where: { userId: id } }), // Cost: 1 prisma.permission.findMany({ where: { userId: id } }) // Cost: 1 ]); // Total parallel cost: 1 (max of group, not sum) // vs Sequential (would be cost: 3) const user = await prisma.user.findUnique({ where: { id } }); const profile = await prisma.profile.findUnique({ where: { userId: id } }); const permissions = await prisma.permission.findMany({ where: { userId: id } }); ``` ### **Cost Variance Analysis** Identifies methods with high cost variance between execution paths: ``` āš ļø High cost variance (2-6) - Consider optimizing expensive paths šŸ’” Consider caching frequently accessed data šŸŽÆ Use Promise.all() for independent operations ``` ### **Framework Detection** Automatically detects and configures for popular ORMs and frameworks: - **Prisma**: `prisma.model.operation()` - **TypeORM**: `repository.operation()` - **Mongoose**: `Model.operation()` - **Supabase**: `supabase.from().operation()` - **HTTP Clients**: `axios.get()`, `fetch()` - **Cache**: Redis operations ## šŸ”„ Development Workflow ### **Development Mode** ```bash # Watch files during development sca watch ./src/users/users.service.ts --framework nestjs # Outputs real-time cost analysis as you code šŸ‘€ Watching ./src/users/users.service.ts for changes... šŸ”„ File changed, re-analyzing... āœ… Method: createUser - Cost: 2-3 requests (2 paths) āš ļø Method: updateUser - Cost: 1-5 requests (3 paths) - High variance detected ``` ### **IDE Integration** Add to VS Code tasks (`.vscode/tasks.json`): ```json { "version": "2.0.0", "tasks": [ { "label": "Analyze API Costs", "type": "shell", "command": "sca", "args": ["file", "${file}", "--framework", "nestjs"], "group": "build", "presentation": { "echo": true, "reveal": "always" } } ] } ``` ## šŸ“ˆ Optimization Strategies ### **Recommended Patterns** 1. **Use Parallel Execution** ```typescript // āŒ Sequential (Cost: 3) const user = await getUser(id); const posts = await getPosts(id); const comments = await getComments(id); // āœ… Parallel (Cost: 1) const [user, posts, comments] = await Promise.all([ getUser(id), getPosts(id), getComments(id) ]); ``` 2. **Reduce Database Roundtrips** ```typescript // āŒ Multiple queries (Cost: N+1) const users = await prisma.user.findMany(); for (const user of users) { user.profile = await prisma.profile.findUnique({ where: { userId: user.id } }); } // āœ… Single query with relations (Cost: 1) const users = await prisma.user.findMany({ include: { profile: true } }); ``` 3. **Implement Caching** ```typescript // Add caching layer for expensive operations @Cache('user-profile', 300) // 5 minutes async getUserProfile(id: string) { return await prisma.user.findUnique({ where: { id }, include: { profile: true } }); } ``` 4. **Use Batch Operations** ```typescript // āŒ Multiple inserts (Cost: N) for (const userData of users) { await prisma.user.create({ data: userData }); } // āœ… Batch insert (Cost: 1) await prisma.user.createMany({ data: users }); ``` ## šŸ› ļø Troubleshooting ### **Common Issues** 1. **"No operations found"** - Check if your patterns match your code - Verify framework preset is correct - Add custom patterns for non-standard operations 2. **"File not found" error** - Use absolute paths or correct relative paths - Ensure TypeScript files are accessible 3. **Incorrect costs** - Update operation costs in configuration - Add custom patterns for your specific operations ### **Custom Pattern Examples** ```json { "patterns": { "custom_database": { "pattern": "myDB\\.(query|execute|find)", "defaultCost": 1, "description": "Custom database operations" }, "external_api": { "pattern": "apiClient\\.(get|post|put|delete)", "defaultCost": 2, "description": "External API calls" }, "cache_operations": { "pattern": "cache\\.(get|set|del)", "defaultCost": 0.5, "description": "Cache operations" } } } ``` ## šŸ“š API Reference ### **Core Classes** #### `ApiCostAnalyzer` ```typescript class ApiCostAnalyzer { constructor(config?: Partial<AnalyzerConfig>) setFramework(framework: string): void updateConfig(config: Partial<AnalyzerConfig>): void analyzeFile(filePath: string): FileAnalysis analyzeFiles(filePaths: string[]): FileAnalysis[] analyzeProject(projectPath: string, patterns?: string[]): ProjectAnalysis } ``` #### `ReportGenerator` ```typescript class ReportGenerator { static generateFileReport(analysis: FileAnalysis, format: ReportFormat): string static generateProjectReport(files: FileAnalysis[], format: ReportFormat): string static saveReport(content: string, filePath: string): void } ``` ### **Configuration Types** ```typescript interface AnalyzerConfig { operations: Record<string, number>; patterns: Record<string, PatternConfig>; parallelExecutionPatterns: string[]; ignorePatterns: string[]; costMultipliers: CostMultipliers; methodCosts?: Record<string, MethodCostConfig>; } interface FileAnalysis { filePath: string; fileName: string; methods: MethodAnalysis[]; summary: FileSummary; } interface MethodAnalysis { methodName: string; className?: string; totalPaths: number; paths: ExecutionPath[]; summary: MethodSummary; recommendations: string[]; } ``` ## šŸ¤ Contributing ### **Development Setup** ```bash git clone https://github.com/mtalhazulf/static-code-analyzer cd static-code-analyzer bun install bun run build bun test ``` ### **Adding Framework Support** 1. Add framework preset in `src/config.ts` 2. Define operation patterns and costs 3. Add tests for the new framework 4. Update documentation ### **Contributing Guidelines** - Follow TypeScript best practices - Add tests for new features - Update documentation - Follow semantic versioning ## šŸ“„ License MIT License - see [LICENSE](LICENSE) file for details. ## šŸ™ Acknowledgments - Built with TypeScript Compiler API - Inspired by static analysis tools like ESLint and SonarQube - Designed for modern JavaScript/TypeScript frameworks ## šŸ“ž Support - šŸ› **Issues**: [GitHub Issues](https://github.com/mtalhazulf/static-code-analyzer/issues) - šŸ“– **Documentation**: [GitHub Wiki](https://github.com/mtalhazulf/static-code-analyzer/wiki) - šŸ’¬ **Discussions**: [GitHub Discussions](https://github.com/mtalhazulf/static-code-analyzer/discussions) --- **Made with ā¤ļø for the TypeScript/JavaScript community** Start optimizing your API costs today: ```bash # Using Bun (recommended) bun install -g static-code-analyzer sca init --framework nestjs sca project ./src # Or using npm npm install -g static-code-analyzer ```