on master help sign in
urbit.org/lib/cache.js
90 lines 2.4 kB history raw
1const fs = require("fs");
2const path = require("path");
3const matter = require("gray-matter");
4const toml = require("@iarna/toml");
5const markdoc = require("@urbit/markdoc");
7const options = {
8 engines: {
9 toml: toml.parse.bind(toml),
10 },
11 language: "toml",
12 delimiters: "+++",
13};
15const index = [];
17function buildSearchIndex(dir) {
18 // Assume years belong to Grants for now.
19 const dirName = dir.split("/").slice(-1).join("");
20 const parentName = String(Number(dirName)).length === 4
21 ? "Grants"
22 : dirName.charAt(0).toUpperCase() + dirName.slice(1);
23 let metadata = {
24 data: {
25 title: parentName,
26 },
27 };
29 try {
30 metadata = matter(fs.readFileSync(path.join(dir, "_index.md")), options);
31 } catch (err) { }
33 const children = fs.readdirSync(dir, { withFileTypes: true });
34 const pages = children.filter((f) => f.isFile() && f.name !== "_index.md");
35 const subdirs = children.filter(
36 (f) => f.isDirectory() && f.name !== "ids" && f.name !== "glossary"
37 );
39 index.push(
40 ...pages.map((page) => {
41 const { data: pageData, content: pageContent } = matter(
42 fs.readFileSync(path.join(dir, page.name)),
43 options
44 );
45 const parsed = markdoc.parse(pageContent);
46 const transform = markdoc.transform(parsed);
47 const slug = dir.includes("/grants/")
48 ? `/grants/${page.name.replace(/.md$/, "")}`
49 : path.join(
50 dir.substr(dir.indexOf("content") + 7),
51 "/",
52 page.name.replace(/.md$/, "")
53 );
54 return {
55 title: pageData.title,
56 base: page.name,
57 slug,
58 content: pageData.description || "",
59 headings: transform.children
60 .filter((e) => e.name === "h2" || e.name === "h3")
61 .map((e) => e.children)
62 .flat()
63 .filter((e) => typeof e === "string"),
64 parent: metadata.data.title,
65 };
66 })
67 );
69 Object.fromEntries(
70 subdirs.map((subdir) => [
71 subdir.name,
72 buildSearchIndex(path.join(dir, subdir.name)),
73 ])
74 );
77buildSearchIndex(path.join(process.cwd(), "content"));
79const fileContents = `export const index = ${JSON.stringify(index)}`;
81try {
82 fs.readdirSync("cache");
83} catch (err) {
84 fs.mkdirSync("cache");
87fs.writeFile("cache/data.js", fileContents, function (err) {
88 if (err) return console.error(err);
89 console.log("Site index created.");
90});