2022-10-14 13:11:33 +00:00
|
|
|
import { findNodeOfType, traverseTree } from "$sb/lib/tree.ts";
|
|
|
|
import { markdown, space } from "$sb/silverbullet-syscall/mod.ts";
|
2022-10-10 12:50:21 +00:00
|
|
|
import * as YAML from "yaml";
|
2022-07-15 09:17:02 +00:00
|
|
|
|
|
|
|
export async function readYamlPage(
|
|
|
|
pageName: string,
|
2022-10-10 12:50:21 +00:00
|
|
|
allowedLanguages = ["yaml"],
|
2022-07-15 09:17:02 +00:00
|
|
|
): Promise<any> {
|
2022-10-14 13:11:33 +00:00
|
|
|
const text = await space.readPage(pageName);
|
|
|
|
const tree = await markdown.parseMarkdown(text);
|
2022-07-15 09:17:02 +00:00
|
|
|
let data: any = {};
|
|
|
|
|
|
|
|
traverseTree(tree, (t): boolean => {
|
|
|
|
// Find a fenced code block
|
|
|
|
if (t.type !== "FencedCode") {
|
|
|
|
return false;
|
|
|
|
}
|
2022-10-14 13:11:33 +00:00
|
|
|
const codeInfoNode = findNodeOfType(t, "CodeInfo");
|
2022-07-15 09:17:02 +00:00
|
|
|
if (!codeInfoNode) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
if (!allowedLanguages.includes(codeInfoNode.children![0].text!)) {
|
|
|
|
return false;
|
|
|
|
}
|
2022-10-14 13:11:33 +00:00
|
|
|
const codeTextNode = findNodeOfType(t, "CodeText");
|
2022-07-15 09:17:02 +00:00
|
|
|
if (!codeTextNode) {
|
|
|
|
// Honestly, this shouldn't happen
|
|
|
|
return false;
|
|
|
|
}
|
2022-10-14 13:11:33 +00:00
|
|
|
const codeText = codeTextNode.children![0].text!;
|
2022-07-15 09:17:02 +00:00
|
|
|
try {
|
|
|
|
data = YAML.parse(codeText);
|
|
|
|
} catch (e: any) {
|
|
|
|
console.error("YAML Page parser error", e);
|
|
|
|
throw new Error(`YAML Error: ${e.message}`);
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
});
|
|
|
|
|
|
|
|
return data;
|
|
|
|
}
|
2022-09-01 08:17:20 +00:00
|
|
|
|
|
|
|
export async function writeYamlPage(
|
|
|
|
pageName: string,
|
2022-10-10 12:50:21 +00:00
|
|
|
data: any,
|
2022-11-20 09:56:52 +00:00
|
|
|
prelude = "",
|
2022-09-01 08:17:20 +00:00
|
|
|
): Promise<void> {
|
2022-11-20 09:56:52 +00:00
|
|
|
const text = YAML.stringify(data, {
|
|
|
|
noCompatMode: true,
|
|
|
|
});
|
|
|
|
await space.writePage(pageName, prelude + "```yaml\n" + text + "\n```");
|
2022-09-01 08:17:20 +00:00
|
|
|
}
|