web/src/utils/parse-markdown.ts

50 lines · 1636 bytes

 1import { marked } from 'marked';
 2
 3export const parseMarkdown = (text: string | undefined): string => {
 4  if (!text) return '';
 5
 6  // Custom renderer
 7  const renderer = new marked.Renderer();
 8
 9  // Override function to handle headings
10  renderer.heading = (text, level) => {
11    const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
12    return `<h${level} id="${escapedText}">${text}</h${level}>`;
13  };
14
15  // Override function to handle links
16  renderer.link = (href, title, text) => {
17    if (href.startsWith('/')) {
18      href = `https://github.com/Lissy93/personal-security-checklist/blob/old-version/${href}`;
19    }
20    title = title ? `title="${title}"` : '';
21    return `<a href="${href}" ${title} target="_blank" rel="noopener noreferrer">${text}</a>`;
22  };
23
24  // Sanitize the input to remove <script> tags
25  const sanitizeHtml = (html: string): string => {
26    return html.replace(
27      /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
28      '',
29    );
30  };
31
32  // Configure marked with the custom renderer
33  marked.use({ renderer });
34
35  // Parse the markdown, then sanitize the HTML to remove <script> tags
36  const rawHtml = marked.parse(text, { async: false }) as string;
37  const sanitizedHtml = sanitizeHtml(rawHtml);
38
39  return sanitizedHtml;
40};
41
42export const formatLink = (link: string) => {
43  return (link || '')
44    .replace(/^(https?:\/\/)?(www\.)?/, '')
45    .replace(/\/+$/, '');
46};
47
48// Resolve a `codeberg` field (either `owner/repo` shorthand or a full URL) to a full URL.
49export const codebergUrl = (codeberg: string) =>
50  /^https?:\/\//.test(codeberg) ? codeberg : `https://codeberg.org/${codeberg}`;