0.9.6 โ€ข Published 9 months ago

@regele/devtools v0.9.6

Weekly downloads
-
License
MIT
Repository
-
Last release
9 months ago

@regele/devtools

DevTools Version

npm version npm downloads License TypeScript Node.js


โœจ Features

๐ŸŒˆ Multi-language Support

Works with 30+ languages and file types including:

  • JavaScript/TypeScript: .js, .jsx, .ts, .tsx, .mjs, .cjs, .vue, .svelte, .astro
  • HTML/XML: .html, .htm, .xml, .svg, .jsp, .asp, .ejs, .hbs
  • CSS: .css, .scss, .sass, .less, .stylus, .postcss
  • C-style: .c, .h, .cpp, .hpp, .java, .cs, .go, .swift
  • Others: .php, .py, .rb, .sql, .md, .txt, .json, .yaml

๐Ÿ“ฆ Installation

npm install @regele/devtools
# or
yarn add @regele/devtools
# or
pnpm add @regele/devtools
npm install -g @regele/devtools
# or
yarn global add @regele/devtools
# or
pnpm add -g @regele/devtools
  • Node.js: v14.x or higher
  • NPM: v6.x or higher
  • Operating Systems: Windows, macOS, Linux
  • Optional Dependencies:
    • Prettier (for enhanced code formatting)
    • ESLint (for enhanced code analysis)

๐Ÿš€ Quick Start

๐Ÿงน Comment Remover

import { CommentRemover, FileType } from '@regele/devtools';

// Create a new comment remover with default options
const commentRemover = new CommentRemover();

// Remove comments from JavaScript code
const jsCode = `
// This is a comment
function hello() {
  /* This is a
     multiline comment */
  console.log('Hello world'); // End of line comment
}
`;

const cleanCode = commentRemover.removeComments(jsCode, FileType.JavaScript);
console.log(cleanCode);
function hello() {
  console.log('Hello world');
}
// Customize removal options
const customRemover = new CommentRemover({
  singleLine: true,     // Remove single-line comments (// in JS)
  multiLine: true,      // Remove multi-line comments (/* */ in JS)
  jsxComments: true,    // Remove JSX comments ({/* */} in JSX/TSX)
  emptyLines: false     // Preserve empty lines after comment removal
});

// Or update options on an existing instance
commentRemover.updateOptions({
  singleLine: true,
  multiLine: false,     // Keep multi-line comments
  emptyLines: true
});

// Get current configuration
const options = commentRemover.getOptions();
console.log(options);
// Process multiple files with glob patterns
const results = await commentRemover.cleanFiles('src/**/*.{js,ts}', {
  write: true,          // Write changes back to files
  ignore: ['node_modules/**', 'dist/**'],  // Ignore patterns
  silent: false         // Show processing output
});

console.log(`Processed ${results.length} files`);

๐Ÿ’… Code Beautifier

import { Beautifier, FileType } from '@regele/devtools';

// Create a new beautifier with custom options
const beautifier = new Beautifier({
  semi: true,
  singleQuote: true,
  tabWidth: 2
});

// Format JavaScript code
const jsCode = `function hello(){console.log("Hello world")}`;

// Format code (returns a promise)
const formattedCode = await beautifier.format(jsCode, FileType.JavaScript);
console.log(formattedCode);
function hello() {
  console.log('Hello world');
}
// Create with specific options
const beautifier = new Beautifier({
  semi: false,          // No semicolons
  singleQuote: true,    // Use single quotes
  tabWidth: 4,          // 4-space indentation
  useTabs: false,       // Use spaces instead of tabs
  printWidth: 100,      // Line width limit
  trailingComma: 'es5', // Trailing commas where valid in ES5
  bracketSpacing: true, // Spaces in object literals
  arrowParens: 'always' // Parentheses around arrow function parameters
});

// Update options on an existing instance
beautifier.updateOptions({
  semi: true,
  printWidth: 80
});
import prettier from 'prettier';

// Use with Prettier for enhanced formatting capabilities
const prettierBeautifier = new Beautifier({
  // Prettier options
  semi: true,
  singleQuote: true
}, prettier);

