Find the first balanced JSON object in a string (depth-counting on braces, respecting strings).
(text: string)
| 432 | |
| 433 | /** Find the first balanced JSON object in a string (depth-counting on braces, respecting strings). */ |
| 434 | function findFirstJsonObject(text: string): string | null { |
| 435 | const start = text.indexOf('{'); |
| 436 | if (start === -1) return null; |
| 437 | let depth = 0; |
| 438 | let inString = false; |
| 439 | let escape = false; |
| 440 | for (let i = start; i < text.length; i++) { |
| 441 | const c = text[i]!; |
| 442 | if (escape) { escape = false; continue; } |
| 443 | if (c === '\\') { escape = true; continue; } |
| 444 | if (c === '"') { inString = !inString; continue; } |
| 445 | if (inString) continue; |
| 446 | if (c === '{') depth++; |
| 447 | else if (c === '}') { |
| 448 | depth--; |
| 449 | if (depth === 0) return text.slice(start, i + 1); |
| 450 | } |
| 451 | } |
| 452 | return null; |
| 453 | } |
| 454 | |
| 455 | /** Find the last balanced JSON object — useful when the model writes prose then ends with a call. */ |
| 456 | function findLastJsonObject(text: string): { text: string; start: number; end: number } | null { |
no outgoing calls
no test coverage detected