Skip to content

AI Code Explainer — TypeScript source

Paste any code snippet and get a plain-language explanation from an LLM — beginner, developer, or expert depth — with your own free Groq key, straight from your browser.

This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// src/lib/code-explainer.ts — the pure core of the AI code explainer
// (AI Studio tool #4, FEAT-076; class rollout per the FEAT-049 verdict).
// Language guessing + depth-graded prompt building + reply cleanup are pure
// so the island is a thin shell over the shared provider layer
// (src/lib/ai-studio), and this file is a future Go-twin candidate.

export type ExplanationLevel = 'beginner' | 'developer' | 'expert';

const MAX_CODE_CHARS = 12000;

/**
 * Cheap keyword heuristics — enough to name the language in the prompt so
 * the model starts right; never a language detector. Falls back to 'text'.
 */
export function guessLanguage(code: string): string {
  const rules: Array<{ lang: string; re: RegExp }> = [
    { lang: 'go', re: /\bpackage\s+\w+|\bfunc\s+\w+|:=/ },
    { lang: 'rust', re: /\bfn\s+\w+|\blet\s+mut\b|\bimpl\b/ },
    { lang: 'python', re: /\bdef\s+\w+\s*\(|\bprint\s*\(|\bimport\s+\w+\s*$/m },
    { lang: 'sql', re: /\bSELECT\b.+\bFROM\b/i },
    { lang: 'typescript', re: /\binterface\s+\w+\s*\{|\btype\s+\w+\s*=|:\s*(string|number|boolean)\b/ },
    { lang: 'javascript', re: /\bconst\s+\w+\s*=|=>|console\.log/ },
    { lang: 'css', re: /[.#]?[\w-]+\s*\{[^}]*:[^}]*;/ },
    { lang: 'html', re: /<\/?[a-z][\w-]*(\s+[\w-]+="[^"]*")*\s*\/?>/i },
  ];
  for (const { lang, re } of rules) {
    if (re.test(code)) return lang;
  }
  return 'text';
}

const LEVEL_CONTRACT: Record<ExplanationLevel, string> = {
  beginner:
    'Explain for a smart newcomer: no unexplained jargon, short sentences, one everyday analogy if it helps. Say what it does first, then how, step by step.',
  developer:
    'Explain for a working developer: concise and practical. Lead with what it does, then the flow, the patterns used, and the pitfalls an editor should catch.',
  expert:
    'Explain for an expert: dense and precise. Cover invariants, complexity, edge cases, and anything subtle an experienced reviewer would flag.',
};

/** Build the [system, user] chat messages for the provider layer. */
export function buildPromptMessages(
  code: string,
  opts: { level: ExplanationLevel },
): Array<{ role: 'system' | 'user'; content: string }> {
  // Truncate BEFORE guessing: the heuristics only need a sample, and running
  // them over a 30k-char paste is pure waste (this showed up as a suite-load
  // timeout in the cap test).
  const truncated = code.length > MAX_CODE_CHARS;
  const body = truncated ? `${code.slice(0, MAX_CODE_CHARS)}\n… (code truncated)` : code;
  const lang = guessLanguage(body);
  return [
    {
      role: 'system',
      content: `You explain code. ${LEVEL_CONTRACT[opts.level]} The code appears to be ${lang}${
        lang === 'text' ? ' (no clear language — say so and reason about it as pseudocode)' : ''
      }. Use short paragraphs or bullets; markdown is fine.`,
    },
    { role: 'user', content: body },
  ];
}

/**
 * Clean the model's reply into displayable explanation text. No strict
 * format contract — any non-empty cleaned text is the explanation; null
 * only when nothing survives.
 */
export function parseExplanation(text: string): string | null {
  const cleaned = text.replace(/```[a-z]*\n?/g, '').trim();
  return cleaned.length > 0 ? cleaned : null;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →