CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-plato

JavaScript source analysis and visualizer that generates detailed complexity reports

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

utilities.mddocs/

Utility Functions

Helper functions for file operations, JSON processing, and output formatting. These utilities support the core analysis functionality and provide common operations used throughout Plato.

Capabilities

File Path Operations

Find common base paths from arrays of file paths for consistent report generation.

/**
 * Find common base path from array of file paths
 * @param {Array} files - Array of file paths
 * @returns {String} Common base path
 */
function findCommonBase(files);

Parameters:

  • files (Array): Array of file paths to analyze

Returns: String - The common base path shared by all input files

Usage Examples:

const { findCommonBase } = require('plato/lib/util');

// Find common base for report generation
const files = [
  '/project/src/app.js',
  '/project/src/utils/helper.js',
  '/project/src/components/modal.js'
];

const basePath = findCommonBase(files);
console.log(basePath); // '/project/src'

// Use with relative paths
const relativeFiles = [
  'src/app.js',
  'src/utils/helper.js',
  'test/app.test.js'
];

const relativeBase = findCommonBase(relativeFiles);
console.log(relativeBase); // '.'

JSON Processing

Format and read JSON data with specialized handling for reports and configuration files.

/**
 * Format JSON with identifier stripping for clean output
 * @param {Object} report - Report object to format
 * @returns {String} Formatted JSON string
 */
function formatJSON(report);

/**
 * Read and parse JSON file with error handling
 * @param {String} file - File path to JSON file
 * @param {Object} options - Options object
 * @returns {Object} Parsed JSON or empty object on error
 */
function readJSON(file, options);

formatJSON Parameters:

  • report (Object): Report object to format and stringify

Returns: String - Formatted JSON string with identifiers stripped

readJSON Parameters:

  • file (String): File path to the JSON file to read
  • options (Object): Configuration options for reading

Returns: Object - Parsed JSON object, or empty object {} if file read/parse fails

Usage Examples:

const { formatJSON, readJSON } = require('plato/lib/util');

// Format report for output
const report = {
  complexity: { cyclomatic: 5 },
  info: { file: 'app.js' }
};

const formatted = formatJSON(report);
console.log(formatted); // Clean JSON string

// Read configuration files
const jshintConfig = readJSON('.jshintrc', {});
const packageInfo = readJSON('package.json', {});

// Safe reading - returns {} if file doesn't exist
const config = readJSON('nonexistent.json', {});
console.log(config); // {}

Source Code Processing

Process JavaScript source code for analysis and reporting.

/**
 * Remove JavaScript comments from source code string
 * @param {String} str - Source code string
 * @returns {String} Code without comments
 */
function stripComments(str);

Parameters:

  • str (String): JavaScript source code string

Returns: String - Source code with all comments removed

Usage Examples:

const { stripComments } = require('plato/lib/util');

const sourceCode = `
// This is a comment
function hello() {
  /* Multi-line comment
     spanning multiple lines */
  console.log('Hello World');
}
`;

const cleanCode = stripComments(sourceCode);
console.log(cleanCode);
// Output:
// function hello() {
//   console.log('Hello World');
// }

HTML Processing

Escape HTML entities for safe output in generated reports.

/**
 * Escape HTML entities in string for safe output
 * @param {String} html - HTML string to escape
 * @returns {String} Escaped HTML string
 */
function escapeHTML(html);

Parameters:

  • html (String): HTML string containing potential entities to escape

Returns: String - HTML string with entities properly escaped

Usage Examples:

const { escapeHTML } = require('plato/lib/util');

// Escape potentially dangerous HTML
const userInput = '<script>alert("XSS")</script>';
const safeHTML = escapeHTML(userInput);
console.log(safeHTML); // '&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;'

// Use in report generation
const fileName = 'app<test>.js';
const safeFileName = escapeHTML(fileName);
console.log(safeFileName); // 'app&lt;test&gt;.js'

Integration with Core Functionality

These utilities are used throughout Plato's core functionality:

Report Generation

// Example of utility integration in report generation
const { findCommonBase, formatJSON, escapeHTML } = require('plato/lib/util');

function generateReport(files, reports) {
  // Find common base for consistent paths
  const basePath = findCommonBase(files);
  
  // Process each report
  reports.forEach(report => {
    // Safe HTML for file names
    report.info.fileSafe = escapeHTML(report.info.file);
    
    // Format report data
    const jsonData = formatJSON(report);
    
    // Write to file...
  });
}

Configuration Loading

// Example of configuration loading
const { readJSON } = require('plato/lib/util');

function loadConfiguration() {
  // Load various config files safely
  const packageConfig = readJSON('package.json', {});
  const jshintConfig = readJSON('.jshintrc', {});
  const platoConfig = readJSON('.plato.json', {});
  
  return {
    package: packageConfig,
    jshint: jshintConfig,
    plato: platoConfig
  };
}

Source Code Analysis

// Example of source processing
const { stripComments } = require('plato/lib/util');
const fs = require('fs');

function analyzeFile(filePath) {
  const source = fs.readFileSync(filePath, 'utf8');
  
  // Remove comments for certain analysis types
  const cleanSource = stripComments(source);
  
  // Perform analysis on clean source
  return performComplexityAnalysis(cleanSource);
}

Error Handling

The utility functions are designed to be robust and handle common error scenarios:

File Operations

  • readJSON() returns empty object {} instead of throwing on file read errors
  • findCommonBase() handles empty arrays and invalid paths gracefully

String Processing

  • stripComments() handles malformed or incomplete comments
  • escapeHTML() processes null/undefined input safely
  • formatJSON() handles circular references and non-serializable objects

Safe Usage Patterns:

const { readJSON, findCommonBase } = require('plato/lib/util');

// Always safe - won't throw
const config = readJSON('might-not-exist.json', {});
const basePath = findCommonBase([]) || '.';

// Check results as needed
if (Object.keys(config).length > 0) {
  console.log('Configuration loaded');
}

Install with Tessl CLI

npx tessl i tessl/npm-plato

docs

cli-api.md

index.md

models.md

programmatic-api.md

reporters.md

utilities.md

tile.json