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): scaffold Obsidian vault importer
Elian Doran663e0b5b890b
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 0664bdff1d..687bd123d1 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -292,6 +292,13 @@"choose_file": "Anytype export (.zip)","import": "Import"},+ "obsidian_import": {+ "name": "Obsidian",+ "description": "From a vault",+ "description_long": "Zip your Obsidian vault folder, then choose the resulting .zip file here.",+ "choose_file": "Obsidian vault (.zip)",+ "import": "Import"+ },"evernote_import": {"name": "Evernote","description": "From .enex files",diff --git a/apps/client/src/widgets/dialogs/import/icons/obsidian.svg b/apps/client/src/widgets/dialogs/import/icons/obsidian.svgnew file mode 100644index 0000000000..132259bbe0--- /dev/null+++ b/apps/client/src/widgets/dialogs/import/icons/obsidian.svg@@ -0,0 +1,6 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="none">+ <path d="M148 24 78 60 44 140l52 78 70 14 46-72-24-92-40-44Z" fill="#6c56cc"/>+ <path d="M148 24 110 96l34 90-48 32 70 14 46-72-24-92-40-44Z" fill="#a288f5"/>+ <path d="M110 96 78 60 44 140l52 78 48-32-34-90Z" fill="#8b6df0"/>+ <path d="M110 96 148 24l40 44 24 92-46 72-22-46 30-86-64 20Z" fill="#4f3bb3" opacity="0.55"/>+</svg>diff --git a/apps/client/src/widgets/dialogs/import/index.ts b/apps/client/src/widgets/dialogs/import/index.tsindex 8e1bff3c9d..1c6e2706ca 100644--- a/apps/client/src/widgets/dialogs/import/index.ts+++ b/apps/client/src/widgets/dialogs/import/index.ts@@ -3,6 +3,7 @@ import evernoteProvider from "./evernote.js";import filesProvider from "./files.js";import keepProvider from "./keep.js";import notionProvider from "./notion.js";+import obsidianProvider from "./obsidian.js";import oneNoteProvider from "./onenote.js";import type { ImportProvider } from "./types.js";@@ -11,6 +12,6 @@ import type { ImportProvider } from "./types.js";* picker (services in a grid, local file import grouped full-width beneath) and each provider's panel* automatically.*/-export const importProviders: ImportProvider[] = [filesProvider, oneNoteProvider, notionProvider, keepProvider, evernoteProvider, anytypeProvider];+export const importProviders: ImportProvider[] = [filesProvider, oneNoteProvider, notionProvider, keepProvider, evernoteProvider, anytypeProvider, obsidianProvider];export type { ImportProvider, ImportProviderPanelProps } from "./types.js";diff --git a/apps/client/src/widgets/dialogs/import/obsidian.tsx b/apps/client/src/widgets/dialogs/import/obsidian.tsxnew file mode 100644index 0000000000..bebb1511dd--- /dev/null+++ b/apps/client/src/widgets/dialogs/import/obsidian.tsx@@ -0,0 +1,65 @@+import { useCallback, useEffect, useRef, useState } from "preact/hooks";++import { t } from "../../../services/i18n.js";+import importService from "../../../services/import.js";+import Button from "../../react/Button.js";+import { Card, CardSection } from "../../react/Card.js";+import FileDropZone from "../../react/FileDropZone.js";+import iconUrl from "./icons/obsidian.svg?url";+import type { ImportProvider, ImportProviderPanelProps } from "./types.js";++function ObsidianPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPanelProps) {+ const [file, setFile] = useState<File | null>(null);++ const onChange = useCallback((files: FileList | null) => setFile(files?.[0] ?? null), []);++ const doImport = useCallback(async () => {+ if (!file) {+ return;+ }++ // Close immediately and let the shared import toasts (registered in import.ts) report progress,+ // completion and any error. `format: "obsidian"` routes the upload to the Obsidian importer on the+ // shared file-import endpoint, overriding the .zip extension's default (the generic zip importer).+ // uploadFiles surfaces any upload error via its own toast; swallow the rejection so this void-ed+ // call doesn't raise an unhandled rejection.+ closeDialog();+ await importService.uploadFiles("notes", parentNoteId, [file], { format: "obsidian", safeImport: "true", shrinkImages: "false" }).catch(() => {});+ }, [file, parentNoteId, closeDialog]);++ // Keep the latest import handler in a ref so the footer effect depends only on `file` being present,+ // never on doImport's identity — otherwise re-pushing the footer on every change would loop with the+ // parent re-rendering us back (see the Anytype/Notion panels for the same reasoning).+ const doImportRef = useRef(doImport);+ doImportRef.current = doImport;++ useEffect(() => {+ setFooter(+ <Button+ text={t("obsidian_import.import")}+ kind="primary"+ disabled={!file}+ onClick={() => void doImportRef.current()}+ />+ );+ }, [file, setFooter]);++ return (+ <Card heading={t("obsidian_import.choose_file")}>+ <CardSection>+ <p className="import-files-description">{t("obsidian_import.description_long")}</p>+ <FileDropZone onChange={onChange} />+ </CardSection>+ </Card>+ );+}++const provider: ImportProvider = {+ id: "obsidian",+ name: t("obsidian_import.name"),+ iconUrl,+ description: t("obsidian_import.description"),+ Panel: ObsidianPanel+};++export default provider;diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 24f66bd8f7..2747e5678d 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -332,6 +332,9 @@"protobuf-export-unsupported": "This looks like an Anytype \"Protobuf\" export, which Trilium cannot import. Please re-export your Anytype space using the \"Any-Block\" format with \"JSON\" selected and import that instead.","markdown-export-unsupported": "This looks like an Anytype \"Markdown\" export, which Trilium cannot import. Please re-export your Anytype space using the \"Any-Block\" format with \"JSON\" selected and import that instead."},+ "obsidian_import": {+ "root-title": "Obsidian import"+ },"pdf": {"export_filter": "PDF Document (*.pdf)","unable-to-export-message": "The current note could not be exported as a PDF.",diff --git a/packages/trilium-core/src/routes/api/import.ts b/packages/trilium-core/src/routes/api/import.tsindex fab30df1db..2f158f7ad6 100644--- a/packages/trilium-core/src/routes/api/import.ts+++ b/packages/trilium-core/src/routes/api/import.ts@@ -13,6 +13,7 @@ import anytypeImportService from "../../services/import/anytype/importer.js";import enexImportService from "../../services/import/enex.js";import keepImportService from "../../services/import/keep/importer.js";import notionImportService from "../../services/import/notion/importer.js";+import obsidianImportService from "../../services/import/obsidian/importer.js";import opmlImportService from "../../services/import/opml.js";import singleImportService from "../../services/import/single.js";import zipImportService from "../../services/import/zip.js";@@ -70,6 +71,10 @@ async function importNotesToBranch(req: ImportRequest<{ parentNoteId: string }>)// An Anytype JSON export is likewise a plain `.zip`; the Anytype import dialog tags the upload so// it routes to the Anytype importer rather than the generic zip importer.note = await anytypeImportService.importAnytype(taskContext, file.buffer, parentNote, file.originalname);+ } else if (format === "obsidian" && typeof file.buffer !== "string") {+ // An Obsidian vault is exported as a plain `.zip` of Markdown files, indistinguishable from a+ // Trilium export by extension alone; the Obsidian import dialog tags the upload to route it here.+ note = await obsidianImportService.importObsidian(taskContext, file.buffer, parentNote, file.originalname);} else if (extension === ".zip" && options.explodeArchives && typeof file.buffer !== "string") {note = await zipImportService.importZip(taskContext, file.buffer, parentNote);} else if (extension === ".opml" && options.explodeArchives) {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.tsnew file mode 100644index 0000000000..f1d69460ca--- /dev/null+++ b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts@@ -0,0 +1,61 @@+import { ZipArchive } from "archiver";+import { PassThrough } from "stream";+import { describe, expect, it } from "vitest";++import becca from "../../../becca/becca.js";+import type BNote from "../../../becca/entities/bnote.js";+import { getContext } from "../../context.js";+import TaskContext from "../../task_context.js";+import obsidianImporter from "./importer.js";++/** Builds an in-memory zip from a map of entry name -> contents. */+async function createZipBuffer(files: Record<string, string | Buffer>): Promise<Buffer> {+ const archive = new ZipArchive();+ const chunks: Buffer[] = [];+ const passthrough = new PassThrough();+ passthrough.on("data", (chunk: Buffer) => chunks.push(chunk));+ archive.pipe(passthrough);+ for (const [name, content] of Object.entries(files)) {+ archive.append(content, { name });+ }+ await archive.finalize();+ return Buffer.concat(chunks);+}++/** Runs the Obsidian importer over `files` and returns the import root note. */+async function importObsidian(files: Record<string, string | Buffer>, fileName?: string): Promise<BNote> {+ const buffer = await createZipBuffer(files);+ const taskContext = TaskContext.getInstance("obsidian-integration", "importNotes", { safeImport: true });++ return new Promise<BNote>((resolve, reject) => {+ void getContext().init(async () => {+ try {+ const root = becca.getNoteOrThrow("root");+ resolve(await obsidianImporter.importObsidian(taskContext, new Uint8Array(buffer), root, fileName));+ } catch (e) {+ reject(e);+ }+ });+ });+}++describe("Obsidian importer — integration", () => {+ // Scaffold only: structure/content processing (folders → notes, Markdown → HTML, links, …) is not wired+ // up yet, so for now the importer just creates the import root. These assertions lock in that contract.+ it("creates an 'Obsidian import' text root with an import icon", async () => {+ const importRoot = await importObsidian({+ "Welcome.md": "# Welcome\n\nFirst note.",+ "Folder/Nested.md": "Nested note."+ });++ expect(importRoot.title).toBe("Obsidian import");+ expect(importRoot.type).toBe("text");+ expect(importRoot.getOwnedLabelValue("iconClass")).toBe("bx bx-import");+ });++ it("does not import any notes yet (processing arrives in a later pass)", async () => {+ const importRoot = await importObsidian({ "Note.md": "body" }, "My Vault.zip");++ expect(importRoot.getChildNotes()).toHaveLength(0);+ });+});diff --git a/packages/trilium-core/src/services/import/obsidian/importer.ts b/packages/trilium-core/src/services/import/obsidian/importer.tsnew file mode 100644index 0000000000..78428056f6--- /dev/null+++ b/packages/trilium-core/src/services/import/obsidian/importer.ts@@ -0,0 +1,33 @@+/**+ * Imports an Obsidian vault (a zipped folder of Markdown files plus attachments) into a Trilium note tree.+ *+ * This is the integration scaffold only: it creates a fresh "Obsidian import" root and returns it. Vault+ * traversal and structure/content processing — folders → subtree, Markdown → HTML, wikilinks, embeds,+ * frontmatter → labels, tags, callouts, attachments, `.canvas`/`.excalidraw.md` — land in later passes.+ *+ * Invoked from the shared file-import dispatcher (routes/api/import.ts) when the upload is tagged+ * `format=obsidian`, so progress, completion and failure are reported by that dispatcher's TaskContext —+ * this service just builds the tree and returns its root note, like the zip/notion/anytype importers.+ */++import { t } from "i18next";++import type BNote from "../../../becca/entities/bnote.js";+import noteService from "../../notes.js";+import protectedSessionService from "../../protected_session.js";+import type TaskContext from "../../task_context.js";++async function importObsidian(taskContext: TaskContext<"importNotes">, _fileBuffer: Uint8Array, importRootNote: BNote, _fileName?: string): Promise<BNote> {+ /* v8 ignore next -- the protected branch needs a protected import root with an active protected session, which the in-memory test DB has no way to set up */+ const isProtected = importRootNote.isProtected && protectedSessionService.isProtectedSessionAvailable();++ const rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: t("obsidian_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;+ rootNote.addLabel("iconClass", "bx bx-import");++ // No notes imported yet — structure processing arrives in a later pass.+ taskContext.setTotalCount(0);++ return rootNote;+}++export default { importObsidian };