1 | import { inspect, InspectOptions } from 'node:util'
|
2 | import { StringifyAnyOptions, _stringifyAny, JsonStringifyFunction } from '@naturalcycles/js-lib'
|
3 |
|
4 | export interface InspectAnyOptions extends StringifyAnyOptions, InspectOptions {}
|
5 |
|
6 | const INSPECT_OPT: InspectOptions = {
|
7 | breakLength: 80, // default: ??
|
8 | depth: 10, // default: 2
|
9 | }
|
10 |
|
11 | /**
|
12 | * Just a convenience export of a const that fulfills the JsonStringifyFunction interface.
|
13 | */
|
14 | export const inspectAnyStringifyFn: JsonStringifyFunction = obj => inspectAny(obj)
|
15 |
|
16 | /**
|
17 | * Transforms ANY to human-readable string (via util.inspect mainly).
|
18 | * Safe (no error throwing).
|
19 | *
|
20 | * Correclty prints Errors, AppErrors, ErrorObjects: error.message + \n + inspect(error.data)
|
21 | *
|
22 | * Enforces max length (default to 10_000, pass 0 to skip it).
|
23 | *
|
24 | * Logs numbers as-is, e.g: `6`.
|
25 | * Logs strings as-is (without single quotes around, unlike default util.inspect behavior).
|
26 | * Otherwise - just uses util.inspect() with reasonable defaults.
|
27 | *
|
28 | * Returns 'empty_string' if empty string is passed.
|
29 | * Returns 'undefined' if undefined is passed (default util.inspect behavior).
|
30 | *
|
31 | * Based on `_stringifyAny` from `js-lib`, just replaced `JSON.stringify` with `util.inspect`.
|
32 | */
|
33 | export function inspectAny(obj: any, opt: InspectAnyOptions = {}): string {
|
34 | // Inspect handles functions better
|
35 | if (typeof obj === 'function') {
|
36 | return inspect(obj, {
|
37 | ...INSPECT_OPT,
|
38 | ...opt,
|
39 | })
|
40 | }
|
41 |
|
42 | return _stringifyAny(obj, {
|
43 | ...opt,
|
44 | stringifyFn: obj =>
|
45 | inspect(obj, {
|
46 | ...INSPECT_OPT,
|
47 | ...opt,
|
48 | }),
|
49 | })
|
50 | }
|