// HTML helpers of the chat text renderer (chatText.ts), ported from a
// Golem15 SPA's markdown.ts: escaping, the link-target allow-list and
// bold/italic on escaped text.
//
// Links must be http(s), mailto, a site path or an anchor; anything else
// (javascript:, data:, ...) is refused. An http(s) target must also pass
// honestHttpUrl (urlGuard.ts): its written host is the host it opens.
import { honestHttpUrl } from './urlGuard'
const ESC: Record = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }
export function escapeHtml(s: string): string {
return s.replace(/[&<>"']/g, (c) => ESC[c])
}
/** Returns the URL when it is allowed as a link target, else null. */
export function safeUrl(raw: string): string | null {
// Strip whitespace and control characters browsers ignore inside schemes.
// eslint-disable-next-line no-control-regex
const url = raw.trim().replace(/[\u0000-\u001f\u007f\s]+/g, '')
if (/^https?:/i.test(url)) return honestHttpUrl(url) ? url : null
if (/^mailto:[^\s]+$/i.test(url)) return url
// A site path: a "/" not followed by another "/" or a backslash (browsers
// read "/\host" as "//host", an external link).
if (/^\/(?![/\\])/.test(url) || url.startsWith('#')) return url
return null
}
/** Bold and italic on already-escaped text (shared with the chat renderer). */
export function formatSpans(escaped: string): string {
return escaped
.replace(/\*\*([^*\n]+)\*\*/g, '$1')
.replace(/(^|[\s(])\*([^*\n]+)\*(?=$|[\s).,;:!?])/g, '$1$2')
.replace(/(^|[\s(])_([^_\n]+)_(?=$|[\s).,;:!?])/g, '$1$2')
}