repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/the-system/markdown.ts
RawFile outline
import { remarkDefinitionList } from "remark-definition-list";
import remarkFrontmatter from "remark-frontmatter";
import remarkGfm from "remark-gfm";
import remarkGithubAlert from "remark-github-blockquote-alert";
import remarkMath from "remark-math";
import remarkParse from "remark-parse";
import { unified } from "unified";
import {
Alias,
isMap,
isScalar,
isSeq,
type Node,
type Pair,
parseDocument,
} from "yaml";
export type FrontmatterValue =
| null
| boolean
| number
| string
| readonly FrontmatterValue[]
| FrontmatterMap;
export type FrontmatterMap = ReadonlyMap<string, FrontmatterValue>;
type MarkdownRoot = Readonly<{
type: "root";
children: readonly Readonly<{ type: string; value?: string }>[];
}>;
export type RichMarkdownDocument = Readonly<{
tree: MarkdownRoot;
frontmatter: FrontmatterMap;
}>;
export class MarkdownDocumentError extends Error {
readonly code: string;
constructor(code: string, message: string) {
super(message);
this.code = code;
this.name = "MarkdownDocumentError";
}
}
export const createMarkdownParser = () =>
unified()
.use(remarkParse)
.use(remarkFrontmatter, ["yaml"])
.use(remarkGfm)
.use(remarkDefinitionList)
.use(remarkMath)
.use(remarkGithubAlert);
const unsupported = (message: string): never => {
throw new MarkdownDocumentError("frontmatter.unsupported", message);
};
const convertNode = (node: Node | null): FrontmatterValue => {
if (node === null) return null;
if (node instanceof Alias)
return unsupported("YAML aliases are not frontmatter values");
if (isScalar(node)) {
const value = node.value;
if (
value === null ||
typeof value === "boolean" ||
typeof value === "string"
)
return value;
if (typeof value === "number" && Number.isFinite(value)) return value;
return unsupported(`Unsupported YAML scalar: ${String(value)}`);
}
if (isSeq(node))
return node.items.map((item) => convertNode(item as Node | null));
if (isMap(node)) return convertMap(node.items);
return unsupported("Unsupported YAML node");
};
const convertMap = (items: readonly Pair[]): FrontmatterMap => {
const result = new Map<string, FrontmatterValue>();
for (const pair of items) {
const key = pair.key as Node | null;
const keyValue = isScalar(key) ? key.value : undefined;
if (typeof keyValue === "string") {
result.set(keyValue, convertNode(pair.value as Node | null));
continue;
}
unsupported("Frontmatter map keys must be strings");
}
return result;
};
export function parseRichMarkdown(source: string): RichMarkdownDocument {
const parser = createMarkdownParser();
const tree = parser.runSync(parser.parse(source)) as MarkdownRoot;
const blocks = tree.children.filter((node) => node.type === "yaml");
if (blocks.length === 0)
throw new MarkdownDocumentError(
"frontmatter.missing",
"Document requires one leading YAML frontmatter block",
);
if (blocks.length !== 1)
throw new MarkdownDocumentError(
"frontmatter.multiple",
`Document requires one YAML frontmatter block; received ${blocks.length}`,
);
const document = parseDocument(blocks[0]?.value ?? "", {
schema: "core",
strict: true,
uniqueKeys: true,
});
if (document.errors.length > 0)
throw new MarkdownDocumentError(
"frontmatter.invalid",
document.errors.map((error) => error.message).join("; "),
);
if (!isMap(document.contents))
throw new MarkdownDocumentError(
"frontmatter.shape",
"Frontmatter must be a YAML map",
);
return { tree, frontmatter: convertMap(document.contents.items) };
}