// Format files with specific parser
const tsCode = `interface User{name:string;age:number}`;
const formattedTS = await prettierBeautifier.format(tsCode, FileType.TypeScript);
console.log(formattedTS);
interface User {
  name: string;
  age: number;
}
// Format multiple files with glob patterns
const results = await beautifier.formatFiles('src/**/*.{js,ts,jsx,tsx}', {
  write: true,          // Write changes back to files
  ignore: ['node_modules/**', 'dist/**'],  // Ignore patterns
  silent: false         // Show processing output
});

console.log(`Beautified ${results.length} files`);

๐Ÿ“Š Word Counter & โฑ๏ธ Handwriting Timer

import { WordCounter } from '@regele/devtools';

// Create a new word counter with text
const text = "This is a sample text. It has two sentences. And it has multiple paragraphs.\n\nThis is the second paragraph.";
const wordCounter = new WordCounter(text);

// Get all statistics at once
const stats = wordCounter.getStats();
console.log(stats);
{
  characters: 104,
  charactersNoSpaces: 85,
  words: 20,
  sentences: 3,
  paragraphs: 2,
  readingTime: "1 min",
  handwritingTime: "~3 mins",
  keyboardTime: "~2 mins"
}
// Get individual statistics
console.log(wordCounter.getWordCount());        // 20
console.log(wordCounter.getSentenceCount());    // 3
console.log(wordCounter.getReadingTime());      // "1 min"
console.log(wordCounter.getHandwritingTime());  // "~3 mins"

// Set new text to analyze
wordCounter.setText("New text to analyze");

// Customize reading/writing speeds (words per minute)
wordCounter.setReadingSpeed(250);      // Fast reader
wordCounter.setHandwritingSpeed(20);   // Slow writer
wordCounter.setKeyboardSpeed(80);      // Fast typist

// Advanced analysis
const frequency = wordCounter.getWordFrequency();
console.log(frequency);  // { "new": 1, "text": 1, "to": 1, "analyze": 1 }

// Get most frequent words
const topWords = wordCounter.getMostFrequentWords(5);
console.log(topWords);   // [["new", 1], ["text", 1], ["to", 1], ["analyze", 1]]

// Get readability score (Flesch Reading Ease)
const readability = wordCounter.getReadabilityScore();
console.log(readability); // Higher score means easier to read
// Start a writing session
wordCounter.startWritingSession();

// Update text during the session (this also takes a snapshot)
wordCounter.updateText("Writing in progress...");

// After some time, update with more text
wordCounter.updateText("Writing in progress... Adding more content.");

// Get current writing speed
const writingSpeed = wordCounter.getWritingSpeed();
console.log(writingSpeed);
{
  wordsPerMinute: 15,
  charactersPerMinute: 85,
  totalWords: 8,
  totalCharacters: 45,
  elapsedTimeMs: 32000
}
// Timer control methods
wordCounter.pauseWritingSession();   // Pause the timer
wordCounter.startWritingSession();   // Resume the timer
wordCounter.stopWritingSession();    // Stop the current session
wordCounter.resetWritingSession();   // Reset the timer and session

// Get elapsed time
const elapsedTime = wordCounter.getElapsedTime();
const formattedTime = wordCounter.getFormattedElapsedTime(); // "00:05:32"

// Check timer status
const isRunning = wordCounter.isTimerRunning();

// Register tick callback (called every 100ms by default)
wordCounter.onTimerTick((elapsedTime) => {
  console.log(`Timer running: ${elapsedTime}ms`);
});

// Get the complete writing session history
const sessions = wordCounter.getWritingSessionHistory();
console.log(sessions);
[
  {
    id: 1628506892451,
    startTime: "2023-08-09T12:34:52.451Z",
    duration: 65000,
    textSnapshots: [
      {
        timestamp: "2023-08-09T12:35:12.451Z",
        text: "Writing in progress...",
        elapsedTime: 20000
      },
      {
        timestamp: "2023-08-09T12:35:42.451Z",
        text: "Writing in progress... Adding more content.",
        elapsedTime: 50000
      }
    ]
  }
]
// Analyze multiple text files
const results = await wordCounter.analyzeFiles('content/**/*.{md,txt}', {
  ignore: ['node_modules/**', 'dist/**']
});

