import { Marked } from 'marked'; import { escapeHtml } from './util'; function cleanHref(href: string | null | undefined): string | null { if (!href) return null; const h = href.trim(); if (h.startsWith('#')) return h; try { const u = new URL(h); if (u.protocol === 'https:' || u.protocol === 'http:' || u.protocol === 'mailto:') return u.toString(); } catch { /* relative links have nowhere to point on a skill page */ } return null; } const md = new Marked({ gfm: true, breaks: false }); md.use({ renderer: { // Raw HTML in a SKILL.md is shown as text, never rendered. html(token) { return escapeHtml(token.text); }, link(token) { const text = this.parser.parseInline(token.tokens); const href = cleanHref(token.href); if (!href) return text; return `${text}`; }, // Remote images would let a skill author track readers, so they render as links. image(token) { const href = cleanHref(token.href); const label = escapeHtml(token.text || 'image'); return href ? `[image: ${label}]` : `[image: ${label}]`; }, }, }); export function renderMarkdown(src: string): string { return md.parse(src, { async: false }) as string; } export type Frontmatter = { name?: string; description?: string; [k: string]: string | undefined }; /** Reads the simple `key: value` YAML header of a SKILL.md. */ export function parseSkillMd(src: string): { meta: Frontmatter; body: string } { const text = src.replace(/^/, '').replace(/\r\n/g, '\n'); const m = /^---\n([\s\S]*?)\n---[ \t]*(\n|$)/.exec(text); if (!m) return { meta: {}, body: text }; const meta: Frontmatter = {}; const lines = m[1].split('\n'); for (let i = 0; i < lines.length; i++) { const kv = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(lines[i]); if (!kv) continue; let value = kv[2].trim(); if (value === '' || /^[>|][+-]?$/.test(value)) { const folded = value.startsWith('>') || value === ''; const parts: string[] = []; while (i + 1 < lines.length && (/^\s+\S/.test(lines[i + 1]) || lines[i + 1].trim() === '')) { parts.push(lines[++i].trim()); } value = folded ? parts.join(' ').replace(/\s+/g, ' ').trim() : parts.join('\n').trim(); } else if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { value = value.slice(1, -1).replace(/\\"/g, '"'); } meta[kv[1].toLowerCase()] = value; } return { meta, body: text.slice(m[0].length) }; }