src/md.js
raw
import { Marked } from 'marked';
export const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const safeHref = h => {
const s = String(h || '').trim();
return /^(https?:\/\/|\/(?!\/)|#|mailto:)/i.test(s) ? s : '#';
};
const marked = new Marked({
gfm: true, breaks: true,
renderer: {
html({ text }) { return esc(text); },
link({ href, title, tokens }) {
const t = this.parser.parseInline(tokens);
const ext = /^https?:/i.test(href);
return `<a href="${esc(safeHref(href))}"${title ? ` title="${esc(title)}"` : ''}${ext ? ' rel="nofollow ugc noopener" target="_blank"' : ''}>${t}</a>`;
},
image({ href, text }) {
return /^https:\/\//i.test(href || '') ? `<img src="${esc(href)}" alt="${esc(text)}" loading="lazy" referrerpolicy="no-referrer">` : esc(text);
},
},
});
export const md = s => marked.parse(String(s ?? ''));
// @handles become links
export const mdLinked = s => md(s).replace(/(^|[\s(>])@([a-z0-9][a-z0-9-]{1,23})\b/g, '$1<a class="mention" href="/m/$2">@$2</a>');