From 302a80d1cdda921ed340e2b730ae0eed30f21a0a Mon Sep 17 00:00:00 2001 From: Sam Chau Date: Wed, 5 Nov 2025 07:28:52 +1030 Subject: [PATCH] feat(markdown): add utility functions for parsing and stripping markdown --- src/lib/server/utils/markdown/markdown.ts | 35 +++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/lib/server/utils/markdown/markdown.ts diff --git a/src/lib/server/utils/markdown/markdown.ts b/src/lib/server/utils/markdown/markdown.ts new file mode 100644 index 0000000..af3ed24 --- /dev/null +++ b/src/lib/server/utils/markdown/markdown.ts @@ -0,0 +1,35 @@ +/** + * Markdown utility for parsing markdown to HTML + */ + +import { marked } from 'marked'; +import sanitizeHtml from 'sanitize-html'; + +/** + * Parse markdown to sanitized HTML + */ +export function parseMarkdown(markdown: string | null | undefined): string { + if (!markdown) return ''; + + // Parse markdown to HTML + const html = marked.parse(markdown) as string; + + // Sanitize HTML to prevent XSS + return sanitizeHtml(html, { + allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img', 'h1', 'h2']), + allowedAttributes: { + ...sanitizeHtml.defaults.allowedAttributes, + img: ['src', 'alt', 'title'] + } + }); +} + +/** + * Strip markdown formatting and return plain text + */ +export function stripMarkdown(markdown: string | null | undefined): string { + if (!markdown) return ''; + + const html = parseMarkdown(markdown); + return html.replace(/<[^>]*>/g, '').trim(); +}