// Process results
for (const result of results) {
  if (result.success) {
    console.log(`File: ${result.path}`);
    console.log(`Words: ${result.stats?.words}`);
    console.log(`Reading time: ${result.stats?.readingTime}`);
    console.log(`Most frequent words:`, result.frequentWords);
    console.log(`Readability score: ${result.readabilityScore}`);
  }
}

๐Ÿ–ฅ๏ธ CLI Usage

Add these scripts to your package.json for easy access to all tools:

"scripts": {
  "format": "devtools-beautify src/**/*.{js,jsx,ts,tsx,json,css,html}",
  "clean": "devtools-clean src/**/*.{js,jsx,ts,tsx,json,css,html}",
  "analyze": "devtools-analyze src/**/*.{js,jsx,ts,tsx,md,txt}",
  "analyze-code": "devtools-analyze-code src/**/*.{js,jsx,ts,tsx}"
}

Then run with npm:

npm run format    # Format all project files
npm run clean     # Remove comments from all project files
npm run analyze   # Analyze text content in project
npm run analyze-code  # Analyze code for issues
# Remove comments from files
devtools-clean "src/**/*.js" --write
# Remove only single-line comments
devtools-clean "src/**/*.js" --single-line --no-multi-line --write

# Keep JSX comments but remove others
devtools-clean "src/**/*.jsx" --no-jsx --write

# Remove comments but keep empty lines
devtools-clean "src/**/*.ts" --no-empty-lines --write
# Process multiple file types at once
devtools-clean "src/**/*.{js,ts,jsx,tsx,css,html}" --write

# Ignore specific files or directories
devtools-clean "src/**/*.js" --ignore "src/vendor/**,**/*.min.js" --write
# Beautify files
devtools-beautify "src/**/*.js" --write
# Use a custom Prettier config
devtools-beautify "src/**/*.js" --config .prettierrc --write

# Silent mode (no output)
devtools-beautify "src/**/*.js" --silent --write
# Process multiple file types at once
devtools-beautify "src/**/*.{js,ts,jsx,tsx,css,html}" --write

# Ignore specific files or directories
devtools-beautify "src/**/*.js" --ignore "src/vendor/**,**/*.min.js" --write
# Analyze text files
devtools-analyze "src/**/*.{md,txt}"
# Generate a detailed JSON report
devtools-analyze "src/**/*.{md,txt}" --output report.json

# Show only summary information
devtools-analyze "src/**/*.md" --summary
  • Character count (with and without spaces)
  • Word, sentence, and paragraph counts
  • Reading time estimates (based on 200 words per minute)
  • Handwriting time estimates (based on 25 words per minute)
  • Keyboard typing time estimates (based on 60 words per minute)
  • Readability score (Flesch Reading Ease)
  • Most frequent words
# Analyze code for issues
devtools-analyze-code "src/**/*.js"
# Filter by severity level
devtools-analyze-code "src/**/*.js" --severity warning

# Filter by category
devtools-analyze-code "src/**/*.js" --category security,performance

# Limit analysis depth
devtools-analyze-code "src/**/*.js" --max-depth 3
# Generate HTML report
devtools-analyze-code "src/**/*.js" --output report.html

# Generate JSON report
devtools-analyze-code "src/**/*.js" --output report.json --format json
  • Performance: Nested loops, unbatched DOM updates, unthrottled event listeners
  • Security: Unsanitized user input, unsafe eval usage, dangerous innerHTML
  • Maintainability: Complex functions, deep nesting, duplicated code, missing JSDoc
  • Bugs: Off-by-one errors, unhandled promises, null dereferences, inconsistent returns
  • Style: Naming conventions, indentation, semicolon usage, function style
