katex-render.mjs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. #!/usr/bin/env node
  2. /**
  3. * KaTeX 服务端渲染脚本
  4. * 用法: echo "HTML内容" | node katex-render.js
  5. * 或: node katex-render.js < input.html > output.html
  6. *
  7. * 将 HTML 中的 LaTeX 公式渲染为 KaTeX HTML
  8. */
  9. import { createRequire } from 'module';
  10. const require = createRequire(import.meta.url);
  11. // 尝试多个路径加载 KaTeX
  12. let katex;
  13. const possiblePaths = [
  14. '/usr/local/lib/node_modules/katex', // npm -g 全局安装路径
  15. '/usr/lib/node_modules/katex', // Alpine 系统路径
  16. 'katex', // 本地 node_modules
  17. ];
  18. let loadError = null;
  19. for (const modulePath of possiblePaths) {
  20. try {
  21. katex = require(modulePath);
  22. break;
  23. } catch (e) {
  24. loadError = e;
  25. }
  26. }
  27. if (!katex) {
  28. console.error('Error: KaTeX module not found.');
  29. console.error('Tried paths:', possiblePaths.join(', '));
  30. if (loadError) console.error('Last error:', loadError.message);
  31. process.exit(1);
  32. }
  33. // 读取标准输入
  34. let input = '';
  35. process.stdin.setEncoding('utf8');
  36. process.stdin.on('readable', () => {
  37. let chunk;
  38. while ((chunk = process.stdin.read()) !== null) {
  39. input += chunk;
  40. }
  41. });
  42. process.stdin.on('end', () => {
  43. try {
  44. const output = renderMathInHtml(input);
  45. process.stdout.write(output);
  46. } catch (error) {
  47. console.error('KaTeX render error:', error.message);
  48. process.exit(1);
  49. }
  50. });
  51. /**
  52. * 解码 HTML 实体
  53. */
  54. function decodeHtmlEntities(text) {
  55. return text
  56. .replace(/&lt;/g, '<')
  57. .replace(/&gt;/g, '>')
  58. .replace(/&amp;/g, '&')
  59. .replace(/&quot;/g, '"')
  60. .replace(/&#39;/g, "'")
  61. .replace(/&apos;/g, "'")
  62. .replace(/&nbsp;/g, ' ');
  63. }
  64. /**
  65. * 编码 HTML 实体(用于安全输出)
  66. */
  67. function encodeHtmlEntities(text) {
  68. return text
  69. .replace(/&/g, '&amp;')
  70. .replace(/</g, '&lt;')
  71. .replace(/>/g, '&gt;');
  72. }
  73. /**
  74. * 渲染 HTML 中的所有数学公式
  75. */
  76. function renderMathInHtml(html) {
  77. // 定界符配置(按优先级排序)
  78. const delimiters = [
  79. { left: '$$', right: '$$', display: true },
  80. { left: '\\[', right: '\\]', display: true },
  81. { left: '\\(', right: '\\)', display: false },
  82. { left: '$', right: '$', display: false },
  83. ];
  84. let result = html;
  85. // 按顺序处理每种定界符
  86. for (const delimiter of delimiters) {
  87. result = processDelimiter(result, delimiter.left, delimiter.right, delimiter.display);
  88. }
  89. return result;
  90. }
  91. /**
  92. * 处理特定定界符的公式
  93. */
  94. function processDelimiter(html, left, right, displayMode) {
  95. // 转义正则特殊字符
  96. const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  97. const leftEscaped = escapeRegex(left);
  98. const rightEscaped = escapeRegex(right);
  99. // 构建正则表达式
  100. // 【关键修复】排除包含 HTML 标签的内容(不匹配 < 或 >)
  101. let pattern;
  102. if (left === '$' && right === '$') {
  103. // 单个 $...$:不匹配 $$,不匹配包含 < > 的内容
  104. pattern = new RegExp(`(?<!\\$)\\$(?!\\$)([^$<>]+?)(?<!\\$)\\$(?!\\$)`, 'g');
  105. } else if (left === '$$' && right === '$$') {
  106. // $$...$$:不匹配包含 < > 的内容
  107. pattern = new RegExp(`\\$\\$([^<>]*?)\\$\\$`, 'g');
  108. } else {
  109. // \(...\) 和 \[...\]:不匹配包含 < > 的内容
  110. pattern = new RegExp(`${leftEscaped}([^<>]*?)${rightEscaped}`, 'g');
  111. }
  112. return html.replace(pattern, (match, latex) => {
  113. try {
  114. // 清理 LaTeX 内容 - 先解码 HTML 实体
  115. let cleanLatex = decodeHtmlEntities(latex.trim());
  116. // 跳过空内容
  117. if (!cleanLatex) {
  118. return match;
  119. }
  120. // 【安全检查】如果内容看起来不像 LaTeX,跳过
  121. // 跳过只有普通文本的内容(没有任何 LaTeX 特征)
  122. if (!/[\\^_{}]/.test(cleanLatex) && !/[a-zA-Z]{2,}/.test(cleanLatex)) {
  123. // 可能只是普通数字或单字母,检查是否有意义
  124. if (/^[\d\s\.\,\-\+]+$/.test(cleanLatex)) {
  125. return match; // 纯数字,不渲染
  126. }
  127. }
  128. // 渲染 KaTeX
  129. const rendered = katex.renderToString(cleanLatex, {
  130. displayMode: displayMode,
  131. throwOnError: false,
  132. strict: false,
  133. trust: true,
  134. output: 'html',
  135. });
  136. return rendered;
  137. } catch (error) {
  138. // 渲染失败时保留原始内容
  139. // console.error(`KaTeX error for "${latex.substring(0, 50)}...":`, error.message);
  140. return match;
  141. }
  142. });
  143. }