/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */ export function mdToPlain(md: string): string { return md .replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // links → their text .replace(/^#{1,6}\s+/gm, '') // heading markers .replace(/^[>\-*]\s+/gm, '') // quote/list markers .replace(/[*_~`]/g, '') // inline emphasis/code marks .replace(/\s+/g, ' ') .trim() } /** Truncate at a word boundary, adding an ellipsis when cut. */ export function truncate(text: string, max: number): string { if (text.length <= max) {return text} const slice = text.slice(0, max) const lastSpace = slice.lastIndexOf(' ') return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…` } /** Ensure a fragment ends like a sentence, so joined fragments don't run together. */ function terminate(text: string): string { return /[.!?…:]$/.test(text) ? text : `${text}.` } /** * A meta description from a page's Markdown (blocksToMarkdown output). * * Headings are skipped while there's body text — they usually repeat the page * title, which Google already shows above the snippet. Whole sentences are * kept up to `max`; a first sentence longer than that is cut at a word * boundary. Returns '' when the content has no text. */ export function describeFromMarkdown(md: string, max = 155): string { const parts = md.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean) const body = parts.filter((p) => !/^#{1,6}\s/.test(p) && !/^!\[/.test(p)) const source = (body.length ? body : parts).map(mdToPlain).filter(Boolean).map(terminate) const text = source.join(' ') if (!text) {return ''} if (text.length <= max) {return text} // Longest run of whole sentences that fits. const sentences = text.match(/[^.!?…]+[.!?…]+(?=\s|$)/g) ?? [] let out = '' for (const s of sentences) { const next = `${out} ${s.trim()}`.trim() if (next.length > max) {break} out = next } return out || truncate(text, max) }