# Show help and version
devtools --help
devtools --version
# Run commands through the unified interface
devtools beautify "src/**/*.js"
devtools clean "src/**/*.js"
devtools analyze "src/**/*.md"
devtools analyze-code "src/**/*.js"
# Verbose output with detailed information
devtools --verbose analyze-code "src/**/*.js"

# Quiet mode (minimal output)
devtools --quiet clean "src/**/*.js"

# Use configuration file
devtools --config .devtoolsrc analyze-code "src/**/*.js"

# Dry run (no changes to files)
devtools --dry-run beautify "src/**/*.js"

๐Ÿ”ง Supported File Types

โš™๏ธ Configuration Options

// Default options shown
const options = {
  singleLine: true,    // Remove single-line comments (// in JS)
  multiLine: true,     // Remove multi-line comments (/* */ in JS)
  jsxComments: true,   // Remove JSX comments ({/* */} in JSX/TSX)
  emptyLines: true     // Remove empty lines after comment removal
};

const commentRemover = new CommentRemover(options);
// Default options shown
const options = {
  semi: true,          // Add semicolons
  singleQuote: true,   // Use single quotes
  tabWidth: 2,         // Tab width
  useTabs: false,      // Use spaces instead of tabs
  printWidth: 80,      // Line width
  trailingComma: 'es5',// Trailing commas where valid in ES5
  bracketSpacing: true,// Spaces in object literals
  arrowParens: 'always'// Parentheses around arrow function parameters
};

const beautifier = new Beautifier(options);
// Default options shown
const wordCounter = new WordCounter(
  "Text to analyze",   // Initial text
  200,                 // Reading speed (words per minute)
  25,                  // Handwriting speed (words per minute)
  60,                  // Keyboard typing speed (words per minute)
  {                    // Timer options
    tickInterval: 100, // Timer tick interval in ms
    onTick: (elapsed) => console.log(`Time: ${elapsed}ms`)
  }
);

๐Ÿ“‹ CLI Options

Usage: devtools-clean [options] <patterns...>

Remove comments from code files

Arguments:
  patterns              File patterns to clean (e.g., "src/**/*.js")

Options:
  --single-line         Remove single-line comments (default: true)
  --multi-line          Remove multi-line comments (default: true)
  --jsx                 Remove JSX comments (default: true)
  --empty-lines         Remove empty lines (default: true)
  --ignore <pattern>    Files to ignore (comma-separated)
  --write               Write changes to files (default: true)
  --silent              Suppress output (default: false)
  -h, --help            display help for command
# Basic usage
devtools-clean "src/**/*.js"

# Keep multi-line comments
devtools-clean "src/**/*.js" --no-multi-line

# Preserve empty lines
devtools-clean "src/**/*.js" --no-empty-lines
Usage: devtools-beautify [options] <patterns...>

Format and beautify code files

Arguments:
  patterns              File patterns to beautify (e.g., "src/**/*.js")

Options:
  --config <path>       Path to prettier config
  --ignore <pattern>    Files to ignore (comma-separated)
  --write               Write changes to files (default: true)
  --silent              Suppress output (default: false)
  -h, --help            display help for command
# Basic usage
devtools-beautify "src/**/*.js"

# Use custom Prettier config
devtools-beautify "src/**/*.js" --config .prettierrc

# Preview changes without writing
devtools-beautify "src/**/*.js" --no-write
Usage: devtools-analyze [options] <patterns...>

Analyze text content in files

Arguments:
  patterns              File patterns to analyze (e.g., "src/**/*.md")

Options:
  --summary             Show summary only (default: false)
  --ignore <pattern>    Files to ignore (comma-separated)
  --output <path>       Write report to file
  -h, --help            display help for command
# Basic usage
devtools-analyze "src/**/*.md"

# Generate JSON report
devtools-analyze "src/**/*.md" --output report.json

# Show only summary
devtools-analyze "src/**/*.md" --summary
Usage: devtools-analyze-code [options] <patterns...>

Analyze code for potential issues, bugs, and improvements

Arguments:
  patterns                 File patterns to analyze (e.g., "src/**/*.js")

