File size: 4,654 Bytes
ceea2c9
58c3261
ceea2c9
58c3261
 
 
ceea2c9
 
 
58c3261
21c8074
 
ceea2c9
 
 
 
 
 
21c8074
 
c58b657
 
 
 
 
 
21c8074
 
401629b
 
 
506a948
 
 
 
21c8074
0bd4e31
21c8074
 
0bd4e31
 
21c8074
0bd4e31
 
 
 
506a948
21c8074
c6832b1
 
 
c71ba63
21c8074
 
 
 
 
0248c94
21c8074
ceea2c9
 
21c8074
 
ceea2c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/**
 * Math Preprocessing for KaTeX Rendering
 * 
 * This file contains utilities to preprocess mathematical content before
 * KaTeX rendering. It handles common LaTeX formatting issues, delimiter
 * normalization, and edge cases that would otherwise break rendering.
 */

/**
 * Preprocesses content to make it KaTeX-compatible.
 * Comprehensive preprocessing to handle user input edge cases.
 * Backend prompt reduces LLM errors, but this handles ALL input.
 */
export function preprocessMathContent(content: string): string {
  if (!content) return content;
  
  let processed = content;
  
  // Step 1: Normalize delimiters (MUST BE FIRST)
  // Convert \(...\) to $...$ and \[...\] to $$...$$
  processed = processed
    .replace(/\\\(/g, '$')
    .replace(/\\\)/g, '$')
    .replace(/\\\[/g, '\n$$')
    .replace(/\\\]/g, '$$\n');
  
  // Step 2: Remove nested inline math delimiters inside display math
  // Pattern: $$...$ ... $...$$ → $$... ... ...$$
  // Must handle both single-line and multi-line display math
  processed = processed.replace(/\$\$([\s\S]*?)\$\$/g, (_match, content) => {
    // Remove ALL $ signs inside display math (they're always wrong)
    const cleaned = content.replace(/\$/g, '');
    return `$$${cleaned}$$`;
  });
  
  // Step 3: Clean up delimiter stacking ($$$$, $$$, etc.)
  while (processed.includes('$$$')) {
    processed = processed.replace(/\$\$\$\$+/g, '$$');
    processed = processed.replace(/\$\$\$/g, '$$');
  }
  
  // Step 4: Fix malformed \left and \right
  processed = processed.replace(/\\left\\frac/g, '\\frac');
  processed = processed.replace(/\\right\\frac/g, '\\frac');
  processed = processed.replace(/\\left(?![(\[{|])/g, '');
  processed = processed.replace(/\\right(?![)\]}|])/g, '');
  
  // Step 5: Fix list markers contaminating delimiters
  processed = processed.replace(/(\d+)\$\$/g, '$1. $$');
  processed = processed.replace(/\$\$(\d+)\$/g, '$$ $1.');
  processed = processed.replace(/\$(\d+)\$/g, '$ $1. $');
  
  // Step 6: Ensure display math has proper newlines
  processed = processed.replace(/\$\$([\s\S]*?)\$\$/g, (_match, math) => {
    const trimmed = math.trim();
    if (trimmed.includes('\n')) {
      return `$$\n${trimmed}\n$$\n`;
    }
    return `$$${trimmed}$$\n`;
  });
  
  // Step 7: Clean up multiple newlines
  processed = processed.replace(/\n{3,}/g, '\n\n');
  
  return processed;
}

/**
 * Extract math expressions from content for validation/preview
 */
export function extractMathExpressions(content: string): Array<{
  type: 'inline' | 'display';
  content: string;
  raw: string;
}> {
  const expressions: Array<{ type: 'inline' | 'display'; content: string; raw: string }> = [];
  
  // Extract display math $$...$$
  const displayRegex = /\$\$([\s\S]*?)\$\$/g;
  let match;
  while ((match = displayRegex.exec(content)) !== null) {
    expressions.push({
      type: 'display',
      content: match[1].trim(),
      raw: match[0]
    });
  }
  
  // Extract inline math $...$ (but not $$...$$)
  const inlineRegex = /(?<!\$)\$([^$\n]+?)\$(?!\$)/g;
  while ((match = inlineRegex.exec(content)) !== null) {
    expressions.push({
      type: 'inline',
      content: match[1].trim(),
      raw: match[0]
    });
  }
  
  return expressions;
}

/**
 * Check if content contains valid-looking math
 */
export function hasMathContent(content: string): boolean {
  if (!content) return false;
  
  // Check for common math patterns
  const patterns = [
    /\$[^$]+\$/,                    // Inline math
    /\$\$[\s\S]*?\$\$/,             // Display math
    /\\\([\s\S]*?\\\)/,            // \(...\)
    /\\\[[\s\S]*?\\\]/,            // \[...\]
    /\\begin\{(align|aligned|equation|gather|multline|math|displaymath)/,  // Environments
    /\\(frac|sum|prod|int|lim|sqrt|alpha|beta|gamma|delta|epsilon|pi|theta|phi|lambda)/,  // Common commands
    /_[a-zA-Z0-9]/,                 // Subscripts
    /\^[a-zA-Z0-9]/,                // Superscripts
  ];
  
  return patterns.some(pattern => pattern.test(content));
}

/**
 * Sanitize math content to prevent XSS while preserving LaTeX
 * MathJax's safe extension handles most of this, but we add extra protection
 */
export function sanitizeMathContent(content: string): string {
  if (!content) return content;
  
  // Remove script tags (though MathJax shouldn't execute them anyway)
  let sanitized = content.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
  
  // Remove event handlers
  sanitized = sanitized.replace(/\s*on\w+\s*=\s*["'][^"']*["']/gi, '');
  
  // Allow only safe HTML tags that don't interfere with math
  // (MathJax handles the rest)
  
  return sanitized;
}