Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,32 @@ npm install -g errlens

---

## ⚡ Quick Start

```bash
# Analyze an error message
errlens analyze "TypeError: Cannot read property 'name' of undefined"

# Run a script with error monitoring
errlens run your-script.js

# Get JSON output for CI/CD pipelines
errlens analyze "is not a function" --json
```

---

## 🛠 Usage

### Available Commands

```bash
errlens run <file> [--json] # Run a script and analyze any crashes
errlens analyze <error> [--json] # Analyze a specific error message
errlens --version # Show version information
errlens --help # Show help
```

### 1️⃣ Automatic Monitoring (The "Pro" Way)

Run your script through ErrLens. If it crashes, ErrLens intercepts the error and explains the fix before the process exits.
Expand All @@ -71,7 +95,7 @@ errlens run your-app.js
Found a weird error in your logs? Just paste the message:

```bash
errlens "TypeError: Cannot read properties of undefined"
errlens analyze "TypeError: Cannot read properties of undefined"
```

---
Expand All @@ -81,7 +105,7 @@ errlens "TypeError: Cannot read properties of undefined"
Get machine-readable results for your own tooling or automated reports:

```bash
errlens "is not a function" --json
errlens analyze "is not a function" --json
```

Run a script and write the JSON report directly to a file in CI:
Expand Down
88 changes: 56 additions & 32 deletions bin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,40 @@

const { Command } = require("commander");
const { spawn } = require("child_process");
const ora = require("ora").default;
const chalk = require("chalk");
const path = require("path");
const { findError } = require("../lib/matcher");
const { formatError } = require("../lib/formatter");
const { version } = require("../package.json");

const program = new Command();

program
.name("errlens")
.description("Professional JS Error Analytics")
.version("1.3.1");
.version(version)
.option("--json", "Output JSON instead of pretty UI"); // ✅ GLOBAL OPTION

