From c8029d72ae1c9d85b01e77d1995d949f3af56fc2 Mon Sep 17 00:00:00 2001 From: Lovinson Dieujuste Date: Wed, 4 Nov 2026 04:36:49 -0500 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20add=20math=20core=20for=20formattin?= =?UTF-8?q?g=20AI=20answers=20=F0=9F=A7=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the pure math helpers that decide which `$...$` spans are math and which are prices, plus code masking and LaTeX cleanup. Nothing uses them yet; they are the first piece of the fix for #914. Co-Authored-By: Claude Opus 5.5 --- packages/utils/package.json | 3 +- packages/utils/src/ai-formatting/index.ts | 1 + packages/utils/src/ai-formatting/math.test.ts | 204 ++++++++ packages/utils/src/ai-formatting/math.ts | 475 ++++++++++++++++++ packages/utils/tsconfig.json | 3 +- 5 files changed, 684 insertions(+), 2 deletions(-) create mode 100644 packages/utils/src/ai-formatting/index.ts create mode 100644 packages/utils/src/ai-formatting/math.test.ts create mode 100644 packages/utils/src/ai-formatting/math.ts diff --git a/packages/utils/package.json b/packages/utils/package.json index 9685cb2d7..d9fed5882 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -4,7 +4,8 @@ "private": true, "type": "module", "exports": { - ".": "./src/index.ts" + ".": "./src/index.ts", + "./ai-formatting": "./src/ai-formatting/index.ts" }, "scripts": { "lint": "eslint .", diff --git a/packages/utils/src/ai-formatting/index.ts b/packages/utils/src/ai-formatting/index.ts new file mode 100644 index 000000000..353160663 --- /dev/null +++ b/packages/utils/src/ai-formatting/index.ts @@ -0,0 +1 @@ +export * from './math'; diff --git a/packages/utils/src/ai-formatting/math.test.ts b/packages/utils/src/ai-formatting/math.test.ts new file mode 100644 index 000000000..d9cb2b944 --- /dev/null +++ b/packages/utils/src/ai-formatting/math.test.ts @@ -0,0 +1,204 @@ +import { describe, expect, test } from 'bun:test'; + +import { + balanceLatexBraces, + decodeHtmlEntities, + escapeHtml, + findInlineMathDollarSpans, + isInlineMathSpan, + isKaTeXErrorOutput, + isPlainNumericMathContent, + looksLikeLatex, + normalizeLatex, + protectCodeRegions, + replaceInlineMathDollarSpans, + wrapBareLatexSetBraces, +} from './math'; + +function mathIn(text: string): string[] { + return findInlineMathDollarSpans(text).map((span) => span.inner); +} + +describe(findInlineMathDollarSpans.name, () => { + test('Should only find math between prices, not the prices themselves.', () => { + expect(mathIn('Costs $5, $10, $20 and $x$.')).toEqual(['x']); + }); + + test.each([ + '$5 and $10', + '$5-$10', + '$100,000 is twice $50,000', + 'It costs $5 or $10 per month.', + ])('Should treat "%s" as currency.', (text) => { + expect(mathIn(text)).toEqual([]); + }); + + test.each([ + ['$3x$', '3x'], + ['$f(x)$', 'f(x)'], + ["$f''(t)$", "f''(t)"], + ['$|x - 3|$', '|x - 3|'], + ["$A'$", "A'"], + ['$2x < 4$', '2x < 4'], + ['$x >= 0$', 'x >= 0'], + ['$a != b$', 'a != b'], + ['$O(n \\log n)$', 'O(n \\log n)'], + ])('Should treat "%s" as math.', (text, inner) => { + expect(mathIn(text)).toEqual([inner]); + }); + + test.each(['$x-axis$', '$p-value$', '$low-level$'])( + 'Should treat "%s" as prose.', + (text) => { + expect(mathIn(text)).toEqual([]); + } + ); + + test('A hard math signal should win over the spacing rule.', () => { + expect(mathIn('$ E = mc^2 $')).toEqual([' E = mc^2 ']); + }); + + test('A padded simple span should stay literal (same as pandoc).', () => { + expect(mathIn('$ x $')).toEqual([]); + }); + + test('A lone price on one line should not stop math on later lines.', () => { + expect(mathIn('It costs $5.\nSolve $x^2 = 4$.')).toEqual(['x^2 = 4']); + }); + + test('Should skip escaped dollar signs and display math.', () => { + expect(mathIn('\\$x\\$ and $$y^2$$')).toEqual([]); + }); +}); + +describe(replaceInlineMathDollarSpans.name, () => { + test('Should replace only the math and keep the currency as is.', () => { + const result = replaceInlineMathDollarSpans( + 'Pay $5 to get $x^2$.', + (latex) => `[${latex}]` + ); + + expect(result).toEqual('Pay $5 to get [x^2].'); + }); +}); + +describe(isInlineMathSpan.name, () => { + test('A span containing an HTML tag is never math.', () => { + expect(isInlineMathSpan('5
  • ', undefined)).toBe(false); + }); + + test('A digit right after the closer means it is currency.', () => { + expect(isInlineMathSpan('x', '1')).toBe(false); + }); +}); + +describe(looksLikeLatex.name, () => { + test('A sentence is not LaTeX.', () => { + expect(looksLikeLatex('this is just a long sentence')).toBe(false); + }); + + test('A bare number is only math when allowed.', () => { + expect(looksLikeLatex('12')).toBe(false); + expect(looksLikeLatex('12', { allowBareNumbers: true })).toBe(true); + }); + + test('An interval is LaTeX.', () => { + expect(looksLikeLatex('(0, 1]')).toBe(true); + }); +}); + +describe(isPlainNumericMathContent.name, () => { + test.each(['7.23', '1,234.56', ' 10 '])('"%s" is a number.', (value) => { + expect(isPlainNumericMathContent(value)).toBe(true); + }); + + test.each(['', '3x', '1/2'])('"%s" is not a number.', (value) => { + expect(isPlainNumericMathContent(value)).toBe(false); + }); +}); + +describe(normalizeLatex.name, () => { + test('Should map Unicode math letters to ASCII.', () => { + expect(normalizeLatex('๐‘ฅ + ๐€')).toEqual('x + A'); + }); + + test('Should fix "x 2" written instead of "x^2".', () => { + expect(normalizeLatex('x 2 + y 2 = 1')).toEqual('x^2 + y^2 = 1'); + }); + + test('Should replace the Unicode minus and collapse "++".', () => { + expect(normalizeLatex('a โˆ’ b ++ c')).toEqual('a - b + c'); + }); + + test('Should drop a duplicated equation tail.', () => { + expect(normalizeLatex('x^2 + y^2 = 1. x 2 + y 2')).toEqual('x^2 + y^2 = 1'); + }); + + test('Should keep primes.', () => { + expect(normalizeLatex("A'")).toEqual("A'"); + }); +}); + +describe(balanceLatexBraces.name, () => { + test('Should drop a stray closing brace.', () => { + expect(balanceLatexBraces('w = abba \\in \\Sigma^*}')).toEqual( + 'w = abba \\in \\Sigma^*' + ); + }); + + test('Should close an unclosed group.', () => { + expect(balanceLatexBraces('\\frac{1}{2')).toEqual('\\frac{1}{2}'); + }); + + test('Should ignore escaped braces.', () => { + expect(balanceLatexBraces('\\{1, 2\\}')).toEqual('\\{1, 2\\}'); + }); +}); + +describe(wrapBareLatexSetBraces.name, () => { + test('Should wrap bare set braces in $.', () => { + expect(wrapBareLatexSetBraces('S = \\{1, 2\\}')).toEqual( + 'S = $\\{1, 2\\}$' + ); + }); + + test('Should leave wrapped set braces alone.', () => { + expect(wrapBareLatexSetBraces('$\\{1, 2\\}$')).toEqual('$\\{1, 2\\}$'); + }); +}); + +describe(protectCodeRegions.name, () => { + test('Should mask code so math passes cannot touch it.', () => { + const text = 'Use `price = $5` and\n```\n$x$\n```\nthen $y^2$.'; + const code = protectCodeRegions(text); + + expect(code.hasCode).toBe(true); + expect(code.masked).not.toContain('price'); + expect(mathIn(code.masked)).toEqual(['y^2']); + expect(code.restore(code.masked)).toEqual(text); + }); + + test('Should only mask fences when asked to.', () => { + const code = protectCodeRegions('`a` and\n```\nb\n```', { + fencesOnly: true, + }); + + expect(code.masked).toStartWith('`a` and\n'); + }); +}); + +describe(escapeHtml.name, () => { + test('Should escape HTML and decode back to the same text.', () => { + const text = `Tom's & Jerry's`; + + expect(escapeHtml(text)).not.toContain('<'); + expect(decodeHtmlEntities(escapeHtml(text))).toEqual(text); + }); +}); + +describe(isKaTeXErrorOutput.name, () => { + test('Should detect KaTeX error markup.', () => { + expect(isKaTeXErrorOutput('')).toBe(true); + expect(isKaTeXErrorOutput('')).toBe(false); + }); +}); diff --git a/packages/utils/src/ai-formatting/math.ts b/packages/utils/src/ai-formatting/math.ts new file mode 100644 index 000000000..8e39c3d80 --- /dev/null +++ b/packages/utils/src/ai-formatting/math.ts @@ -0,0 +1,475 @@ +// Math core for rendering AI output. This module has no KaTeX import, so it +// can be used on the server and in tests. + +export function escapeHtml(s: string): string { + return s + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +export function decodeHtmlEntities(text: string): string { + return text + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/&/g, '&'); +} + +/** + * Drops a duplicated equation tail that models sometimes append after a + * period (ie: "... = 1. x 2 + y 2"). + */ +export function trimSloppyDuplicateEquationSuffix(latex: string): string { + const parts = latex.split(/\.\s+(?=[a-zA-Z]\s*2\b)/u); + + return parts.length <= 1 ? latex : (parts[0]?.trim() ?? latex); +} + +// Unicode Mathematical Alphanumeric ranges (bold, italic, bold italic, sans, +// sans bold, sans italic) mapped to the ASCII letter they start at. +const MATH_LATIN_RANGES: Array<[number, number]> = [ + [0x1d400, 0x41], + [0x1d41a, 0x61], + [0x1d434, 0x41], + [0x1d44e, 0x61], + [0x1d468, 0x41], + [0x1d482, 0x61], + [0x1d5a0, 0x41], + [0x1d5ba, 0x61], + [0x1d5d4, 0x41], + [0x1d5ee, 0x61], + [0x1d608, 0x41], + [0x1d622, 0x61], +]; + +/** + * Maps Unicode Mathematical Alphanumeric letters (๐‘ฅ, ๐€, ๐—ฎ...) to ASCII. + */ +export function normalizeMathematicalLatinLetters(text: string): string { + let out = ''; + + for (const ch of text) { + const cp = ch.codePointAt(0)!; + + const range = MATH_LATIN_RANGES.find(([start]) => { + return cp >= start && cp <= start + 25; + }); + + out += range ? String.fromCharCode(range[1] + (cp - range[0])) : ch; + } + + return out; +} + +/** + * Cleans LaTeX right before KaTeX: zero-width characters, "++", wrapping + * quotes, the Unicode minus and "x 2" written instead of "x^2". + */ +export function normalizeLatex(latex: string): string { + let s = latex + .replace(/[\u200B-\u200D\uFEFF\u00A0]/g, ' ') + .replace(/\+\s*\+/g, '+') + // ASCII `'` is left alone, since it is a prime (ie: `A'`, `f''(x)`). + .replace(/^\s*[โ€˜โ€™`]\s*|\s*[โ€˜โ€™`]\s*$/g, '') + .trim(); + + s = normalizeMathematicalLatinLetters(s); + s = s.replace(/โˆ’/g, '-'); + s = trimSloppyDuplicateEquationSuffix(s); + + let prev = ''; + + while (prev !== s) { + prev = s; + s = s.replace(/\b([a-zA-Z])\s+2\b/g, '$1^2'); + } + + return s.replace(/\s+/g, ' ').trim(); +} + +function hasLetterLike(s: string): boolean { + return /[a-zA-Z]|\p{L}/u.test(s); +} + +function hasDigitLike(s: string): boolean { + return /\d|\p{N}/u.test(s); +} + +/** + * A comparison with an operand on BOTH sides (`2x < 4`), so that `5<` (from + * `$5<$10`) and `
  • ` are excluded. + */ +function hasComparisonWithOperands(s: string): boolean { + return /(?:[A-Za-z0-9)\]}]|\p{L}|\p{N})\s*(?:<=|>=|!=|[<>โ‰คโ‰ฅโ‰ ])\s*(?:[-+]?(?:[A-Za-z0-9([{\\]|\p{L}|\p{N}))/u.test( + s + ); +} + +/** + * Returns true for a plain number (ie: `7.23`, `1,234.56`), which is not + * LaTeX. + */ +export function isPlainNumericMathContent(content: string): boolean { + const t = content.trim(); + + return !!t && /^\d+(?:[.,]\d+)*$/.test(t); +} + +export type InlineMathOptions = { + /** + * Treats a paired bare number (`$12$`) as math rather than currency. Only + * use this for math-heavy documents. + */ + allowBareNumbers?: boolean; + + /** + * Classifies the entity-decoded text (ie: for stored HTML like `$3 < 5$`). + */ + decodeEntities?: boolean; +}; + +/** + * Returns true if the content between a `$` pair looks like LaTeX rather than + * prose or currency. + */ +export function looksLikeLatex( + content: string, + options?: InlineMathOptions +): boolean { + const t = content.trim(); + + if (!t) { + return false; + } + + // Unicode math letters, or LaTeX syntax: \cmd, ^, _, {}. + if (/[\u{1D400}-\u{1D7FF}]/u.test(t) || /\\|[\^_{}]/.test(t)) { + return true; + } + + // Hyphenated words: "low-level", "x-axis", "p-value". + if (/[a-zA-Z]{2,}-[a-zA-Z]+|[a-zA-Z]+-[a-zA-Z]{2,}/.test(t)) { + return false; + } + + // A sentence. + if (t.split(/\s+/).filter((w) => /^[a-zA-Z]{3,}$/.test(w)).length >= 4) { + return false; + } + + // Prose with an equals sign: "the mean is 5 when...". + if (/=/.test(t) && /\b[a-zA-Z]{4,}\b/.test(t)) { + return false; + } + + if ( + /^\p{L}{1,3}$/u.test(t) || // x, sin, KE + /^\d+(?:\.\d+)?\s*\p{L}$/u.test(t) || // 3x + /^[a-zA-Z]\s*[\^_]\s*\{?[^}]*\}?$/.test(t) || + /^[a-zA-Z]{1,8}(?:['โ€ฒโ€ณ]+|_\w+|_\{[^}]+\}|\^\w+|\^\{[^}]+\})*\s*\([^()\n]{0,60}\)\s*$/.test( + t + ) // f(x), f'(x) + ) { + return true; + } + + // |x - 3| + if (/^\|[^|\n]{1,24}\|$/.test(t) && (hasLetterLike(t) || hasDigitLike(t))) { + return true; + } + + // "$10" is currency. + if (isPlainNumericMathContent(t)) { + return options?.allowBareNumbers === true; + } + + if (/=/.test(t) && (hasLetterLike(t) || hasDigitLike(t))) { + return true; + } + + if (hasComparisonWithOperands(t)) { + return true; + } + + if (hasLetterLike(t) && /[+\-*/=โˆ’]/.test(t)) { + return true; + } + + if (hasDigitLike(t) && /[+\-*/โˆ’]/.test(t)) { + return true; + } + + // Intervals: [a, b], (0, 1]. + return /^[[(].*[\])]$/.test(t) && (hasLetterLike(t) || hasDigitLike(t)); +} + +const HTML_TAG_IN_SPAN = + /<\/[A-Za-z][\w:-]*\s*>|<[A-Za-z][\w:-]*(?:\s[^<>]*)?\/?>/; + +const HARD_MATH_SIGNAL = /[\\^_{}]|[\u{1D400}-\u{1D7FF}]/u; + +/** + * Returns true if the text between a `$` pair is math. + * + * @param inner - NOT trimmed, since the spacing is a signal (same flanking + * rules as pandoc and markdown-it-texmath). + * @param after - The character right after the closing `$`. + */ +export function isInlineMathSpan( + inner: string, + after?: string, + options?: InlineMathOptions +): boolean { + if (!inner) { + return false; + } + + const probe = options?.decodeEntities ? decodeHtmlEntities(inner) : inner; + + // A span containing an HTML tag is never math. + if (HTML_TAG_IN_SPAN.test(probe)) { + return false; + } + + // `$ E = mc^2 $` still works. + if (HARD_MATH_SIGNAL.test(probe)) { + return true; + } + + // A', f'' + if (/^[A-Za-z]'+$/.test(probe)) { + return true; + } + + // "$5 and $10" + if (/^\s/.test(probe) || /\s$/.test(probe)) { + return false; + } + + // "$5-$10": the closer is really the next amount's opener. + if (after !== undefined && /\d/.test(after)) { + return false; + } + + return looksLikeLatex(probe.trim(), options); +} + +export type InlineMathSpan = { + end: number; + inner: string; + start: number; +}; + +/** + * Finds real `$...$` math spans. This is a scanner and not a regex replace, + * because a rejected span must re-anchor at `open + 1` so that its closing + * `$` can serve as the next span's opener (ie: `Costs $5, $10 and $x$.` must + * still find `$x$`). + * + * `$$` is skipped (display math has its own pass), and `\$` is a literal + * dollar sign. + */ +export function findInlineMathDollarSpans( + text: string, + options?: InlineMathOptions +): InlineMathSpan[] { + const spans: InlineMathSpan[] = []; + + let i = 0; + + while (i < text.length) { + const open = text.indexOf('$', i); + + if (open < 0) { + break; + } + + if (text[open - 1] === '\\') { + i = open + 1; + continue; + } + + if (text[open + 1] === '$') { + i = open + 2; + continue; + } + + let close = -1; + let lineEnd = -1; + + for (let j = open + 1; j < text.length; j++) { + // Inline math never spans lines. + if (text[j] === '\n') { + lineEnd = j; + break; + } + + if (text[j] === '$' && text[j - 1] !== '\\') { + close = j; + break; + } + } + + if (close < 0) { + if (lineEnd < 0) { + break; + } + + // A lone price: skip the rest of the line, but keep scanning. + i = lineEnd + 1; + continue; + } + + const inner = text.slice(open + 1, close); + + if (isInlineMathSpan(inner, text[close + 1], options)) { + spans.push({ end: close, inner, start: open }); + i = close + 1; + } else { + // Re-anchor, and do NOT skip the closer. + i = open + 1; + } + } + + return spans; +} + +/** + * Renders the accepted math spans. Every other character (including currency + * `$`) stays the same. + */ +export function replaceInlineMathDollarSpans( + text: string, + render: (inner: string) => string, + options?: InlineMathOptions +): string { + const spans = findInlineMathDollarSpans(text, options); + + if (!spans.length) { + return text; + } + + let out = ''; + let cursor = 0; + + for (const span of spans) { + out += text.slice(cursor, span.start) + render(span.inner.trim()); + cursor = span.end + 1; + } + + return out + text.slice(cursor); +} + +/** + * Wraps `\{ ... \}` in `$` when the model omitted the delimiters. + */ +export function wrapBareLatexSetBraces(text: string): string { + return text.replace(/(? { + return `$${full}$`; + }); +} + +/** + * Balances `{}` groups by dropping stray closers and closing unclosed groups. + * Escaped `\{` and `\}` are ignored. + */ +export function balanceLatexBraces(latex: string): string { + let depth = 0; + const strays: number[] = []; + + for (let i = 0; i < latex.length; i++) { + const c = latex[i]; + + if (c === '\\') { + i++; + } else if (c === '{') { + depth++; + } else if (c === '}') { + if (depth === 0) { + strays.push(i); + } else { + depth--; + } + } + } + + if (!strays.length && depth === 0) { + return latex; + } + + let out = ''; + let cursor = 0; + + for (const i of strays) { + out += latex.slice(cursor, i); + cursor = i + 1; + } + + return out + latex.slice(cursor) + '}'.repeat(depth); +} + +// Code regions are where `$`, `*`, `_` and `<` are literal. +const CODE_REGION_PATTERNS: RegExp[] = [ + /```[\s\S]*?```/g, + /~~~[\s\S]*?~~~/g, + //gi, + //gi, + /`[^`\n]*`/g, +]; + +// Letters and digits only, so that no math pass mistakes it for notation. +function sentinel(i: number): string { + return `CODEREGION${i}ENDCODEREGION`; +} + +/** + * Masks code fences and inline code with sentinels, so that math and HTML + * passes can't touch them. Call `restore` on the processed text afterwards. + */ +export function protectCodeRegions( + text: string, + options?: { fencesOnly?: boolean } +) { + const stash: string[] = []; + + const patterns = options?.fencesOnly + ? CODE_REGION_PATTERNS.slice(0, 2) + : CODE_REGION_PATTERNS; + + let masked = text; + + for (const pattern of patterns) { + masked = masked.replace(pattern, (match) => { + stash.push(match); + + return sentinel(stash.length - 1); + }); + } + + return { + hasCode: stash.length > 0, + masked, + restore(processed: string): string { + let out = processed; + + // Outermost first, since later regions can be nested in earlier ones. + for (let i = stash.length - 1; i >= 0; i--) { + out = out.split(sentinel(i)).join(stash[i]!); + } + + return out; + }, + }; +} + +export function isKaTeXErrorOutput(html: string): boolean { + return ( + html.includes('parse-error') || + html.includes('#cc0000') || + html.includes('in math mode at position') + ); +} diff --git a/packages/utils/tsconfig.json b/packages/utils/tsconfig.json index 118911ac3..5f7392e81 100644 --- a/packages/utils/tsconfig.json +++ b/packages/utils/tsconfig.json @@ -3,6 +3,7 @@ "include": ["src"], "compilerOptions": { "module": "ESNext", - "moduleResolution": "Bundler" + "moduleResolution": "Bundler", + "target": "ESNext" } } From 6111c37c0f7ef9d71c8ce981a98b1614a1769529 Mon Sep 17 00:00:00 2001 From: Lovinson Dieujuste Date: Wed, 4 Nov 2026 04:37:17 -0500 Subject: [PATCH 2/2] =?UTF-8?q?feat:=20add=20KaTeX=20rendering=20and=20mar?= =?UTF-8?q?kdown=20parsers=20for=20AI=20answers=20=F0=9F=93=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds `safeKatexRender` (falls back to the escaped source instead of KaTeX's red error output), `preprocessContent` (normalizes `\(...\)` and `\[...\]` to `$`/`$$` and strips stray HTML, never touching code), and the inline and block parsers that turn raw AI output into tokens a renderer can map to elements. Nothing uses them yet. Part of #914. Co-Authored-By: Claude Opus 5.5 --- bun.lock | 7 + packages/utils/package.json | 6 +- .../utils/src/ai-formatting/blocks.test.ts | 138 +++++++++++ packages/utils/src/ai-formatting/blocks.ts | 220 ++++++++++++++++++ packages/utils/src/ai-formatting/index.ts | 3 + .../utils/src/ai-formatting/inline.test.ts | 105 +++++++++ packages/utils/src/ai-formatting/inline.ts | 143 ++++++++++++ .../utils/src/ai-formatting/katex.test.ts | 39 ++++ packages/utils/src/ai-formatting/katex.ts | 31 +++ .../src/ai-formatting/preprocess.test.ts | 48 ++++ .../utils/src/ai-formatting/preprocess.ts | 52 +++++ 11 files changed, 791 insertions(+), 1 deletion(-) create mode 100644 packages/utils/src/ai-formatting/blocks.test.ts create mode 100644 packages/utils/src/ai-formatting/blocks.ts create mode 100644 packages/utils/src/ai-formatting/inline.test.ts create mode 100644 packages/utils/src/ai-formatting/inline.ts create mode 100644 packages/utils/src/ai-formatting/katex.test.ts create mode 100644 packages/utils/src/ai-formatting/katex.ts create mode 100644 packages/utils/src/ai-formatting/preprocess.test.ts create mode 100644 packages/utils/src/ai-formatting/preprocess.ts diff --git a/bun.lock b/bun.lock index 8b867586c..2f47a4d5d 100644 --- a/bun.lock +++ b/bun.lock @@ -276,6 +276,9 @@ "packages/utils": { "name": "@oyster/utils", "version": "0.0.0", + "dependencies": { + "katex": "^0.19.1", + }, "devDependencies": { "@oyster/eslint-config": "workspace:*", "nanoid": "^3.0.0", @@ -1766,6 +1769,8 @@ "jws": ["jws@3.2.2", "", { "dependencies": { "jwa": "^1.4.1", "safe-buffer": "^5.0.1" } }, "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA=="], + "katex": ["katex@0.19.1", "", { "dependencies": { "commander": "^15.0.0" }, "bin": { "katex": "cli.js" } }, "sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA=="], + "keyv": ["keyv@4.5.4", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="], "kind-of": ["kind-of@2.0.1", "", { "dependencies": { "is-buffer": "^1.0.2" } }, "sha512-0u8i1NZ/mg0b+W3MGGw5I7+6Eib2nx72S/QvXa0hYjEkjTknYmEYQJwGu3mLC0BrhtJjtQafTkyRUQ75Kx0LVg=="], @@ -2692,6 +2697,8 @@ "js-beautify/glob": ["glob@10.4.5", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^1.11.1" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg=="], + "katex/commander": ["commander@15.0.0", "", {}, "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg=="], + "kysely-codegen/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], "log-symbols/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], diff --git a/packages/utils/package.json b/packages/utils/package.json index d9fed5882..dc4f59ab7 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -5,7 +5,8 @@ "type": "module", "exports": { ".": "./src/index.ts", - "./ai-formatting": "./src/ai-formatting/index.ts" + "./ai-formatting": "./src/ai-formatting/index.ts", + "./katex": "./src/ai-formatting/katex.ts" }, "scripts": { "lint": "eslint .", @@ -13,6 +14,9 @@ "test": "bun test", "type-check": "tsc --noEmit" }, + "dependencies": { + "katex": "^0.19.1" + }, "devDependencies": { "@oyster/eslint-config": "workspace:*", "nanoid": "^3.0.0" diff --git a/packages/utils/src/ai-formatting/blocks.test.ts b/packages/utils/src/ai-formatting/blocks.test.ts new file mode 100644 index 000000000..4c3972407 --- /dev/null +++ b/packages/utils/src/ai-formatting/blocks.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, test } from 'bun:test'; + +import { parseAiMarkdown } from './blocks'; + +function text(content: string) { + return { type: 'text' as const, content }; +} + +describe(parseAiMarkdown.name, () => { + test('Should parse paragraphs and skip blank lines.', () => { + expect(parseAiMarkdown('First.\n\nSecond.')).toEqual([ + { type: 'paragraph', children: [text('First.')] }, + { type: 'paragraph', children: [text('Second.')] }, + ]); + }); + + test('Should parse headings, longest prefix first.', () => { + expect(parseAiMarkdown('# One\n#### Four')).toEqual([ + { type: 'heading', children: [text('One')], level: 1 }, + { type: 'heading', children: [text('Four')], level: 4 }, + ]); + }); + + test('Should parse unordered and ordered lists.', () => { + expect(parseAiMarkdown('- a\n* b\nโ€ข c\n\n3. d\n4. e')).toEqual([ + { + type: 'list', + items: [[text('a')], [text('b')], [text('c')]], + ordered: false, + start: 1, + }, + { + type: 'list', + items: [[text('d')], [text('e')]], + ordered: true, + start: 3, + }, + ]); + }); + + test('Should parse references inside list items.', () => { + expect(parseAiMarkdown('1. **Apply early** [ref:2]')).toEqual([ + { + type: 'list', + items: [ + [ + { type: 'bold', children: [text('Apply early')] }, + text(' '), + { type: 'ref', number: 2 }, + ], + ], + ordered: true, + start: 1, + }, + ]); + }); + + test('Should parse fenced code verbatim.', () => { + expect(parseAiMarkdown('```python\nx = $x$ * 2\n```')).toEqual([ + { type: 'code', content: 'x = $x$ * 2', language: 'python' }, + ]); + }); + + test('Should keep mermaid source unchanged and drop empty fences.', () => { + expect( + parseAiMarkdown('```mermaid\nA[Mean ($\\mu$)]\n```\n```\n\n```') + ).toEqual([ + { type: 'code', content: 'A[Mean ($\\mu$)]', language: 'mermaid' }, + ]); + }); + + test('Should parse display math on one line, with trailing text.', () => { + expect(parseAiMarkdown('$$x^2$$ is a square.')).toEqual([ + { type: 'math', latex: 'x^2' }, + { type: 'paragraph', children: [text('is a square.')] }, + ]); + }); + + test('Should parse display math across lines.', () => { + expect(parseAiMarkdown('$$\na + b\n= c\n$$ done')).toEqual([ + { type: 'math', latex: 'a + b\n= c' }, + { type: 'paragraph', children: [text('done')] }, + ]); + }); + + test('Should parse \\[ \\] as display math.', () => { + expect(parseAiMarkdown('\\[ \\int f \\]')).toEqual([ + { type: 'math', latex: '\\int f' }, + ]); + }); + + test('Should parse blockquotes and start a new one on > ".', () => { + expect(parseAiMarkdown('> a\n>\n> b\n> "c"')).toEqual([ + { type: 'quote', lines: [[text('a')], [text('b')]] }, + { type: 'quote', lines: [[text('"c"')]] }, + ]); + }); + + test('Should parse horizontal rules.', () => { + expect(parseAiMarkdown('a\n---\n***\n___')).toEqual([ + { type: 'paragraph', children: [text('a')] }, + { type: 'hr' }, + { type: 'hr' }, + { type: 'hr' }, + ]); + }); + + test('Should show images as links.', () => { + expect(parseAiMarkdown('![Logo](https://x.com/a.png)')).toEqual([ + { + type: 'paragraph', + children: [{ type: 'link', text: 'Logo', url: 'https://x.com/a.png' }], + }, + ]); + }); + + test('Should parse tables, with math in the cells.', () => { + expect( + parseAiMarkdown( + '| Algo | Time |\n|---|:---:|\n| Merge sort | $O(n \\log n)$ |' + ) + ).toEqual([ + { + type: 'table', + header: [[text('Algo')], [text('Time')]], + rows: [ + [[text('Merge sort')], [{ type: 'math', latex: 'O(n \\log n)' }]], + ], + }, + ]); + }); + + test('Should parse a table without a separator row as body rows.', () => { + expect(parseAiMarkdown('| a | b |')).toEqual([ + { type: 'table', header: [], rows: [[[text('a')], [text('b')]]] }, + ]); + }); +}); diff --git a/packages/utils/src/ai-formatting/blocks.ts b/packages/utils/src/ai-formatting/blocks.ts new file mode 100644 index 000000000..b11cac20d --- /dev/null +++ b/packages/utils/src/ai-formatting/blocks.ts @@ -0,0 +1,220 @@ +import { type InlineToken, parseInline } from './inline'; +import { preprocessContent } from './preprocess'; + +export type Block = + | { type: 'code'; content: string; language: string } + | { type: 'heading'; children: InlineToken[]; level: number } + | { type: 'hr' } + | { type: 'list'; items: InlineToken[][]; ordered: boolean; start: number } + | { type: 'math'; latex: string } + | { type: 'paragraph'; children: InlineToken[] } + | { type: 'quote'; lines: InlineToken[][] } + | { type: 'table'; header: InlineToken[][]; rows: InlineToken[][][] }; + +const FENCE_REGEX = /^\s*```\s*([\w+-]*)/; +const HEADING_REGEX = /^(#{1,6})\s+(.*)$/; +const HR_REGEX = /^(?:-{3,}|\*{3,}|_{3,})$/; +const IMAGE_REGEX = /^!\[([^\]]*)\]\((https?:\/\/[^\s)]+)\)$/; +const ORDERED_ITEM_REGEX = /^(\d+)\.\s+(.*)$/; +const TABLE_SEPARATOR_CELL_REGEX = /^[\s\-:]+$/; +const UNORDERED_ITEM_REGEX = /^[-*โ€ข]\s+(.*)$/; + +/** + * Parses raw model output (markdown with LaTeX math) into blocks that a + * renderer can map to elements. Every run of text is parsed with + * `parseInline`. + */ +export function parseAiMarkdown(raw: string): Block[] { + const lines = preprocessContent(raw).split('\n'); + const blocks: Block[] = []; + + // The list, table or blockquote that is currently open. + let list: Extract | null = null; + let quote: string[] | null = null; + let table: string[][] | null = null; + + function flush() { + if (list) { + blocks.push(list); + } + + if (quote) { + blocks.push({ type: 'quote', lines: quote.map(parseInline) }); + } + + if (table) { + blocks.push(toTableBlock(table)); + } + + list = null; + quote = null; + table = null; + } + + function pushParagraph(text: string) { + if (text.trim()) { + blocks.push({ type: 'paragraph', children: parseInline(text.trim()) }); + } + } + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!.trim(); + + // 1. Fenced code: collect lines verbatim until the closing fence. + const fence = line.match(FENCE_REGEX); + + if (fence) { + flush(); + + const content: string[] = []; + + while (++i < lines.length && !FENCE_REGEX.test(lines[i]!)) { + content.push(lines[i]!); + } + + if (content.some((l) => l.trim())) { + blocks.push({ + type: 'code', + content: content.join('\n'), + language: fence[1] || 'text', + }); + } + + continue; + } + + // 2. Display math: on one line, with trailing text, or across lines. + if (line.startsWith('$$')) { + flush(); + + let rest = line.slice(2); + let close = rest.indexOf('$$'); + + const latex: string[] = []; + + while (close < 0 && ++i < lines.length) { + latex.push(rest); + rest = lines[i]!; + close = rest.indexOf('$$'); + } + + latex.push(close < 0 ? rest : rest.slice(0, close)); + + blocks.push({ type: 'math', latex: latex.join('\n').trim() }); + + if (close >= 0) { + pushParagraph(rest.slice(close + 2)); + } + + continue; + } + + // 3. Headings. + const heading = line.match(HEADING_REGEX); + + if (heading) { + flush(); + + blocks.push({ + type: 'heading', + children: parseInline(heading[2]!), + level: heading[1]!.length, + }); + + continue; + } + + // 4. Blockquotes. A lone `>` keeps the quote open, and `> "` starts a new + // one. + if (line.startsWith('>')) { + const text = line.replace(/^>\s?/, ''); + + if (!quote || text.startsWith('"')) { + flush(); + quote = []; + } + + if (text) { + quote.push(text); + } + + continue; + } + + // 5. Horizontal rules. + if (HR_REGEX.test(line)) { + flush(); + blocks.push({ type: 'hr' }); + continue; + } + + // 6. Images are shown as links, so that we never load arbitrary images. + const image = line.match(IMAGE_REGEX); + + if (image) { + flush(); + + blocks.push({ + type: 'paragraph', + children: [ + { type: 'link', text: image[1] || image[2]!, url: image[2]! }, + ], + }); + + continue; + } + + // 7. Tables. + if (line.startsWith('|')) { + if (!table) { + flush(); + table = []; + } + + table.push(line.split('|').slice(1, -1)); + continue; + } + + // 8. Lists. + const ordered = line.match(ORDERED_ITEM_REGEX); + const unordered = line.match(UNORDERED_ITEM_REGEX); + + if (ordered || unordered) { + const isOrdered = !!ordered; + + if (!list || list.ordered !== isOrdered) { + flush(); + + list = { + type: 'list', + items: [], + ordered: isOrdered, + start: ordered ? Number(ordered[1]) : 1, + }; + } + + list.items.push(parseInline(ordered ? ordered[2]! : unordered![1]!)); + continue; + } + + // 9. Paragraphs. A blank line flushes the open block. + flush(); + pushParagraph(line); + } + + flush(); + + return blocks; +} + +function toTableBlock(rows: string[][]): Block { + const cells = rows.map((row) => row.map((cell) => parseInline(cell.trim()))); + + const hasHeader = + rows.length > 1 && + rows[1]!.every((cell) => TABLE_SEPARATOR_CELL_REGEX.test(cell)); + + return hasHeader + ? { type: 'table', header: cells[0]!, rows: cells.slice(2) } + : { type: 'table', header: [], rows: cells }; +} diff --git a/packages/utils/src/ai-formatting/index.ts b/packages/utils/src/ai-formatting/index.ts index 353160663..355b5bdf6 100644 --- a/packages/utils/src/ai-formatting/index.ts +++ b/packages/utils/src/ai-formatting/index.ts @@ -1 +1,4 @@ +export * from './blocks'; +export * from './inline'; export * from './math'; +export * from './preprocess'; diff --git a/packages/utils/src/ai-formatting/inline.test.ts b/packages/utils/src/ai-formatting/inline.test.ts new file mode 100644 index 000000000..7dae67264 --- /dev/null +++ b/packages/utils/src/ai-formatting/inline.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, test } from 'bun:test'; + +import { parseInline } from './inline'; + +describe(parseInline.name, () => { + test('Should keep multiplication asterisks as text.', () => { + expect(parseInline('5 * 3 * 2')).toEqual([ + { type: 'text', content: '5 * 3 * 2' }, + ]); + }); + + test('Should keep math inside bold.', () => { + expect(parseInline('**solve $x^2$**')).toEqual([ + { + type: 'bold', + children: [ + { type: 'text', content: 'solve ' }, + { type: 'math', latex: 'x^2' }, + ], + }, + ]); + }); + + test('Should not turn the * in two formulas into italics.', () => { + expect( + parseInline('$w \\in \\Sigma^*$ and $L \\subseteq \\Sigma^*$') + ).toEqual([ + { type: 'math', latex: 'w \\in \\Sigma^*' }, + { type: 'text', content: ' and ' }, + { type: 'math', latex: 'L \\subseteq \\Sigma^*' }, + ]); + }); + + test('Should keep the stray brace inside the math for KaTeX to fix.', () => { + expect(parseInline('$w = abba \\in \\Sigma^*}$')).toEqual([ + { type: 'math', latex: 'w = abba \\in \\Sigma^*}' }, + ]); + }); + + test('Should show a bare number wrapped in $ as plain text.', () => { + expect(parseInline('the mean was $7.23$')).toEqual([ + { type: 'text', content: 'the mean was ' }, + { type: 'text', content: '7.23' }, + ]); + }); + + test('Should treat $$ in a sentence as inline math.', () => { + expect(parseInline('Solve $$2x+3=11$$.')).toEqual([ + { type: 'text', content: 'Solve ' }, + { type: 'math', latex: '2x+3=11' }, + { type: 'text', content: '.' }, + ]); + }); + + test('Should keep prices as text.', () => { + expect(parseInline('Costs $5, $10, $20 and $x$.')).toEqual([ + { type: 'text', content: 'Costs $5, $10, $20 and ' }, + { type: 'math', latex: 'x' }, + { type: 'text', content: '.' }, + ]); + }); + + test('Should not touch the contents of inline code.', () => { + expect(parseInline('Run `price = $5` or `**a** *b* $x$`.')).toEqual([ + { type: 'text', content: 'Run ' }, + { type: 'code', content: 'price = $5' }, + { type: 'text', content: ' or ' }, + { type: 'code', content: '**a** *b* $x$' }, + { type: 'text', content: '.' }, + ]); + }); + + test('Should parse italics.', () => { + expect(parseInline('This is *really* early.')).toEqual([ + { type: 'text', content: 'This is ' }, + { type: 'italic', content: 'really' }, + { type: 'text', content: ' early.' }, + ]); + }); + + test('Should fold typographic asterisks, but not the โˆ— operator.', () => { + expect(parseInline('๏ผŠ๏ผŠbold๏ผŠ๏ผŠ and a โˆ— b โˆ— c')).toEqual([ + { type: 'bold', children: [{ type: 'text', content: 'bold' }] }, + { type: 'text', content: ' and a โˆ— b โˆ— c' }, + ]); + }); + + test('Should parse thread references and links.', () => { + expect( + parseInline('Apply early [ref:1]. See [the guide](https://x.com/a).') + ).toEqual([ + { type: 'text', content: 'Apply early ' }, + { type: 'ref', number: 1 }, + { type: 'text', content: '. See ' }, + { type: 'link', text: 'the guide', url: 'https://x.com/a' }, + { type: 'text', content: '.' }, + ]); + }); + + test('Should not parse links that are not http(s).', () => { + expect(parseInline('[click](javascript:alert(1))')).toEqual([ + { type: 'text', content: '[click](javascript:alert(1))' }, + ]); + }); +}); diff --git a/packages/utils/src/ai-formatting/inline.ts b/packages/utils/src/ai-formatting/inline.ts new file mode 100644 index 000000000..ad09ee4ad --- /dev/null +++ b/packages/utils/src/ai-formatting/inline.ts @@ -0,0 +1,143 @@ +import { findInlineMathDollarSpans, protectCodeRegions } from './math'; + +export type InlineToken = + | { type: 'bold'; children: InlineToken[] } + | { type: 'code'; content: string } + | { type: 'italic'; content: string } + | { type: 'link'; text: string; url: string } + | { type: 'math'; latex: string } + | { type: 'ref'; number: number } + | { type: 'text'; content: string }; + +type Match = { + end: number; + start: number; + token: InlineToken; +}; + +const BOLD_REGEX = /\*\*(.+?)\*\*/g; + +// `$$2x+3=11$$` written in the middle of a sentence. +const INLINE_DISPLAY_MATH_REGEX = /\$\$([^$\n]+)\$\$/g; + +// A bare number wrapped for emphasis (ie: "the mean was $7.23$"). +const BARE_NUMBER_REGEX = /(? string; + +/** + * Bold is parsed first and outermost, so that `**solve $x$**` keeps both the + * bold and the math. + */ +function parseBold(text: string, restoreCode: RestoreCode): InlineToken[] { + const tokens: InlineToken[] = []; + + let cursor = 0; + + for (const match of text.matchAll(BOLD_REGEX)) { + tokens.push(...parseFlat(text.slice(cursor, match.index), restoreCode)); + + tokens.push({ + type: 'bold', + children: parseFlat(match[1]!, restoreCode), + }); + + cursor = match.index! + match[0].length; + } + + tokens.push(...parseFlat(text.slice(cursor), restoreCode)); + + return tokens; +} + +function parseFlat(text: string, restoreCode: RestoreCode): InlineToken[] { + if (!text) { + return []; + } + + const matches: Match[] = []; + + function add(start: number, end: number, token: InlineToken) { + const overlaps = matches.some((m) => start < m.end && end > m.start); + + if (!overlaps) { + matches.push({ end, start, token }); + } + } + + function addAll( + regex: RegExp, + toToken: (match: RegExpMatchArray) => InlineToken + ) { + for (const match of text.matchAll(regex)) { + add(match.index!, match.index! + match[0].length, toToken(match)); + } + } + + // Single `$` math comes from the scanner, never from a regex. + for (const span of findInlineMathDollarSpans(text)) { + add(span.start, span.end + 1, { type: 'math', latex: span.inner.trim() }); + } + + addAll(INLINE_DISPLAY_MATH_REGEX, (m) => ({ type: 'math', latex: m[1]! })); + addAll(BARE_NUMBER_REGEX, (m) => ({ type: 'text', content: m[1]! })); + + addAll(CODE_SENTINEL_REGEX, (m) => ({ + type: 'code', + content: restoreCode(m[0]), + })); + + addAll(REF_REGEX, (m) => ({ type: 'ref', number: Number(m[1]) })); + addAll(LINK_REGEX, (m) => ({ type: 'link', text: m[1]!, url: m[2]! })); + addAll(ITALIC_REGEX, (m) => ({ type: 'italic', content: m[1]! })); + + matches.sort((a, b) => a.start - b.start); + + const tokens: InlineToken[] = []; + + let cursor = 0; + + for (const match of matches) { + if (match.start > cursor) { + tokens.push({ type: 'text', content: text.slice(cursor, match.start) }); + } + + tokens.push(match.token); + cursor = match.end; + } + + if (cursor < text.length) { + tokens.push({ type: 'text', content: text.slice(cursor) }); + } + + return tokens; +} diff --git a/packages/utils/src/ai-formatting/katex.test.ts b/packages/utils/src/ai-formatting/katex.test.ts new file mode 100644 index 000000000..31a4c733d --- /dev/null +++ b/packages/utils/src/ai-formatting/katex.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, test } from 'bun:test'; + +import { safeKatexRender } from './katex'; + +describe(safeKatexRender.name, () => { + test('Should render valid LaTeX.', () => { + const html = safeKatexRender('x^2 + y^2 = z^2', false); + + expect(html).toContain('class="katex"'); + }); + + test('Should render display math.', () => { + const html = safeKatexRender('\\int_{a}^{b} f(x) \\, dx', true); + + expect(html).toContain('katex-display'); + }); + + test('Should show the escaped source instead of the KaTeX error.', () => { + const html = safeKatexRender('\\frac{', false); + + expect(html).toEqual('\\frac{'); + expect(html).not.toContain('#cc0000'); + expect(html).not.toContain('parse-error'); + }); + + test('Should escape HTML in the fallback.', () => { + const html = safeKatexRender('\\notacommand{