Options:
  --severity <level>       Minimum severity level to report (info, warning, error, critical) (default: "info")
  --category <categories>  Categories to include (comma-separated: performance, security, maintainability, bugs, style)
  --ignore <pattern>       Files to ignore (comma-separated)
  --max-depth <depth>      Maximum depth for recursive analysis
  --root-dir <path>        Root directory for analysis
  --output <path>          Write report to file (json or html)
  --format <format>        Output format (text, json, html) (default: "text")
  --silent                 Suppress output (default: false)
  -h, --help               display help for command
# Basic usage
devtools-analyze-code "src/**/*.js"

# Filter by severity
devtools-analyze-code "src/**/*.js" --severity warning

# Filter by category
devtools-analyze-code "src/**/*.js" --category security,performance

# Generate HTML report
devtools-analyze-code "src/**/*.js" --output report.html

๐Ÿ“š API Reference

๐Ÿ“Š WordCounter

Analyzes text for statistics and provides timing estimates.

Constructor & Basic Methods

  • constructor(text: string = '', wordsPerMinute: number = 200, handwritingWpm: number = 25, keyboardWpm: number = 60, timerOptions?: HandwritingTimerOptions): Creates a new WordCounter instance with optional text and timing parameters.
  • setText(text: string): void: Sets the text to analyze.
  • getText(): string: Gets the current text being analyzed.

Speed Settings

  • setReadingSpeed(wordsPerMinute: number): void: Sets the reading speed in words per minute.
  • getReadingSpeed(): number: Gets the current reading speed.
  • setHandwritingSpeed(wordsPerMinute: number): void: Sets the handwriting speed in words per minute.
  • getHandwritingSpeed(): number: Gets the current handwriting speed.
  • setKeyboardSpeed(wordsPerMinute: number): void: Sets the keyboard typing speed in words per minute.
  • getKeyboardSpeed(): number: Gets the current keyboard typing speed.

Text Statistics

  • getStats(): WordCountStats: Gets all text statistics in a single object.
  • getCharacterCount(): number: Gets the total character count.
  • getCharacterCountNoSpaces(): number: Gets the character count excluding spaces.
  • getWordCount(): number: Gets the word count.
  • getSentenceCount(): number: Gets the sentence count.
  • getParagraphCount(): number: Gets the paragraph count.

Time Estimates

  • getReadingTime(): string: Gets the estimated reading time as a formatted string.
  • getHandwritingTime(): string: Gets the estimated handwriting time as a formatted string.
  • getKeyboardTime(): string: Gets the estimated keyboard typing time as a formatted string.

Advanced Analysis

  • getWordFrequency(): Record<string, number>: Gets the frequency of each word in the text.
  • getMostFrequentWords(limit: number = 10): [string, number][]: Gets the most frequently used words in the text.
  • getReadabilityScore(): number: Gets the readability score (Flesch Reading Ease).
  • analyzeFiles(patterns: string | string[], options?: object): Promise<AnalysisResult[]>: Analyzes multiple files matching the glob patterns.

Writing Session

  • startWritingSession(): void: Starts or resumes a writing session timer.
  • pauseWritingSession(): void: Pauses the current writing session timer.
  • stopWritingSession(): void: Stops the current writing session timer.
  • resetWritingSession(): void: Resets the writing session timer and history.
  • updateText(text: string): void: Updates the text and takes a snapshot for the timer.
  • getWritingSpeed(): WritingSpeedStats: Gets the current writing speed statistics.
  • getWritingSessionHistory(): WritingSession[]: Gets the complete writing session history.
  • getElapsedTime(): number: Gets the elapsed time in milliseconds.
  • getFormattedElapsedTime(): string: Gets the elapsed time as a formatted string (HH:MM:SS).
  • isTimerRunning(): boolean: Checks if the writing timer is currently running.
  • onTimerTick(callback: (elapsedTime: number) => void): void: Sets a callback function for timer tick events.

โฑ๏ธ HandwritingTimer

