or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-cross-inspect

Cross platform implementation of Node's util.inspect for formatting JavaScript values

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/cross-inspect@1.0.x

To install, run

npx @tessl/cli install tessl/npm-cross-inspect@1.0.0

index.mddocs/

Cross Inspect

Cross Inspect provides a cross-platform implementation of Node.js's util.inspect function for formatting and displaying JavaScript values. It offers comprehensive value formatting including strings, functions, objects, arrays, and error handling with circular reference detection and configurable recursion limits.

Package Information

  • Package Name: cross-inspect
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install cross-inspect

Core Imports

import { inspect } from "cross-inspect";

CommonJS:

const { inspect } = require("cross-inspect");

Basic Usage

import { inspect } from "cross-inspect";

// Basic value formatting
console.log(inspect("hello")); // "\"hello\""
console.log(inspect(42)); // "42"
console.log(inspect(true)); // "true"
console.log(inspect(null)); // "null"
console.log(inspect(undefined)); // "undefined"

// Function formatting
function myFunction() {}
console.log(inspect(myFunction)); // "[function myFunction]"

// Object formatting
const obj = { name: "Alice", age: 30 };
console.log(inspect(obj)); // "{ name: \"Alice\", age: 30 }"

// Array formatting
const arr = [1, 2, 3];
console.log(inspect(arr)); // "[1, 2, 3]"

// Error formatting
const error = new Error("Something went wrong");
console.log(inspect(error)); // "Error: Something went wrong;\n [stack trace]"

// Special case: GraphQLError always uses toString() (note: assignment behavior in source)
const graphqlError = new Error("GraphQL error message");
console.log(inspect(graphqlError)); // Uses toString() method (name gets set to "GraphQLError")

Architecture

Cross Inspect is built around several key components:

  • Value Type Detection: Uses JavaScript's typeof operator and instanceof checks to determine formatting strategy
  • Circular Reference Prevention: Tracks previously seen values in a readonly array to detect and prevent infinite recursion
  • Depth Limiting: Limits inspection depth to 3 levels (MAX_RECURSIVE_DEPTH) to prevent performance issues with deeply nested objects
  • Special Type Handling: Custom formatting for Error objects, functions, and objects with toJSON() methods
  • Cross-platform Compatibility: No Node.js dependencies, works in any JavaScript environment

Capabilities

Value Inspection

Formats any JavaScript value into a human-readable string representation for debugging and logging purposes.

/**
 * Used to print values in error messages.
 * Provides cross-platform implementation of Node's util.inspect functionality.
 * 
 * @param value - Any JavaScript value to format
 * @returns String representation of the input value
 */
function inspect(value: unknown): string;

Constants

/**
 * Maximum depth for recursive object inspection.
 * Objects nested deeper than this will be displayed as [ObjectType] placeholders.
 */
const MAX_RECURSIVE_DEPTH: 3;

Usage Examples:

import { inspect } from "cross-inspect";

// Primitive values
inspect("text")      // "\"text\""
inspect(123)         // "123"
inspect(true)        // "true"
inspect(null)        // "null"
inspect(undefined)   // "undefined"

// Functions
const fn = function namedFn() { return 42; };
inspect(fn)          // "[function namedFn]"

const arrow = () => {};
inspect(arrow)       // "[function]"

// Objects
inspect({ a: 1, b: 2 })                    // "{ a: 1, b: 2 }"
inspect({})                                // "{}"

// Arrays
inspect([1, "two", true])                  // "[1, \"two\", true]"
inspect([])                                // "[]"

// Nested structures
inspect({ users: [{ name: "Alice" }] })    // "{ users: [{ name: \"Alice\" }] }"

// Circular references
const circular = { self: null };
circular.self = circular;
inspect(circular)                          // "{ self: [Circular] }"

// Error objects
const err = new Error("Failed");
inspect(err)                               // "Error: Failed;\n [stack trace]"

// GraphQLError (special handling - uses toString(), name gets assigned)
const graphqlError = new Error("Custom GraphQL error");
inspect(graphqlError)                      // Uses toString() method

// AggregateError (special handling - includes sub-errors)
const subError = new Error("Database connection failed");
const aggErr = new AggregateError([subError], "Multiple errors occurred");
inspect(aggErr)                            // Shows main error + formatted sub-errors array

// Objects with toJSON method
const jsonable = {
  name: "test",
  toJSON() { return { serialized: true }; }
};
inspect(jsonable)                          // "{ serialized: true }"

// Deep nesting (limited by MAX_RECURSIVE_DEPTH = 3)
const deep = { l1: { l2: { l3: { l4: "too deep" } } } };
inspect(deep)                              // "{ l1: { l2: { l3: [Object] } } }"

Key Features

  • Cross-platform compatibility: Works in any JavaScript environment without Node.js dependencies
  • Circular reference detection: Safely handles objects with circular references by marking them as [Circular]
  • Depth limiting: Prevents infinite recursion by limiting inspection depth to 3 levels
  • Type-aware formatting: Different formatting strategies for strings, functions, objects, arrays, and errors
  • Error handling: Special formatting for Error objects, GraphQLError (uses toString()), and AggregateError with sub-error details
  • JSON compatibility: Respects toJSON() methods when available
  • Memory efficient: Uses read-only arrays for tracking seen values to minimize memory impact