| 17 | const CLOSE = '\n```'; |
| 18 | |
| 19 | export function splitForStream(text: string, maxLen: number): Piece[] { |
| 20 | if (text.length === 0) return [{ display: '', consumed: 0 }]; |
| 21 | |
| 22 | // Tokenize into lines, keeping each trailing "\n" attached so offsets stay exact. |
| 23 | const lines: string[] = []; |
| 24 | let s = 0; |
| 25 | for (let i = 0; i < text.length; i++) { |
| 26 | if (text[i] === '\n') { lines.push(text.slice(s, i + 1)); s = i + 1; } |
| 27 | } |
| 28 | if (s < text.length) lines.push(text.slice(s)); |
| 29 | |
| 30 | const pieces: Piece[] = []; |
| 31 | let disp = ''; |
| 32 | let consumed = 0; |
| 33 | let fenceOpen = false; |
| 34 | let fenceInfo = ''; |
| 35 | |
| 36 | const reopenPrefix = () => '```' + fenceInfo + '\n'; |
| 37 | const isFresh = () => disp.length === (fenceOpen ? reopenPrefix().length : 0); |
| 38 | const cut = () => { |
| 39 | pieces.push({ display: fenceOpen ? disp + CLOSE : disp, consumed }); |
| 40 | disp = fenceOpen ? reopenPrefix() : ''; |
| 41 | consumed = 0; |
| 42 | }; |
| 43 | |
| 44 | for (let li = 0; li < lines.length; li++) { |
| 45 | let line = lines[li]!; |
| 46 | const isFenceLine = FENCE.test(line); |
| 47 | const willBeOpen = isFenceLine ? !fenceOpen : fenceOpen; |
| 48 | const room = () => maxLen - (willBeOpen ? CLOSE.length : 0) - disp.length; |
| 49 | |
| 50 | while (line.length > room()) { |
| 51 | if (!isFresh()) { cut(); continue; } // flush current piece, retry on a clean one |
| 52 | const take = Math.max(1, room()); // line alone too big → hard char-split |
| 53 | disp += line.slice(0, take); consumed += take; |
| 54 | cut(); |
| 55 | line = line.slice(take); |
| 56 | } |
| 57 | |
| 58 | disp += line; consumed += line.length; |
| 59 | if (isFenceLine) { |
| 60 | if (!fenceOpen) { fenceOpen = true; fenceInfo = line.trim().slice(3).trim(); } |
| 61 | else { fenceOpen = false; fenceInfo = ''; } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | pieces.push({ display: disp, consumed }); |
| 66 | return pieces; |
| 67 | } |