Elffuss BraidHub

kikocis/continue public

54ea0739010d · 2.0 KiBRawPermalink
1import { basename } from "path";
2import * as YAML from "yaml";
3import { RuleWithSource } from "../..";
4
5/**
6 * Parses markdown content with YAML frontmatter
7 */
8export function parseMarkdownRule(content: string): {
9 frontmatter: Record<string, any>;
10 markdown: string;
11} {
12 // Normalize line endings to \n
13 const normalizedContent = content.replace(/\r\n/g, "\n");
14
15 // More reliable frontmatter detection
16 const parts = normalizedContent.split(/^---\s*$/m);
17
18 // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter
19 if (parts.length >= 3) {
20 const frontmatterStr = parts[1];
21 // Join the remaining parts back together (in case there are more --- in the markdown)
22 const markdownContent = parts.slice(2).join("---");
23
24 try {
25 // Parse YAML frontmatter
26 const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter
27 return { frontmatter, markdown: markdownContent.trim() };
28 } catch (e) {
29 // Error parsing frontmatter, treat as markdown only
30 console.warn("Error parsing markdown frontmatter:", e);
31 return { frontmatter: {}, markdown: normalizedContent };
32 }
33 }
34
35 // No frontmatter found
36 return { frontmatter: {}, markdown: normalizedContent };
37}
38
39/**
40 * Converts a markdown file with YAML frontmatter to a RuleWithSource object
41 */
42export function convertMarkdownRuleToContinueRule(
43 path: string,
44 content: string,
45): RuleWithSource {
46 const { frontmatter, markdown } = parseMarkdownRule(content);
47
48 // Try to extract title from first heading if no name in frontmatter
49 let name = frontmatter.name;
50 if (!name) {
51 // Look for a heading in the markdown
52 const headingMatch = markdown.match(/^#\s+(.+)$/m);
53 if (headingMatch) {
54 name = headingMatch[1].trim();
55 } else {
56 // Fall back to filename
57 name = basename(path).replace(/\.md$/, "");
58 }
59 }
60
61 return {
62 name,
63 rule: markdown,
64 globs: frontmatter.globs,
65 description: frontmatter.description,
66 source: "rules-block",
67 ruleFile: path,
68 };
69}