// Builds the NextFloor documentation site (English + German) from docs/content into tools/docs/dist.
// node build.mjs build
// node build.mjs --check build and fail on broken links, missing images or pages missing in one language
import { readFileSync, writeFileSync, mkdirSync, cpSync, existsSync, readdirSync, rmSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { Marked } from "marked";
const here = dirname(fileURLToPath(import.meta.url));
const repo = resolve(here, "../..");
const content = join(repo, "docs/content");
const out = resolve(here, process.argv.find((a) => a.startsWith("--out="))?.slice(6) ?? "dist");
const check = process.argv.includes("--check");
const SITE = "https://therealmrbk.github.io/NextFloor";
const GH = "https://github.com/therealMRBK/NextFloor";
const LANGS = ["en", "de"];
const version = JSON.parse(readFileSync(join(repo, "custom_components/nextfloor/manifest.json"), "utf8")).version;
const UI = {
en: {
docs: "Documentation", overview: "Overview", search: "Search", searchHint: "Type to search the documentation", searchNone: "Nothing found. Try fewer or other words.",
searchFoot: "↑↓ choose · ↵ open · esc close", demo: "Live demo", github: "GitHub", menu: "Menu", onPage: "On this page", prev: "Previous", next: "Next",
editPage: "Edit this page", report: "Found a mistake? Open an issue", copy: "Copy", theme: "Switch light and dark", skip: "Skip to content", lang: "Deutsch",
footer: "NextFloor is free and MIT licensed. Made for Home Assistant.", home: "Documentation", tip: "Tip", note: "Note", warn: "Careful", danger: "Important",
notFound: "This page does not exist", notFoundText: "The link may be old. Use the search or start from the overview.", toOverview: "To the overview",
},
de: {
docs: "Dokumentation", overview: "Übersicht", search: "Suche", searchHint: "Tippen, um die Dokumentation zu durchsuchen", searchNone: "Nichts gefunden. Versuche weniger oder andere Wörter.",
searchFoot: "↑↓ wählen · ↵ öffnen · Esc schließen", demo: "Live-Demo", github: "GitHub", menu: "Menü", onPage: "Auf dieser Seite", prev: "Zurück", next: "Weiter",
editPage: "Diese Seite bearbeiten", report: "Fehler gefunden? Issue öffnen", copy: "Kopieren", theme: "Hell und Dunkel wechseln", skip: "Zum Inhalt springen", lang: "English",
footer: "NextFloor ist kostenlos und MIT-lizenziert. Gemacht für Home Assistant.", home: "Dokumentation", tip: "Tipp", note: "Hinweis", warn: "Vorsicht", danger: "Wichtig",
notFound: "Diese Seite gibt es nicht", notFoundText: "Der Link ist vielleicht alt. Nutze die Suche oder starte bei der Übersicht.", toOverview: "Zur Übersicht",
},
};
const ICONS = {
menu: '',
search: '',
sun: '',
moon: '',
copy: '',
check: '',
arrow: '',
ext: '',
github: '',
info: '',
bulb: '',
warn: '',
stop: '',
globe: '',
};
const sprite = ``;
const ic = (n, cls = "") => ``;
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
const slugify = (s) => s.toLowerCase().replace(/ä/g, "ae").replace(/ö/g, "oe").replace(/ü/g, "ue").replace(/ß/g, "ss").replace(/<[^>]+>/g, "").replace(/&[a-z]+;/g, "").normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "section";
const plain = (html) => html.replace(/
/g, " ").replace(/<[^>]+>/g, " ").replace(/ /g, " ").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/\s+/g, " ").trim();
function frontMatter(src) {
const m = src.match(/^---\n([\s\S]*?)\n---\n?/);
if (!m) return [{}, src];
const meta = {};
for (const line of m[1].split("\n")) {
const k = line.match(/^(\w+):\s*(.*)$/);
if (k) meta[k[1]] = k[2].replace(/^["']|["']$/g, "");
}
return [meta, src.slice(m[0].length)];
}
const nav = JSON.parse(readFileSync(join(content, "nav.json"), "utf8"));
const problems = [];
const problem = (m) => problems.push(m);
const allSlugs = nav.sections.flatMap((s) => s.pages);
// ---------- pages ----------
function loadPages(lang) {
const pages = new Map();
for (const slug of allSlugs) {
if (slug === "index") continue;
const f = join(content, lang, `${slug}.md`);
if (!existsSync(f)) { problem(`missing page ${lang}/${slug}.md`); continue; }
let [meta, body] = frontMatter(readFileSync(f, "utf8"));
if (meta.generated === "changelog") {
body = readFileSync(join(repo, "CHANGELOG.md"), "utf8").split("\n").slice(2).join("\n").replace(/^## \[Unreleased\][\s\S]*?(?=^## \[)/m, "").replace(/^## /gm, "## ").replace(/^### /gm, "#### ");
}
if (!meta.title) problem(`${lang}/${slug}.md has no title`);
pages.set(slug, { slug, lang, meta, body, file: `docs/content/${lang}/${slug}.md` });
}
return pages;
}
function render(page, lang, base) {
const toc = [];
const used = new Map();
const t = UI[lang];
const marked = new Marked({ gfm: true, breaks: false });
marked.use({
renderer: {
heading({ tokens, depth }) {
let inner = this.parser.parseInline(tokens);
const custom = inner.match(/\s*\{#([\w-]+)\}\s*$/);
if (custom) inner = inner.slice(0, custom.index);
let id = custom ? custom[1] : slugify(inner);
const n = used.get(id) ?? 0;
used.set(id, n + 1);
if (n) id += `-${n + 1}`;
if (depth === 2 || depth === 3) toc.push({ id, depth, text: plain(inner) });
return `${inner}#\n`;
},
code({ text, lang: l }) {
const label = l && !["text", "txt"].includes(l) ? ` data-lang="${esc(l)}"` : "";
return `
${esc(text)}
\n`;
},
table(token) {
const head = `
${token.header.map((c) => `
${this.parser.parseInline(c.tokens)}
`).join("")}
`;
const rows = token.rows.map((r) => `
${r.map((c) => `
${this.parser.parseInline(c.tokens)}
`).join("")}
`).join("");
return `
${head}${rows}
\n`;
},
image({ href, text, title }) {
let src = href;
if (!/^https?:/.test(src)) {
const name = src.replace(/^(\.\.\/)*(docs\/)?images\//, "").replace(/^\.?\//, "");
if (!existsSync(join(repo, "docs/images", name))) problem(`${page.file}: image not found: ${href}`);
src = `${base}img/${name}`;
}
const cap = title ? `${esc(title)}` : "";
return `${cap}\n`;
},
link({ href, tokens }) {
const inner = this.parser.parseInline(tokens);
if (/^(https?:|mailto:|#)/.test(href)) {
const ext = /^https?:/.test(href);
return `${inner}`;
}
const m = href.match(/^(?:\.\/)?(?:docs\/)?([\w-]+)\.md(#.*)?$/);
if (m) {
if (!allSlugs.includes(m[1])) problem(`${page.file}: link to unknown page ${href}`);
return `${inner}`;
}
if (page.meta.generated) return `${inner}`;
problem(`${page.file}: unsupported link ${href}`);
return `${inner}`;
},
},
});
let html = marked.parse(page.body);
// numbered lists with three or more steps become a step list
html = html.replace(/((?:(?!<\/ol>)[\s\S])*)<\/ol>/g, (all, inner) => ((inner.match(/