# loqatevars

## Overview

This is an npm module named "loqatevars" designed to help locate errant variable use in LLM-created applications. The module scans JavaScript codebases to identify files that mix variable declarations (const) with environment variable access (process.env), enabling developers to centralize variable declarations and environment variable naming instead of having them scattered and mutated throughout the codebase. It provides both programmatic API and CLI interface for code quality auditing and refactoring guidance.

## System Architecture

### Frontend Architecture
- **Type**: N/A (This is a library module, not a frontend application)

### Backend Architecture
- **Type**: Node.js library module
- **Entry Point**: `index.js` serves as the main export file
- **Organization**: Modular structure with separate library directory
- **Export Strategy**: CommonJS module exports with centralized export management

### Key Design Decisions
1. **Modular Structure**: Separates library code into `lib/` directory for better organization
2. **Centralized Exports**: Uses `index.js` to consolidate and expose public API
3. **Error Handling**: Implements comprehensive input validation and error throwing
4. **Documentation**: JSDoc comments for all public functions
5. **CLI Support**: Provides command-line interface with flexible options
6. **Recursive Scanning**: Walks directory trees while respecting ignore patterns

## Key Components

### Core Files
- **`index.js`**: Main entry point that re-exports scanner functions from `lib/utils.js`
- **`lib/utils.js`**: Core scanner implementation with file system operations
- **`cli.js`**: Command-line interface for terminal usage
- **Tests**: Automated test suite executed with Jest via `npm test`

### Scanner Functions
1. **`findMatchingFiles(dir, ignoreFiles, extensions)`**: Identifies files with meaningful variable declarations or process.env usage, intelligently excluding files that only contain import/require const declarations
2. **`findMatchingFilesDetailed(dir, ignoreFiles, extensions)`**: Enhanced analysis providing detailed const usage breakdown, distinguishing between import const and variable const declarations to help prioritize refactoring efforts

### Error Handling Strategy
- Input type validation for all functions
- Descriptive error messages
- Defensive programming practices
- Empty input validation

## Data Flow

```
External Consumer
    ↓
index.js (main entry) ←→ cli.js (CLI interface)
↓
lib/utils.js (scanner implementation)
↓
File System (recursive directory walking)
```

1. Consumer imports scanner functions from main `index.js` or uses CLI via `cli.js`
2. `index.js` re-exports scanner functions from `lib/utils.js`
3. Scanner implementation walks file system recursively
4. Returns matching files as arrays of file paths or detailed objects

## External Dependencies

### Runtime Dependencies
- **None**: Pure Node.js implementation using only built-in modules

### Development Dependencies
- **None**: No external testing frameworks or build tools required

### Built-in Node.js Modules Used
- **fs**: File system operations for reading files and directories
- **path**: Path manipulation and resolution utilities

## Recent Changes

### January 2025 - Critical Bug Fixes
- **Scope Tracking Bug Fix**: Fixed logic in `analyzeConstUsage()` to properly distinguish between top-level and nested const declarations. Only top-level const declarations are now considered for flagging, correctly ignoring const declarations inside functions, classes, and blocks.
- **Package Compatibility**: Resolved yargs ES module compatibility issue by downgrading from v18+ to v17.7.2 and pinning the exact version (removed caret) to prevent future compatibility breaks.
- **Test Suite**: All 26 test suites with 64 tests now pass successfully after fixes.

## Deployment Strategy

### Package Distribution
- **Type**: NPM package template
- **Installation**: Git-based installation with remote URL setup
- **Structure**: Standard npm module layout ready for publication

### Development Workflow
1. Clone template repository
2. Update git remote to target repository
3. Implement custom utility functions
4. Run tests with `npm test`
5. Publish to npm registry

## User Preferences

Preferred communication style: Simple, everyday language.

## Changelog

