// Zalo rejects over-long texts. Split long replies, preferring paragraph // boundaries when chunkMode is 'newline'. export function chunk(text: string, limit: number, mode: 'length' | 'newline'): string[] { if (text.length <= limit) return [text] const out: string[] = [] let rest = text while (rest.length > limit) { let cut = limit if (mode === 'newline') { // Prefer the last double-newline (paragraph), then single newline, // then space. Fall back to hard cut. const para = rest.lastIndexOf('\n\n', limit) const line = rest.lastIndexOf('\n', limit) const space = rest.lastIndexOf(' ', limit) cut = para > limit / 2 ? para : line > limit / 2 ? line : space > 0 ? space : limit } out.push(rest.slice(0, cut)) rest = rest.slice(cut).replace(/^\n+/, '') } if (rest) out.push(rest) return out }