Elffuss BraidHub

kikocis/continue public

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