// SafeHtml is the only string the SSR response may carry. Escape produces it. Tag builders
// concatenate it. A bare string is not SafeHtml, so it cannot be passed to htmlResponse or raw().
import { raw } from 'hono/html';
declare const safeHtmlBrand: unique symbol;
export type SafeHtml = string & { readonly [safeHtmlBrand]: 'SafeHtml' };
function mark(value: string): SafeHtml {
return value as SafeHtml;
}
/** Text and double-quoted attribute values. Named entities, so `"` is not a raw quote. */
export function escapeHtml(value: string): SafeHtml {
return mark(value
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, '''));
}
export function concatHtml(parts: readonly SafeHtml[]): SafeHtml {
return mark(parts.join(''));
}
export type MdTag = 'p' | 'ul' | 'ol' | 'li' | 'pre' | 'code' | 'strong' | 'em' | 'del' | 'blockquote' | 'table' | 'thead' | 'tbody' | 'tr' | 'th' | 'td' | 'div' | 'span';
/** Fixed class names the markdown renderer may attach. Never derived from the source text. */
export type MdClass = 'md-code' | 'md-code-lang' | 'md-table' | 'task' | 'task done' | 'task-item' | 'al-l' | 'al-c' | 'al-r' | 'md-img' | 'md-frontmatter';
export function tag(name: MdTag, content: SafeHtml, cls: MdClass | null): SafeHtml {
const open = cls === null ? `<${name}>` : `<${name} class="${cls}">`;
return concatHtml([mark(open), content, mark(`${name}>`)]);
}
export function voidTag(name: 'br' | 'hr'): SafeHtml {
return mark(`<${name}>`);
}
/** h2–h6. The id is a slug of [a-z0-9-] only, so a README's `[x](#usage)` lands on its heading. */
export function heading(level: 2 | 3 | 4 | 5 | 6, slug: string, content: SafeHtml): SafeHtml {
const id = /^[a-z0-9][a-z0-9-]{0,79}$/.test(slug) ? ` id="${slug}"` : '';
return concatHtml([mark(`
'), escapeHtml(message), mark('
'), ]); }