Tracks writing sessions with detailed statistics and snapshots.

  • constructor(options?: HandwritingTimerOptions): Creates a new HandwritingTimer instance with optional configuration.
  • start(): void: Starts or resumes the timer.
  • pause(): void: Pauses the timer.
  • stop(): void: Stops the timer and finalizes the current session.
  • reset(): void: Resets the timer and clears the current session.
  • takeTextSnapshot(text: string): void: Takes a snapshot of the current text for writing speed calculation.
  • calculateWritingSpeed(): WritingSpeedStats: Calculates the writing speed based on text snapshots.
  • getSessionHistory(): WritingSession[]: Gets the complete session history.
  • getElapsedTime(): number: Gets the elapsed time in milliseconds.
  • getFormattedTime(): string: Gets the elapsed time as a formatted string (HH:MM:SS).
  • isTimerRunning(): boolean: Checks if the timer is currently running.
  • onTick(callback: (elapsedTime: number) => void): void: Sets a callback function for timer tick events.

๐Ÿ” CodeAnalyzer

Analyzes code for potential issues, bugs, and improvements.

Methods

  • constructor(options?: CodeAnalysisOptions): Creates a new CodeAnalyzer instance with optional configuration.
  • analyzeFile(filePath: string): Promise<CodeAnalysisResult>: Analyzes a single file for issues and returns detailed results.
  • analyzeFiles(patterns: string | string[]): Promise<CodeAnalysisResult[]>: Analyzes multiple files matching the glob patterns.

Examples

import { CodeAnalyzer, SeverityLevel, CategoryType } from '@regele/devtools';

// Create analyzer with custom options
const analyzer = new CodeAnalyzer({
  minSeverity: SeverityLevel.Warning,  // Only report warnings and above
  categories: [                         // Only include these categories
    CategoryType.Security,
    CategoryType.Performance
  ],
  maxDepth: 3,                         // Maximum recursion depth
  ignore: ['node_modules/**', 'dist/**'] // Patterns to ignore
});

// Analyze a single file
const result = await analyzer.analyzeFile('src/app.js');
console.log(`Found ${result.findings.length} issues in ${result.filePath}`);

// Process findings
result.findings.forEach(finding => {
  console.log(`[${finding.severity}] ${finding.message} at line ${finding.line}`);
  console.log(`Category: ${finding.category}`);
  console.log(`Suggestion: ${finding.suggestion}`);
});

// Analyze multiple files
const results = await analyzer.analyzeFiles('src/**/*.js');
const totalIssues = results.reduce((sum, r) => sum + r.findings.length, 0);
console.log(`Found ${totalIssues} issues across ${results.length} files`);

// Calculate quality score
const qualityScore = results.reduce((score, result) => {
  // Higher score means better quality
  const fileScore = 100 - (result.findings.length * 5);
  return score + Math.max(0, fileScore);
}, 0) / results.length;

console.log(`Overall code quality score: ${qualityScore.toFixed(2)}/100`);

Analysis Categories

The CodeAnalyzer detects issues in the following categories:

  • Performance: Nested loops, unbatched DOM updates, unthrottled event listeners
  • Security: Unsanitized user input, unsafe eval usage, dangerous innerHTML
  • Maintainability: Complex functions, deep nesting, duplicated code, missing JSDoc
  • Bugs: Off-by-one errors, unhandled promises, null dereferences, inconsistent returns
  • Style: Naming conventions, indentation, semicolon usage, function style

๐Ÿ“ License


0.9.6

9 months ago

0.9.5

9 months ago

0.9.4

9 months ago

0.9.3

9 months ago

0.9.2

9 months ago

0.9.1

9 months ago

0.9.0

9 months ago

0.8.4

9 months ago

0.8.3

9 months ago

0.8.1

9 months ago

0.7.0

9 months ago

0.6.3

9 months ago

0.6.2

9 months ago

0.5.2

9 months ago

0.5.0

9 months ago

0.4.0

9 months ago

0.3.2

9 months ago

0.3.1

9 months ago

0.3.0

9 months ago

0.2.3

9 months ago

0.2.2

9 months ago

0.2.1

9 months ago

0.2.0

9 months ago

0.1.0

9 months ago