60-90% Token Reduction
Dramatically reduce LLM context size while preserving complete meaning and business logic
Transform TypeScript/JavaScript into LLM-friendly Markdown + intelligently detect and remove dead code with confidence levels
M2JS solves two critical development challenges:
Transform verbose TypeScript code into clean, AI-ready documentation with massive token savings.
Find and safely remove unused code with confidence-based analysis that goes beyond traditional linters.
The original code with all implementation details, comments, and boilerplate:
export class AuthService {
private readonly jwtSecret: string;
private readonly tokenExpiry: number;
private readonly userRepository: UserRepository;
private readonly loggerService: LoggerService;
constructor(
userRepo: UserRepository,
logger: LoggerService,
config: AuthConfig
) {
this.userRepository = userRepo;
this.loggerService = logger;
this.jwtSecret = config.jwtSecret;
this.tokenExpiry = config.tokenExpiry || 3600;
}
/**
* Authenticate user with email and password
* Business rule: Rate limiting - max 5 attempts per hour
* Security: Passwords must be validated with bcrypt
*/
async login(email: string, password: string): Promise<AuthResult> {
try {
// Validate input parameters
if (!email || !password) {
this.loggerService.warn('Login attempt with missing credentials');
throw new AuthenticationError('Email and password are required');
}
// Check rate limiting
const attempts = await this.getRateLimitAttempts(email);
if (attempts >= 5) {
this.loggerService.warn(`Rate limit exceeded for email: ${email}`);
throw new RateLimitError('Too many login attempts. Try again later.');
}
// Fetch user from database
const user = await this.userRepository.findByEmail(email);
if (!user || !user.isActive) {
this.loggerService.warn(`Login attempt for inactive user: ${email}`);
throw new AuthenticationError('Invalid credentials');
}
// Validate password
const isPasswordValid = await bcrypt.compare(password, user.passwordHash);
if (!isPasswordValid) {
await this.incrementRateLimitAttempts(email);
this.loggerService.warn(`Invalid password for user: ${email}`);
throw new AuthenticationError('Invalid credentials');
}
// Generate JWT token
const payload = {
userId: user.id,
email: user.email,
role: user.role,
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + this.tokenExpiry
};
const token = jwt.sign(payload, this.jwtSecret);
// Reset rate limiting on successful login
await this.resetRateLimitAttempts(email);
// Log successful authentication
this.loggerService.info(`Successful login for user: ${email}`);
// Return authentication result
return {
success: true,
token,
user: {
id: user.id,
email: user.email,
name: user.name,
role: user.role
},
expiresAt: new Date(Date.now() + this.tokenExpiry * 1000)
};
} catch (error) {
if (error instanceof AuthenticationError || error instanceof RateLimitError) {
throw error;
}
this.loggerService.error('Unexpected error during authentication:', error);
throw new AuthenticationError('Authentication failed');
}
}
// ... 150+ more lines of helper methods
}
Clean, structured documentation focused on business value and API contracts:
# AuthService.ts
## Business Context
**Domain**: Authentication (98% confidence)
**Framework**: Node.js + JWT + TypeScript
**Patterns**: Service Layer, Repository Pattern
**Architecture**: Clean Architecture
## Architecture Insights
**Layer**: Service Layer
**Responsibility**: User authentication and JWT management
**Dependencies**: UserRepository, LoggerService, AuthConfig
**Security**: Rate limiting, password hashing, token-based auth
## Entity Relationships
- **User** → *authenticates via* → **AuthService**
- **AuthResult** → *contains* → **JWT Token + User Data**
- **AuthService** → *depends on* → **UserRepository**
## Functions
### login
```typescript
async login(email: string, password: string): Promise<AuthResult>
Business Rules:
Usage Pattern: Authentication workflow Returns: AuthResult with JWT token and user data Throws: AuthenticationError, RateLimitError
Example:
const result = await authService.login('user@example.com', 'password123');
if (result.success) {
console.log('Logged in:', result.user.email);
}
Input: Your messy project with accumulated unused code
m2js src/ --detect-unused
Output: Smart analysis with confidence levels
Dead Code Analysis Report
Analyzing 45 files...
Dead Exports (12 found):
┌─────────────────────────────────────────────────┐
│ src/utils.ts:25 [HIGH]
│ └─ function internalHelper
│ Export never imported - safe to remove
│
│ src/api.ts:15 [MEDIUM]
│ └─ function createApi
│ Risk factors:
│ • Export name suggests it may be used by external packages
│
│ src/config.ts:5 [LOW]
│ └─ default export
│ Risk factors:
│ • Default export - may be imported with different names
│ • Configuration file - may be loaded dynamically
└─────────────────────────────────────────────────┘
Removal Suggestions:
┌─────────────────────────────────────────────────┐
│ SAFE TO REMOVE:
│ Remove function: internalHelper
│ utils.ts:25
│ # Remove lines around 25 in utils.ts
│
│ REVIEW BEFORE REMOVING:
│ Remove function: createApi
│ api.ts:15
│ Export name suggests it may be used by external packages
│
│ HIGH RISK:
│ 3 suggestions require careful analysis
│ Manual review strongly recommended
└─────────────────────────────────────────────────┘
Next Steps:
1. Start with safe-to-remove items (high confidence)
2. Use provided commands for quick removal
3. Review medium-risk items manually
Result: Confident dead code removal with detailed risk assessment!
For AI Assistants: The structured format helps ChatGPT, Claude, and GitHub Copilot understand your code's business intent, not just syntax.
For Developers: Focus on business logic and architecture patterns instead of implementation details.
For Teams: Share context-rich documentation that captures domain knowledge and design decisions.
For Code Maintenance: Safely remove dead code with confidence levels and actionable suggestions that go beyond traditional linters.
Get up and running in under 2 minutes:
# Install globally via NPM
npm install -g @paulohenriquevn/m2js
# Transform any TypeScript/JavaScript file
m2js src/UserService.ts
m2js src/ --batch # Process entire directory
# Smart dead code detection
m2js src/ --detect-unused
# Advanced: AI-enhanced analysis (temporarily disabled)
# m2js UserService.ts --ai-enhanced
# Install as dev dependency
npm install --save-dev @paulohenriquevn/m2js
# Add to package.json scripts
{
"scripts": {
"docs:ai": "m2js src/ --batch --output docs/ai/",
"cleanup": "m2js src/ --detect-unused",
"cleanup-safe": "m2js src/ --detect-unused | grep 'SAFE TO REMOVE'"
}
}
# Generate documentation or analyze dead code
npm run docs:ai
npm run cleanup
# 1. Install "M2JS" from VS Code marketplace
# 2. Right-click any .ts/.js file
# 3. Select "Generate M2JS Documentation"
# 4. Copy optimized output to your AI assistant
# Or use Command Palette:
# Ctrl+Shift+P → "M2JS: Generate Documentation"
# .github/workflows/docs.yml
name: Generate AI Documentation
on: [push, pull_request]
jobs:
generate-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- run: npm install -g @paulohenriquevn/m2js
- run: m2js src/ --batch --output docs/ai/
- uses: actions/upload-artifact@v3
with:
name: ai-docs
path: docs/ai/
# Install globally (recommended for CLI usage)
npm install -g @paulohenriquevn/m2js
# Verify installation
m2js --version
# Install as project dependency
npm install --save-dev @paulohenriquevn/m2js
# Use in package.json scripts
{
"scripts": {
"docs": "m2js src/ --batch",
"cleanup": "m2js src/ --detect-unused"
}
}
# Install from VS Code Marketplace
# Search for "M2JS" in Extensions
# Or install via command line
code --install-extension paulohenriquevn.m2js-vscode
Traditional Linters | M2JS Smart Detection |
---|---|
"This is unused" | "This is unused AND here's how to safely remove it" |
File-by-file analysis | Cross-project understanding |
Binary unused/used | Confidence levels + risk assessment |
Generic warnings | Context-aware suggestions |
Manual investigation needed | Ready-to-execute commands |
How to Use Together
# Don't replace ESLint - enhance it!
npm run lint # ESLint for code quality
m2js src --detect-unused # M2JS for smart dead code removal
M2JS is not a linter replacement. It's a smart assistant for confident dead code cleanup.
M2JS consistently delivers massive token savings across different project sizes:
File Size | Processing Time | Token Reduction | Memory Usage |
---|---|---|---|
< 10KB | < 1s | 60-70% | < 50MB |
10-100KB | 1-5s | 70-80% | 50-100MB |
100KB-1MB | 5-15s | 80-90% | 100-200MB |
Project Size | Files | Processing Time | Memory Usage | Cache Hit Rate |
---|---|---|---|---|
Small | < 50 | < 5s | < 100MB | N/A (first run) |
Medium | 50-500 | 10-30s | 100-300MB | 60-80% |
Large | 500-2000 | 30-120s | 300-500MB | 80-90% |
Enterprise | > 2000 | 2-10min | 500MB-1GB | 90%+ |
AI Documentation - Ideal For
Dead Code Detection - Ideal For
Current Status
Get started in under 2 minutes: