Skip to content

Build your personal knowledge base with Trilium Notes

fix(import): nest Notion pages by their export folder, not the page id

Elian Doranb3c5cd5b19ff
diff --git a/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts b/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts
index 57e61fbe75..37867debf0 100644
--- a/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts
@@ -39,10 +39,23 @@ async function importNotion(files: Record<string, string | Buffer>): Promise<BNo
});
}
-const pageHtml = (title: string) =>
- `<html><head><title>${title}</title></head><body><div id="386c5eca1b8b80439520cad27a0d2749" class="page"><div class="page-body"><p>Hello</p></div></div></body></html>`;
+const pageHtml = (title: string, id = "386c5eca1b8b80439520cad27a0d2749") =>
+ `<html><head><title>${title}</title></head><body><div id="${id}" class="page"><div class="page-body"><p>Hello</p></div></div></body></html>`;
describe("Notion importer — integration", () => {
+ it("nests child pages under the parent named by their containing folder", async () => {
+ // Notion names the children folder by title only ("Examples"), while the page file keeps its id.
+ const importRoot = await importNotion({
+ "Examples 579da56a22844fb9a769e27d53067adc.html": pageHtml("Examples", "579da56a22844fb9a769e27d53067adc"),
+ "Examples/Hello world 2c6c5eca1b8b80f7b9eaf4f396b755dc.html": pageHtml("Hello world", "2c6c5eca1b8b80f7b9eaf4f396b755dc"),
+ "Examples/Quick Note 3aa38acf20c74649b4370fab0195b882.html": pageHtml("Quick Note", "3aa38acf20c74649b4370fab0195b882")
+ });
+
+ const examples = importRoot.getChildNotes().find((note) => note.title === "Examples");
+ expect(importRoot.getChildNotes().map((note) => note.title)).toEqual(["Examples"]);
+ expect(examples?.getChildNotes().map((note) => note.title).sort()).toEqual(["Hello world", "Quick Note"]);
+ });
+
it("recurses into a root-level nested export zip (the part Notion makes you extract)", async () => {
const innerZip = await createZipBuffer({ "Inner page 386c5eca1b8b80439520cad27a0d2749.html": pageHtml("Inner page") });
const importRoot = await importNotion({ "Export-Part-1.zip": innerZip });
@@ -50,13 +63,6 @@ describe("Notion importer — integration", () => {
expect(importRoot.getChildNotes().map((note) => note.title)).toContain("Inner page");
});
- it("descends into a nested export zip even when it sits inside a top-level wrapper folder", async () => {
- const innerZip = await createZipBuffer({ "Inner page 386c5eca1b8b80439520cad27a0d2749.html": pageHtml("Wrapped page") });
- const importRoot = await importNotion({ "My Export/Export-Part-1.zip": innerZip });
-
- expect(importRoot.getChildNotes().map((note) => note.title)).toContain("Wrapped page");
- });
-
it("descends through two levels of nested export zips", async () => {
const innermost = await createZipBuffer({ "Inner page 386c5eca1b8b80439520cad27a0d2749.html": pageHtml("Deep page") });
const middle = await createZipBuffer({ "Export-Part-1.zip": innermost });
diff --git a/packages/trilium-core/src/services/import/notion/importer.spec.ts b/packages/trilium-core/src/services/import/notion/importer.spec.ts
index 3f474f3120..b77948078f 100644
--- a/packages/trilium-core/src/services/import/notion/importer.spec.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.spec.ts
@@ -1,7 +1,7 @@
import { parse } from "node-html-parser";
import { describe, expect, it } from "vitest";
-import { firstChildNotionId, type LinkTarget, resolveResourcePath, rewriteLinks } from "./importer.js";
+import { firstChildNotionId, type LinkTarget, ownedFolderKey, parentFolderKey, resolveResourcePath, rewriteLinks } from "./importer.js";
describe("resolveResourcePath", () => {
it("resolves an image path relative to the page's directory in the zip", () => {
@@ -52,6 +52,28 @@ describe("rewriteLinks", () => {
});
});
+describe("folder-based parenting keys", () => {
+ // Notion names a page's children folder by title only (no id), while the page file keeps its id.
+ const wrapper = "Export-21e2de27-9565-4851-8e2b-604e20bd0418";
+
+ it("matches a child's containing folder to the parent page that owns it (title-only folder)", () => {
+ const parent = `${wrapper}/45 cff419ddfc69457aad14bd0381cf0172.html`;
+ const child = `${wrapper}/45/Brown fox 4731219279d04d78aca408c0a60c4263.html`;
+ expect(ownedFolderKey(parent)).toBe("Export/45");
+ expect(parentFolderKey(child)).toBe(ownedFolderKey(parent));
+ });
+
+ it("also matches when the folder itself carries an id", () => {
+ const parent = `Parent ${"a".repeat(32)}.html`;
+ const child = `Parent ${"a".repeat(32)}/Child ${"b".repeat(32)}.html`;
+ expect(parentFolderKey(child)).toBe(ownedFolderKey(parent));
+ });
+
+ it("leaves a top-level page with no owning folder", () => {
+ expect(parentFolderKey("45 cff419ddfc69457aad14bd0381cf0172.html")).toBe("");
+ });
+});
+
describe("firstChildNotionId", () => {
const bodyOf = (inner: string) => parse(`<body>${inner}</body>`).querySelector("body");
diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.ts
index ae7008589c..7ae409fdd1 100644
--- a/packages/trilium-core/src/services/import/notion/importer.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.ts
@@ -24,16 +24,14 @@ import type TaskContext from "../../task_context.js";
import dateUtils from "../../utils/date.js";
import { getZipProvider } from "../../zip_provider.js";
import { convertNotionHtml } from "./converter.js";
-import { getNotionId, parseParentIds, stripNotionId } from "./notion_id.js";
+import { getNotionId, stripNotionId } from "./notion_id.js";
interface ParsedPage {
- /** The page's own Notion id, used to resolve child pages and (later) internal links to it. */
+ /** The page's own Notion id, used to resolve cross-page links pointing at it. */
id: string;
title: string;
- /** Path of the .html entry inside the zip; retained for diagnostics. */
+ /** Path of the .html entry inside the zip; drives both image resolution and folder-based parenting. */
path: string;
- /** Notion ids of ancestor pages (outermost first); the last is this page's immediate parent. */
- parentIds: string[];
/** The page's body HTML, sanitized; empty when the body could not be located. */
content: string;
utcDateCreated?: string;
@@ -52,9 +50,8 @@ async function importNotion(taskContext: TaskContext<"importNotes">, fileBuffer:
* normalized path so page content can later reference it. The `index.html` summary is skipped.
*
* A Notion workspace export wraps its content in a nested zip at the archive root — the part you'd
- * otherwise have to extract by hand — so export-level `.zip` entries are descended into. A zip is
- * "export-level" when no ancestor folder carries a Notion id; a zip inside a page folder (which does) is
- * a user's attachment and kept as-is. Recursion is depth-bounded as a guard against pathological archives.
+ * otherwise have to extract by hand — so root-level `.zip` entries are descended into. A zip nested inside
+ * a folder is a user's attachment and kept as-is. Recursion is depth-bounded against pathological archives.
*/
const MAX_NESTED_ZIP_DEPTH = 2;
@@ -70,7 +67,7 @@ async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[];
if (isDirectory(path)) {
return;
}
- if (path.toLowerCase().endsWith(".zip") && parseParentIds(path).length === 0) {
+ if (path.toLowerCase().endsWith(".zip") && !path.includes("/")) {
if (depth < MAX_NESTED_ZIP_DEPTH) {
await readArchive(await readContent(), depth + 1);
}
@@ -113,7 +110,6 @@ function parsePage(path: string, html: string): ParsedPage | null {
id,
title,
path,
- parentIds: parseParentIds(path),
content,
utcDateCreated: extractDate(root, "property-row-created_time"),
utcDateModified: extractDate(root, "property-row-last_edited_time")
@@ -121,9 +117,11 @@ function parsePage(path: string, html: string): ParsedPage | null {
}
/**
- * Creates the note tree under a fresh "Notion import" root. Pages are created shallowest-first so a
- * page's parent always exists before it; each page is parented under the note created for its
- * immediate-parent id, or under the import root when it has no (resolvable) parent. Returns that root.
+ * Creates the note tree under a fresh "Notion import" root. Notion encodes the hierarchy through the
+ * folder structure: a page `Title <id>.html` keeps its children in a sibling folder named after its title
+ * (no id, e.g. `Title/`). So each page is parented under whichever page "owns" its containing folder —
+ * matched on a normalized, id-stripped folder path so it works whether or not the folders carry ids.
+ * Pages are created shallowest-first, so a parent's note exists before its children. Returns the root.
*/
function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<string, Uint8Array>, taskContext: TaskContext<"importNotes">): BNote {
const isProtected = importRootNote.isProtected && protectedSessionService.isProtectedSessionAvailable();
@@ -131,16 +129,15 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<
const rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: t("notion_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;
rootNote.addLabel("iconClass", "bx bx-import");
- const noteIdByPageId = new Map<string, string>();
+ const noteIdByFolder = new Map<string, string>();
const targetByPageId = new Map<string, LinkTarget>();
const created: { note: BNote; content: string; page: ParsedPage }[] = [];
- const ordered = [...pages].sort((a, b) => a.parentIds.length - b.parentIds.length);
+ const ordered = [...pages].sort((a, b) => folderDepth(a.path) - folderDepth(b.path));
// First pass: create every note (so cross-page links can resolve in the second pass) and save its
// referenced images as attachments. Content is only rewritten/saved once, in the second pass.
for (const page of ordered) {
- const parentPageId = page.parentIds[page.parentIds.length - 1];
- const targetParentId = (parentPageId && noteIdByPageId.get(parentPageId)) || rootNote.noteId;
+ const targetParentId = noteIdByFolder.get(parentFolderKey(page.path)) ?? rootNote.noteId;
const { note } = noteService.createNewNote({
parentNoteId: targetParentId,
@@ -150,7 +147,7 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<
mime: "text/html",
isProtected
});
- noteIdByPageId.set(page.id, note.noteId);
+ noteIdByFolder.set(ownedFolderKey(page.path), note.noteId);
targetByPageId.set(page.id, { noteId: note.noteId, title: page.title });
// Attachments hang off the note, so this must run after creation; it returns the content with the
@@ -293,6 +290,36 @@ function normalizePath(path: string): string {
return parts.join("/");
}
+/** Folder depth of a page path — pages are created shallowest-first so parents precede their children. */
+function folderDepth(path: string): number {
+ return path.split("/").length;
+}
+
+/**
+ * The folder a page's children live in: its directory plus its own title (the file's id and extension
+ * dropped). Keyed against {@link parentFolderKey} to attach children to their parent.
+ */
+export function ownedFolderKey(path: string): string {
+ const title = stripNotionId(removeExtension(baseName(path)));
+ const dir = dirname(path);
+ return folderKey(dir ? `${dir}/${title}` : title);
+}
+
+/** A page's containing folder (its path's directory), normalized for matching against an owned folder. */
+export function parentFolderKey(path: string): string {
+ return folderKey(dirname(path));
+}
+
+/** Strips the Notion id from each segment so a title-only folder (`Title`) and a page (`Title <id>`) match. */
+function folderKey(folderPath: string): string {
+ return folderPath.split("/").map((segment) => stripNotionId(segment)).join("/");
+}
+
+function dirname(path: string): string {
+ const lastSlash = path.lastIndexOf("/");
+ return lastSlash >= 0 ? path.slice(0, lastSlash) : "";
+}
+
/**
* Returns the Notion id of `body`'s page-wrapper child. Only `body`'s direct children are considered: a
* nested block whose id happens to match the 32-hex pattern must not be taken for the page id.
diff --git a/packages/trilium-core/src/services/import/notion/notion_id.spec.ts b/packages/trilium-core/src/services/import/notion/notion_id.spec.ts
index fcebbff342..8206efc63d 100644
--- a/packages/trilium-core/src/services/import/notion/notion_id.spec.ts
+++ b/packages/trilium-core/src/services/import/notion/notion_id.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { getNotionId, parseParentIds, stripNotionId } from "./notion_id.js";
+import { getNotionId, stripNotionId } from "./notion_id.js";
const ID = "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d";
@@ -32,20 +32,3 @@ describe("stripNotionId", () => {
expect(stripNotionId("Workspace")).toBe("Workspace");
});
});
-
-describe("parseParentIds", () => {
- it("returns the ids of ancestor folders, outermost first", () => {
- const parentId = "0000000000000000000000000000aaaa";
- const grandParentId = "0000000000000000000000000000bbbb";
- expect(parseParentIds(`Export/Grandparent ${grandParentId}/Parent ${parentId}/Child ${ID}.html`))
- .toEqual([grandParentId, parentId]);
- });
-
- it("drops folder segments that carry no id (e.g. the workspace root)", () => {
- expect(parseParentIds(`Export/Child ${ID}.html`)).toEqual([]);
- });
-
- it("returns an empty array for a top-level file", () => {
- expect(parseParentIds(`Child ${ID}.html`)).toEqual([]);
- });
-});
diff --git a/packages/trilium-core/src/services/import/notion/notion_id.ts b/packages/trilium-core/src/services/import/notion/notion_id.ts
index 2f6f5e6fe0..775e833623 100644
--- a/packages/trilium-core/src/services/import/notion/notion_id.ts
+++ b/packages/trilium-core/src/services/import/notion/notion_id.ts
@@ -1,11 +1,10 @@
/**
- * Notion-export identity helpers. Every page/attachment Notion exports carries a 32-character hex id
- * appended to its file and folder names ("Page Title <id>.html", "Page Title <id>/"), and internal
- * links reference those same names. These helpers extract and strip those ids and derive a page's
- * ancestry from its path inside the zip.
+ * Notion-export identity helpers. Every page Notion exports carries a 32-character hex id appended to its
+ * file name ("Page Title <id>.html"), and internal links reference those same names. These helpers
+ * extract and strip those ids.
*
* Ported from Obsidian's importer (https://github.com/obsidianmd/obsidian-importer,
- * src/formats/notion/notion-utils.ts and parse-info.ts), MIT-licensed, © 2023 Obsidian.
+ * src/formats/notion/notion-utils.ts), MIT-licensed, © 2023 Obsidian.
*/
/** Strips the trailing Notion id (and its separating space/hyphen) from a name, keeping the extension. */
@@ -17,18 +16,3 @@ export function stripNotionId(id: string): string {
export function getNotionId(id: string): string | undefined {
return id.replace(/-/g, "").match(/([a-z0-9]{32})(\?|\.|$)/)?.[1];
}
-
-/**
- * Returns the Notion ids of a file's ancestor pages, outermost first, read from its folder path inside
- * the zip. Folder segments without an id (e.g. the export's top-level workspace folder) are dropped, so
- * the last entry is the file's immediate parent page.
- */
-export function parseParentIds(filePath: string): string[] {
- // Zip entry names always use forward slashes, so split on "/" directly (rather than a node `path`
- // helper, whose behaviour differs on Windows) and drop the last segment (the file itself).
- const segments = filePath.split("/");
- segments.pop();
- return segments
- .map((segment) => getNotionId(segment))
- .filter((id): id is string => !!id);
-}