Extract escapeHtml into shared module for reuse across client and server

The same HTML entity escaping logic was duplicated in three places:
MessageBubble.tsx, html-exporter.ts, and markdown.ts. Consolidate into
a single shared/escape-html.ts with a single-pass regex+lookup implementation
instead of five chained .replace() calls.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-30 01:08:38 -05:00
parent 6d2a687259
commit 8e713b9c50

18
src/shared/escape-html.ts Normal file
View File

@@ -0,0 +1,18 @@
/**
* HTML-escape a string for safe interpolation into HTML content and attributes.
* Escapes the 5 characters that have special meaning in HTML: & < > " '
*
* Single-pass implementation: one regex scan with a lookup map instead of
* five chained .replace() calls.
*/
const ESC_MAP: Record<string, string> = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#039;",
};
export function escapeHtml(text: string): string {
return text.replace(/[&<>"']/g, (ch) => ESC_MAP[ch]);
}