thefoldwithin-earth/tools/generate-index.mjs

64 lines
1.8 KiB
JavaScript
Raw Normal View History

2025-11-08 09:05:04 -06:00
import { promises as fs } from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
2025-11-08 10:00:24 -06:00
const PUBLIC = path.resolve(__dirname, "../public");
2025-11-08 09:05:04 -06:00
const ROOTS = ["pinned", "posts"];
2025-11-08 10:00:24 -06:00
const exts = [".html", ".md"];
2025-11-08 09:05:04 -06:00
2025-11-08 10:00:24 -06:00
async function walk(dir, base) {
const entries = await fs.readdir(dir, { withFileTypes: true });
const nodes = [];
2025-11-08 09:05:04 -06:00
for (const e of entries) {
2025-11-08 10:00:24 -06:00
if (e.name.startsWith(".")) continue;
const abs = path.join(dir, e.name);
const rel = path.posix.join(base, e.name);
const st = await fs.stat(abs);
2025-11-08 09:05:04 -06:00
if (e.isDirectory()) {
2025-11-08 10:00:24 -06:00
const children = await walk(abs, rel);
nodes.push({ type: "dir", name: e.name, path: rel, children });
2025-11-08 09:05:04 -06:00
} else {
2025-11-08 10:00:24 -06:00
const ext = path.extname(e.name);
if (!exts.includes(ext)) continue;
nodes.push({
2025-11-08 09:05:04 -06:00
type: "file",
name: e.name,
2025-11-08 10:00:24 -06:00
path: rel,
2025-11-08 09:05:04 -06:00
ext,
2025-11-08 10:00:24 -06:00
pinned: base.startsWith("pinned"),
mtime: st.mtimeMs
2025-11-08 09:05:04 -06:00
});
}
}
2025-11-08 10:00:24 -06:00
return nodes;
2025-11-08 09:05:04 -06:00
}
2025-11-08 10:00:24 -06:00
async function buildIndex() {
const tree = [];
const flat = [];
2025-11-08 09:05:04 -06:00
for (const root of ROOTS) {
2025-11-08 10:00:24 -06:00
const abs = path.join(PUBLIC, root);
try {
const children = await walk(abs, root);
const node = { type: "dir", name: root, path: root, children };
tree.push(node);
for (const c of children) flatten(c, flat);
} catch {
console.warn(`Skipping missing ${root}/`);
2025-11-08 09:05:04 -06:00
}
}
2025-11-08 10:00:24 -06:00
const data = { generatedAt: Date.now(), tree, flat };
await fs.writeFile(path.join(PUBLIC, "index.json"), JSON.stringify(data, null, 2));
console.log("✅ index.json generated:", flat.length, "files.");
}
2025-11-08 09:05:04 -06:00
2025-11-08 10:00:24 -06:00
function flatten(node, arr) {
if (node.type === "file") arr.push(node);
else node.children.forEach(c => flatten(c, arr));
2025-11-08 09:05:04 -06:00
}
2025-11-08 10:00:24 -06:00
await buildIndex();