@@ -20,6 +20,7 @@ type FenceSplit = {
2020type BreakResult = {
2121 index : number ;
2222 fenceSplit ?: FenceSplit ;
23+ preserveNextWhitespace ?: boolean ;
2324} ;
2425
2526type ParagraphBreak = {
@@ -124,6 +125,28 @@ function extendBreakThroughParagraphSeparator(buffer: string, index: number): nu
124125 return paragraphSeparator ? index + paragraphSeparator [ 0 ] . length : index ;
125126}
126127
128+ function findTableRowBreakBeforeLimit ( params : {
129+ buffer : string ;
130+ table : TableSpan ;
131+ offset : number ;
132+ minChars : number ;
133+ maxChars : number ;
134+ } ) : number {
135+ const { buffer, table, offset, minChars, maxChars } = params ;
136+ const tableStart = Math . max ( 0 , table . start - offset ) ;
137+ const tableEnd = Math . min ( buffer . length , table . end - offset ) ;
138+ const limit = Math . min ( maxChars , tableEnd ) ;
139+ let newlineIdx = buffer . lastIndexOf ( "\n" , limit - 1 ) ;
140+ while ( newlineIdx >= tableStart ) {
141+ const candidate = newlineIdx + 1 ;
142+ if ( candidate > tableStart && candidate >= minChars && candidate <= maxChars ) {
143+ return candidate ;
144+ }
145+ newlineIdx = buffer . lastIndexOf ( "\n" , newlineIdx - 1 ) ;
146+ }
147+ return - 1 ;
148+ }
149+
127150export class EmbeddedBlockChunker {
128151 #buffer = "" ;
129152 readonly #chunking: BlockReplyChunking ;
@@ -285,10 +308,17 @@ export class EmbeddedBlockChunker {
285308 }
286309
287310 const nextStart =
288- absoluteBreakIdx < source . length && / \s / . test ( source [ absoluteBreakIdx ] )
311+ ! breakResult . preserveNextWhitespace &&
312+ absoluteBreakIdx < source . length &&
313+ / \s / . test ( source [ absoluteBreakIdx ] )
289314 ? absoluteBreakIdx + 1
290315 : absoluteBreakIdx ;
291- return { start : skipLeadingNewlines ( source , nextStart ) , reopenFence : undefined } ;
316+ return {
317+ start : breakResult . preserveNextWhitespace
318+ ? nextStart
319+ : skipLeadingNewlines ( source , nextStart ) ,
320+ reopenFence : undefined ,
321+ } ;
292322 }
293323
294324 #pickSoftBreakIndex(
@@ -448,8 +478,22 @@ export class EmbeddedBlockChunker {
448478 }
449479 const tableEnd = table . end - offset ;
450480 if ( tableEnd > 0 && tableEnd <= buffer . length ) {
451- return { index : extendBreakThroughParagraphSeparator ( buffer , tableEnd ) } ;
481+ const extendedTableEnd = extendBreakThroughParagraphSeparator ( buffer , tableEnd ) ;
482+ if ( extendedTableEnd <= maxChars ) {
483+ return { index : extendedTableEnd } ;
484+ }
485+ }
486+ const rowBreak = findTableRowBreakBeforeLimit ( {
487+ buffer,
488+ table,
489+ offset,
490+ minChars,
491+ maxChars,
492+ } ) ;
493+ if ( rowBreak !== - 1 ) {
494+ return { index : rowBreak , preserveNextWhitespace : true } ;
452495 }
496+ return { index : maxChars , preserveNextWhitespace : true } ;
453497 }
454498 return { index : maxChars } ;
455499 }
0 commit comments