UNPKG

@gramio/split

Version:

Split messages into multiple parts

55 lines (50 loc) 1.62 kB
import { FormattableString } from '@gramio/format'; const TEXT_LIMIT = 4096; function splitText(text, entities, mode = "symbol", textLimit = TEXT_LIMIT) { if (text.length <= textLimit) return [{ text, entities }]; const splitIndex = textLimit; const partText = text.slice(0, splitIndex); const remainingText = text.slice(splitIndex); const currentEntities = entities?.flatMap((e) => { if (e.offset >= splitIndex) return []; if (e.offset + e.length <= splitIndex) return [{ ...e }]; return [ { ...e, length: splitIndex - e.offset } ]; }) ?? []; const remainingEntities = entities?.flatMap((e) => { if (e.offset + e.length <= splitIndex) return []; const offset = Math.max(e.offset - splitIndex, 0); const length = e.offset < splitIndex ? e.length - (splitIndex - e.offset) : e.length; return length > 0 ? [{ ...e, offset, length }] : []; }) ?? []; return [ { text: partText, entities: currentEntities.length ? currentEntities : void 0 }, ...splitText(remainingText, remainingEntities, mode, textLimit) ]; } async function splitMessage(text, action, limit = TEXT_LIMIT) { const splittedParts = splitText( text.toString(), typeof text === "string" ? void 0 : text.entities, "symbol", limit ); const responses = []; for (const part of splittedParts) { const formattableString = new FormattableString( part.text, part.entities ?? [] ); const response = await action(formattableString); responses.push(response); } return responses; } export { splitMessage };