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(import): resolve Obsidian wikilinks to Trilium internal links
Elian Doran57b835d4df25
diff --git a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.tsindex b1f75b4df2..987a3af802 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts@@ -162,4 +162,61 @@ describe("Obsidian importer — integration", () => {expect(note?.getAttachmentsByRole("image")).toHaveLength(0);expect(note?.getAttachmentsByRole("file")).toHaveLength(0);});++ it("resolves a wikilink to a reference link and records an internalLink relation (backlink)", async () => {+ const importRoot = await importObsidian({ "A.md": "See [[B]].", "B.md": "I am B." });++ const a = importRoot.getChildNotes().find((n) => n.title === "A");+ const b = importRoot.getChildNotes().find((n) => n.title === "B");+ if (!a || !b) {+ throw new Error("notes were not imported");+ }++ // The link resolves to a reference link (the live-title chip) pointing at B.+ expect(decodeUtf8(a.getContent())).toContain(`<a class="reference-link" href="#root/${b.noteId}">`);+ // ...and drives backlinks both ways.+ expect(a.getRelations().filter((r) => r.name === "internalLink").map((r) => r.value)).toEqual([b.noteId]);+ expect(b.getTargetRelations().filter((r) => r.name === "internalLink").map((r) => r.noteId)).toEqual([a.noteId]);+ });++ it("uses the alias as the link text for [[Target|alias]]", async () => {+ const importRoot = await importObsidian({ "A.md": "[[B|the bee]]", "B.md": "b" });++ const a = importRoot.getChildNotes().find((n) => n.title === "A");+ const b = importRoot.getChildNotes().find((n) => n.title === "B");+ const content = decodeUtf8(a?.getContent() ?? "");+ // An aliased link is a plain internal link carrying the alias text, not a live-title reference link.+ expect(content).toContain(`<a href="#root/${b?.noteId}">the bee</a>`);+ expect(content).not.toContain("reference-link");+ });++ it("resolves a path-qualified wikilink even when the base name is ambiguous", async () => {+ const importRoot = await importObsidian({+ "Linker.md": "[[Folder 1/Note]]",+ "Folder 1/Note.md": "one",+ "Folder 2/Note.md": "two"+ });++ const linker = importRoot.getChildNotes().find((n) => n.title === "Linker");+ const target = importRoot.getChildNotes().find((n) => n.title === "Folder 1")?.getChildNotes()[0];+ expect(decodeUtf8(linker?.getContent() ?? "")).toContain(`href="#root/${target?.noteId}"`);+ });++ it("unwraps unresolvable and ambiguous wikilinks to plain text, recording no relation", async () => {+ const importRoot = await importObsidian({+ "Missing.md": "Go to [[Nowhere]].",+ "Ambiguous.md": "[[Dup]]",+ "Folder 1/Dup.md": "one",+ "Folder 2/Dup.md": "two"+ });++ const missing = importRoot.getChildNotes().find((n) => n.title === "Missing");+ expect(decodeUtf8(missing?.getContent() ?? "")).toBe("<p>Go to Nowhere.</p>");+ expect(missing?.getRelations().filter((r) => r.name === "internalLink")).toHaveLength(0);++ // "Dup" is shared by two notes, so it's ambiguous and left unresolved rather than guessed.+ const ambiguous = importRoot.getChildNotes().find((n) => n.title === "Ambiguous");+ expect(decodeUtf8(ambiguous?.getContent() ?? "")).toBe("<p>Dup</p>");+ expect(ambiguous?.getRelations().filter((r) => r.name === "internalLink")).toHaveLength(0);+ });});diff --git a/packages/trilium-core/src/services/import/obsidian/importer.ts b/packages/trilium-core/src/services/import/obsidian/importer.tsindex 834336f267..c7a67cb7c4 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.ts@@ -29,6 +29,7 @@ import { basename } from "../../utils/path.js";import { getZipProvider } from "../../zip_provider.js";import markdownService from "../markdown.js";import { applyAttachments, buildAttachmentIndex } from "./attachments.js";+import { buildNoteIndex, resolveLinks } from "./links.js";interface VaultNote {/** The note's vault-root-relative POSIX path, e.g. `Folder 1/First note.md` (the wrapper folder stripped). */@@ -107,21 +108,35 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Mapconst shrinkImages = !!taskContext.data?.shrinkImages;// Folder path (POSIX) -> its container note. The empty path maps to the import root.const folderNotes = new Map<string, BNote>();+ const created: { note: BNote; path: string; rendered: string; content: string }[] = [];+ // First pass: create every note (so cross-note links can resolve below) with its Markdown rendered and+ // attachments saved. Content is persisted once, in the link pass, to avoid a second write per note.for (const vaultNote of notes) {const parent = ensureFolder(parentFolder(vaultNote.path), rootNote, folderNotes, isProtected);- const html = markdownService.renderToHtml(vaultNote.markdown, vaultNote.title);- const { note } = noteService.createNewNote({ parentNoteId: parent.noteId, title: vaultNote.title, content: html, type: "text", mime: "text/html", isProtected });+ const rendered = markdownService.renderToHtml(vaultNote.markdown, vaultNote.title);+ const { note } = noteService.createNewNote({ parentNoteId: parent.noteId, title: vaultNote.title, content: rendered, type: "text", mime: "text/html", isProtected });// Attachments hang off the note, so this runs after creation; it returns the content with embedded// images/files rewritten to point at the saved attachments.- const finalHtml = applyAttachments(note, html, attachmentIndex, shrinkImages);- if (finalHtml !== html) {- note.setContent(finalHtml);- }+ const content = applyAttachments(note, rendered, attachmentIndex, shrinkImages);+ created.push({ note, path: vaultNote.path, rendered, content });taskContext.increaseProgressCount();}+ // Second pass: now that every note's name -> id is known, resolve wikilinks to Trilium internal links and+ // record the resulting `internalLink` relations (so backlinks / "what links here" work).+ const noteIndex = buildNoteIndex(created);+ for (const { note, rendered, content } of created) {+ const { html, targets } = resolveLinks(content, noteIndex);+ if (html !== rendered) {+ note.setContent(html);+ }+ for (const target of targets) {+ note.addRelation("internalLink", target);+ }+ }+return rootNote;}diff --git a/packages/trilium-core/src/services/import/obsidian/links.ts b/packages/trilium-core/src/services/import/obsidian/links.tsnew file mode 100644index 0000000000..7bf81e0161--- /dev/null+++ b/packages/trilium-core/src/services/import/obsidian/links.ts@@ -0,0 +1,113 @@+/**+ * Resolves Obsidian wikilinks in a rendered note's HTML to Trilium internal links.+ *+ * The Markdown renderer's wikilink extension has already turned `[[Target]]`, `[[Target|alias]]` and+ * `[[Target#heading]]` into `<a class="reference-link" href="/<inner>">…</a>` (the raw target lives in the+ * href). This pass walks those anchors with an HTML parser — never scanning text for `[[…]]` — and splits any+ * `|alias` / `#heading` off with string ops. The target is resolved by name against the imported notes,+ * mirroring Obsidian's shortest-path rule: an exact vault path first, then a unique base name. A name shared+ * by 2+ notes is ambiguous and left unresolved (never guessed), as is a target with no matching note.+ *+ * A resolved link becomes `#root/<noteId>` — a reference link (the live-title chip) when there's no alias, or+ * a plain link carrying the alias text otherwise. An unresolved link is unwrapped to plain text, since+ * Trilium has no dangling-link concept. Attachment links already rewritten by the attachments pass carry a+ * `#root/…` href (not `/…`), so they're skipped. Returns the rewritten HTML and the resolved target note ids+ * for recording `internalLink` relations (backlinks).+ */++import { parse } from "node-html-parser";++import { escapeHtml } from "../../utils/index.js";+import { basename } from "../../utils/path.js";++export interface NoteIndex {+ /** Lower-cased vault path without `.md` -> noteId (for path-qualified links like `[[Folder/Note]]`). */+ byPath: Map<string, string>;+ /** Lower-cased base name -> noteId, or null when the name is shared by 2+ notes (ambiguous). */+ byName: Map<string, string | null>;+}++export function buildNoteIndex(notes: { note: { noteId: string }; path: string }[]): NoteIndex {+ const byPath = new Map<string, string>();+ const byName = new Map<string, string | null>();+ for (const { note, path } of notes) {+ const key = stripMd(path.toLowerCase());+ byPath.set(key, note.noteId);+ const base = basename(key);+ byName.set(base, byName.has(base) ? null : note.noteId);+ }+ return { byPath, byName };+}++export function resolveLinks(html: string, index: NoteIndex): { html: string; targets: string[] } {+ // The wikilink extension emits a vault-relative `href="/…"`; nothing to do without one.+ if (!html.includes(`href="/`)) {+ return { html, targets: [] };+ }+ const root = parse(html);+ const targets = new Set<string>();+ let changed = false;++ for (const anchor of root.querySelectorAll("a")) {+ const href = anchor.getAttribute("href");+ // Only the extension's wikilink placeholders: class `reference-link` + a vault-relative `/…` href.+ // Attachment links (already `#root/…`) and plain Markdown links (no class) are left alone.+ if (!href || !href.startsWith("/") || !(anchor.getAttribute("class") ?? "").includes("reference-link")) {+ continue;+ }+ const { target, alias } = splitWikilink(safeDecode(href.slice(1)));+ const noteId = resolveNote(index, target);+ if (noteId) {+ anchor.setAttribute("href", `#root/${noteId}`);+ if (alias) {+ // A plain link keeps the alias text; a bare link stays a reference link (the live-title chip).+ anchor.removeAttribute("class");+ anchor.set_content(escapeHtml(alias));+ }+ targets.add(noteId);+ } else {+ anchor.insertAdjacentHTML("beforebegin", escapeHtml(alias ?? target));+ anchor.remove();+ }+ changed = true;+ }++ return { html: changed ? root.toString() : html, targets: [...targets] };+}++/** Resolves a wikilink target to a noteId: an exact vault path first, then a unique base-name match. */+function resolveNote(index: NoteIndex, target: string): string | null {+ if (!target) {+ return null;+ }+ const key = stripMd(target.toLowerCase());+ return index.byPath.get(key) ?? index.byName.get(basename(key)) ?? null;+}++/** Splits a wikilink's inner text into its target and optional display alias, dropping any `#heading`. */+function splitWikilink(inner: string): { target: string; alias?: string } {+ let target = inner;+ let alias: string | undefined;+ const pipe = target.indexOf("|");+ if (pipe !== -1) {+ alias = target.slice(pipe + 1).trim();+ target = target.slice(0, pipe);+ }+ const hash = target.indexOf("#");+ if (hash !== -1) {+ target = target.slice(0, hash);+ }+ return { target: target.trim(), alias };+}++function stripMd(path: string): string {+ return path.endsWith(".md") ? path.slice(0, -3) : path;+}++function safeDecode(value: string): string {+ try {+ return decodeURIComponent(value);+ } catch {+ return value;+ }+}