#!/usr/bin/env bun /** * Bulk fix: adds const logger = createLogger(env) to files that import * createLogger and use logger.X but don't define logger locally. */ import { readFileSync, writeFileSync } from "node:fs"; const FILES = process.argv.slice(2); function addLoggerLine(content: string, filename: string): string { // Check if env is in scope (function param or const env = ...) const hasEnv = /\benv\s*[:=]\s*\w+\s*Env\b/.test(content) || /\bc\.env\b/.test(content) || /\benv\./.test(content); if (!hasEnv) { console.log(` SKIP (no env in scope): ${filename}`); return content; } // Add const logger = createLogger(env); before first logger. usage // Find the function body where logger is used const lines = content.split("\n"); const result: string[] = []; let inLoggerFunc = false; let braceDepth = 0; let foundLine: number | null = null; for (let i = 0; i < lines.length; i++) { const line = lines[i]; // Check if this is a function definition if (/(?:function\s+\w+|=>\s*\{|\)\s*=>|\) =>|\):.*=>)\s*\{?/.test(line)) { inLoggerFunc = false; braceDepth = 0; } if (line.includes("logger.") && !line.trim().startsWith("//") && !line.includes("const logger") && !line.includes("let logger") && !line.includes("logger:")) { if (!foundLine) { foundLine = i; } // logger used but not defined — go back and add definition } } // Simple approach: find the first { after export/signature and add logger // This is heuristic and may need manual review let firstBrace = false; let fixed = false; const newLines: string[] = []; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (!fixed && line.includes("logger.") && !line.trim().startsWith("//") && !line.includes("const logger") && !line.includes("let logger") && !line.includes("logger:") && !line.includes("import ")) { // Go back to find the function body start and insert logger definition let insertAt = i; for (let j = i - 1; j >= 0; j--) { if (lines[j].includes("{") && /\b(?:function|=>|async|export|const\s+\w+\s*=|let\s+\w+\s*=)\b/.test(lines.slice(Math.max(0, j-5), j+1).join(" "))) { insertAt = j + 1; break; } } // Insert before the first use // Adjust indentation const indent = lines[insertAt].match(/^(\s*)/)?.[1] || ""; newLines.push(`${indent}const logger = createLogger(env);`); console.log(` FIXED: ${filename}`); fixed = true; // Now continue adding remaining lines for (let k = i; k < lines.length; k++) { newLines.push(lines[k]); } break; } newLines.push(line); } return fixed ? newLines.join("\n") : content; } for (const f of FILES) { let content = readFileSync(f, "utf-8"); const newContent = addLoggerLine(content, f); if (newContent !== content) { writeFileSync(f, newContent); } }