```
Changelog:
- June 29, 2025. Initial setup as npm module template
- June 29, 2025. Complete transformation to loqatevars functionality
  - Replaced utility functions with codebase scanning capabilities
  - Added findMatchingFiles() and findMatchingFilesDetailed() functions
  - Implemented CLI interface with flexible options
  - Added comprehensive test suite with sample file generation
  - Enhanced error handling for file system operations
- June 29, 2025. Updated module name to "loqatevars"
  - Updated all documentation and CLI references
  - Clarified module purpose as variable locator for LLM-generated code
  - Added comprehensive documentation explaining refactoring patterns
  - Established clear use case: helping centralize scattered variable declarations
- June 30, 2025. Fixed scanning logic and implemented proper CLI commands
  - Changed from AND to OR logic (finds files with either const OR process.env)
  - Restructured CLI with command-based interface (scan, detailed, help)
  - Created proper npm package with bin configuration
  - Successfully implemented "loqatevars" command with npm link
  - Updated all documentation to use proper command syntax
- July 1, 2025. Enhanced const analysis to exclude import/require declarations
  - Added smart const analysis that distinguishes import const from variable const
  - Files with only import/require const declarations are no longer flagged
  - Enhanced detailed analysis shows breakdown of const usage types
  - Improved accuracy in identifying files that need variable centralization
  - Added comprehensive test cases demonstrating the enhanced logic
- July 1, 2025. Added file count display to basic scan output
  - Basic scan now shows file count after blank line (e.g., "Found 5 files")
  - Enhanced user feedback for both CLI and programmatic usage
  - Maintains clean output format with proper spacing
- July 1, 2025. Added frontend directory exclusion
  - Scanner now ignores common frontend directories (public, static, assets, dist, build, etc.)
  - Excludes framework-specific frontend folders (components, views, pages, styles, etc.)
  - Focuses scanning on backend/server code where variable centralization is most relevant
  - Improves scan accuracy by avoiding frontend-specific JavaScript patterns
```

## Usage Examples

### Programmatic Usage
```javascript
const { findMatchingFiles, findMatchingFilesDetailed } = require('loqatevars');

// Basic usage - returns an array of file paths
const matches = findMatchingFiles('./src');
console.log(matches); // ["src/config.js", "src/server.js"]

// Detailed usage - returns object with statistics
const detailed = findMatchingFilesDetailed('./src');
console.log(detailed.summary.matchingFiles); // 2
console.log(detailed.matches[0].relativePath); // "config.js"
```

### CLI Usage
```bash
# Basic scan
node cli.js ./src

# Detailed output
node cli.js ./src --detailed

# Custom ignore files
node cli.js ./src --ignore "spec.js,localVars.js"

# Multiple file extensions
node cli.js ./src --extensions ".js,.ts"
```

## Primary Use Case

loqatevars addresses a common problem in LLM-generated code: scattered variable declarations and inconsistent environment variable usage. When AI generates code, it often creates multiple files that directly access `process.env` while also declaring local constants, making configuration management difficult and error-prone.

### Problem Pattern (What loqatevars identifies)
Files that mix local variable declarations with direct environment variable access:
```javascript
// database.js - problematic pattern
const dbHost = process.env.DB_HOST || 'localhost';
const timeout = 5000;

// server.js - problematic pattern
const port = process.env.PORT || 3000;
const maxConnections = 100;
```

### Solution Pattern (Refactoring goal)
Centralized configuration with clean separation:
```javascript
// localVars.js - centralized config (ignored by scanner)
module.exports = {
  database: { host: process.env.DB_HOST || 'localhost' },
  server: { port: process.env.PORT || 3000 }
};

// database.js - clean consumer
const config = require('./localVars');
const timeout = 5000; // local constants only
```

## Notes

- Module follows CommonJS pattern for maximum compatibility
- Recursive directory scanning with intelligent ignore patterns
- Comprehensive error handling for file system operations
- CLI provides both simple and detailed output modes
- Default ignore pattern assumes `localVars.js` as intended centralized config file
- Helps identify refactoring opportunities in LLM-generated codebases