MCPcopy Index your code
hub / github.com/Effect-TS/effect / formatUnknown

Function formatUnknown

packages/effect/src/Inspectable.ts:75–160  ·  view source on GitHub ↗
(
  input: unknown,
  options?: {
    readonly space?: number | string | undefined
    readonly ignoreToString?: boolean | undefined
  }
)

Source from the content-addressed store, hash-verified

73
74/** @internal */
75export function formatUnknown(
76 input: unknown,
77 options?: {
78 readonly space?: number | string | undefined
79 readonly ignoreToString?: boolean | undefined
80 }
81): string {
82 const space = options?.space ?? 0
83 const seen = new WeakSet<object>()
84 const gap = !space ? "" : (Predicate.isNumber(space) ? " ".repeat(space) : space)
85 const ind = (d: number) => gap.repeat(d)
86
87 const wrap = (v: unknown, body: string): string => {
88 const ctor = (v as any)?.constructor
89 return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body
90 }
91
92 const ownKeys = (o: object): Array<PropertyKey> => {
93 try {
94 return Reflect.ownKeys(o)
95 } catch {
96 return ["[ownKeys threw]"]
97 }
98 }
99
100 function go(v: unknown, d = 0): string {
101 if (Array.isArray(v)) {
102 if (seen.has(v)) return CIRCULAR
103 seen.add(v)
104 if (!gap || v.length <= 1) return `[${v.map((x) => go(x, d)).join(",")}]`
105 const inner = v.map((x) => go(x, d + 1)).join(",\n" + ind(d + 1))
106 return `[\n${ind(d + 1)}${inner}\n${ind(d)}]`
107 }
108
109 if (Predicate.isDate(v)) return formatDate(v)
110
111 if (
112 !options?.ignoreToString &&
113 Predicate.hasProperty(v, "toString") &&
114 Predicate.isFunction(v["toString"]) &&
115 v["toString"] !== Object.prototype.toString &&
116 v["toString"] !== Array.prototype.toString
117 ) {
118 const s = safeToString(v)
119 if (v instanceof Error && v.cause) {
120 return `${s} (cause: ${go(v.cause, d)})`
121 }
122 return s
123 }
124
125 if (Predicate.isString(v)) return JSON.stringify(v)
126
127 if (
128 Predicate.isNumber(v) ||
129 v == null ||
130 Predicate.isBoolean(v) ||
131 Predicate.isSymbol(v)
132 ) return String(v)

Callers 9

booleanFunction · 0.85
urlFunction · 0.85
portFunction · 0.85
dateFunction · 0.85
numberFunction · 0.85
integerFunction · 0.85
literalFunction · 0.85
logLevelFunction · 0.85
durationFunction · 0.85

Calls 1

goFunction · 0.70

Tested by

no test coverage detected