/** * Turns a Mermaid parse/render failure into something a user can act on, * instead of leaving the graph area stuck on its loading state. */ import { MERMAID_MAX_TEXT_SIZE } from './dependency-graph-shared'; export interface MermaidErrorDetails { /** One-line summary for the error banner. */ message: string; /** Numbered chart source around the failing line, when Mermaid reports one. */ excerpt?: string; } /** Returns an error up front when the chart is too large for Mermaid to accept. */ export function checkChartSize(chart: string, maxTextSize = MERMAID_MAX_TEXT_SIZE): MermaidErrorDetails | null { if (chart.length <= maxTextSize) return null; return { message: `The graph source is ${chart.length.toLocaleString('en-US')} characters, above Mermaid's ` + `${maxTextSize.toLocaleString('en-US')} character limit. Turn off Types, Private or Exported ` + 'nodes, or scan fewer folders.', }; } export function describeMermaidError(error: unknown, chart: string): MermaidErrorDetails { const raw = error instanceof Error ? error.message : typeof error === 'object' && error && 'message' in error ? String((error as { message: unknown }).message) : String(error); const message = raw.split('\n')[0].trim() || 'Unknown Mermaid error'; const lineMatch = raw.match(/on line (\d+)/i); if (!lineMatch) return { message }; const lines = chart.split('\n'); const failing = Number(lineMatch[1]); const from = Math.max(1, failing - 2); const to = Math.min(lines.length, failing + 2); const width = String(to).length; const excerpt = lines .slice(from - 1, to) .map((text, i) => { const n = from + i; return `${n === failing ? '>' : ' '} ${String(n).padStart(width)} | ${text}`; }) .join('\n'); return { message, excerpt }; }