| 124 | } |
| 125 | |
| 126 | function toYaml(obj: any, indent = 0): string { |
| 127 | const spaces = ' '.repeat(indent) |
| 128 | |
| 129 | if (obj === null || obj === undefined) { |
| 130 | return 'null' |
| 131 | } |
| 132 | |
| 133 | if (typeof obj === 'string') { |
| 134 | if (obj.includes('\n')) { |
| 135 | const lines = obj.split('\n') |
| 136 | return ( |
| 137 | '|\n' + lines.map((line) => ' '.repeat(indent + 1) + line).join('\n') |
| 138 | ) |
| 139 | } |
| 140 | return obj.includes(':') || obj.includes('#') ? `"${obj}"` : obj |
| 141 | } |
| 142 | |
| 143 | if (typeof obj === 'number' || typeof obj === 'boolean') { |
| 144 | return String(obj) |
| 145 | } |
| 146 | |
| 147 | if (Array.isArray(obj)) { |
| 148 | if (obj.length === 0) return '[]' |
| 149 | return ( |
| 150 | '\n' + |
| 151 | obj |
| 152 | .map((item) => spaces + '- ' + toYaml(item, indent + 1).trimStart()) |
| 153 | .join('\n') |
| 154 | ) |
| 155 | } |
| 156 | |
| 157 | if (typeof obj === 'object') { |
| 158 | const entries = Object.entries(obj) |
| 159 | if (entries.length === 0) return '{}' |
| 160 | |
| 161 | return entries |
| 162 | .map(([key, value]) => { |
| 163 | const yamlValue = toYaml(value, indent + 1) |
| 164 | if ( |
| 165 | typeof value === 'object' && |
| 166 | value !== null && |
| 167 | !Array.isArray(value) && |
| 168 | Object.keys(value).length > 0 |
| 169 | ) { |
| 170 | return `${spaces}${key}:\n${yamlValue}` |
| 171 | } |
| 172 | if (typeof value === 'string' && value.includes('\n')) { |
| 173 | return `${spaces}${key}: ${yamlValue}` |
| 174 | } |
| 175 | return `${spaces}${key}: ${yamlValue}` |
| 176 | }) |
| 177 | .join('\n') |
| 178 | } |
| 179 | |
| 180 | return String(obj) |
| 181 | } |
| 182 | |
| 183 | export function formatToolOutput(output: unknown): string { |