// ----------------- RUN COMMAND -----------------
program
.command("run <file>")
.option('--json', 'Output JSON instead of pretty UI')
.description("Run a Javascript file and analyze crashes")
.action((file, options) => {
.action(async (file) => {
const { default: ora } = await import("ora");

const isJson = Boolean(program.opts().json);
const filePath = path.resolve(process.cwd(), file);
const isJson = Boolean(options.json || process.argv.includes("--json"));
const spinner = isJson ? null : ora(`Running ${chalk.yellow(file)}...`).start();
const spinner = isJson
? null
: ora(`Running ${chalk.yellow(file)}...`).start();

const child = spawn(process.execPath, [filePath], { stdio: ["inherit", "pipe", "pipe"] });
const child = spawn(process.execPath, [filePath], {
stdio: ["inherit", "pipe", "pipe"],
});

let errorOutput = "";

// Stream logs to terminal in real-time
// Stream stdout only in pretty mode
child.stdout.on("data", (data) => {
if (!isJson) {
spinner.stop();
Expand All @@ -38,7 +44,7 @@ program
}
});

// Capture stderr for analysis
// Capture stderr (DO NOT print in JSON mode)
child.stderr.on("data", (data) => {
errorOutput += data.toString();

Expand All @@ -48,34 +54,46 @@ program
});

child.on("close", (code, signal) => {
if (!isJson) {
if (!isJson && spinner) {
spinner.stop();
}

const { count, matches } = findError(errorOutput);

// Process killed by signal
if (code === null) {
const result = { code: 1, count, matches };

if (isJson) {
const result = { code: 1, count, matches };
console.log(JSON.stringify(result, null, 2));
} else {
console.log(chalk.red.bold(`\n⚠️ Process killed by signal: ${signal}`));
console.log(
chalk.red.bold(`\n⚠️ Process killed by signal: ${signal}`)
);
}

process.exit(1);
return;
}

// JSON MODE
if (isJson) {
const result = { code, count, matches };
console.log(JSON.stringify(result, null, 2));
} else if (code === 0) {
console.log(chalk.green.bold("\n✨ Process finished successfully."));
console.log(JSON.stringify({ code, count, matches }, null, 2));
process.exit(code ?? 1);
}

// PRETTY MODE
if (code === 0) {
console.log(chalk.green.bold("\n✨ Process finished successfully."));
} else {
if (count > 0) {
console.log(chalk.bold.cyan(`\n🚀 ErrLens Analysis (${count} Issue(s)):`));
matches.forEach(m => console.log(formatError(m))); // Pretty UI only here
console.log(
chalk.bold.cyan(`\n🚀 ErrLens Analysis (${count} Issue(s)):`)
);
matches.forEach((m) => console.log(formatError(m)));
} else {
console.log(chalk.red.bold("\n❌ Crash detected (No known fix in database):"));
console.log(
chalk.red.bold("\n❌ Crash detected (No known fix in database):")
);
console.log(chalk.gray(errorOutput));
}
}
Expand All @@ -84,42 +102,48 @@ program
});

child.on("error", (err) => {
const result = { code: 1, count: 0, matches: [] };

if (isJson) {
const result = { code: 1, count: 0, matches: [] };
console.log(JSON.stringify(result, null, 2));
} else {
spinner.fail(chalk.red(`System Error: ${err.message}`));
console.log(chalk.red(`System Error: ${err.message}`));
}

process.exit(1);
});
Comment on lines 104 to 114
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Stop spinner before printing error in pretty mode.

The error handler doesn't stop the spinner before logging the error message. In pretty mode, this can cause garbled output where the spinner animation overlaps with the error text.

🛡️ Proposed fix
     child.on("error", (err) => {
       const result = { code: 1, count: 0, matches: [] };
 
       if (isJson) {
         console.log(JSON.stringify(result, null, 2));
       } else {
+        if (spinner) spinner.stop();
         console.log(chalk.red(`System Error: ${err.message}`));
       }
 
       process.exit(1);
     });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
child.on("error", (err) => {
const result = { code: 1, count: 0, matches: [] };
if (isJson) {
const result = { code: 1, count: 0, matches: [] };
console.log(JSON.stringify(result, null, 2));
} else {
spinner.fail(chalk.red(`System Error: ${err.message}`));
console.log(chalk.red(`System Error: ${err.message}`));
}
process.exit(1);
});
child.on("error", (err) => {
const result = { code: 1, count: 0, matches: [] };
if (isJson) {
console.log(JSON.stringify(result, null, 2));
} else {
if (spinner) spinner.stop();
console.log(chalk.red(`System Error: ${err.message}`));
}
process.exit(1);
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@bin/index.js` around lines 104 - 114, The error handler for child.on("error",
(err) => { ... }) must stop the CLI spinner before writing the pretty (non-JSON)
error to avoid overlapping output; update the handler to check for the spinner
instance (e.g., spinner) and call its stop/clear method (or stopSpinner())
before calling console.log(chalk.red(...)) while leaving JSON output path
unchanged and then call process.exit(1).

});

// ----------------- ANALYZE COMMAND -----------------
program
.arguments("<errorString>") // default command if no "run"
.command("analyze <errorString>")
.description("Analyze a specific error string")
.option('--json', 'Output result in JSON format')
.action((errorString, options) => {
.action((errorString) => {
const isJson = Boolean(program.opts().json);
const { count, matches } = findError(errorString);
const exitCode = count > 0 ? 1 : 0;
const isJson = Boolean(options.json || process.argv.includes("--json"));

if (isJson) {
console.log(JSON.stringify({ code: exitCode, count, matches }, null, 2));
console.log(
JSON.stringify({ code: exitCode, count, matches }, null, 2)
);
process.exit(exitCode);
return;
}

if (count > 0) {
console.log(chalk.bold.cyan(`\n🚀 ErrLens Analysis (${count} Issue(s)):`));
matches.forEach(m => console.log(formatError(m))); // Pretty UI
console.log(
chalk.bold.cyan(`\n🚀 ErrLens Analysis (${count} Issue(s)):`)
);
matches.forEach((m) => console.log(formatError(m)));
} else {
console.log(chalk.red.bold("\n❌ Crash detected (No known fix in database):"));
console.log(
chalk.red.bold("\n❌ Crash detected (No known fix in database):")
);
console.log(chalk.gray(errorString));
}

process.exit(exitCode);
});

// ----------------- PARSE ARGUMENTS -----------------
// ----------------- PARSE -----------------
program.parse(process.argv);