Elffuss BraidHub

kikocis/continue public

dd84f7eaed6c · 2.5 KiBRawPermalink
1import * as YAML from "yaml";
2import {
3 PackageIdentifier,
4 packageIdentifierToDisplayName,
5} from "../browser.js";
6import { RuleObject } from "../schemas/index.js";
7
8export interface RuleFrontmatter {
9 globs?: RuleObject["globs"];
10 regex?: RuleObject["regex"];
11 name?: RuleObject["name"];
12 description?: RuleObject["description"];
13 alwaysApply?: RuleObject["alwaysApply"];
14}
15
16/**
17 * Parses markdown content with YAML frontmatter
18 */
19export function parseMarkdownRule(content: string): {
20 frontmatter: RuleFrontmatter;
21 markdown: string;
22} {
23 // Normalize line endings to \n
24 const normalizedContent = content.replace(/\r\n/g, "\n");
25
26 // More reliable frontmatter detection
27 const parts = normalizedContent.split(/^---\s*$/m);
28
29 // If we have at least 3 parts (before ---, frontmatter, after ---), we have frontmatter
30 if (parts.length >= 3) {
31 const frontmatterStr = parts[1];
32 // Join the remaining parts back together (in case there are more --- in the markdown)
33 const markdownContent = parts.slice(2).join("---");
34
35 try {
36 // Parse YAML frontmatter
37 const frontmatter = YAML.parse(frontmatterStr) || {}; // Handle empty frontmatter
38 return { frontmatter, markdown: markdownContent.trim() };
39 } catch (e) {
40 // Error parsing frontmatter, treat as markdown only
41 console.warn("Error parsing markdown frontmatter:", e);
42 return { frontmatter: {}, markdown: normalizedContent };
43 }
44 }
45
46 // No frontmatter found
47 return { frontmatter: {}, markdown: normalizedContent };
48}
49
50export function getRuleName(
51 frontmatter: RuleFrontmatter,
52 id: PackageIdentifier,
53): string {
54 if (frontmatter.name) {
55 return frontmatter.name;
56 }
57
58 const displayName = packageIdentifierToDisplayName(id);
59
60 // If it's a file identifier, extract the last two parts of the file path
61 if (id.uriType === "file") {
62 // Handle both forward slashes and backslashes, get the last two segments
63 const segments = displayName.split(/[/\\]/);
64 const lastTwoParts = segments.slice(-2);
65 return lastTwoParts.join("/");
66 }
67
68 // Otherwise return the display name as-is (for slug identifiers)
69 return displayName;
70}
71
72export function markdownToRule(
73 rule: string,
74 id: PackageIdentifier,
75): RuleObject {
76 const { frontmatter, markdown } = parseMarkdownRule(rule);
77
78 return {
79 name: getRuleName(frontmatter, id),
80 rule: markdown,
81 globs: frontmatter.globs,
82 regex: frontmatter.regex,
83 description: frontmatter.description,
84 alwaysApply: frontmatter.alwaysApply,
85 };
86}