Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(docs): writing-documentation skill and a headless edit-docs sync
Elian Doranb40e00f9ccd2
diff --git a/.claude/skills/writing-documentation/SKILL.md b/.claude/skills/writing-documentation/SKILL.mdnew file mode 100644index 0000000000..6f90e4769d--- /dev/null+++ b/.claude/skills/writing-documentation/SKILL.md@@ -0,0 +1,177 @@+---+name: writing-documentation+description: Use whenever a change is user-facing — a new feature, a moved or removed button, a label, a shortcut, an option, a default, a note type, a collection view, a dialog, an import format — or when asked to write, fix, restructure or audit Trilium's documentation ("document this", "update the User Guide", "add a page for X", "is X documented?", "which page describes X?", "the docs still say…", "rename/move this page", "add a screenshot", "which icon do I use?"). Covers the three docs trees (`docs/User Guide`, `docs/Developer Guide`, `docs/Release Notes`) and the generated in-app help they feed, the `!!!meta.json` note metadata (noteId, shareAlias, iconClass, attachments), the house style of the User Guide (register, page templates, reference-link pills, `<kbd>`, admonitions, figures, the `bx`/`cke` icon spans), and `docs.mjs`, which finds and shows pages, scaffolds a page with correct metadata, registers images, renames/moves/deletes pages, maps a code diff to the pages it affects, audits the trees, and regenerates the help HTML headless — so `!!!meta.json` and `apps/server/src/assets/doc_notes` never have to be read or hand-edited. A user-facing change is not finished until the User Guide describes it, in the same commit.+---++# Writing Trilium's documentation++Trilium's User Guide is a tree of Trilium notes, exported to Markdown under `docs/User Guide/` and+described by `docs/User Guide/!!!meta.json`. From that Markdown the repo generates the **in-app help**+(`apps/server/src/assets/doc_notes/en/User Guide/**/*.html` + a minified help meta, and+`apps/standalone/src/assets/help_meta.json`) and the public site (docs.triliumnotes.org). The Markdown+is the source; everything under `doc_notes` and `help_meta.json` is generated and never hand-edited.++Every mechanical step is [docs.mjs](docs.mjs):++```bash+D=.claude/skills/writing-documentation/docs.mjs+node $D find "kanban" # pages by title / alias / path; --content searches bodies+node $D show kanban-board # metadata, URL, outline, inbound links, code that links it+node $D tree Collections --depth 1 # the note tree with aliases and icons+node $D impact --diff # pages a branch's code changes touch (also: impact "Print note")+node $D new Collections "Timeline" --icon bx-time-five --after Dashboard # scaffold page + meta entry+node $D image timeline shot.png # register a screenshot; prints the <figure> to paste+node $D icons quote --pack cke # icon classes for a toolbar button / app control+node $D rename timeline "Timeline view" # retitle; move <page> <parent>; delete <page>+node $D sync # regenerate Markdown, help HTML and help metas headless+node $D check # meta ↔ disk, links, images, icons, aliases, code refs, style+```++## The rule: a user-facing change ships with its documentation++A change is user-facing when it alters anything a user sees or does: a control added, moved, relabeled+or removed; a shortcut; an option, its default or where it lives; a note type, collection view, dialog,+import/export format, launcher, badge, tooltip; a behavior a page describes. **It is not done until the+User Guide describes the new state, in the same commit or PR as the code.** Docs are not a follow-up.++The workflow, every time:++1. `node $D impact --diff` — lists the pages that mention the UI strings the branch changed and the+ help pages wired from the touched components. Also run `impact "<feature name>" "<button label>"`+ for the names the diff cannot know. **Read every hit** — a page describing a control that moved,+ a label that changed or a default that flipped is wrong until edited.+2. Edit the Markdown (below), or `new` a page for a feature no page covers.+3. `node $D sync` — normalizes your Markdown the way the editor would and regenerates the help HTML+ and both help metas. Review `git diff -- docs` (what the round trip did to your text) and+ `git diff --stat -- apps/server/src/assets/doc_notes`.+4. `node $D check` — must report 0 errors (a handful are pre-existing, listed at the end).+5. Commit the code, the Markdown, `!!!meta.json`, the `doc_notes` HTML and `help_meta.json` together.++Two traps `CLAUDE.md` names still apply: verify **where a control actually mounts** by grepping the+component, not by inference; and a widened **capability gate** (a note type added to a list a widget+switches on) surfaces panels the change never mentioned — grep the gate's readers.++Do **not** write release notes on a branch: the maintainer writes `docs/Release Notes/Release+Notes/v<x>.md` from the merged commits at release time. Make the commit subject carry the bullet+("Area: what changed", issue keyword). The one per-version page a feature branch does touch is a+`Scripting/Breaking changes/v<next>.0 <title>` page for a scripting API break.++## Editing a page by hand++Hand-editing the Markdown is fine — `sync` is what makes it safe. What to know first:++- **Line 1 is `# <Title>`, body starts on line 2, no trailing newline.** The exporter writes that+ shape; the importer demotes a differing H1. `sync` normalizes whatever you wrote.+- **Links to other pages** are relative `.md` paths, `%20`-encoded (`&` → `%26`, parentheses escaped+ `\(` in Markdown links, literal in `href=`). On import they resolve to note IDs and are re-derived on+ export — so a renamed or moved target fixes every link on the next `sync`. A path that does not+ resolve imports as dead text; `check` catches it.+- **The HTML inside the Markdown is real** — reference-link pills, `<kbd>`, `<figure>`, icon spans,+ admonitions as `> [!NOTE]`. Reproduce them exactly as [references/style-guide.md](references/style-guide.md)+ shows; CKEditor is what reads them.+- **Images are attachments**, registered in `!!!meta.json` and named `<Page Title>_<name>` beside the+ page. Never drop a file in by hand: `image <page> <file>` copies it, registers it, and prints the+ `<figure>` with real dimensions. An attachment nothing references is erased by the next `sync`.+- **`sync` rewrites every tree from scratch** (`rm -rf` + export) — a file on disk that is in no+ `!!!meta.json` entry disappears, and a `.md` with no entry makes the import throw. Everything that+ touches the tree shape goes through `new` / `image` / `rename` / `move` / `delete`.+- After `sync`, HTML churn like reflow, ` ` shifted across a tag, `<li><p>` ↔ `<li>` or a+ `style` gaining a `;` is normal and is not mentioned in a commit. A changed `href`, a dropped+ `<img src>` or a paragraph that lost text is a defect: fix it before committing.+- `pnpm edit-docs:edit-docs` (the Electron editor) still works and is the better tool for heavy+ restructuring or for pasting screenshots; it exports 10 s after a change. `sync` is the headless+ twin of that export, so both leave the same files.++## Adding a page++```bash+node $D new "Note Types" "Timeline" --icon bx-time-five --after "Web View"+```++`new` writes `<Parent dir>/Timeline.md` with the H1, inserts a complete meta entry (fresh 12-char+noteId, `notePath`, `notePosition` a multiple of 10 among the siblings, `shareAlias`, `iconClass`,+`format: "markdown"`, `mime: "text/html"`), turns a leaf parent into a folder, and prints the pill to+paste into the parent page. Then write the body, `image` the screenshots, `sync`, `check`.++- **Alias** defaults to the kebab-case title; pass `--alias` to shorten (`setup`, `docker`, `mfa`,+ `and` for `&`). The public URL is the chain of ancestor aliases, so it only has to be unique among+ siblings; a page without one has no URL and is dropped from the standalone help. Once published, an+ alias is an external link (README ×41, website, web clipper, about dialog) — `show` lists who uses it.+- **Icon**: the feature's own icon — a note type's `NOTE_TYPE_ICONS` entry, a collection's template+ icon in `hidden_subtree_templates.ts`, otherwise `icons <query>`. Boxicons (`bx bx-…`) only for+ `iconClass`.+- **Title characters**: letters, digits, space, `_ - ( ) & . , \``. The in-app help refuses anything+ else (`doc_renderer.ts`), and `new` refuses too. `/`, `:` and `"` are dropped from the file name.+- **Wire it into the app** when the page documents a surface with a help affordance: `<HelpButton+ helpPage="<noteId>">` (settings panes, dialogs), `helpPageId` on a `Modal`, or the maps in+ `apps/client/src/services/in_app_help.ts` (`byNoteType`, `byBookType`, sidebar sections). The app+ links help by **noteId**, so those IDs are permanent: `show` reports them under "referenced from+ code", `delete` refuses while any exist, and `rename`/`move` keep the ID.+- Link the page from its parent and from the pages that mention the feature; a page nothing links to+ is only reachable from the tree.++## Renaming, moving, deleting++`rename` changes the title and H1 and keeps the noteId; `sync` then renames the file, its attachments+and its folder and rewrites every inbound link. `move` relocates the files and the meta entry+(`notePath` of the subtree included); the public URL changes, so `show` the page first for+hard-coded URLs. `delete` removes the entry and its files and refuses if the app links the noteId.+All three want a `sync` right after; `check` before committing.++Which pages is the app itself attached to? `show <page>` → "referenced from code", or `check`, which+fails when a `helpPage` literal or a `docs.triliumnotes.org/user-guide/…` URL in code points nowhere.++## House style, the short version++The full guide with counts and examples is [references/style-guide.md](references/style-guide.md);+skeletons per page kind are [references/page-templates.md](references/page-templates.md).++1. Product is **Trilium** (not TriliumNext, not "Trilium Notes" outside legal text). US spelling.+2. Present tense, impersonal or "you"; "we" only for the project. Never "I". Plain, semi-formal,+ contractions fine. Recommendations are soft ("Generally…", "consider…", "Prefer…").+3. One definitional first sentence ("X is/are …", "Trilium allows …"), optionally after a hero figure.+ Headings `##`/`###` in sentence case. Sections in this order when they apply: Creating → Interaction+ → Configuration → Limitations → Mobile support → Under the hood → See also.+4. Steps: "To <goal>, <imperative>." bullets (`* `, three spaces); numbered `1. ` only for strict+ sequences; nest with four spaces.+5. Other pages by title as a pill, preceded by a non-breaking space:+ ` <a class="reference-link" href="../Rel/Path%20Name.md">Path Name</a>` (text = target title).+ Inline phrases as `[phrase](../Rel/Path.md)`. Issues go to "[report the issue](…/Troubleshooting/Reporting%20issues.md)".+6. UI labels and menu items in _italics_; paths with `→`: `<Options pill> → _Appearance_ → _Fonts_`.+ Settings by their UI path, never by option key.+7. Keys: `<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>R</kbd>`, no spaces. Labels/relations in backticks with+ prefix: `` `#board:groupBy` ``, `` `~template` ``. Files, values, env vars, syntax in backticks.+8. A button is shown by its icon: `<span class="tn-icon cke cke-<name>"></span>` for a text-editor+ toolbar button, `<span class="tn-icon bx bx-<name>"></span>` for the rest of the app, followed by+ "button"/"icon"/"menu". Never a cropped screenshot of a button. `icons` finds the class.+9. Callouts: `> [!NOTE]` context/history · `> [!TIP]` a better way · `> [!IMPORTANT]` beta status,+ requirement, third-party disclaimer · `> [!WARNING]` data/security risk or a version-gated break.+10. Version facts: "Since v0.104.0, …", "Starting with v0.104.0, …", "Versions prior to v0.103.0 …".+11. Figures: `<figure class="image image-style-align-center"><img style="aspect-ratio:W/H;" src="Title_image.png" width="W" height="H"></figure>`+ (`image` prints it); light theme, tight crop, no annotations; `image-style-align-right image_resized`+ + `style="width:50%;"` on the figure to float beside a list.+12. Tables are GFM `| a | b |` with a pill or a backticked label in the first cell; code fences carry+ a language tag when one applies.++## Known warnings in the trees today++`check` reports 0 errors; its ~70 warnings predate any current work and are listed so nobody+rediscovers them. Fix what you pass by; none blocks a change:++- Four User Guide pages without a `shareAlias` (AI chat tab, Office documents, Privacy, Text Snippets)+ and ~40 without an `iconClass`; four Developer Guide pages that are empty (`Backlinks`, `Branch+ prefixes`, `Deleted notes`, `Integration testing`).+- ~20 pills whose text differs from the target's title, ~35 plain-text shortcuts, two unreferenced+ attachments, a handful of British spellings.+- Typos: "togged" (Canvas, Mind Map), "belwo" (Presentation), "Triliumin" (Troubleshooting), "to the+ to the" (Kanban Board), "expect printer" (Printing & Exporting as PDF).++## Related++- **building-client-ui** — `HelpButton` / `HelpTooltipButton` / `HelpDropdown` are the in-app help+ affordances; wire a new page through them.+- **working-with-translations** — the English strings `impact --diff` reads come from those catalogues.+- **ckeditor5-plugin-development** — the `cke` icon pack: an editor icon added, renamed or removed+ means regenerating the font and grepping the docs for the old `cke-<name>` class.+- [references/pipeline.md](references/pipeline.md) — how the trees, the meta files, the in-app help and+ the docs site are produced and consumed, and which identifiers are load-bearing.diff --git a/.claude/skills/writing-documentation/docs.mjs b/.claude/skills/writing-documentation/docs.mjsnew file mode 100644index 0000000000..19b6936650--- /dev/null+++ b/.claude/skills/writing-documentation/docs.mjs@@ -0,0 +1,994 @@+#!/usr/bin/env node+/**+ * Workbench for Trilium's documentation trees (`docs/User Guide`, `docs/Developer Guide`,+ * `docs/Release Notes`): Markdown pages described by a `!!!meta.json` note tree.+ *+ * node .claude/skills/writing-documentation/docs.mjs <command> [args]+ *+ * find <text> [--content] [--tree t] pages whose title, alias, path (or body) match+ * show <page> metadata, URL, outline, inbound links, code references+ * tree [page] [--depth n] [--tree t] the note tree with aliases and icons+ * new <parent> <title> [opts] scaffold a page: .md + meta entry (+ alias, icon)+ * image <page> <file> [--title t] register an image as an attachment; prints the <figure>+ * rename <page> <title> retitle a page (meta + H1); links follow on `sync`+ * move <page> <parent> [--after s|--first] reparent a page and its files+ * delete <page> remove a page; refuses when the app links to it+ * icons <query...> [--pack bx|cke] search the icon fonts the docs can use+ * impact [--diff [range]] [terms...] which pages a code change or a term touches+ * check [--tree t] consistency + style audit of the trees+ * sync regenerate everything (help HTML, meta) headless+ *+ * <page> a noteId, a shareAlias, or a unique title/path fragment. <parent> likewise.+ * --tree user (default) | dev | release+ *+ * The meta file is 6000+ lines and the HTML mirror is generated, so nothing here should ever+ * need either read by hand. `new`/`image`/`rename`/`move`/`delete` edit `!!!meta.json` through+ * the file's own layout (4-space indent, exporter key order); `sync` then makes the Markdown,+ * the help HTML and the standalone meta agree, the same way edit-docs does after an edit.+ */+import { execFileSync, spawnSync } from "node:child_process";+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++const SKILL_DIR = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(SKILL_DIR, "../../..");++const BASE_URL = "https://docs.triliumnotes.org";++const TREES = {+ user: {+ dir: "docs/User Guide",+ rootId: "pOsGYCXsbNQG",+ html: "apps/server/src/assets/doc_notes/en/User Guide",+ helpMeta: "apps/server/src/assets/doc_notes/en/User Guide/!!!meta.json",+ standaloneMeta: "apps/standalone/src/assets/help_meta.json"+ },+ dev: { dir: "docs/Developer Guide", rootId: "jdjRLhLV3TtI" },+ release: { dir: "docs/Release Notes", rootId: "hD3V4hiu2VW4" }+};++const ICON_PACKS = {+ bx: "packages/trilium-core/src/services/icon_pack_boxicons-v2.json",+ cke: "packages/trilium-core/src/services/icon_pack_text_editor.json"+};++/** `apps/client/src/services/doc_renderer.ts` refuses any other character in a help page path. */+const DOC_NAME_CHARS = /^[a-zA-Z0-9_/\- ()&.,`]+$/;++/** Where the app hard-codes help pages (by noteId) and public docs URLs (by alias path). */+const CODE_SCAN_DIRS = ["apps/client/src", "apps/server/src", "apps/desktop/src", "apps/standalone/src", "apps/website/src", "apps/web-clipper", "apps/edit-docs/demo", "packages/trilium-core/src", "packages/commons/src"];+const URL_SCAN_FILES = ["README.md", ...CODE_SCAN_DIRS];++const treeCache = new Map();+const iconCache = new Map();+/** Key order the exporter writes, kept so a one-page change is a small diff. */+const ENTRY_KEY_ORDER = ["isClone", "noteId", "notePath", "title", "notePosition", "prefix", "isExpanded", "type", "mime", "attributes", "format", "dataFileName", "attachments", "dirFileName", "children"];++const args = process.argv.slice(2);+const command = args.shift();+const flags = parseFlags(args);++const COMMANDS = { find, show, tree, new: newPage, image, rename, move, delete: deletePage, icons, impact, check, sync, help };+if (!command || !(command in COMMANDS)) {+ help();+ process.exit(command ? 1 : 0);+}+COMMANDS[command]();++// ---------------------------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------------------------++function help() {+ console.log(fs.readFileSync(fileURLToPath(import.meta.url), "utf-8").split("\n").slice(1, 26).map((l) => l.replace(/^ \*\/?\s?/, "")).join("\n"));+}++function find() {+ const text = flags._[0];+ if (!text) die("usage: find <text> [--content] [--tree user|dev|release]");+ const needle = text.toLowerCase();+ const trees = flags.tree ? [flags.tree] : Object.keys(TREES);+ let hits = 0;+ for (const treeName of trees) {+ const index = loadTree(treeName);+ for (const page of index.pages) {+ const inMeta = page.title.toLowerCase().includes(needle) || (page.alias ?? "").includes(needle) || page.relPath.toLowerCase().includes(needle);+ let bodyHits = [];+ if (flags.content && page.file) {+ const lines = readPage(page).split("\n");+ bodyHits = lines.map((l, i) => [i + 1, l]).filter(([, l]) => l.toLowerCase().includes(needle));+ }+ if (!inMeta && bodyHits.length === 0) continue;+ hits++;+ console.log(`${page.noteId} ${page.relPath}${page.url ? ` ${page.url.replace(BASE_URL, "")}` : ""}${page.isClone ? " (clone)" : ""}`);+ for (const [n, l] of bodyHits.slice(0, 5)) console.log(` :${n} ${stripHtml(l).trim().slice(0, 140)}`);+ if (bodyHits.length > 5) console.log(` … ${bodyHits.length - 5} more lines`);+ }+ }+ if (!hits) console.log(`no page matches "${text}"${flags.content ? "" : " (try --content to search page bodies)"}`);+}++function show() {+ const page = resolvePage(flags._[0]);+ const index = page.index;+ console.log(`${page.title}`);+ console.log(` noteId ${page.noteId}${page.isClone ? " (clone entry; primary is " + index.byId.get(page.noteId).relPath + ")" : ""}`);+ console.log(` tree ${page.treeName}`);+ console.log(` file ${page.file ?? "(folder only, no data file)"}`);+ console.log(` path ${page.ancestors.map((a) => a.title).concat(page.title).join(" › ")}`);+ console.log(` position ${page.entry.notePosition ?? "(clone)"} siblings: ${page.parent ? page.parent.entry.children.length : 0}`);+ console.log(` type ${page.entry.type}${page.entry.mime ? ` (${page.entry.mime})` : ""}`);+ console.log(` alias ${page.alias ?? "(none — no docUrl, dropped from the standalone help)"}`);+ console.log(` url ${page.url ?? "(none)"}`);+ if (page.treeName === "user") console.log(` docName ${page.docName ?? "(none)"}`);+ console.log(` icon ${page.icon ?? "(none → bx bx-file / bx bx-folder)"}`);+ const otherAttrs = (page.entry.attributes ?? []).filter((a) => !["shareAlias", "iconClass"].includes(a.name));+ if (otherAttrs.length) console.log(` attributes ${otherAttrs.map((a) => `${a.type === "relation" ? "~" : "#"}${a.name}=${a.value}`).join(" ")}`);+ if (page.entry.attachments?.length) {+ console.log(` attachments`);+ for (const a of page.entry.attachments) console.log(` ${a.attachmentId} ${a.dataFileName} (${a.mime})`);+ }+ if (page.entry.children?.length) {+ console.log(` children ${page.entry.children.length}`);+ for (const c of page.entry.children) console.log(` ${c.noteId} ${c.title}${c.isClone ? " (clone)" : ""}`);+ }+ if (page.file) {+ const md = readPage(page);+ const headings = md.split("\n").filter((l) => /^#{2,4} /.test(l));+ if (headings.length) {+ console.log(` outline`);+ for (const h of headings) console.log(` ${h.replace(/^(#+) /, (m, hs) => " ".repeat(hs.length - 2))}`);+ }+ console.log(` words ${md.split(/\s+/).length}`);+ }+ const inbound = findInboundLinks(index, page);+ console.log(` linked from ${inbound.length} page(s)`);+ for (const p of inbound.slice(0, 15)) console.log(` ${p}`);+ if (inbound.length > 15) console.log(` … ${inbound.length - 15} more`);+ const refs = findCodeReferences(page);+ console.log(` referenced from code: ${refs.length ? "" : "none — safe to rename, move or delete"}`);+ for (const r of refs) console.log(` ${r}`);+ if (page.treeName === "user" && page.file) {+ const html = page.file.replace(/\.md$/, ".html").replace(TREES.user.dir, TREES.user.html);+ console.log(` help html ${fs.existsSync(path.join(ROOT, html)) ? html : "(missing — run sync)"}`);+ }+}++function tree() {+ const depthLimit = flags.depth ? Number(flags.depth) : 99;+ let root;+ let index;+ if (flags._[0]) {+ root = resolvePage(flags._[0]);+ index = root.index;+ } else {+ index = loadTree(flags.tree ?? "user");+ root = index.root;+ }+ const print = (page, depth) => {+ const marks = [page.alias ? `/${page.alias}` : "(no alias)", page.icon ?? ""].filter(Boolean).join(" ");+ console.log(`${" ".repeat(depth)}${page.title} ${dim(page.noteId)} ${dim(marks)}${page.isClone ? dim(" clone") : ""}`);+ if (depth >= depthLimit) return;+ for (const child of page.children) print(child, depth + 1);+ };+ print(root, 0);+}++function newPage() {+ const [parentQuery, title] = flags._;+ if (!parentQuery || !title) die('usage: new <parent> "<Title>" [--alias slug] [--icon bx-name] [--after <sibling>|--first] [--tree t]');+ const parent = resolvePage(parentQuery, flags.tree);+ if (parent.isClone) die("the parent is a clone entry; pick its primary location");+ const index = parent.index;+ const treeName = parent.treeName;++ checkTitle(title, parent);+ const alias = flags.alias ?? slugify(title);+ checkAlias(alias, parent);+ const icon = flags.icon ? normalizeIconClass(flags.icon) : undefined;+ if (icon) assertIconExists(icon);+ if (!icon && treeName !== "release") warn("no --icon given; the page will show as a generic file icon in the help tree (see `icons <query>`)");++ const noteId = newEntityId();+ const dataFileName = `${sanitize(title)}.md`;+ const parentDir = childrenDir(parent);+ const filePath = path.join(parentDir, dataFileName);+ if (fs.existsSync(path.join(ROOT, filePath))) die(`${filePath} already exists`);++ const attributes = [];+ if (alias) attributes.push({ type: "label", name: "shareAlias", value: alias, isInheritable: false, position: 10 });+ if (icon) attributes.push({ type: "label", name: "iconClass", value: icon, isInheritable: false, position: 20 });+ const entry = {+ isClone: false,+ noteId,+ notePath: [...parent.entry.notePath, noteId],+ title,+ notePosition: 0,+ prefix: null,+ isExpanded: false,+ type: "text",+ mime: "text/html",+ attributes,+ format: "markdown",+ dataFileName,+ attachments: []+ };++ // A leaf parent becomes a folder: it gains a directory, but keeps its own .md where it was.+ if (!parent.entry.children) {+ parent.entry.dirFileName = sanitize(parent.title);+ parent.entry.children = [];+ fs.mkdirSync(path.join(ROOT, parentDir), { recursive: true });+ }+ insertChild(parent.entry, entry, flags);++ fs.writeFileSync(path.join(ROOT, filePath), `# ${title}\n`);+ writeMeta(index);+ console.log(`created ${filePath}`);+ console.log(` noteId ${noteId} alias ${alias ?? "(none)"} icon ${icon ?? "(none)"} position ${entry.notePosition}`);+ if (alias) console.log(` url ${computeUrl(parent, alias)}`);+ console.log(`\nWrite the page, then \`docs.mjs sync\` to normalize it and generate the help HTML.`);+ console.log(`Link it from its parent with:\n <a class="reference-link" href="${relativeHref(parent, { ...entry, file: filePath })}">${escapeHtml(title)}</a>`);+}++function image() {+ const [pageQuery, file] = flags._;+ if (!pageQuery || !file) die("usage: image <page> <file.png|.gif|.webp|.jpg> [--title name.png]");+ const page = resolvePage(pageQuery, flags.tree);+ if (!page.file) die("the page has no data file; images attach to a page with content");+ const source = path.resolve(file);+ if (!fs.existsSync(source)) die(`${file} not found`);+ const ext = path.extname(source).toLowerCase();+ const mime = { ".png": "image/png", ".gif": "image/gif", ".webp": "image/webp", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".svg": "image/svg+xml" }[ext];+ if (!mime) die(`unsupported image type ${ext}`);+ const title = flags.title ?? `image${ext}`;+ const dir = path.dirname(page.file);+ const base = `${path.basename(page.file, ".md")}_${title}`;+ const dataFileName = uniqueFileName(path.join(ROOT, dir), base);+ fs.copyFileSync(source, path.join(ROOT, dir, dataFileName));+ const attachment = { attachmentId: newEntityId(), title, role: "image", mime, position: 10, dataFileName };+ page.entry.attachments = [...(page.entry.attachments ?? []), attachment].sort((a, b) => a.attachmentId.localeCompare(b.attachmentId));+ writeMeta(page.index);+ const dims = imageDimensions(fs.readFileSync(source));+ const src = escapeHtml(dataFileName);+ console.log(`added ${path.join(dir, dataFileName)} as attachment ${attachment.attachmentId}`);+ console.log(`\nPaste into ${page.file}:`);+ if (dims) {+ console.log(` <figure class="image image-style-align-center"><img style="aspect-ratio:${dims.width}/${dims.height};" src="${src}" width="${dims.width}" height="${dims.height}"></figure>`);+ console.log(` <figure class="image image-style-align-right image_resized" style="width:50%;"><img style="aspect-ratio:${dims.width}/${dims.height};" src="${src}" width="${dims.width}" height="${dims.height}"></figure>`);+ } else {+ console.log(` <img src="${src}">`);+ }+ console.log(`Then \`docs.mjs sync\` copies it into the help HTML tree.`);+}++function rename() {+ const [pageQuery, title] = flags._;+ if (!pageQuery || !title) die('usage: rename <page> "<New title>"');+ const page = resolvePage(pageQuery, flags.tree);+ if (page.isClone) die("rename the primary entry, not the clone");+ checkTitle(title, page.parent, page);+ const oldTitle = page.title;+ page.entry.title = title;+ if (page.file) {+ const md = readPage(page);+ const lines = md.split("\n");+ if (lines[0] === `# ${oldTitle}`) lines[0] = `# ${title}`;+ fs.writeFileSync(path.join(ROOT, page.file), lines.join("\n"));+ }+ writeMeta(page.index);+ console.log(`retitled "${oldTitle}" → "${title}" (noteId ${page.noteId} unchanged)`);+ console.log(`Now run \`docs.mjs sync\`: it renames the file, its attachments and the folder, and rewrites every link to the page.`);+ if (page.alias === slugify(oldTitle)) console.log(`The alias is still "${page.alias}"; keep it if the URL is referenced (\`show\`), otherwise set the new one in !!!meta.json before syncing.`);+}++function move() {+ const [pageQuery, parentQuery] = flags._;+ if (!pageQuery || !parentQuery) die("usage: move <page> <new-parent> [--after <sibling>|--first]");+ const page = resolvePage(pageQuery, flags.tree);+ if (page.isClone) die("move the primary entry, not the clone");+ const parent = resolvePage(parentQuery, page.treeName);+ if (parent.isClone) die("the destination is a clone entry; pick its primary location");+ if (parent.noteId === page.noteId || parent.ancestors.some((a) => a.noteId === page.noteId)) die("cannot move a page under itself");+ const index = page.index;++ // Files first, so a failure leaves the meta untouched.+ const oldDir = page.file ? path.dirname(page.file) : childrenDir(page.parent);+ const newDir = childrenDir(parent);+ if (!parent.entry.children) {+ parent.entry.dirFileName = sanitize(parent.title);+ parent.entry.children = [];+ }+ fs.mkdirSync(path.join(ROOT, newDir), { recursive: true });+ const moved = [];+ const moveFile = (name) => {+ if (fs.existsSync(path.join(ROOT, newDir, name))) die(`${path.join(newDir, name)} already exists`);+ fs.renameSync(path.join(ROOT, oldDir, name), path.join(ROOT, newDir, name));+ moved.push(name);+ };+ if (page.entry.dataFileName) moveFile(page.entry.dataFileName);+ for (const a of page.entry.attachments ?? []) moveFile(a.dataFileName);+ if (page.entry.dirFileName) moveFile(page.entry.dirFileName);++ const siblings = page.parent.entry.children;+ siblings.splice(siblings.indexOf(page.entry), 1);+ if (siblings.length === 0 && page.parent.entry.dataFileName) {+ delete page.parent.entry.children;+ delete page.parent.entry.dirFileName;+ fs.rmSync(path.join(ROOT, oldDir), { recursive: true, force: true });+ }+ const rePath = (entry, parentPath) => {+ entry.notePath = [...parentPath, entry.noteId];+ for (const c of entry.children ?? []) rePath(c, entry.notePath);+ };+ rePath(page.entry, parent.entry.notePath);+ insertChild(parent.entry, page.entry, flags);+ writeMeta(index);+ console.log(`moved "${page.title}" under "${parent.title}" (position ${page.entry.notePosition}); moved ${moved.length} file(s)`);+ console.log(`Now run \`docs.mjs sync\` to rewrite links and the help tree.`);+ if (page.alias) console.log(`URL changes to ${computeUrl(parent, page.alias)} — check \`show\` for code that hard-codes the old one.`);+}++function deletePage() {+ const page = resolvePage(flags._[0], flags.tree);+ if (page.isClone) die("delete the clone by removing its entry from !!!meta.json; this command removes primary pages");+ if (page.entry.children?.length) die("the page has children; move or delete them first");+ const refs = findCodeReferences(page);+ if (refs.length && !flags.force) {+ console.error(`refusing: the app links to this page\n ${refs.join("\n ")}\nRepoint those first (or --force).`);+ process.exit(1);+ }+ const inbound = findInboundLinks(page.index, page);+ const dir = page.file ? path.dirname(page.file) : childrenDir(page.parent);+ if (page.entry.dataFileName) fs.rmSync(path.join(ROOT, dir, page.entry.dataFileName), { force: true });+ for (const a of page.entry.attachments ?? []) fs.rmSync(path.join(ROOT, dir, a.dataFileName), { force: true });+ const siblings = page.parent.entry.children;+ siblings.splice(siblings.indexOf(page.entry), 1);+ if (siblings.length === 0 && page.parent.entry.dataFileName) {+ delete page.parent.entry.children;+ delete page.parent.entry.dirFileName;+ fs.rmSync(path.join(ROOT, dir), { recursive: true, force: true });+ }+ writeMeta(page.index);+ console.log(`deleted "${page.title}" (${page.noteId})`);+ if (inbound.length) console.log(`${inbound.length} page(s) still link to it — fix them before \`sync\`:\n ${inbound.join("\n ")}`);+ else console.log(`Now run \`docs.mjs sync\` to drop it from the help tree.`);+}++function icons() {+ const packs = flags.pack ? [flags.pack] : Object.keys(ICON_PACKS);+ if (flags.check) {+ const problems = checkIconUsage(loadTree("user")).concat(checkIconUsage(loadTree("dev")));+ for (const p of problems) console.log(p);+ console.log(problems.length ? `${problems.length} unknown icon class(es)` : "every icon class in the docs exists in a built-in pack");+ return;+ }+ const query = flags._.map((q) => q.toLowerCase());+ if (!query.length) die("usage: icons <query...> [--pack bx|cke] | icons --check");+ for (const pack of packs) {+ const manifest = loadIconPack(pack);+ const matches = Object.entries(manifest.icons).filter(([name, def]) => query.every((q) => name.includes(q) || (def.terms ?? []).some((t) => t.includes(q))));+ if (!matches.length) continue;+ console.log(`${pack} (${pack === "cke" ? "text editor toolbar" : "app UI, boxicons"}) — ${matches.length} match(es)`);+ for (const [name] of matches.slice(0, 40)) console.log(` <span class="tn-icon ${pack} ${name}"></span>`);+ if (matches.length > 40) console.log(` … ${matches.length - 40} more`);+ }+}++function impact() {+ const terms = new Map(); // term → origin+ const pagesFromCode = new Map(); // noteId → files+ if (flags.diff !== undefined) {+ const range = typeof flags.diff === "string" ? flags.diff : defaultDiffBase();+ const diff = git(["diff", range, "--", "apps", "packages", ":!apps/server/src/assets/doc_notes", ":!apps/standalone/src/assets/help_meta.json"]);+ let file = "";+ const touched = new Set();+ for (const line of diff.split("\n")) {+ if (line.startsWith("+++ b/")) { file = line.slice(6); touched.add(file); continue; }+ if (/translations\/en\/(translation|entry|server)\.json$/.test(file) && /^[-+]\s*"[^"]+":\s*"/.test(line)) {+ const value = line.replace(/^[-+]\s*"[^"]+":\s*"/, "").replace(/",?\s*$/, "").replace(/\\"/g, '"');+ const plain = value.replace(/\{\{-?\s*\w+\s*\}\}/g, "").trim();+ if (plain.length >= 4 && !/^[\W\d]*$/.test(plain)) terms.set(plain, `${line[0] === "-" ? "removed" : "added"} string in ${path.basename(path.dirname(path.dirname(file)))}/${path.basename(file)}`);+ }+ if (/^[-+]/.test(line) && !/^[-+]{3}/.test(line) && file.startsWith("apps/client/src")) {+ for (const m of line.matchAll(/(?:helpPage(?:Id)?=["'{]+|_help_)([A-Za-z0-9]{12})/g)) pagesFromCode.set(m[1], `${file}`);+ }+ }+ for (const f of touched) {+ if (!f.startsWith("apps/client/src")) continue;+ const content = fs.existsSync(path.join(ROOT, f)) ? fs.readFileSync(path.join(ROOT, f), "utf-8") : "";+ for (const m of content.matchAll(/(?:helpPage(?:Id)?=["'{]+|_help_)([A-Za-z0-9]{12})/g)) pagesFromCode.set(m[1], f);+ if (/options_interface\.ts$/.test(f)) terms.set("Options", "options_interface.ts touched");+ if (/hidden_subtree(_launcherbar|_templates)?\.ts$/.test(f)) terms.set("Launch Bar", "hidden subtree touched");+ if (/keyboard_actions/.test(f)) terms.set("Keyboard Shortcuts", "keyboard actions touched");+ }+ console.log(`diff ${range}: ${touched.size} code file(s), ${terms.size} UI string(s) changed, ${pagesFromCode.size} help page(s) wired from touched code\n`);+ }+ for (const t of flags._) terms.set(t, "argument");+ if (!terms.size && !pagesFromCode.size) die("usage: impact --diff [<git range>] | impact <term...>\n(no changed UI strings or help pages found in the diff — pass the feature's names as terms)");++ const index = loadTree("user");+ const bodies = new Map(index.pages.filter((p) => p.file && !p.isClone).map((p) => [p, stripHtml(readPage(p)).toLowerCase()]));+ const report = new Map(); // page → reasons+ const add = (page, reason) => report.set(page, [...(report.get(page) ?? []), reason]);+ for (const [term, origin] of terms) {+ const needle = term.toLowerCase();+ for (const [page, body] of bodies) {+ if (body.includes(needle)) add(page, `mentions "${term}" (${origin})`);+ }+ }+ for (const [noteId, file] of pagesFromCode) {+ const page = index.byId.get(noteId);+ if (page) add(page, `help page of ${file}`);+ else add({ title: `(missing page ${noteId})`, relPath: "", noteId }, `help page of ${file} — DOES NOT EXIST`);+ }+ if (!report.size) {+ console.log("no User Guide page mentions these terms. If the change is user-facing, that is the finding: the feature needs a page or a section (see `new`).");+ return;+ }+ console.log(`${report.size} page(s) to review:`);+ for (const [page, reasons] of [...report].sort((a, b) => b[1].length - a[1].length)) {+ console.log(`\n${page.relPath || page.title} ${dim(page.noteId)}`);+ for (const r of [...new Set(reasons)]) console.log(` - ${r}`);+ }+ console.log(`\nRead every hit; a page that describes a changed control, label, shortcut, default or location is out of date until edited.`);+}++function check() {+ const trees = flags.tree ? [flags.tree] : Object.keys(TREES);+ const errors = [];+ const warnings = [];+ for (const treeName of trees) {+ const index = loadTree(treeName);+ checkStructure(index, errors, warnings);+ checkContent(index, errors, warnings);+ if (treeName === "user") checkHtmlMirror(index, errors, warnings);+ }+ if (trees.includes("user")) {+ checkCodeReferences(loadTree("user"), errors);+ checkUrlLiterals(errors);+ }+ for (const e of errors) console.log(`ERROR ${e}`);+ for (const w of warnings) console.log(`warn ${w}`);+ console.log(`\n${errors.length} error(s), ${warnings.length} warning(s)`);+ if (errors.length) process.exit(1);+}++function sync() {+ console.log("regenerating every docs tree headless (import → export, ~10 s)…");+ const before = gitStatusDocs();+ const result = spawnSync("pnpm", ["edit-docs:sync-docs"], { cwd: ROOT, stdio: ["ignore", "pipe", "inherit"], encoding: "utf-8" });+ if (result.status !== 0) {+ console.error(result.stdout.split("\n").slice(-30).join("\n"));+ die("sync failed — the import rejects a tree whose !!!meta.json and files disagree; run `check`");+ }+ const after = gitStatusDocs();+ const groups = { "docs/ Markdown": [], "docs/ !!!meta.json": [], "help HTML (doc_notes)": [], "help meta": [], images: [] };+ for (const [status, file] of after) {+ const bucket = /!!!meta\.json$/.test(file) && file.startsWith("docs/") ? "docs/ !!!meta.json"+ : /help_meta\.json$|doc_notes.*!!!meta\.json$/.test(file) ? "help meta"+ : /\.(png|gif|webp|jpe?g|svg)$/i.test(file) ? "images"+ : file.startsWith("docs/") ? "docs/ Markdown" : "help HTML (doc_notes)";+ groups[bucket].push(`${status} ${file}`);+ }+ const changedBySync = after.filter(([, f]) => !before.some(([, g]) => g === f)).length;+ console.log(`\nsynced. ${after.length} file(s) differ from HEAD across the docs trees (${changedBySync} first touched by this sync):`);+ for (const [name, files] of Object.entries(groups)) {+ if (!files.length) continue;+ console.log(` ${name}: ${files.length}`);+ for (const f of files.slice(0, 8)) console.log(` ${f}`);+ if (files.length > 8) console.log(` … ${files.length - 8} more`);+ }+ console.log(`\nReview with \`git diff -- docs\` (your Markdown, normalized) and \`git diff --stat -- apps/server/src/assets/doc_notes\`.`);+ console.log(`Reflow, shifted and <li><p> churn in the HTML is expected; a changed href, a dropped <img> or lost text is not.`);+}++// ---------------------------------------------------------------------------------------------+// Checks+// ---------------------------------------------------------------------------------------------++function checkStructure(index, errors, warnings) {+ const { treeName } = index;+ const seen = new Map();+ const aliasPaths = new Map();+ const onDisk = new Set();+ const walkDisk = (dir) => {+ for (const name of fs.readdirSync(path.join(ROOT, dir))) {+ const rel = path.join(dir, name);+ if (fs.statSync(path.join(ROOT, rel)).isDirectory()) walkDisk(rel);+ else if (name !== "!!!meta.json") onDisk.add(rel);+ }+ };+ walkDisk(index.tree.dir);+ const expected = new Set();++ for (const page of index.pages) {+ const where = `${treeName}: ${page.relPath} (${page.noteId})`;+ if (page.isClone) {+ if (!index.byId.has(page.noteId)) errors.push(`${where}: clone of a note that is not in the tree`);+ if (page.file) expected.add(page.file);+ continue;+ }+ if (seen.has(page.noteId)) errors.push(`${where}: duplicate noteId (also ${seen.get(page.noteId)})`);+ seen.set(page.noteId, page.relPath);+ if (!/^[A-Za-z0-9]{12}$/.test(page.noteId)) errors.push(`${where}: noteId is not 12 alphanumerics`);+ const expectedPath = [...page.ancestors.map((a) => a.noteId), page.noteId];+ if (JSON.stringify(page.entry.notePath) !== JSON.stringify(expectedPath)) errors.push(`${where}: notePath does not match the ancestor chain`);+ if (page.file) {+ expected.add(page.file);+ if (!fs.existsSync(path.join(ROOT, page.file))) errors.push(`${where}: dataFileName ${page.entry.dataFileName} is missing on disk`);+ }+ if (page.entry.dirFileName) {+ if (!fs.existsSync(path.join(ROOT, childrenDir(page)))) errors.push(`${where}: dirFileName ${page.entry.dirFileName} is missing on disk`);+ if (!page.entry.children) warnings.push(`${where}: dirFileName without children`);+ } else if (page.entry.children?.length) errors.push(`${where}: has children but no dirFileName`);+ for (const a of page.entry.attachments ?? []) {+ const rel = path.join(page.file ? path.dirname(page.file) : childrenDir(page.parent), a.dataFileName);+ expected.add(rel);+ if (!fs.existsSync(path.join(ROOT, rel))) errors.push(`${where}: attachment ${a.dataFileName} is missing on disk`);+ }+ if (page.entry.type === "text") {+ if (page.entry.format !== "markdown") errors.push(`${where}: text note without format "markdown"`);+ if (page.file && !page.file.endsWith(".md")) errors.push(`${where}: text note data file is not .md`);+ }+ if (page.entry.notePosition !== undefined && page.entry.notePosition % 10 !== 0 && page.depth > 0) warnings.push(`${where}: notePosition ${page.entry.notePosition} is not a multiple of 10`);+ if (page.parent) {+ const siblings = page.parent.entry.children.filter((c) => !c.isClone);+ const i = siblings.indexOf(page.entry);+ if (i > 0 && siblings[i - 1].notePosition > page.entry.notePosition) errors.push(`${where}: children are not in ascending notePosition order`);+ else if (i > 0 && siblings[i - 1].notePosition === page.entry.notePosition) warnings.push(`${where}: shares notePosition ${page.entry.notePosition} with "${siblings[i - 1].title}"`);+ }+ if (treeName === "user" && page.docName && !DOC_NAME_CHARS.test(page.docName)) errors.push(`${where}: title/folder has a character the in-app help refuses (allowed: letters, digits, _ - ( ) & . , \` and space)`);+ if (page.entry.type === "text" && page.file && treeName !== "release") {+ if (!page.alias) warnings.push(`${where}: no shareAlias — no public URL, and dropped from the standalone help`);+ if (!page.icon && treeName === "user") warnings.push(`${where}: no iconClass`);+ }+ if (page.alias && !/^[a-z0-9]+([.-][a-z0-9]+)*$/.test(page.alias)) warnings.push(`${where}: shareAlias "${page.alias}" is not kebab-case`);+ if (page.url) {+ if (aliasPaths.has(page.url)) errors.push(`${where}: URL ${page.url} is also used by ${aliasPaths.get(page.url)}`);+ aliasPaths.set(page.url, page.relPath);+ }+ if (page.icon && !iconExists(page.icon)) errors.push(`${where}: iconClass "${page.icon}" is in no built-in pack`);+ if ((page.entry.attributes ?? []).some((a, i) => i > 0 && page.entry.attributes[i - 1].position >= a.position)) warnings.push(`${where}: attribute positions are not ascending`);+ }+ for (const f of onDisk) if (!expected.has(f)) errors.push(`${treeName}: ${f} is on disk but in no !!!meta.json entry (edit-docs would crash on it)`);+}++function checkContent(index, errors, warnings) {+ const { treeName } = index;+ const titleByFile = new Map(index.pages.filter((p) => p.file).map((p) => [p.file, p.title]));+ for (const page of index.pages) {+ if (!page.file || page.isClone || !page.file.endsWith(".md")) continue;+ const md = readPage(page);+ const where = `${treeName}: ${page.relPath}`;+ const lines = md.split("\n");+ let fenced = false;+ const prose = lines.map((l) => {+ if (/^\s*```/.test(l)) { fenced = !fenced; return ""; }+ return fenced ? "" : l;+ }).join("\n");+ if (!md.trim()) warnings.push(`${where}: empty page`);+ else if (lines[0] !== `# ${page.title}`) warnings.push(`${where}: line 1 is not "# ${page.title}" (the importer demotes a differing H1)`);+ const dir = path.dirname(page.file);+ const usedAttachments = new Set();+ for (const [, href] of prose.matchAll(/(?:href|src)="([^"]+)"/g)) checkLink(unescapeHtml(href), false);+ for (const [, href] of prose.matchAll(/\]\(((?:\\.|[^()\s])+)\)/g)) checkLink(href.replace(/\\([()])/g, "$1"), true);+ for (const [, cls] of prose.matchAll(/<span class="tn-icon ([^"]+)"/g)) {+ if (!iconExists(cls)) errors.push(`${where}: unknown icon class "${cls}"`);+ }+ for (const a of page.entry.attachments ?? []) {+ if (!usedAttachments.has(a.dataFileName)) warnings.push(`${where}: attachment ${a.dataFileName} is not referenced by the page (edit-docs erases unused attachments)`);+ }+ for (const [n, l] of prose.split("\n").entries()) {+ if (treeName !== "user") break;+ const at = `${where}:${n + 1}`;+ if (/[A-Za-z]\\\\[A-Za-z]/.test(l)) warnings.push(`${at}: stray backslash inside a word ("${l.match(/\w*\\\\\w*/)[0]}")`);+ if (/\b(colour|centre|organis(e|ation)|customis|behaviour|synchronis|recognis|licence\b|grey\b)/i.test(l) && !/```|http/.test(l)) warnings.push(`${at}: British spelling (the docs are US English)`);+ if (/TriliumNext Notes/.test(l)) warnings.push(`${at}: "TriliumNext Notes" — the product is "Trilium"`);+ if (/\b(Ctrl|Shift|Alt|Cmd)\s*\+\s*\w/.test(l) && !/<kbd>/.test(l) && !/^\s*[`|]|```/.test(l)) warnings.push(`${at}: plain-text shortcut — write each key as <kbd>…</kbd>`);+ for (const [, href, text] of l.matchAll(/<a class="reference-link" href="([^"]+)">([^<]*)<\/a>/g)) {+ const target = resolveRelative(dir, unescapeHtml(href));+ const title = titleByFile.get(target);+ if (title && unescapeHtml(text) !== title) warnings.push(`${at}: reference-link text "${unescapeHtml(text)}" differs from the target's title "${title}"`);+ if (text === "[missing note]") errors.push(`${at}: reference-link to a missing note`);+ }+ }+ if (md.endsWith("\n") && treeName === "user") warnings.push(`${where}: trailing newline (the exporter writes none; \`sync\` normalizes it)`);++ function checkLink(href, isMarkdown) {+ if (/^(https?:|mailto:|data:)/.test(href)) return;+ const [target, hash] = href.split("#");+ if (href.startsWith("#root/")) {+ const id = href.split("/").pop().split("?")[0];+ if (!id.startsWith("_") && !index.byId.has(id) && !otherTreesHave(id)) errors.push(`${where}: link to #root/${id}, a note in no docs tree`);+ if (href.startsWith("#root/_options") || href.startsWith("#root/_backendLog") || href.startsWith("#root/_sqlConsole")) errors.push(`${where}: ${href} skips _hidden/ — the canonical path is #root/_hidden/…`);+ return;+ }+ if (href.startsWith("#")) return;+ if (!target) return;+ const rel = resolveRelative(dir, isMarkdown ? decodeURIComponent(target) : decodeURIComponent(target));+ if (/^api\//.test(target)) { errors.push(`${where}: link to ${target} (an unresolved in-app URL)`); return; }+ if (!fs.existsSync(path.join(ROOT, rel))) errors.push(`${where}: ${isMarkdown ? "link" : "href/src"} ${href} does not resolve (${rel})`);+ else if (path.dirname(rel) === dir) usedAttachments.add(path.basename(rel));+ void hash;+ }+ }+}++function checkHtmlMirror(index, errors, warnings) {+ const status = gitStatusDocs();+ const modifiedMd = status.filter(([, f]) => f.startsWith(`${TREES.user.dir}/`) && f.endsWith(".md")).map(([, f]) => f);+ for (const page of index.pages) {+ if (!page.file || page.depth === 0) continue;+ const html = page.file.replace(/\.md$/, ".html").replace(TREES.user.dir, TREES.user.html);+ if (page.file.endsWith(".md") && !fs.existsSync(path.join(ROOT, html))) { errors.push(`user: ${page.relPath} has no help HTML twin — run \`sync\``); continue; }+ if (modifiedMd.includes(page.file) && !status.some(([, f]) => f === html)) warnings.push(`user: ${page.relPath} is modified but its help HTML is not — run \`sync\``);+ }+ const helpMeta = JSON.parse(fs.readFileSync(path.join(ROOT, TREES.user.helpMeta), "utf-8"));+ const helpIds = new Set();+ const walk = (items) => { for (const i of items) { helpIds.add(i.id); walk(i.children ?? []); } };+ walk(helpMeta);+ for (const page of index.pages) {+ if (page.depth === 0 || page.isClone) continue;+ if (!helpIds.has(`_help_${page.noteId}`)) errors.push(`user: ${page.relPath} is not in the help meta (${TREES.user.helpMeta}) — run \`sync\``);+ }+}++function checkCodeReferences(index, errors) {+ const ids = new Set();+ const rg = grep(String.raw`(helpPage(Id)?=["'{]+|_help_)[A-Za-z0-9]{12}\b`, ["apps/client/src"]);+ for (const line of rg) {+ const [file, , ...rest] = line.split(":");+ const m = rest.join(":").match(/([A-Za-z0-9]{12})$/);+ if (m) ids.add([m[1], file]);+ }+ const inAppHelp = path.join(ROOT, "apps/client/src/services/in_app_help.ts");+ if (fs.existsSync(inAppHelp)) for (const m of fs.readFileSync(inAppHelp, "utf-8").matchAll(/[:=]\s*"([A-Za-z0-9]{12})"/g)) ids.add([m[1], "apps/client/src/services/in_app_help.ts"]);+ const reported = new Set();+ for (const [id, file] of ids) {+ if (index.byId.has(id) || reported.has(id)) continue;+ reported.add(id);+ errors.push(`code: ${file} links help page ${id}, which is not in the User Guide`);+ }+}++function checkUrlLiterals(errors) {+ const index = loadTree("user");+ const urls = new Set(index.pages.filter((p) => p.url).map((p) => p.url.replace(BASE_URL, "")));+ const devUrls = new Set(loadTree("dev").pages.filter((p) => p.url).map((p) => p.url.replace(BASE_URL, "")));+ for (const line of grep(String.raw`docs\.triliumnotes\.org/(user-guide|developer-guide)[^[:space:]"'\`)<>,]*`, URL_SCAN_FILES)) {+ const [file, ...rest] = line.split(":");+ for (const m of rest.join(":").matchAll(/docs\.triliumnotes\.org(\/(?:user-guide|developer-guide)[^\s"'`)<>,]*)/g)) {+ const p = m[1].replace(/\.html$/, "").replace(/\/$/, "").split(/[#?]/)[0];+ if (!urls.has(p) && !devUrls.has(p)) errors.push(`code: ${file} links ${m[1]}, which no page's shareAlias chain produces`);+ }+ }+}++function checkIconUsage(index) {+ const out = [];+ for (const page of index.pages) {+ if (page.icon && !iconExists(page.icon)) out.push(`${page.relPath}: iconClass "${page.icon}"`);+ if (!page.file || page.isClone || !page.file.endsWith(".md")) continue;+ for (const [, cls] of readPage(page).matchAll(/<span class="tn-icon ([^"]+)"/g)) if (!iconExists(cls)) out.push(`${page.relPath}: <span class="tn-icon ${cls}">`);+ }+ return out;+}++// ---------------------------------------------------------------------------------------------+// Tree model+// ---------------------------------------------------------------------------------------------++/** Reads a tree's `!!!meta.json` and indexes every entry with its path, URL and docName. */+function loadTree(treeName) {+ if (treeCache.has(treeName)) return treeCache.get(treeName);+ const tree = TREES[treeName];+ if (!tree) die(`unknown tree "${treeName}" (user | dev | release)`);+ const metaPath = path.join(ROOT, tree.dir, "!!!meta.json");+ const raw = fs.readFileSync(metaPath, "utf-8");+ const meta = JSON.parse(raw);+ const index = { treeName, tree, meta, metaPath, raw, pages: [], byId: new Map(), root: null };+ const visit = (entry, parent, dir, parentUrl, docNameRoot) => {+ const alias = entry.attributes?.find((a) => a.type === "label" && a.name === "shareAlias")?.value;+ const currentUrl = parentUrl && alias ? `${parentUrl}/${alias}` : parentUrl;+ const page = {+ entry, parent, index, treeName, isClone: entry.isClone === true,+ noteId: entry.noteId, title: entry.title, alias,+ url: alias ? currentUrl : undefined,+ icon: entry.attributes?.find((a) => a.type === "label" && a.name === "iconClass")?.value,+ depth: parent ? parent.depth + 1 : 0,+ ancestors: parent ? [...parent.ancestors, parent] : [],+ file: entry.dataFileName ? path.join(dir, entry.dataFileName) : undefined,+ children: []+ };+ page.relPath = page.file ?? path.join(dir, entry.dirFileName ?? entry.title);+ page.docName = treeName === "user" && entry.type === "text" && entry.dataFileName ? `${docNameRoot}/${path.basename(entry.dataFileName, ".md")}`.substring(1) : undefined;+ index.pages.push(page);+ if (!page.isClone) index.byId.set(entry.noteId, page);+ const childDir = entry.dirFileName ? path.join(dir, entry.dirFileName) : dir;+ const childDocRoot = entry.dirFileName ? `${docNameRoot}/${entry.dirFileName}` : docNameRoot;+ for (const child of entry.children ?? []) page.children.push(visit(child, page, childDir, currentUrl, childDocRoot));+ return page;+ };+ index.root = visit(meta.files[0], null, tree.dir, BASE_URL, `/${meta.files[0].dirFileName ?? ""}`);+ treeCache.set(treeName, index);+ return index;+}++function resolvePage(query, treeName) {+ if (!query) die("which page? give a noteId, a shareAlias, or a unique title/path fragment");+ const trees = treeName ? [treeName] : Object.keys(TREES);+ const candidates = [];+ for (const t of trees) {+ const index = loadTree(t);+ const exact = index.byId.get(query);+ if (exact) return exact;+ for (const p of index.pages) {+ if (p.isClone) continue;+ if (p.alias === query || p.title.toLowerCase() === query.toLowerCase()) candidates.push(p);+ }+ }+ if (candidates.length === 1) return candidates[0];+ if (candidates.length === 0) {+ const q = query.toLowerCase();+ for (const t of trees) for (const p of loadTree(t).pages) if (!p.isClone && (p.title.toLowerCase().includes(q) || p.relPath.toLowerCase().includes(q))) candidates.push(p);+ }+ if (candidates.length === 1) return candidates[0];+ if (candidates.length === 0) die(`no page matches "${query}"`);+ die(`"${query}" is ambiguous:\n${candidates.map((p) => ` ${p.noteId} ${p.treeName}: ${p.relPath}`).join("\n")}\nuse the noteId`);+}++function readPage(page) {+ return fs.readFileSync(path.join(ROOT, page.file), "utf-8");+}++function childrenDir(page) {+ if (page.depth === 0) return path.join(page.index.tree.dir, page.entry.dirFileName ?? sanitize(page.title));+ const base = page.file ? path.dirname(page.file) : childrenDir(page.parent);+ return path.join(base, page.entry.dirFileName ?? sanitize(page.title));+}++function computeUrl(parent, alias) {+ const parentUrl = parent.url ?? parent.ancestors.concat(parent).reverse().find((a) => a.url)?.url ?? BASE_URL;+ return `${parentUrl}/${alias}`;+}++function relativeHref(fromPage, toEntry) {+ const fromDir = fromPage.file ? path.dirname(fromPage.file) : childrenDir(fromPage.parent);+ return path.relative(fromDir, toEntry.file).split("/").map(encodeURIComponent).join("/");+}++function insertChild(parentEntry, entry, opts) {+ const children = parentEntry.children;+ const positioned = children.filter((c) => !c.isClone);+ let at = children.length;+ if (opts.first) {+ at = 0;+ if (positioned.length && positioned[0].notePosition >= 20) {+ entry.notePosition = positioned[0].notePosition - 10;+ } else {+ for (const c of positioned) c.notePosition += 10;+ entry.notePosition = 10;+ }+ } else if (opts.after) {+ const sibling = children.find((c) => c.noteId === opts.after || c.title.toLowerCase() === String(opts.after).toLowerCase());+ if (!sibling) die(`--after: no sibling "${opts.after}" under "${parentEntry.title}"`);+ at = children.indexOf(sibling) + 1;+ const next = children.slice(at).find((c) => !c.isClone);+ if (next && next.notePosition - sibling.notePosition < 20) {+ for (const c of positioned.slice(positioned.indexOf(next))) c.notePosition += 10;+ }+ entry.notePosition = sibling.notePosition + 10;+ } else {+ entry.notePosition = positioned.length ? positioned[positioned.length - 1].notePosition + 10 : 10;+ }+ children.splice(at, 0, entry);+}++/** Rewrites the meta file in the exporter's layout: 4-space indent, no trailing newline. */+function writeMeta(index) {+ const ordered = orderKeys(index.meta);+ fs.writeFileSync(index.metaPath, JSON.stringify(ordered, null, 4));+}++function orderKeys(value) {+ if (Array.isArray(value)) return value.map(orderKeys);+ if (value && typeof value === "object") {+ const keys = Object.keys(value);+ const isEntry = keys.includes("noteId") && keys.includes("notePath");+ const sorted = isEntry ? [...ENTRY_KEY_ORDER.filter((k) => keys.includes(k)), ...keys.filter((k) => !ENTRY_KEY_ORDER.includes(k))] : keys;+ return Object.fromEntries(sorted.map((k) => [k, orderKeys(value[k])]));+ }+ return value;+}++function findInboundLinks(index, page) {+ if (!page.file) return [];+ const out = [];+ for (const other of index.pages) {+ if (!other.file || other.isClone || other === page || !other.file.endsWith(".md")) continue;+ const dir = path.dirname(other.file);+ const md = readPage(other);+ const hrefs = [...md.matchAll(/href="([^"]+)"/g)].map((m) => unescapeHtml(m[1])).concat([...md.matchAll(/\]\(((?:\\.|[^()\s])+)\)/g)].map((m) => m[1].replace(/\\([()])/g, "$1")));+ if (hrefs.some((h) => !/^(https?:|#)/.test(h) && resolveRelative(dir, decodeURIComponent(h.split("#")[0])) === page.file)) out.push(other.relPath);+ }+ return out;+}++function findCodeReferences(page) {+ const refs = [];+ for (const line of grep(page.noteId, CODE_SCAN_DIRS)) refs.push(`noteId in ${line.slice(0, 160)}`);+ if (page.url) {+ const p = page.url.replace(BASE_URL, "");+ for (const line of grep(`docs\\.triliumnotes\\.org${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\.html)?([[:space:]"'\`)<>,/#?]|$)`, URL_SCAN_FILES)) refs.push(`url in ${line.split(":").slice(0, 2).join(":")}`);+ }+ return refs;+}++function otherTreesHave(id) {+ return Object.keys(TREES).some((t) => loadTree(t).byId.has(id));+}++// ---------------------------------------------------------------------------------------------+// Validation helpers+// ---------------------------------------------------------------------------------------------++function checkTitle(title, parent, self) {+ if (!title.trim()) die("empty title");+ const docName = `${parent ? childrenDir(parent) : ""}/${sanitize(title)}`;+ if (parent && parent.treeName === "user" && !DOC_NAME_CHARS.test(docName.replace(/^docs\/User Guide\//, ""))) die(`the in-app help cannot open a page whose title has characters outside letters, digits, _ - ( ) & . , \` and space: "${title}"`);+ const fileBase = sanitize(title).toLowerCase();+ for (const c of parent?.entry.children ?? []) {+ if (c === self?.entry) continue;+ if ((c.dataFileName ?? "").toLowerCase() === `${fileBase}.md` || (c.dirFileName ?? "").toLowerCase() === fileBase) die(`a sibling already produces the file name "${sanitize(title)}"`);+ }+ if (sanitize(title) !== title) warn(`the file will be named "${sanitize(title)}.md" (illegal file-name characters dropped)`);+}++function checkAlias(alias, parent) {+ if (!alias) return;+ if (!/^[a-z0-9]+([.-][a-z0-9]+)*$/.test(alias)) die(`alias "${alias}" must be kebab-case (lowercase letters, digits, hyphens)`);+ const url = computeUrl(parent, alias);+ const clash = parent.index.pages.find((p) => p.url === url);+ if (clash) die(`alias "${alias}" gives ${url}, already used by ${clash.relPath}`);+}++function assertIconExists(cls) {+ if (!iconExists(cls)) die(`icon "${cls}" is in no built-in pack — try \`icons <query>\``);+}++function loadIconPack(pack) {+ if (!iconCache.has(pack)) iconCache.set(pack, JSON.parse(fs.readFileSync(path.join(ROOT, ICON_PACKS[pack]), "utf-8")));+ return iconCache.get(pack);+}++/** `bx bx-star`, `bx bxs-grid`, `cke cke-quote`, with optional modifiers such as `bx-flip-horizontal`. */+function iconExists(cls) {+ const parts = cls.trim().split(/\s+/);+ const pack = parts[0];+ if (!(pack in ICON_PACKS)) return false;+ const name = parts.find((p) => p !== pack && p.startsWith(`${pack}`) && !/^bx-(flip|rotate|spin|tada|flashing|burst|fade|pull|xs|sm|md|lg|fw|border|tada)/.test(p));+ return Boolean(name && loadIconPack(pack).icons[name]);+}++function normalizeIconClass(input) {+ const name = input.trim().replace(/^(bx|cke)\s+/, "");+ const pack = name.startsWith("cke-") ? "cke" : "bx";+ return `${pack} ${name}`;+}++// ---------------------------------------------------------------------------------------------+// Small utilities+// ---------------------------------------------------------------------------------------------++function newEntityId() {+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";+ for (;;) {+ const id = Array.from(crypto.randomBytes(12), (b) => chars[b % chars.length]).join("");+ if (!Object.keys(TREES).some((t) => loadTree(t).raw.includes(id))) return id;+ }+}++/** What `sanitize-filename` does to a title on export. */+function sanitize(name) {+ return name.replace(/[/?<>\\:*|"\x00-\x1f\x80-\x9f]/g, "").replace(/^\.+$/, "").replace(/[. ]+$/, "").trim();+}++function slugify(title) {+ return title.toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");+}++function uniqueFileName(dir, name) {+ const existing = fs.existsSync(dir) ? new Set(fs.readdirSync(dir).map((f) => f.toLowerCase())) : new Set();+ if (!existing.has(name.toLowerCase())) return name;+ for (let i = 1; ; i++) if (!existing.has(`${i}_${name}`.toLowerCase())) return `${i}_${name}`;+}++function imageDimensions(buf) {+ if (buf.length > 24 && buf.toString("ascii", 1, 4) === "PNG") return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };+ if (buf.toString("ascii", 0, 3) === "GIF") return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };+ if (buf.toString("ascii", 0, 4) === "RIFF" && buf.toString("ascii", 8, 12) === "WEBP") {+ const chunk = buf.toString("ascii", 12, 16);+ if (chunk === "VP8X") return { width: 1 + buf.readUIntLE(24, 3), height: 1 + buf.readUIntLE(27, 3) };+ if (chunk === "VP8 ") return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };+ if (chunk === "VP8L") { const b = buf.readUInt32LE(21); return { width: (b & 0x3fff) + 1, height: ((b >> 14) & 0x3fff) + 1 }; }+ }+ if (buf[0] === 0xff && buf[1] === 0xd8) {+ let i = 2;+ while (i < buf.length) {+ if (buf[i] !== 0xff) return null;+ const marker = buf[i + 1];+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) };+ i += 2 + buf.readUInt16BE(i + 2);+ }+ }+ return null;+}++function resolveRelative(dir, href) {+ return path.normalize(path.join(dir, href));+}++function stripHtml(s) {+ return s.replace(/<[^>]+>/g, "").replace(/ | /g, " ").replace(/&/g, "&");+}++function escapeHtml(s) {+ return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);+}++function unescapeHtml(s) {+ return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"');+}++function grep(pattern, paths) {+ const existing = paths.filter((p) => fs.existsSync(path.join(ROOT, p)));+ const result = spawnSync("grep", ["-rnoE", "--include=*.ts", "--include=*.tsx", "--include=*.js", "--include=*.json", "--include=*.md", "--include=*.html", "--exclude-dir=node_modules", "--exclude-dir=dist", "--exclude-dir=doc_notes", "--exclude=help_meta.json", pattern, ...existing], { cwd: ROOT, encoding: "utf-8", maxBuffer: 64 * 1024 * 1024 });+ return (result.stdout ?? "").split("\n").filter(Boolean);+}++function git(argv) {+ return execFileSync("git", argv, { cwd: ROOT, encoding: "utf-8", maxBuffer: 256 * 1024 * 1024 });+}++function gitStatusDocs() {+ return git(["status", "--porcelain", "--", "docs", TREES.user.html, TREES.user.standaloneMeta]).split("\n").filter(Boolean).map((l) => [l.slice(0, 2).trim() || "M", l.slice(3).replace(/^"|"$/g, "").replace(/\\"/g, '"')]);+}++function defaultDiffBase() {+ const branch = git(["rev-parse", "--abbrev-ref", "HEAD"]).trim();+ if (branch === "main") return "HEAD";+ for (const main of ["main", "origin/main"]) {+ try { return execFileSync("git", ["merge-base", main, "HEAD"], { cwd: ROOT, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch { /* next candidate */ }+ }+ return "HEAD";+}++function parseFlags(argv) {+ const out = { _: [] };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a.startsWith("--")) {+ const key = a.slice(2);+ const next = argv[i + 1];+ if (next !== undefined && !next.startsWith("--") && !["content", "check", "first", "force"].includes(key)) { out[key] = next; i++; }+ else out[key] = true;+ } else out._.push(a);+ }+ return out;+}++function dim(s) {+ return s ? `\x1b[2m${s}\x1b[0m` : "";+}++function warn(msg) {+ console.error(`warning: ${msg}`);+}++function die(msg) {+ console.error(msg);+ process.exit(1);+}diff --git a/.claude/skills/writing-documentation/references/page-templates.md b/.claude/skills/writing-documentation/references/page-templates.mdnew file mode 100644index 0000000000..f1d7795aaa--- /dev/null+++ b/.claude/skills/writing-documentation/references/page-templates.md@@ -0,0 +1,188 @@+# Page templates++Skeletons drawn from real pages. Copy the shape, not the words. Line 1 is the H1, line 2 starts the+body, no trailing newline; `docs.mjs sync` normalizes the rest.++## Note-type page (`Note Types/Mind Map.md`, `Canvas.md`, `Spreadsheets.md`, `Mermaid Diagrams.md`)++```markdown+# Mind Map+<figure class="image image-style-align-center"><img style="aspect-ratio:892/675;" src="Mind Map_image.png" width="892" height="675"></figure>++> [!IMPORTANT]+> Spreadsheets are a new type of note introduced in v0.103.0 and are currently considered experimental/beta.++The mind map allows for easy jotting down of ideas and storing them in a hierarchical fashion.++## Terminology++* A **node** is a single idea…+* The **root node** is…++## Interaction++* To create a new node at the same level as the current one, press <kbd>Enter</kbd> or…+* To delete a node, …++## Embedding notes+…++## Supported features / Limitations++### Share functionality+### Mobile support+```++## Collection page (`Collections/Kanban Board.md`, `Table.md`, `Grid View.md`, `Presentation.md`)++```markdown+# Kanban Board+<figure class="image image-style-align-center"><img …></figure>++The Board view presents sub-notes in columns for a Kanban-like experience…++## Creating a Kanban board++Right click on an existing note in the <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20Tree.md">Note Tree</a> and select _Insert child note_ and look for _Kanban Board_.++## How it works+…++## Interaction++### Working with columns+### Working with notes+### Keyboard interaction++## Configuration++### Grouping by another label++…the `#board:groupBy` label…++## Limitations++## Use in search+```++## UI-element page (`UI Elements/Split View.md`, `Right Sidebar.md`, `Floating buttons.md`, `Zoom.md`)++```markdown+# Split View+<figure class="image image-style-align-right image_resized" style="width:50%;"><img …></figure>++In Trilium, it's possible to display two notes side-by-side…++## Interaction++* To open a split view, press the <span class="tn-icon bx bx-dock-right"></span> button to the right of a note's title.+* To close a split view, …++## Mobile support++Since v0.100.0, …++## Keyboard shortcuts++* <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>…</kbd>: _Create New Split_.+```++## Settings-driven section (inside `Content width.md`, `Personalizing the font.md`)++```markdown+## Adjusting the content width++Go to <a class="reference-link" href="../Options.md">Options</a> → _Appearance_ → _Content Width_ and adjust the _Max content width_ option.++## Adjusting at note level++Manually apply the `fullContentWidth` [label](../../../Advanced%20Usage/Attributes/Labels.md) to a note…+```++## Concept page (`Collections.md`, `Note Types.md`, `Attributes/Labels.md`, `Notes/Cloning Notes.md`)++```markdown+# Labels+A label is an [attribute](../Attributes.md) of a note which has a name and optionally a value.++## Common labels for basic functionality++| Label | Description |+| --- | --- |+| `disableVersioning` | Disables automatic creation of… |++## Creating a label+…++## Configuration / Advanced use cases++### …++## Under the hood++Collections don't store their configuration … but as attachments.+```++## Installation / how-to page (`Desktop Installation.md`, `Using Docker.md`, `Backup.md`)++```markdown+# Using Docker+Official docker images are published on Docker Hub for…++## Prerequisites+…++## Running with Docker Compose++1. **Download the Latest Release**: Obtain the latest `docker-compose.yml`…+2. **Start the container**:++ ```sh+ docker compose up -d+ ```++> [!TIP]+> It's generally a good idea to use a reverse proxy…+```++## Breaking-change page (`Scripting/Breaking changes/v0.106.0 Removal of cheerio.md`)++```markdown+# v0.106.0: Removal of cheerio+Starting with v0.106.0, `cheerio` is no longer available in the backend script API.++## Reasoning+…++## Migration++### Parsing HTML++Before (cheerio):++```javascript+…+```++After:++```javascript+…+```+```++The title carries a colon; the file name drops it (`v0.106.0 Removal of cheerio.md`), which the+exporter does on its own.++## Relocation stub++When a page moves to a different home and the old noteId is referenced from code:++```markdown+# Old title+> [!NOTE]+> This page has been relocated to <a class="reference-link" href="../New%20Home.md">New Home</a>.+```++A `*.clone.md` file ("This is a clone of a note. Go to its [primary location](…).") is written by the+exporter for a cloned note and is never hand-written.diff --git a/.claude/skills/writing-documentation/references/pipeline.md b/.claude/skills/writing-documentation/references/pipeline.mdnew file mode 100644index 0000000000..62759cebb5--- /dev/null+++ b/.claude/skills/writing-documentation/references/pipeline.md@@ -0,0 +1,116 @@+# How the documentation is produced and consumed++## The trees++| Tree | Root noteId | Source | Generated from it |+| --- | --- | --- | --- |+| User Guide | `pOsGYCXsbNQG` | `docs/User Guide/` (Markdown + `!!!meta.json`) | `apps/server/src/assets/doc_notes/en/User Guide/**/*.html` + its minified `!!!meta.json`; `apps/standalone/src/assets/help_meta.json`; `site/user-guide` on the docs site |+| Developer Guide | `jdjRLhLV3TtI` | `docs/Developer Guide/` | `site/developer-guide` |+| Release Notes | `hD3V4hiu2VW4` | `docs/Release Notes/` | the GitHub release body (`scripts/release-notes-body.mts`, `release.yml`) |++`edit-docs-config.yaml` at the repo root is the single list of these mappings; both the editor and the+headless sync read it.++## The round trip++`pnpm edit-docs:edit-docs` (`apps/edit-docs/src/edit-docs.ts`) zips every non-`exportOnly` mapping,+imports it into an in-memory database with `preserveIds: true`, opens an Electron window, and — 10 s+after any entity change — `rm -rf`s **every** mapping's directory and re-exports it from the+database: Markdown for the three trees, HTML for the User Guide. Nothing exports on close, and an+untouched session writes nothing.++`pnpm edit-docs:sync-docs` (`apps/edit-docs/src/sync-docs.ts`, `docs.mjs sync`) is the same import+and the same export with no window: `apps/edit-docs/src/docs_pipeline.ts` holds the shared code.+Running it on a clean tree is byte-stable; running it after a hand edit normalizes the Markdown the+way the editor would (the import renders Markdown to HTML, the export turns it back) and regenerates+the HTML and both help metas. ~7 s.++Consequences:++- The import resolves every relative `.md` link to a noteId; the export re-derives paths and file+ names from titles. So a rename or move only needs the title/entry changed — links, attachment file+ names and folder names follow on the next sync.+- A file in no `!!!meta.json` entry is deleted by the export; a `.md` in an existing folder with no+ entry makes the import throw (`Cannot find parentNoteId`). Tree-shape changes go through `docs.mjs+ new` / `image` / `rename` / `move` / `delete`, which write the entry.+- The export adds `# <title>` when the body does not start with it; the importer removes a matching+ first H1 and demotes a differing one.+- `internalLink` / `imageLink` relations are never in the meta — they are rebuilt from content.+- `pnpm docs:build` (`apps/build-docs`) is the **site** build: it imports `docs/` again and share-exports+ it to `site/`, ignoring `edit-docs-config.yaml`. It is not a way to regenerate `doc_notes`.++## `!!!meta.json` (formatVersion 2)++`{ formatVersion: 2, files: [rootEntry] }`, written 4-space indented, key order `isClone, noteId,+notePath, title, notePosition, prefix, isExpanded, type, mime, attributes, format, dataFileName,+attachments, dirFileName, children`. Types: `packages/trilium-core/src/meta.ts`; producer+`services/export/zip.ts` (`createNoteMeta`); consumer `services/import/zip.ts` (`getMeta`).++- `noteId`: 12 chars `[A-Za-z0-9]` (`newEntityId()`). Kept on import. **Permanent** once the app or+ a page links it.+- `notePath`: ancestor noteIds from the tree root down to the entry.+- `notePosition`: multiples of 10, ascending within `children` (ties allowed); the root is forced to 1.+- `type` / `mime`: `text` / `text/html` for a page (`text/markdown` is a legacy mime on 71 older+ pages); `webView` for the Script/REST API frames (`webViewSrc`); `code` for a few `.js`/`.jsx`/`.json`+ notes; `book` for the Breaking-changes folder.+- `format: "markdown"` on every text entry (that is what makes the importer render the file).+- `dataFileName`: `sanitize(title) + ".md"`; absent for a folder note with empty content (13 in the+ User Guide). `dirFileName`: `sanitize(title)`, present only with `children`. `sanitize` strips+ `/ \ : * ? " < > |`.+- `attributes[]`: owned labels/relations `{type, name, value, isInheritable, position}`. In the+ User Guide: `shareAlias` (295), `iconClass` (254, all `bx …`), `webViewSrc` (7), `sorted` (3), and+ on the root `label:shareAlias` (the promoted "Slug" field, inheritable) and `readOnly`.+- `attachments[]`: `{attachmentId, title, role: "image", mime, position: 10, dataFileName}` sorted by+ `attachmentId`; file `<page base>_<title>`, `N_` prefixed when the directory already has that name.+- `isClone: true` entries (2) carry only `noteId, notePath, title, prefix, dataFileName: "<Title>.clone.md",+ type, format, isExpanded` — the same noteId appears twice in the tree.++## What the app reads++- **In-app help** (`F1`, help buttons): `apps/server/src/in_app_help_provider.ts` loads+ `doc_notes/en/User Guide/!!!meta.json` — a minified `HiddenSubtreeItem[]` (not a NoteMetaFile)+ built by `apps/edit-docs/src/help_meta_generator.ts`: each page becomes `_help_<noteId>` of type+ `doc` with `#docName` (`User Guide/User Guide/<folders>/<title>`), `#docUrl` (the alias chain) and+ `#iconClass`. `checkHiddenSubtree()` materializes it under `_help`; `doc_renderer.ts` fetches+ `doc_notes/en/<docName>.html` and refuses a docName outside `[a-zA-Z0-9_/\- ()&.,\`]`.+- **Standalone/mobile**: `apps/standalone/src/assets/help_meta.json` — the same tree as `webView`+ items pointing at `docUrl`; a page without an alias is dropped.+- **Help buttons link by noteId** (`<HelpButton helpPage="…">` → `openInAppHelpFromUrl` →+ `_help_<id>`; `Modal helpPageId`; `services/in_app_help.ts` maps note types, collection views and+ sidebar sections). ~60 IDs are hard-coded in `apps/client/src`; `docs.mjs show` lists them per page+ and `check` fails when one points nowhere. `apps/client/src/services/in_app_help.spec.ts` is the CI+ guard for the `in_app_help.ts` maps, the docName files and the `_help_` links inside the HTML.+- **Public URL** = `https://docs.triliumnotes.org` + `/` + each ancestor's `shareAlias` (ancestors+ without one contribute nothing). Unique as a full path, not globally (`troubleshooting` is used+ three times). Hard-coded in `README.md` (mirrored to 40 translated READMEs by CI), `apps/website`,+ `apps/web-clipper`, the about dialog; `check` resolves every literal against the alias chains.+- **Search docs examples**: `packages/trilium-core/src/services/search/docs_examples.spec.ts`+ requires every query shown in `Navigation/Search.md` and `Quick search.md` to have a test.+- **LLM tools** read the same `doc_notes` files (`apps/server/src/services/llm/tools/doc_notes.ts`).++`doc_notes/cn/` holds nine legacy hand-written system snippets (launch-bar and hidden-note docs), no+User Guide, and is frozen; the client always requests the User Guide in `en`.++## What the site build reads++`.github/workflows/deploy-docs.yml` runs `pnpm docs:build` on pushes to `main`/`stable` and on PRs+touching `docs/**`, `apps/edit-docs/**`, `apps/build-docs/**` or `packages/share-theme/**`, validates+only that `site/index.html` and `site/developer-guide/index.html` exist, and deploys to Cloudflare+Pages. No link or image check runs anywhere in CI — `docs.mjs check` is the only one.++## Where features are documented (a map for `impact`)++Settings panes → `Basic Concepts and Features/UI Elements/Options.md` plus the feature's own page+(Appearance → `Themes.md`, `UI Elements/{New Layout, Ribbon, Zoom, Content width}.md`; Shortcuts →+`Keyboard Shortcuts.md`; Text notes → `Note Types/Text/*`; Code notes → `Note Types/Code.md`; Images →+`Note Types/Text/Images.md`, `Advanced Usage/Text Extraction (OCR).md`; Spellcheck → `Note Types/Text/+Spell Check.md`; Password/TOTP → `Installation & Setup/Server Installation/*`; ETAPI → `Advanced+Usage/ETAPI (REST API).md`; Backup → `Installation & Setup/Backup.md`; Sync → `Installation & Setup/+Synchronization.md`; AI → `AI.md`, `AI/*`). Ribbon, launcher bar, right sidebar, tabs, split view,+floating buttons, note tree, global menu → `Basic Concepts and Features/UI Elements/*`. Note types →+`Note Types/<type>.md`; collection views → `Collections/<view>.md`; search → `Basic Concepts and+Features/Navigation/{Search, Quick search, Jump to & command palette}.md`; attributes → `Advanced+Usage/Attributes/*`; import/export → `Basic Concepts and Features/Import & Export/*`; scripting →+`Scripting/*`; themes/icon packs → `Theme development/*`; desktop/mobile → `Installation & Setup/+{Desktop Installation, Mobile Frontend}.md`. `Feature Highlights.md` is a per-version list of major+features the maintainer curates at release time.diff --git a/.claude/skills/writing-documentation/references/style-guide.md b/.claude/skills/writing-documentation/references/style-guide.mdnew file mode 100644index 0000000000..e216504472--- /dev/null+++ b/.claude/skills/writing-documentation/references/style-guide.md@@ -0,0 +1,188 @@+# User Guide house style++Extracted from the 276 pages under `docs/User Guide/User Guide/` (counts are from that tree). The+Markdown is an export of CKEditor notes, so the HTML fragments in it are part of the format, not+leftovers: a new page has to look exactly like what the exporter produces, and `docs.mjs sync`+normalizes what it can.++## Register and voice++- **Person.** Impersonal or passive by default ("The note can be toggled…", "It is possible to…");+ "you" where it reads naturally (759 uses). "The user" only in technical third-person descriptions.+ "We" (110) is the project team: "We do plan to increase the coverage…". **Never "I"** — the three+ pages that use it (FAQ, Patterns of personal knowledge, Scripting) are the original author's voice.+- **Mood and tense.** Present tense throughout. Steps are imperative inside bullets, usually opened by+ a purpose clause: "To create a new node at the same level as the current one, press+ <kbd>Enter</kbd>…", "To delete a column, right click on its title and select _Delete column_."+ "To do so," (54) bridges a description into its steps.+- **Formality.** Plain and semi-formal; contractions are fine ("it's possible" 41 vs "it is possible"+ 43). Sentences of 15–30 words, paragraphs of 1–3 sentences, one idea each.+- **Recurring phrasings** (use them; they are the voice): "simply" (132), "e.g." with dots, usually in+ parentheses (199), "for example" (105), "Note that" (96), "It's (also) possible to" (123),+ "Generally" (57), "consider …" (49), "feel free to [report the issue](…)" (16), "Do note that" (12).+- **Recommendations are soft.** "Prefer this over other virtual PDF printers…", "it's generally a good+ idea to…", "Generally _Single_ is the desirable option." Strong statements go into an admonition.+- **Spelling is US**: color 211 / colour 1, center 53 / centre 0, organize, customize, behavior,+ synchronize. "synchronisation" (Quick Start) and "localisation" (FAQ) are outliers, not precedent.+- **Naming.** The product is "Trilium" (1283). "TriliumNext" (65) survives only in historical+ contexts ("Since TriliumNext 0.94.1", the theme name, GitHub paths). "Trilium Notes" (29) is the+ formal name in disclaimers and the privacy policy. "TriliumNext Notes" is never used. The original+ maintainer is "Zadam (original Trilium maintainer)".+- **Version facts** carry a `v`-prefixed full semver, never "since version": "Since v0.104.0, …" (40),+ "Starting with v0.104.0, …" (24), "Versions prior to v0.103.0 …" (8), "introduced in v0.103.0" (5).+ Layout-dependent facts say "in the <New Layout pill> only" / "the old layout".++## Page shape++- Line 1 is `# <Title>`, identical to the file name (270/276; the exceptions are titles with a colon,+ which the file name cannot carry). The body starts on **line 2 with no blank line**; there is no+ other H1; the file ends **without a trailing newline**. `sync` enforces all of this.+- Headings are `##` (840) and `###` (429), rarely `####` (24), in **sentence case** ("## Adjusting the+ text size instead", "## Creating a new collection"). Title Case and trailing colons ("### Grab the+ latest docker-compose.yml:") are legacy.+- **First sentence**: definitional in about 100 of 230 content pages — "Collections are a unique type+ of note that don't have content, but instead display their child notes…", "A label is an+ [attribute](../Attributes.md) of a note which has a name and optionally a value." Other openers:+ "The <X> …", "Trilium supports/allows …". 54 pages put a hero `<figure>` on line 2 before it.+ Going straight from the H1 to an `##` with no intro is tolerated, and weaker.+- **Section vocabulary** (H2/H3 counts): `Interaction` (~40, the signature section; keep it at H2),+ `Creating …` (36), `Configuration` (17), `Limitations` / `Known limitations` (20), `Features` /+ `Supported features` (14), `Keyboard shortcuts` (8), `Mobile` / `Mobile support` (7), `See also`+ (6), `Import process` (6), `How it works` (4), `Under the hood` (4), `Reporting issues` (5),+ `Terminology` (2). Not used: "Related", "Known issues", "Technical details".+- Closing a section: "See <pill>." / "See <pill> for more information."++## Cross references++| Form | Count | When |+| --- | --- | --- |+| `<a class="reference-link" href="…">Title</a>` | 1449 | the target note's title used as a noun in the sentence; renders as a note pill |+| `[phrase](../Rel/Path.md)` | 488 | an inline phrase in the running sentence: "see [clones](…)", "the `fullContentWidth` [label](…)" |+| `[text](https://…)` | 208 | external; descriptive text, never the bare URL as text |+| `#heading` anchors | 3 | practically unused |++- Pill text equals the target title in 1393 of 1414 cases; the text is HTML-escaped+ (`Import & Export`). A pill is preceded by a **non-breaking space** (U+00A0; 1183 vs 181 with a+ plain space) — that is what CKEditor writes before an inline widget.+- Paths are relative to the current file (`../` as needed). Spaces `%20`, `&` `%26`, `,` `%2C`.+ Parentheses stay literal inside `href="…"` but are escaped in Markdown links:+ `Server%20Installation/HTTPS%20\(TLS\).md`.+- Links into hidden system notes stay as `#root/_hidden/_options/_optionsTextNotes` (17); the+ `_hidden/` segment is mandatory.+- Issues are reported via the internal page: "feel free to [report the+ issue](../../Troubleshooting/Reporting%20issues.md)", not a raw GitHub URL.+- The Script API is linked through `Scripting/Script%20API.md`; nothing links into the Developer Guide.++## Emphasis and UI names++- **UI labels, menu items, options, tabs, dialog sections in `_italics_`** (741): "select _Insert+ child note_ and look for _Grid View_", "the _Save_ button must be pressed", "the _Owned Attributes_+ section". Curly or straight quotes around UI names are the older style; don't add more.+- **Bold** (404) for defined terms in lists ("A **node** is a single idea…", "**Launcher**: a button…")+ and inline emphasis ("**will not** be visible"). `**Note:**` / `**Rule:**` inline labels are legacy —+ use an admonition.+- **Menu paths** use `→` (U+2192, 180): `<Options pill> → _Appearance_ → _Fonts_`, every segment+ italic; `_Export note_ → _This note and all of its descendants_ → _HTML in ZIP archive_`. Bold paths+ (`**Settings → Backup**`) and ` -> ` are legacy. Settings are named by their UI path and label,+ never by the option key (`options_interface.ts` names appear nowhere in the docs).+- **Keys**: one `<kbd>` per key, joined by `+` without spaces (417 tags in 59 pages):+ `<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>R</kbd>`; macOS `<kbd>⌘</kbd>`; arrows `<kbd>→</kbd>`;+ `<kbd>Right click</kbd>` exists. Plain "Ctrl+X" (37 places) is the inconsistency `check` warns+ about. Shortcut *action names* are italic (`_Create New Split_`) or backticked command ids+ (`toggleZenMode`).+- **Labels and relations** always in backticks with their prefix (277 `#`, 49 `~`, zero bare):+ `` `#searchHome` ``, `` `#board:groupBy` ``, `` `~status` ``, `` `#iconClass="bx bx-calendar"` ``.+ A label name followed by the word "label" is also backticked: "the `fullContentWidth` [label](…)".+- **Inline code** (2142) for env vars, file names (`docker-compose.yml`), values (`1px`), API calls+ (`api.log`), URLs and search syntax.++## Admonitions++GitHub alerts in the Markdown (`> [!NOTE]` on its own line, then `> ` body lines, `> ` as the blank+separator inside); CKEditor stores them as `<aside class="admonition note">`.++| Type | Count | Content |+| --- | --- | --- |+| NOTE | 98 | technical aside, background, history ("Versions prior to v0.103.0 had…"), relocation notices |+| IMPORTANT | 30 | beta/experimental status, third-party disclaimer ("These solutions are third-party and thus not endorsed…"), hard requirement, scope limitation |+| TIP | 28 | an optional better way ("If you prefer keyboard shortcuts, press…", "consider using [backups]…") |+| WARNING | 17 | data or security risk, version-gated behavior change ("Since v0.104.0, LAN access needs to be enabled…") |+| CAUTION | 0 | not used |++An admonition can open with a bold title line: `> **Icon packs are third-party content**`, `> `, body.++## Images and figures++- Files sit beside the `.md`, named `<Page Title>_<attachment title>` — `Mind Map_image.png`, then+ `1_Mind Map_image.png`, `2_…` for more (the exporter numbers duplicates). 210 png, 13 gif (demos),+ 5 webp, 2 svg. `docs.mjs image` registers a file with that name and its meta entry.+- **Modern form** (122): a single-line CKEditor figure with real pixel size and aspect ratio:+ `<figure class="image image-style-align-center"><img style="aspect-ratio:892/675;" src="Mind Map_image.png" width="892" height="675"></figure>`.+ The `src` is **not** URL-encoded (`&` as `&`, spaces literal). Variants: `image` (49),+ `image image-style-align-right` (25), `image image-style-align-right image_resized` with+ `style="width:48.4%;"` on the **figure** (19, floats beside a list), `image image-style-align-center`+ (10), `image image_resized` (8). Resized widths run 28–100 %, mostly about 50 %.+- **Older form** (87): `` — URL-encoded, empty alt. Don't add new ones.+- Captions are rare (9 `<figcaption>`): "Screenshot of the Print preview functionality introduced in+ v0.103.0." Alt text is not set (one `alt="grafik"` is a paste artifact).+- Screenshots: light theme, the current layout, cropped tightly to the widget, no arrows or boxes+ ("marked by red circle" in Scripting.md is legacy). A hero screenshot goes right after the H1.+- Two-column layout tables pair a screenshot with a sentence: an empty header row `| | |`+ (Collections.md, Creating a custom theme.md).++## Icons++A button, menu or toolbar control is named by its icon, never by a cropped screenshot (there are no+`<img>` under 100 px any more):++```html+<span class="tn-icon bx bx-history"></span> <!-- app UI: Boxicons v2 -->+<span class="tn-icon cke cke-three-vertical-dots"></span> <!-- text editor toolbar: Text Editor Icons -->+```++- 106 icons on 36 pages (55 `bx`, 51 `cke`), almost all under Note Types and Basic Concepts. Class is+ always `tn-icon <pack> <pack>-<name>`; solid boxicons are `bx bxs-…`, modifiers append+ (`bx-flip-horizontal`). In the HTML the span follows ` ` (64 vs 35 plain spaces).+- Placement: right before "button" / "icon" / "menu" ("press the <bx-dock-right> button to the right+ of a note's title"); in parentheses after the italic name ("select the _Table properties_ option+ (<cke-table-properties>)"); as the head of a bullet in a list of buttons ("* <bx-history> displays+ the [Note Revisions]…"); nested groups ("press the <cke-trilium-kbd> button in <bx-text> group from+ the <Formatting toolbar pill>").+- `cke` (235 glyphs) is the editor's own icon set built into a font (`packages/trilium-core/src/+ services/icon_pack_text_editor.json`); upstream `IconTableMergeCell` → `cke-table-merge-cell`,+ Trilium's own SVGs → `cke-trilium-<file>` (`cke-trilium-kbd`, `cke-trilium-ai`). `bx` is+ `icon_pack_boxicons-v2.json` (1635). `docs.mjs icons <terms>` searches both; `icons --check`+ validates every class in the docs. `iconClass` in the meta uses `bx` only.++## Lists, tables, code++- Bullets `* ` (asterisk + three spaces, 2584; `- ` is legacy), ordered `1. ` (two spaces, 567),+ nesting by four spaces (` * `, ` 1. `). Bullets are full sentences with a period; short+ feature lists ("Filtering", "Sorting") have none. A lead-in with a colon introduces a list ("Each+ tile contains:", "Of note:"). Numbered lists are for sequences; alternatives are bullets.+- Tables: 64 GFM tables `| Note Type | Description |` / `| --- | --- |`, first cell a pill or a+ backticked label; `<br>` for line breaks inside a cell. Raw `<table class="ck-table-resized">` with+ `<colgroup>` is what CKEditor writes for merged cells or sized columns — only when needed.+- Code fences carry a language tag when one applies (javascript, jsx, css, yaml, html, sh, powershell,+ nginx, diff); attribute snippets and error strings are bare fences. Tabs indent CSS/JS samples.++## HTML that must be reproduced exactly (outside code fences)++`<a class="reference-link">` 1448 · `<kbd>` 417 · `<span class="tn-icon …">` 105 · `<figure+class="image …"><img style="aspect-ratio:W/H;" …>` 122 · `<figcaption>` 9 · CKEditor tables+(`<table>`, `<colgroup>`, `<col style="width:…%">`, `<td>`, `<th>`) · `<code>` inside HTML tables+(backticks don't work there) · `<br>` in cells · `<details><summary>` (1) · footnotes as+`[<sup>[1]</sup>](#fn…)` with `1. [**<sup>^</sup>**](#fnref…)` (CKEditor footnote plugin) · one+`<span style="color:hsl(0,0%,60%);">` wrapping a grey icon. Not used: `<mark>`, `<u>`, `<s>`,+`<sub>`, mermaid fences, math in prose.++The non-breaking space (U+00A0, 2202 occurrences) is a character in the Markdown, written before+pills, arrows and icon spans; a literal ` ` (45) appears only inside code samples.++## Legacy patterns not to copy++First-person voice; `**Note:**` inline; bold or plain menu paths; curly-quoted UI names; Title Case+headings and headings ending in a colon; `[https://…](https://…)` self-labelled URLs; "Available since+Trilium v0.52."; plain-text shortcuts; ` + ` with spaces between keys; `alt="grafik"`; a plain+paragraph used as a caption; `- ` bullets; untagged code fences where a language applies; pill text+that differs from the target title (21 cases); an `##` followed immediately by an `###` with no intro.diff --git a/CLAUDE.md b/CLAUDE.mdindex 935991b9d6..3a36c1a5ad 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -42,7 +42,7 @@ pnpm dev:format-check | dev:format-fix # stylistic formatting- **`origin` is `TriliumNext/Trilium`** — the working directory is named `Notes` and ~19 contributor forks are configured as remotes, so neither the path nor the remote list names the target. `gh` resolves it from `remote.origin.gh-resolved`, already set, so `--repo` is redundant; `upstream` is the archived `zadam/trilium` and is never a base.- **Write the body from the commit bodies, grouped by what the change does** — `git log --format='=== %s%n%b' main..HEAD`. A feature branch here carries a long, self-contained rationale per commit (the measurements, the rejected alternative, the reason a value is what it is), and a PR description that restates the subject lines throws all of it away. Group the commits under headings by area, not chronologically: a reviewer reads the reworked subsystem, not the order it was built in.- **Pass the body via `--body-file`, not `--body`.** Markdown of this length in an argument hits shell quoting and heredoc-in-`fish` problems; write it to the scratchpad first.-- **Cosmetic `edit-docs` churn is ignored, not mentioned.** `pnpm edit-docs:edit-docs` reformats whole `apps/server/src/assets/doc_notes/**/*.html` files it merely opened (`<li><p>x</p></li>` ↔ `<li>x</li>`, ` ` shifted across a tag, attributes rewrapped), so a docs commit routinely touches pages the branch has nothing to do with. That is expected and needs neither a rebase nor a note in the description. Read the diff first, though: reflow is safe, but a changed `href`, a dropped `<img src>` or a paragraph that lost its text is a real defect and must be fixed before the PR goes up.+- **Cosmetic `edit-docs` churn is ignored, not mentioned.** `pnpm edit-docs:edit-docs` (and `edit-docs:sync-docs`) reformats whole `apps/server/src/assets/doc_notes/**/*.html` files it merely opened (`<li><p>x</p></li>` ↔ `<li>x</li>`, ` ` shifted across a tag, attributes rewrapped), so a docs commit routinely touches pages the branch has nothing to do with. That is expected and needs neither a rebase nor a note in the description. Read the diff first, though: reflow is safe, but a changed `href`, a dropped `<img src>` or a paragraph that lost its text is a real defect and must be fixed before the PR goes up.## Monorepo Structure@@ -219,16 +219,19 @@ Use `note.getOwnedAttribute()` for direct, `note.getAttribute()` for inherited.## Documentation- Script API reference — Generated by `apps/build-docs` (TypeDoc) into the gitignored `site/script-api/{backend,frontend,electron}` and published to [docs.triliumnotes.org](https://docs.triliumnotes.org/). Not committed; never hand-edit — it's regenerated from the script API type definitions-- `docs/User Guide/` — Edit via `pnpm edit-docs:edit-docs`, not manually-- `docs/Developer Guide/` and `docs/Release Notes/` — Safe for direct Markdown editing--### Always check the docs against a user-visible change--Any change to what the user sees or does — a button moved or removed, a keyboard shortcut, a label, an-option, a default, where a feature is configured — **can leave the User Guide describing an affordance-that no longer exists**. Before reporting the work done, grep `docs/User Guide/` for the feature and for-the control you touched (its name, its icon, the panel it lived in) and read every hit. Report what needs-updating as part of the change, without waiting to be asked; the docs are a deliverable, not a follow-up.+- `docs/User Guide/` — Markdown pages plus `!!!meta.json`; the in-app help under `apps/server/src/assets/doc_notes/` and `apps/standalone/src/assets/help_meta.json` are **generated from it and never hand-edited**. Edit the Markdown by hand or in the editor (`pnpm edit-docs:edit-docs`), then run `pnpm edit-docs:sync-docs` so the HTML and both help metas follow. A page's shape (a new page, an image, a rename, a move) is meta work — the **`writing-documentation` skill**'s `docs.mjs` does it (`new`, `image`, `rename`, `move`, `delete`) and audits the trees (`check`); load the skill before touching `docs/`+- `docs/Developer Guide/` and `docs/Release Notes/` — Safe for direct Markdown editing (also normalized by `sync-docs`)++### A user-facing change is documented in the same change++Any change to what the user sees or does — a feature, a button moved or removed, a keyboard shortcut, a+label, an option, a default, where a feature is configured — **is not finished until the User Guide+describes the new state, in the same commit or PR as the code.** The docs are a deliverable, not a+follow-up. Before reporting the work done: `node .claude/skills/writing-documentation/docs.mjs impact+--diff` (plus `impact "<feature name>"` for names the diff cannot know) lists the pages that mention the+changed UI strings and the help pages wired from the touched components; read every hit and edit what+describes an affordance that changed; a feature no page covers gets a page (`docs.mjs new`). Then+`docs.mjs sync` and `docs.mjs check`. Release notes are the maintainer's at release time — not on a branch.Two traps this catches:diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b3f2619d73..b2d6e6ee85 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -94,9 +94,11 @@ users.- Add or update tests for the behavior you change. See the[Testing guide](./docs/Developer%20Guide/Developer%20Guide/Testing.md).- Include a screenshot or short recording when the user interface changes.-- When behavior changes, update the User Guide with- `pnpm edit-docs:edit-docs`; do not edit those Markdown files directly.- The Developer Guide can be edited directly.+- When behavior changes, update the User Guide (`docs/User Guide`) in the+ same pull request — in the editor (`pnpm edit-docs:edit-docs`) or by editing+ the Markdown and running `pnpm edit-docs:sync-docs`, which regenerates the+ in-app help from it. Never edit the generated files under+ `apps/server/src/assets/doc_notes`. The Developer Guide can be edited directly.- Every pull request is manually tested and reviewed by a maintainer.Review can take time, especially for large changes. Update the branchwhen it conflicts with `main` or when a maintainer asks.diff --git a/apps/edit-docs/package.json b/apps/edit-docs/package.jsonindex 053135bf52..0051676206 100644--- a/apps/edit-docs/package.json+++ b/apps/edit-docs/package.json@@ -19,6 +19,7 @@"test": "vitest","test-build": "vitest --config vitest.build.config.mts","edit-docs": "cross-env TRILIUM_PORT=37741 TRILIUM_DATA_DIR=data TRILIUM_INTEGRATION_TEST=memory-no-store tsx ../../scripts/electron-start.mts src/edit-docs.ts",+ "sync-docs": "cross-env TRILIUM_DATA_DIR=data TRILIUM_INTEGRATION_TEST=memory-no-store TRILIUM_ENV=dev TRILIUM_RESOURCE_DIR=../server/src tsx src/sync-docs.ts","edit-demo": "cross-env TRILIUM_PORT=37744 TRILIUM_DATA_DIR=data TRILIUM_INTEGRATION_TEST=memory-no-store DOCS_ROOT=../../../docs USER_GUIDE_ROOT=\"../../server/src/assets/doc_notes/en/User Guide\" tsx ../../scripts/electron-start.mts src/edit-demo.ts"}}\ No newline at end of filediff --git a/apps/edit-docs/src/utils.spec.ts b/apps/edit-docs/src/docs_pipeline.spec.tssimilarity index 84%rename from apps/edit-docs/src/utils.spec.tsrename to apps/edit-docs/src/docs_pipeline.spec.tsindex 4e9948c375..c27b78fedb 100644--- a/apps/edit-docs/src/utils.spec.ts+++ b/apps/edit-docs/src/docs_pipeline.spec.ts@@ -1,14 +1,6 @@-import { describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";-import { normalizeLineEndings, rewriteHelpLinks } from "./utils.js";--// utils.ts bootstraps Electron at module load (registers the `trilium-app://` scheme and-// pulls in the desktop window service, whose resource_dir lookup calls process.exit in a-// non-Electron test runner). Stub those side-effectful imports so the pure helpers below-// (rewriteHelpLinks, normalizeLineEndings) can be imported in isolation.-vi.mock("electron", () => ({ default: { app: {}, protocol: { registerSchemesAsPrivileged: () => {} } } }));-vi.mock("@triliumnext/desktop/src/protocol.js", () => ({ registerTriliumAppScheme: () => {}, setupTriliumAppProtocol: () => {} }));-vi.mock("@triliumnext/desktop/src/services/window.js", () => ({ default: {}, setupWindowing: () => {} }));+import { normalizeLineEndings, rewriteHelpLinks } from "./docs_pipeline.js";describe("rewriteHelpLinks", () => {it("prefixes plain help-note links with _help_", () => {diff --git a/apps/edit-docs/src/docs_pipeline.ts b/apps/edit-docs/src/docs_pipeline.tsnew file mode 100644index 0000000000..41179ebaba--- /dev/null+++ b/apps/edit-docs/src/docs_pipeline.ts@@ -0,0 +1,370 @@+/**+ * The import/export half of edit-docs, with no Electron dependency: `edit-docs.ts` runs it+ * behind a window, `sync-docs.ts` runs it headless.+ */+import { BackupService, initializeCore, type AdvancedExportOptions, type MessagingProvider, type NoteMeta, type NoteMetaFile } from "@triliumnext/core";+import AsyncLocalStorageExecutionContext from "@triliumnext/server/src/cls_provider.js";+import NodejsCryptoProvider from "@triliumnext/server/src/crypto_provider.js";+import ServerPlatformProvider from "@triliumnext/server/src/platform_provider.js";+import { serverImageProvider } from "@triliumnext/server/src/services/image_provider.js";+import BetterSqlite3Provider from "@triliumnext/server/src/sql_provider.js";+import NodejsZipProvider from "@triliumnext/server/src/zip_provider.js";+import { type Archiver, ZipArchive } from "archiver";+import { createWriteStream, readFileSync, type WriteStream } from "fs";+import fs from "fs/promises";+import { load } from "js-yaml";+import path from "path";++import { deferred } from "../../../packages/commons/src/index.js";+import { parseNoteMetaFile, serverTextNoteHandler, standaloneTextNoteHandler, stripAppVersion } from "./help_meta_generator.js";++export interface NoteMapping {+ rootNoteId: string;+ path: string;+ format: "markdown" | "html";+ ignoredFiles?: string[];+ exportOnly?: boolean;+}++export interface Config {+ baseUrl: string;+ noteMappings: NoteMapping[];+}++/**+ * Reads `edit-docs-config.yaml`: the given path, else the current directory, else the repository+ * root. Mapping paths resolve against the config file's directory.+ */+export async function loadConfig(configPath?: string): Promise<Config> {+ let resolvedPath = configPath+ ? path.resolve(configPath)+ : path.join(process.cwd(), "edit-docs-config.yaml");++ const exists = await fs.access(resolvedPath).then(() => true).catch(() => false);+ if (!exists && !configPath) {+ resolvedPath = path.join(__dirname, "../../../edit-docs-config.yaml");+ }++ const config = load(await fs.readFile(resolvedPath, "utf-8")) as Config;+ const configDir = path.dirname(resolvedPath);+ return {+ baseUrl: config.baseUrl,+ noteMappings: config.noteMappings.map((mapping) => ({+ ...mapping,+ path: path.resolve(configDir, mapping.path)+ }))+ };+}++// Stub backup service (not used in edit-docs, but required by initializeCore)+class StubBackupService extends BackupService {+ constructor() {+ super({ getOption: () => "", getOptionOrNull: () => null, getOptionBool: () => false, setOption: () => {} });+ }+ scheduleBackups(): void {}+ async backupNow(_name: string): Promise<string> {+ throw new Error("Backup not supported in edit-docs");+ }+ async getExistingBackups() {+ return [];+ }+ async getBackupContent(_filePath: string): Promise<Uint8Array | null> {+ return null;+ }+}++/**+ * Initializes core against an in-memory database. `messaging` is the IPC provider when a window+ * is attached; headless runs pass none.+ */+export async function initializeDocsCore(messaging?: MessagingProvider) {+ const dbProvider = new BetterSqlite3Provider();+ dbProvider.loadFromMemory();++ const { serverZipExportProviderFactory } = await import("@triliumnext/server/src/services/export/zip/factory.js");++ await initializeCore({+ dbConfig: {+ provider: dbProvider,+ isReadOnly: false,+ async onTransactionCommit() {+ if (!messaging) {+ return;+ }+ const { ws } = await import("@triliumnext/core");+ ws.sendTransactionEntityChangesToAllClients();+ },+ onTransactionRollback: () => {}+ },+ crypto: new NodejsCryptoProvider(),+ zip: new NodejsZipProvider(),+ zipExportProviderFactory: serverZipExportProviderFactory,+ executionContext: new AsyncLocalStorageExecutionContext(),+ platform: new ServerPlatformProvider(),+ schema: readFileSync(require.resolve("@triliumnext/core/src/assets/schema.sql"), "utf-8"),+ translations: (await import("@triliumnext/server/src/services/i18n.js")).initializeTranslationsWithParams,+ messaging,+ getDemoArchive: async () => null,+ backup: new StubBackupService(),+ image: serverImageProvider+ });+}++export async function importData(path: string) {+ const buffer = await createImportZip(path);+ const { zipImportService, TaskContext, becca } = (await import("@triliumnext/core"));+ const context = new TaskContext("no-progress-reporting", "importNotes", null);++ const rootNote = becca.getRoot();+ if (!rootNote) {+ throw new Error("Missing root note for import.");+ }+ await zipImportService.importZip(context, buffer, rootNote, {+ preserveIds: true+ });+}++/** Imports every mapping that is not `exportOnly`, in config order. */+export async function importMappings(mappings: NoteMapping[]) {+ for (const mapping of mappings) {+ if (!mapping.exportOnly) {+ await importData(mapping.path);+ }+ }+}++/** Exports every mapping, in config order, replacing each target directory. */+export async function exportMappings(mappings: NoteMapping[], baseUrl: string) {+ for (const mapping of mappings) {+ const ignoredFiles = mapping.ignoredFiles ? new Set(mapping.ignoredFiles) : undefined;+ await exportData(mapping.rootNoteId, mapping.format, mapping.path, baseUrl, ignoredFiles);+ }+}++export async function exportData(noteId: string, format: "markdown" | "html", outputPath: string, baseUrl: string, ignoredFiles?: Set<string>) {+ const zipFilePath = "output.zip";++ try {+ await fs.rm(outputPath, { recursive: true, force: true });+ await fs.mkdir(outputPath, { recursive: true });++ // First export as zip.+ const { zipExportService } = (await import("@triliumnext/core"));++ const exportOpts: AdvancedExportOptions = {};+ if (format === "html") {+ exportOpts.skipHtmlTemplate = true;+ exportOpts.customRewriteLinks = (originalRewriteLinks, getNoteTargetUrl) => {+ return (content: string, noteMeta: NoteMeta) => {+ content = content.replace(/src="[^"]*api\/images\/([a-zA-Z0-9_]+)\/[^"]*"/g, (match, targetNoteId) => {+ const url = getNoteTargetUrl(targetNoteId, noteMeta);++ return url ? `src="${url}"` : match;+ });++ content = content.replace(/src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image\/[^"]*"/g, (match, targetAttachmentId) => {+ const url = findAttachment(targetAttachmentId);++ return url ? `src="${url}"` : match;+ });++ content = content.replace(/href="[^"]*#root[^"]*attachmentId=([a-zA-Z0-9_]+)\/?"/g, (match, targetAttachmentId) => {+ const url = findAttachment(targetAttachmentId);++ return url ? `href="${url}"` : match;+ });++ content = rewriteHelpLinks(content);++ return content;++ function findAttachment(targetAttachmentId: string) {+ let url;++ const attachmentMeta = (noteMeta.attachments || []).find((attMeta) => attMeta.attachmentId === targetAttachmentId);+ if (attachmentMeta) {+ // easy job here, because attachment will be in the same directory as the note's data file.+ url = attachmentMeta.dataFileName;+ } else {+ console.info(`Could not find attachment meta object for attachmentId '${targetAttachmentId}'`);+ }+ return url;+ }+ };+ };+ }++ await zipExportService.exportToZipFile(noteId, format, zipFilePath, exportOpts);+ await extractZip(zipFilePath, outputPath, ignoredFiles);+ } finally {+ await fs.rm(zipFilePath, { force: true });+ }++ await cleanUpMeta(outputPath, format === "html", baseUrl);+}++async function cleanUpMeta(outputPath: string, minify: boolean, baseUrl: string) {+ const metaPath = path.join(outputPath, "!!!meta.json");+ const meta = JSON.parse(await fs.readFile(metaPath, "utf-8")) as NoteMetaFile;+ for (const file of meta.files) {+ file.notePosition = 1;+ traverse(file);+ }++ function traverse(el: NoteMeta) {+ for (const child of el.children || []) {+ traverse(child);+ }++ el.isExpanded = false;++ // Rewrite web view URLs that point to root.+ if (el.type === "webView" && minify) {+ const srcAttr = el.attributes.find(attr => attr.name === "webViewSrc");+ if (srcAttr.value.startsWith("/")) {+ srcAttr.value = baseUrl + srcAttr.value;+ }+ }+ }++ if (minify) {+ const subtree = parseNoteMetaFile(meta, serverTextNoteHandler, baseUrl);+ await fs.writeFile(metaPath, JSON.stringify(subtree));++ // Generate standalone meta: webView-based, pointing to online docs.+ const standaloneSubtree = parseNoteMetaFile(meta, standaloneTextNoteHandler, baseUrl);+ const standaloneMetaPath = path.resolve(__dirname, "../../standalone/src/assets/help_meta.json");+ await fs.writeFile(standaloneMetaPath, JSON.stringify(standaloneSubtree));+ } else {+ await fs.writeFile(metaPath, JSON.stringify(stripAppVersion(meta), null, 4));+ }+}++async function createImportZip(path: string) {+ const inputFile = "input.zip";+ const archive = new ZipArchive({+ zlib: { level: 0 }+ });++ archive.directory(path, "/");++ const outputStream = createWriteStream(inputFile);+ archive.pipe(outputStream);+ await waitForEnd(archive, outputStream);++ try {+ return await fs.readFile(inputFile);+ } finally {+ await fs.rm(inputFile);+ }+}++function waitForEnd(archive: Archiver, stream: WriteStream) {+ return new Promise<void>((res, rej) => {+ stream.on("finish", res);+ stream.on("error", rej);+ archive.on("error", rej);+ archive.finalize().catch(rej);+ });+}++/**+ * Rewrites internal `#root/...` note links in exported help HTML so that they resolve+ * against the help subtree once imported into a production Trilium instance.+ *+ * In the edit-docs instance the help notes carry plain, randomly generated IDs, but in+ * production they live under the `_help` subtree with a `_help_` prefix. This adds that+ * prefix to the link's target note ID, and reduces the link to that ID alone: the editor+ * writes a full note path when a link is created, whose intermediate IDs belong to the+ * docs instance and match nothing in the tree a reader has, leaving the client to fall+ * back to the note's own path. The importer writes the same single-ID form, so a note+ * exported straight after an edit now matches one that has been through an import.+ */+export function rewriteHelpLinks(content: string): string {+ return content.replace(/href="([^"]*#root)(?:[a-zA-Z0-9_/]*\/)?([a-zA-Z0-9_]+)([^"]*)"/g,+ (match, prefix: string, targetNoteId: string, suffix: string) => {+ if (targetNoteId.startsWith("_help_")) {+ return `href="${prefix}/${targetNoteId}${suffix}"`;+ }++ // Canonical hidden-subtree notes (e.g. _options, _optionsTextNotes) keep their IDs in+ // production, so they already start with an underscore, and their path is a real one.+ // Only help notes (random alphanumeric IDs) get the `_help_` prefix; prefixing the+ // others would produce broken `_help__optionsTextNotes`-style links (see issue #9646).+ if (targetNoteId.startsWith("_")) {+ return match;+ }+ return `href="${prefix}/_help_${targetNoteId}${suffix}"`;+ });+}++export async function createZipFromDirectory(dirPath: string, zipPath: string) {+ const archive = new ZipArchive({ zlib: { level: 5 } });+ const outputStream = createWriteStream(zipPath);+ archive.directory(dirPath, false);+ archive.pipe(outputStream);+ await waitForEnd(archive, outputStream);+}++export async function extractZip(zipFilePath: string, outputPath: string, ignoredFiles?: Set<string>) {+ const promise = deferred<void>();+ setTimeout(async () => {+ const { getZipProvider } = (await import("@triliumnext/core"));+ const zipProvider = getZipProvider();+ const buffer = await fs.readFile(zipFilePath);+ await zipProvider.readZipFile(buffer, async (entry, readContent) => {+ // We ignore directories since they can appear out of order anyway.+ if (!entry.fileName.endsWith("/") && !ignoredFiles?.has(entry.fileName)) {+ const destPath = path.join(outputPath, entry.fileName);+ const fileContent = await readContent();++ await fs.mkdir(path.dirname(destPath), { recursive: true });+ await fs.writeFile(destPath, normalizeLineEndings(fileContent));+ }+ });+ promise.resolve();+ }, 1000);+ await promise;+}++/**+ * Rewrites CRLF line endings to LF, so that `extractZip` writes the same bytes on Windows as it+ * does elsewhere. The exported trees (`docs/`, the help HTML, the demo) are stored with LF, and+ * Git only hides the difference once a file is staged.+ *+ * Binary entries such as images keep their bytes. They are detected the way Git detects them: a+ * NUL byte within the first {@link BINARY_DETECTION_LENGTH} bytes marks the content as binary.+ */+export function normalizeLineEndings(content: Uint8Array): Uint8Array {+ if (isBinary(content)) {+ return content;+ }++ const normalized = new Uint8Array(content.length);+ let length = 0;+ for (const [index, byte] of content.entries()) {+ if (byte === CARRIAGE_RETURN && content[index + 1] === LINE_FEED) {+ continue;+ }++ normalized[length++] = byte;+ }++ return length === content.length ? content : normalized.subarray(0, length);+}++const NUL = 0x00;+const LINE_FEED = 0x0a;+const CARRIAGE_RETURN = 0x0d;+const BINARY_DETECTION_LENGTH = 8000;++function isBinary(content: Uint8Array) {+ const end = Math.min(content.length, BINARY_DETECTION_LENGTH);+ for (let index = 0; index < end; index++) {+ if (content[index] === NUL) {+ return true;+ }+ }++ return false;+}diff --git a/apps/edit-docs/src/edit-demo.ts b/apps/edit-docs/src/edit-demo.tsindex 030be01421..68bf4ebe0d 100644--- a/apps/edit-docs/src/edit-demo.ts+++ b/apps/edit-docs/src/edit-demo.ts@@ -1,4 +1,5 @@-import { createZipFromDirectory, extractZip, importData, initializeEditDocsCore, startElectron } from "./utils.js";+import { createZipFromDirectory, extractZip, importData } from "./docs_pipeline.js";+import { initializeEditDocsCore, startElectron } from "./utils.js";import debounce from "@triliumnext/client/src/services/debounce.js";import type { NoteMeta, NoteMetaFile } from "@triliumnext/core";import { cls } from "@triliumnext/core";diff --git a/apps/edit-docs/src/edit-docs.ts b/apps/edit-docs/src/edit-docs.tsindex 7498d02b89..65d7984ce3 100644--- a/apps/edit-docs/src/edit-docs.ts+++ b/apps/edit-docs/src/edit-docs.ts@@ -1,27 +1,9 @@import debounce from "@triliumnext/client/src/services/debounce.js";-import type { AdvancedExportOptions, ExportFormat, NoteMeta, NoteMetaFile } from "@triliumnext/core";import { cls } from "@triliumnext/core";-import { parseNoteMetaFile, serverTextNoteHandler, standaloneTextNoteHandler, stripAppVersion } from "./help_meta_generator.js";-import fs from "fs/promises";-import { load } from "js-yaml";-import path from "path";-import packageJson from "../package.json" with { type: "json" };-import { extractZip, importData, initializeEditDocsCore, rewriteHelpLinks, startElectron } from "./utils.js";--interface NoteMapping {- rootNoteId: string;- path: string;- format: "markdown" | "html";- ignoredFiles?: string[];- exportOnly?: boolean;-}--interface Config {- baseUrl: string;- noteMappings: NoteMapping[];-}+import { type Config, exportMappings, importMappings, loadConfig } from "./docs_pipeline.js";+import { initializeEditDocsCore, startElectron } from "./utils.js";// Parse command-line argumentsfunction parseArgs() {@@ -81,36 +63,10 @@ if (showHelp) {process.exit(0);}-// Configuration variables to be initialized-let BASE_URL: string;-let NOTE_MAPPINGS: NoteMapping[];--// Load configuration from edit-docs-config.yaml-async function loadConfig() {- let CONFIG_PATH = configPath- ? path.resolve(configPath)- : path.join(process.cwd(), "edit-docs-config.yaml");-- const exists = await fs.access(CONFIG_PATH).then(() => true).catch(() => false);- if (!exists && !configPath) {- // Fallback to project root if running from within a subproject- CONFIG_PATH = path.join(__dirname, "../../../edit-docs-config.yaml");- }-- const configContent = await fs.readFile(CONFIG_PATH, "utf-8");- const config = load(configContent) as Config;-- BASE_URL = config.baseUrl;- // Resolve all paths relative to the config file's directory (for flexibility with external configs)- const CONFIG_DIR = path.dirname(CONFIG_PATH);- NOTE_MAPPINGS = config.noteMappings.map((mapping) => ({- ...mapping,- path: path.resolve(CONFIG_DIR, mapping.path)- }));-}+let config: Config;async function main() {- await loadConfig();+ config = await loadConfig(configPath);const initializedPromise = startElectron(() => {// Wait for the import to be finished and the application to be loaded before we listen to changes.setTimeout(() => {@@ -127,11 +83,7 @@ async function main() {await sql_init.createInitialDatabase(true);await beccaLoader.beccaLoaded;- for (const mapping of NOTE_MAPPINGS) {- if (!mapping.exportOnly) {- await importData(mapping.path);- }- }+ await importMappings(config.noteMappings);setOptions();initializedPromise.resolve();});@@ -150,117 +102,12 @@ async function setOptions() {optionsService.setOption("openNoteContexts", JSON.stringify([{ notePath: startNoteId, active: true }]));}-async function exportData(noteId: string, format: ExportFormat, outputPath: string, ignoredFiles?: Set<string>) {- const zipFilePath = "output.zip";-- try {- await fs.rm(outputPath, { recursive: true, force: true });- await fs.mkdir(outputPath, { recursive: true });-- // First export as zip.- const { zipExportService } = (await import("@triliumnext/core"));-- const exportOpts: AdvancedExportOptions = {};- if (format === "html") {- exportOpts.skipHtmlTemplate = true;- exportOpts.customRewriteLinks = (originalRewriteLinks, getNoteTargetUrl) => {- return (content: string, noteMeta: NoteMeta) => {- content = content.replace(/src="[^"]*api\/images\/([a-zA-Z0-9_]+)\/[^"]*"/g, (match, targetNoteId) => {- const url = getNoteTargetUrl(targetNoteId, noteMeta);-- return url ? `src="${url}"` : match;- });-- content = content.replace(/src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image\/[^"]*"/g, (match, targetAttachmentId) => {- const url = findAttachment(targetAttachmentId);-- return url ? `src="${url}"` : match;- });-- content = content.replace(/href="[^"]*#root[^"]*attachmentId=([a-zA-Z0-9_]+)\/?"/g, (match, targetAttachmentId) => {- const url = findAttachment(targetAttachmentId);-- return url ? `href="${url}"` : match;- });-- content = rewriteHelpLinks(content);-- return content;-- function findAttachment(targetAttachmentId: string) {- let url;-- const attachmentMeta = (noteMeta.attachments || []).find((attMeta) => attMeta.attachmentId === targetAttachmentId);- if (attachmentMeta) {- // easy job here, because attachment will be in the same directory as the note's data file.- url = attachmentMeta.dataFileName;- } else {- console.info(`Could not find attachment meta object for attachmentId '${targetAttachmentId}'`);- }- return url;- }- };- };- }-- await zipExportService.exportToZipFile(noteId, format, zipFilePath, exportOpts);- await extractZip(zipFilePath, outputPath, ignoredFiles);- } finally {- await fs.rm(zipFilePath, { force: true });- }-- const minifyMeta = (format === "html" || format === "share");- await cleanUpMeta(outputPath, minifyMeta);-}--async function cleanUpMeta(outputPath: string, minify: boolean) {- const metaPath = path.join(outputPath, "!!!meta.json");- const meta = JSON.parse(await fs.readFile(metaPath, "utf-8")) as NoteMetaFile;- for (const file of meta.files) {- file.notePosition = 1;- traverse(file);- }-- function traverse(el: NoteMeta) {- for (const child of el.children || []) {- traverse(child);- }-- el.isExpanded = false;-- // Rewrite web view URLs that point to root.- if (el.type === "webView" && minify) {- const srcAttr = el.attributes.find(attr => attr.name === "webViewSrc");- if (srcAttr.value.startsWith("/")) {- srcAttr.value = BASE_URL + srcAttr.value;- }- }- }-- if (minify) {- const subtree = parseNoteMetaFile(meta, serverTextNoteHandler, BASE_URL);- await fs.writeFile(metaPath, JSON.stringify(subtree));-- // Generate standalone meta: webView-based, pointing to online docs.- const standaloneSubtree = parseNoteMetaFile(meta, standaloneTextNoteHandler, BASE_URL);- const standaloneMetaPath = path.resolve(__dirname, "../../standalone/src/assets/help_meta.json");- await fs.writeFile(standaloneMetaPath, JSON.stringify(standaloneSubtree));- } else {- await fs.writeFile(metaPath, JSON.stringify(stripAppVersion(meta), null, 4));- }--}-async function registerHandlers() {const { events } = await import("@triliumnext/core");const { erase: eraseService } = await import("@triliumnext/core");const debouncer = debounce(async () => {eraseService.eraseUnusedAttachmentsNow();-- for (const mapping of NOTE_MAPPINGS) {- const ignoredFiles = mapping.ignoredFiles ? new Set(mapping.ignoredFiles) : undefined;- await exportData(mapping.rootNoteId, mapping.format, mapping.path, ignoredFiles);- }+ await exportMappings(config.noteMappings, config.baseUrl);}, 10_000);events.subscribe(events.ENTITY_CHANGED, async (e) => {if (e.entityName === "options") {diff --git a/apps/edit-docs/src/sync-docs.ts b/apps/edit-docs/src/sync-docs.tsnew file mode 100644index 0000000000..6c9e89365e--- /dev/null+++ b/apps/edit-docs/src/sync-docs.ts@@ -0,0 +1,73 @@+/**+ * Regenerates every export target in `edit-docs-config.yaml` from the Markdown trees, with no+ * window: the same import and export that `edit-docs.ts` runs after an edit, so a page edited+ * by hand gets its normalized Markdown, the help HTML under `doc_notes` and the standalone+ * `help_meta.json` without opening Electron.+ *+ * pnpm edit-docs:sync-docs [-- -c <config>]+ *+ * The import rejects a tree whose `!!!meta.json` and files disagree (a `.md` with no entry, a+ * missing `dataFileName`), and that rejection is the check: an error here means the tree would+ * also crash edit-docs at start-up.+ */+import { cls } from "@triliumnext/core";++import { exportMappings, importMappings, initializeDocsCore, loadConfig } from "./docs_pipeline.js";++function parseArgs() {+ const args = process.argv.slice(2);+ let configPath: string | undefined;++ for (let i = 0; i < args.length; i++) {+ if (args[i] === "--config" || args[i] === "-c") {+ configPath = args[i + 1];+ if (!configPath) {+ console.error("Error: --config/-c requires a path argument");+ process.exit(1);+ }+ i++;+ } else if (args[i] === "--help" || args[i] === "-h") {+ console.log("Usage: sync-docs [-c <edit-docs-config.yaml>]");+ process.exit(0);+ }+ }++ return { configPath };+}++async function main() {+ const { configPath } = parseArgs();+ const config = await loadConfig(configPath);++ await initializeDocsCore();++ const { sql_init, becca_loader: beccaLoader, erase: eraseService } = await import("@triliumnext/core");+ await new Promise<void>((resolve, reject) => {+ cls.init(async () => {+ try {+ cls.ignoreEntityChangeIds();+ await sql_init.createInitialDatabase(true);+ await beccaLoader.beccaLoaded;++ console.log("Importing", config.noteMappings.filter((m) => !m.exportOnly).map((m) => m.path).join(", "));+ await importMappings(config.noteMappings);++ eraseService.eraseUnusedAttachmentsNow();++ console.log("Exporting", config.noteMappings.map((m) => m.path).join(", "));+ await exportMappings(config.noteMappings, config.baseUrl);+ resolve();+ } catch (e) {+ reject(e);+ }+ });+ });+}++main().then(+ () => process.exit(0),+ (e) => {+ console.error("Error syncing documentation:", e);+ process.exit(1);+ }+);diff --git a/apps/edit-docs/src/utils.ts b/apps/edit-docs/src/utils.tsindex 5bb50c5fe6..7556968c6e 100644--- a/apps/edit-docs/src/utils.ts+++ b/apps/edit-docs/src/utils.ts@@ -1,49 +1,17 @@-import { BackupService, initializeCore } from "@triliumnext/core";import IpcMessagingProvider from "@triliumnext/desktop/src/ipc_messaging_provider.js";import { registerTriliumAppScheme, setupTriliumAppProtocol } from "@triliumnext/desktop/src/protocol.js";-import AsyncLocalStorageExecutionContext from "@triliumnext/server/src/cls_provider.js";-import NodejsCryptoProvider from "@triliumnext/server/src/crypto_provider.js";-import ServerPlatformProvider from "@triliumnext/server/src/platform_provider.js";-import { serverImageProvider } from "@triliumnext/server/src/services/image_provider.js";import windowService, { setupWindowing } from "@triliumnext/desktop/src/services/window.js";-import BetterSqlite3Provider from "@triliumnext/server/src/sql_provider.js";-import NodejsZipProvider from "@triliumnext/server/src/zip_provider.js";-import { type Archiver, ZipArchive } from "archiver";import electron from "electron";-import { createWriteStream, readFileSync, type WriteStream } from "fs";-import fs from "fs/promises";-import path from "path";import { deferred, type DeferredPromise } from "../../../packages/commons/src/index.js";+import { initializeDocsCore } from "./docs_pipeline.js";// Register the `trilium-app://` scheme synchronously at module load (before any// `await` in edit-docs.ts / edit-demo.ts) so it lands before `app.ready` fires// — otherwise Chromium blocks the navigation with `(blocked:origin)`.registerTriliumAppScheme();-// Stub backup service (not used in edit-docs, but required by initializeCore)-class StubBackupService extends BackupService {- constructor() {- super({ getOption: () => "", getOptionOrNull: () => null, getOptionBool: () => false, setOption: () => {} });- }- scheduleBackups(): void {}- async backupNow(_name: string): Promise<string> {- throw new Error("Backup not supported in edit-docs");- }- async getExistingBackups() {- return [];- }- async getBackupContent(_filePath: string): Promise<Uint8Array | null> {- return null;- }-}-export async function initializeEditDocsCore() {- const dbProvider = new BetterSqlite3Provider();- dbProvider.loadFromMemory();-- const { serverZipExportProviderFactory } = await import("@triliumnext/server/src/services/export/zip/factory.js");-// edit-docs is Electron-based and reuses the desktop preload, so the// renderer talks to the server over the IPC bridge — never opens a// WebSocket. Use IpcMessagingProvider so the server side actually@@ -52,28 +20,7 @@ export async function initializeEditDocsCore() {const messaging = new IpcMessagingProvider();messaging.init();- await initializeCore({- dbConfig: {- provider: dbProvider,- isReadOnly: false,- async onTransactionCommit() {- const { ws } = await import("@triliumnext/core");- ws.sendTransactionEntityChangesToAllClients();- },- onTransactionRollback: () => {}- },- crypto: new NodejsCryptoProvider(),- zip: new NodejsZipProvider(),- zipExportProviderFactory: serverZipExportProviderFactory,- executionContext: new AsyncLocalStorageExecutionContext(),- platform: new ServerPlatformProvider(),- schema: readFileSync(require.resolve("@triliumnext/core/src/assets/schema.sql"), "utf-8"),- translations: (await import("@triliumnext/server/src/services/i18n.js")).initializeTranslationsWithParams,- messaging,- getDemoArchive: async () => null,- backup: new StubBackupService(),- image: serverImageProvider- });+ await initializeDocsCore(messaging);}/**@@ -126,146 +73,3 @@ export function startElectron(callback: () => void): DeferredPromise<void> {return initializedPromise;}--export async function importData(path: string) {- const buffer = await createImportZip(path);- const { zipImportService, TaskContext, becca } = (await import("@triliumnext/core"));- const context = new TaskContext("no-progress-reporting", "importNotes", null);-- const rootNote = becca.getRoot();- if (!rootNote) {- throw new Error("Missing root note for import.");- }- await zipImportService.importZip(context, buffer, rootNote, {- preserveIds: true- });-}--async function createImportZip(path: string) {- const inputFile = "input.zip";- const archive = new ZipArchive({- zlib: { level: 0 }- });-- archive.directory(path, "/");-- const outputStream = createWriteStream(inputFile);- archive.pipe(outputStream);- await waitForEnd(archive, outputStream);-- try {- return await fs.readFile(inputFile);- } finally {- await fs.rm(inputFile);- }-}--function waitForEnd(archive: Archiver, stream: WriteStream) {- return new Promise<void>((res, rej) => {- stream.on("finish", res);- stream.on("error", rej);- archive.on("error", rej);- archive.finalize().catch(rej);- });-}--/**- * Rewrites internal `#root/...` note links in exported help HTML so that they resolve- * against the help subtree once imported into a production Trilium instance.- *- * In the edit-docs instance the help notes carry plain, randomly generated IDs, but in- * production they live under the `_help` subtree with a `_help_` prefix. This adds that- * prefix to the link's target note ID, and reduces the link to that ID alone: the editor- * writes a full note path when a link is created, whose intermediate IDs belong to the- * docs instance and match nothing in the tree a reader has, leaving the client to fall- * back to the note's own path. The importer writes the same single-ID form, so a note- * exported straight after an edit now matches one that has been through an import.- */-export function rewriteHelpLinks(content: string): string {- return content.replace(/href="([^"]*#root)(?:[a-zA-Z0-9_/]*\/)?([a-zA-Z0-9_]+)([^"]*)"/g,- (match, prefix: string, targetNoteId: string, suffix: string) => {- if (targetNoteId.startsWith("_help_")) {- return `href="${prefix}/${targetNoteId}${suffix}"`;- }-- // Canonical hidden-subtree notes (e.g. _options, _optionsTextNotes) keep their IDs in- // production, so they already start with an underscore, and their path is a real one.- // Only help notes (random alphanumeric IDs) get the `_help_` prefix; prefixing the- // others would produce broken `_help__optionsTextNotes`-style links (see issue #9646).- if (targetNoteId.startsWith("_")) {- return match;- }- return `href="${prefix}/_help_${targetNoteId}${suffix}"`;- });-}--export async function createZipFromDirectory(dirPath: string, zipPath: string) {- const archive = new ZipArchive({ zlib: { level: 5 } });- const outputStream = createWriteStream(zipPath);- archive.directory(dirPath, false);- archive.pipe(outputStream);- await waitForEnd(archive, outputStream);-}--export async function extractZip(zipFilePath: string, outputPath: string, ignoredFiles?: Set<string>) {- const promise = deferred<void>();- setTimeout(async () => {- const { getZipProvider } = (await import("@triliumnext/core"));- const zipProvider = getZipProvider();- const buffer = await fs.readFile(zipFilePath);- await zipProvider.readZipFile(buffer, async (entry, readContent) => {- // We ignore directories since they can appear out of order anyway.- if (!entry.fileName.endsWith("/") && !ignoredFiles?.has(entry.fileName)) {- const destPath = path.join(outputPath, entry.fileName);- const fileContent = await readContent();-- await fs.mkdir(path.dirname(destPath), { recursive: true });- await fs.writeFile(destPath, normalizeLineEndings(fileContent));- }- });- promise.resolve();- }, 1000);- await promise;-}--/**- * Rewrites CRLF line endings to LF, so that `extractZip` writes the same bytes on Windows as it- * does elsewhere. The exported trees (`docs/`, the help HTML, the demo) are stored with LF, and- * Git only hides the difference once a file is staged.- *- * Binary entries such as images keep their bytes. They are detected the way Git detects them: a- * NUL byte within the first {@link BINARY_DETECTION_LENGTH} bytes marks the content as binary.- */-export function normalizeLineEndings(content: Uint8Array): Uint8Array {- if (isBinary(content)) {- return content;- }-- const normalized = new Uint8Array(content.length);- let length = 0;- for (const [index, byte] of content.entries()) {- if (byte === CARRIAGE_RETURN && content[index + 1] === LINE_FEED) {- continue;- }-- normalized[length++] = byte;- }-- return length === content.length ? content : normalized.subarray(0, length);-}--const NUL = 0x00;-const LINE_FEED = 0x0a;-const CARRIAGE_RETURN = 0x0d;-const BINARY_DETECTION_LENGTH = 8000;--function isBinary(content: Uint8Array) {- const end = Math.min(content.length, BINARY_DETECTION_LENGTH);- for (let index = 0; index < end; index++) {- if (content[index] === NUL) {- return true;- }- }-- return false;-}diff --git a/package.json b/package.jsonindex 17dd54c367..bc3d19d619 100644--- a/package.json+++ b/package.json@@ -25,6 +25,7 @@"mobile:sync": "pnpm run --filter mobile sync","desktop:start-prod-no-dir": "pnpm run --filter desktop start-prod-no-dir","edit-docs:edit-docs": "pnpm run --filter edit-docs edit-docs",+ "edit-docs:sync-docs": "pnpm run --filter edit-docs sync-docs","edit-docs:build": "pnpm run --filter edit-docs build","website:start": "pnpm run --filter website dev","website:build": "pnpm run --filter website build",