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): set OneNote page dates and refine cross-page link resolution
Elian Doranba51c33cc0d8
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.tsindex 886d7cbc77..609feae302 100644--- a/apps/server/src/services/import/onenote/importer.ts+++ b/apps/server/src/services/import/onenote/importer.ts@@ -12,7 +12,7 @@ import sql from "../../sql.js";import converter, { ONENOTE_ATTACHMENT_CLASS } from "./converter.js";import graph, { type OneNotePage } from "./graph.js";import { inkmlToSvg } from "./inkml.js";-import { rewritePageLinks } from "./links.js";+import { type LinkTarget, rewritePageLinks } from "./links.js";export interface SectionSelection {id: string;@@ -33,6 +33,10 @@ interface FetchedPage {inkSvg: string | null;/** Binary resources (images, file attachments) referenced by the page, downloaded up front. */resources: DownloadedResource[];+ /** OneNote's page creation timestamp (ISO 8601), preserved on the imported note. */+ createdDateTime?: string;+ /** OneNote's last-modified timestamp (ISO 8601), preserved on the imported note. */+ lastModifiedDateTime?: string;}interface DownloadedResource {@@ -72,7 +76,7 @@ export async function importSelection({ accessToken, parentNoteId, sections, tasconst { html: rawHtml, inkml } = await graph.getPageContent(accessToken, page.id);const html = converter.convertPageHtml(rawHtml);const resources = await downloadPageResources(accessToken, html);- fetchedPages.push({ title: page.title, pageId: page.pageId, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources });+ fetchedPages.push({ title: page.title, pageId: page.pageId, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources, createdDateTime: page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime });taskContext.increaseProgressCount();}fetched.push({ title: section.title, notebookTitle: section.notebookTitle, pages: fetchedPages });@@ -96,9 +100,9 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: boconst rootNote = createFolder(parentNoteId, "OneNote import");// Created page notes with their content-so-far (resources/ink applied), plus a map from each- // page's OneNote page-id GUID to the note created for it — both feed the link-resolution pass.- const createdPages: { note: BNote; original: string; content: string }[] = [];- const noteIdByPageId = new Map<string, string>();+ // page's OneNote page-id GUID to its imported note (and title) — both feed the link-resolution pass.+ const createdPages: { note: BNote; original: string; content: string; page: FetchedPage }[] = [];+ const targetByPageId = new Map<string, LinkTarget>();// Group selected sections under a note per notebook so the original hierarchy is preserved.const notebookNotes = new Map<string, string>();@@ -133,9 +137,9 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bocontent += renderInkFigure(pageNote, page.inkSvg);}- createdPages.push({ note: pageNote, original: page.html, content });+ createdPages.push({ note: pageNote, original: page.html, content, page });if (page.pageId) {- noteIdByPageId.set(page.pageId, pageNote.noteId);+ targetByPageId.set(page.pageId, { noteId: pageNote.noteId, title: page.title });}// Debug aid: keep the unmodified Graph HTML (and InkML, when present) alongside the@@ -161,17 +165,34 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo// Second pass: now that every page has a note, resolve cross-page `onenote:` links and persist the// final content. Done once per page (rather than re-saving for resources, then again for links).- for (const { note, original, content } of createdPages) {- const finalContent = rewritePageLinks(content, (pageId) => noteIdByPageId.get(pageId) ?? null);+ for (const { note, original, content, page } of createdPages) {+ const finalContent = rewritePageLinks(content, (pageId) => targetByPageId.get(pageId) ?? null);if (finalContent !== original) {note.setContent(finalContent);void noteService.asyncPostProcessContent(note, finalContent);}++ // Preserve OneNote's original timestamps. Must run after setContent, whose save would otherwise+ // re-stamp the modification date with "now".+ const utcDateCreated = toUtcDbDate(page.createdDateTime);+ const utcDateModified = toUtcDbDate(page.lastModifiedDateTime) ?? utcDateCreated;+ if (utcDateCreated || utcDateModified) {+ note.setDateCreatedAndModified(utcDateCreated, utcDateModified);+ }}return rootNote.noteId;}+/** Converts a Graph ISO 8601 timestamp to Trilium's UTC DB format, or undefined if absent/unparseable. */+function toUtcDbDate(isoDateTime: string | undefined): string | undefined {+ if (!isoDateTime) {+ return undefined;+ }+ const date = new Date(isoDateTime);+ return Number.isNaN(date.getTime()) ? undefined : date_utils.utcDateTimeStr(date);+}+/*** Saves a page's rendered ink SVG as an image attachment on the note and returns the `<figure>` markup* that embeds it inline. Returns an empty string if the attachment could not be created.diff --git a/apps/server/src/services/import/onenote/links.spec.ts b/apps/server/src/services/import/onenote/links.spec.tsindex ef7af46889..19a6459881 100644--- a/apps/server/src/services/import/onenote/links.spec.ts+++ b/apps/server/src/services/import/onenote/links.spec.ts@@ -2,7 +2,7 @@ import { parse } from "node-html-parser";import { describe, expect, it } from "vitest";import converter from "./converter.js";-import { extractPageId, rewritePageLinks } from "./links.js";+import { extractPageId, type LinkTarget, rewritePageLinks } from "./links.js";// Real OneNote source (debug-captured): the "First page" links to "Second page" with an internal// `onenote:` link (carrying page-id) immediately followed by an external "Web view" https link.@@ -14,16 +14,19 @@ const FIRST_PAGE_SOURCE = `<html lang="en-US"></body></html>`;-// The same page-id GUID appears in the page's own client URL (the bridge the importer uses to map a-// page-id to a Graph page) and in a link targeting it.const SECOND_PAGE_GUID = "eb2c4f67-8d3f-4fdb-a93b-32d6b3ba780d";-const SECOND_PAGE_CLIENT_URL = `onenote:https://d.docs.live.net/abc/Documents/Link%20test/Link%20test.one#Second%20page§ion-id={4d9d9af6-7f91-4f16-956a-8bf2c330f6ab}&page-id={${SECOND_PAGE_GUID.toUpperCase()}}&end`;+const SECOND_PAGE_CLIENT_URL = `onenote:https://d.docs.live.net/abc/Link%20test.one#Second%20page§ion-id={4d9d9af6-7f91-4f16-956a-8bf2c330f6ab}&page-id={${SECOND_PAGE_GUID.toUpperCase()}}&end`;++// A resolver that maps the Second page GUID to a note titled "Second page".+const resolveSecondPage = (title = "Second page"): ((pageId: string) => LinkTarget | null) => (pageId) =>+ pageId === SECOND_PAGE_GUID ? { noteId: "noteABC123", title } : null;++const internalLink = (text: string) => `<a href="onenote:#x&page-id={${SECOND_PAGE_GUID}}&end">${text}</a>`;describe("extractPageId", () => {it("pulls the lowercased page-id GUID from an internal link and from a client URL", () => {expect(extractPageId(`onenote:#Second%20page&page-id={${SECOND_PAGE_GUID}}&end`)).toBe(SECOND_PAGE_GUID);- // A client URL carrying the GUID upper-cased is normalized to lowercase.- expect(extractPageId(SECOND_PAGE_CLIENT_URL)).toBe(SECOND_PAGE_GUID);+ expect(extractPageId(SECOND_PAGE_CLIENT_URL)).toBe(SECOND_PAGE_GUID); // upper-cased GUID normalized});it("returns null when there is no page-id (web-view URL, external link, empty input)", () => {@@ -36,52 +39,76 @@ describe("extractPageId", () => {});describe("rewritePageLinks", () => {- const linkHtml = (href: string, text: string) => `<p><a href="${href}">${text}</a></p>`;-- it("rewrites an internal link whose target was imported into a Trilium note link, keeping the text", () => {- const html = linkHtml(`onenote:#Second%20page&page-id={${SECOND_PAGE_GUID}}&end`, "Second page");- const out = rewritePageLinks(html, (pageId) => (pageId === SECOND_PAGE_GUID ? "noteABC123" : null));+ it("turns a link whose text matches the page title into a reference link", () => {+ const out = rewritePageLinks(`<p>${internalLink("Second page")}</p>`, resolveSecondPage());+ const anchor = parse(out).querySelector("a");+ expect(anchor?.getAttribute("href")).toBe("#root/noteABC123");+ expect(anchor?.getAttribute("class")).toBe("reference-link");+ });+ it("keeps the original text on a plain link when it does not match the title", () => {+ const out = rewritePageLinks(`<p>${internalLink("click here")}</p>`, resolveSecondPage());const anchor = parse(out).querySelector("a");expect(anchor?.getAttribute("href")).toBe("#root/noteABC123");- expect(anchor?.textContent).toBe("Second page");+ expect(anchor?.getAttribute("class")).toBeFalsy(); // not a reference link+ expect(anchor?.textContent).toBe("click here");});it("leaves a link untouched when its target was not imported", () => {- const html = linkHtml(`onenote:#Other&page-id={${SECOND_PAGE_GUID}}&end`, "Other");- // resolve always returns null -> nothing changes, and the input is returned verbatim.- expect(rewritePageLinks(html, () => null)).toBe(html);+ const html = `<p>${internalLink("Second page")}</p>`;+ expect(rewritePageLinks(html, () => null)).toBe(html); // resolve returns null -> verbatim input});it("never touches non-onenote links (external / web-view) or link-free content", () => {- const webView = linkHtml("https://onedrive.live.com/...", "Web view");- expect(rewritePageLinks(webView, () => "noteABC123")).toBe(webView);- expect(rewritePageLinks("<p>no links here</p>", () => "noteABC123")).toBe("<p>no links here</p>");+ const webView = `<p><a href="https://onedrive.live.com/...">Web view</a></p>`;+ expect(rewritePageLinks(webView, resolveSecondPage())).toBe(webView);+ expect(rewritePageLinks("<p>no links here</p>", resolveSecondPage())).toBe("<p>no links here</p>");});it("resolves each link independently in mixed content", () => {const html =- linkHtml(`onenote:#A&page-id={11111111-1111-1111-1111-111111111111}&end`, "A") +- linkHtml(`onenote:#B&page-id={22222222-2222-2222-2222-222222222222}&end`, "B") +- linkHtml("https://example.com", "external");- const out = rewritePageLinks(html, (pageId) => (pageId.startsWith("11111111") ? "noteA" : null));+ `<p><a href="onenote:#A&page-id={11111111-1111-1111-1111-111111111111}&end">A</a></p>` ++ `<p><a href="onenote:#B&page-id={22222222-2222-2222-2222-222222222222}&end">B</a></p>` ++ `<p><a href="https://example.com">external</a></p>`;+ const out = rewritePageLinks(html, (pageId) => (pageId.startsWith("11111111") ? { noteId: "noteA", title: "A" } : null));const hrefs = parse(out).querySelectorAll("a").map((a) => a.getAttribute("href"));expect(hrefs).toEqual(["#root/noteA", "onenote:#B&page-id={22222222-2222-2222-2222-222222222222}&end", "https://example.com"]);});++ it("drops the redundant '(Web view)' link and its parentheses next to a reference link", () => {+ const html = `<p>Go to ${internalLink("Second page")} (<a href="https://onedrive.live.com/x?wd=target(${SECOND_PAGE_GUID})">Web view</a>).</p>`;+ const out = rewritePageLinks(html, resolveSecondPage());+ const paragraph = parse(out).querySelector("p");++ expect(paragraph?.querySelectorAll("a")).toHaveLength(1); // only the reference link remains+ expect(out).not.toContain("onedrive");+ expect(paragraph?.textContent).toBe("Go to Second page."); // "( )" wrapper cleaned up+ });++ it("keeps the web-view link when the internal link is a plain (non-matching) link", () => {+ const html = `<p>Go to ${internalLink("click here")} (<a href="https://onedrive.live.com/x?wd=target(${SECOND_PAGE_GUID})">Web view</a>).</p>`;+ const out = rewritePageLinks(html, resolveSecondPage());+ expect(parse(out).querySelectorAll("a")).toHaveLength(2); // web link not dropped+ });});// Guards the load-bearing assumption that the sanitizer keeps the `onenote:` href (the scheme is in// ALLOWED_PROTOCOLS): the importer rewrites links on the *converted* HTML, so if conversion dropped// the href, cross-page links would silently never resolve.describe("convertPageHtml + rewritePageLinks (end to end)", () => {- it("preserves the onenote link through conversion so it can be resolved afterwards", () => {+ it("preserves the link through conversion, makes a reference link and drops the web view", () => {const converted = converter.convertPageHtml(FIRST_PAGE_SOURCE);expect(extractPageId(parse(converted).querySelector("a")?.getAttribute("href"))).toBe(SECOND_PAGE_GUID);- const out = rewritePageLinks(converted, (pageId) => (pageId === SECOND_PAGE_GUID ? "noteABC123" : null));- const anchors = parse(out).querySelectorAll("a");- expect(anchors[0]?.getAttribute("href")).toBe("#root/noteABC123"); // internal link resolved- expect(anchors[1]?.getAttribute("href")).toContain("onedrive.live.com"); // web-view link untouched+ const out = rewritePageLinks(converted, resolveSecondPage());+ const paragraph = parse(out).querySelector("p");+ const anchors = paragraph?.querySelectorAll("a") ?? [];++ expect(anchors).toHaveLength(1);+ expect(anchors[0]?.getAttribute("href")).toBe("#root/noteABC123");+ expect(anchors[0]?.getAttribute("class")).toBe("reference-link");+ expect(out).not.toContain("onedrive");+ expect(paragraph?.textContent?.replace(/\s+/g, " ").trim()).toBe("Go to Second page");});});diff --git a/apps/server/src/services/import/onenote/links.ts b/apps/server/src/services/import/onenote/links.tsindex c93535051f..bce3930472 100644--- a/apps/server/src/services/import/onenote/links.ts+++ b/apps/server/src/services/import/onenote/links.ts@@ -6,29 +6,42 @@* `onenote:#Second%20page§ion-id={…}&page-id={eb2c4f67-…}&end`* That GUID is NOT the Graph page `id` (a composite like `0-{guid}!{n}-{guid}`); the bridge between the* two is the page's own `links.oneNoteClientUrl`, which embeds the same `page-id={GUID}`. So the- * importer builds a `page-id GUID → noteId` map from each imported page's client URL, then rewrites- * every `onenote:` link whose target was imported into a Trilium internal link.+ * importer builds a `page-id GUID → {noteId, title}` map from each imported page's client URL, then+ * rewrites every `onenote:` link whose target was imported into a Trilium internal link.*- * Both pure functions here (extractPageId, rewritePageLinks) are deliberately free of any DB/Graph- * dependency so the two-pass resolution can be unit-tested with a plain resolver callback.+ * When the link's text matches the target page's title, it becomes a Trilium *reference link* (a chip+ * that renders the live note title) and the redundant adjacent "Web view" https link OneNote emits+ * alongside it is dropped. Otherwise the original link text is kept on a plain internal link.+ *+ * The pure functions here (extractPageId, rewritePageLinks) carry no DB/Graph dependency, so the+ * two-pass resolution can be unit-tested with a plain resolver callback.*/-import { parse } from "node-html-parser";+import { HTMLElement, type Node, NodeType, parse, TextNode } from "node-html-parser";++const GUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";++/** A resolved import target: the note created for a OneNote page, plus that page's title. */+export interface LinkTarget {+ noteId: string;+ title: string;+}/** Pulls the OneNote page-id GUID out of a link/URL, lowercased; null if there is none. */export function extractPageId(url: string | null | undefined): string | null {- const match = url?.match(/page-id=\{?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}?/i);+ const match = url?.match(new RegExp(`page-id=\\{?(${GUID})\\}?`, "i"));return match ? match[1].toLowerCase() : null;}/*** Rewrites the page's `onenote:` internal links: a link whose target page-id resolves (via `resolve`)- * to an imported note becomes a Trilium internal link (`#root/{noteId}`) with its original text kept;- * links to pages outside the import — and all non-`onenote:` links (e.g. the "Web view" https link) —- * are left untouched. Returns the input unchanged when nothing was rewritten, so callers can cheaply- * detect a no-op.+ * to an imported note becomes a Trilium internal link (`#root/{noteId}`). If the link text matches the+ * target's title it is rendered as a reference link and the adjacent redundant "Web view" link is+ * removed; otherwise the original text is preserved on a plain link. Links to pages outside the import+ * — and all non-`onenote:` links — are left untouched. Returns the input unchanged when nothing was+ * rewritten, so callers can cheaply detect a no-op.*/-export function rewritePageLinks(html: string, resolve: (pageId: string) => string | null): string {+export function rewritePageLinks(html: string, resolve: (pageId: string) => LinkTarget | null): string {const root = parse(html);let changed = false;@@ -38,12 +51,58 @@ export function rewritePageLinks(html: string, resolve: (pageId: string) => stricontinue;}const pageId = extractPageId(href);- const noteId = pageId ? resolve(pageId) : null;- if (noteId) {- anchor.setAttribute("href", `#root/${noteId}`);- changed = true;+ const target = pageId ? resolve(pageId) : null;+ if (!pageId || !target) {+ continue;}++ anchor.setAttribute("href", `#root/${target.noteId}`);+ if (textMatchesTitle(anchor.textContent, target.title)) {+ anchor.setAttribute("class", "reference-link");+ dropRedundantWebViewLink(anchor, pageId);+ }+ changed = true;}return changed ? root.toString() : html;}++function textMatchesTitle(text: string, title: string): boolean {+ return text.trim().toLowerCase() === title.trim().toLowerCase();+}++/**+ * Removes the "Web view" https link OneNote emits right after an internal link to the same page (it+ * carries the same page-id GUID), along with the `(…)` wrapper text around it, so what's left reads as+ * a single clean reference link rather than "Link ()".+ */+function dropRedundantWebViewLink(internalAnchor: HTMLElement, pageId: string) {+ const web = internalAnchor.nextElementSibling;+ if (!web || web.rawTagName?.toLowerCase() !== "a") {+ return;+ }+ const webHref = web.getAttribute("href") ?? "";+ // The web link is the same page's counterpart when its URL embeds the page-id GUID; guard against+ // accidentally matching an already-rewritten internal link.+ if (webHref.startsWith("#root/") || !containsGuid(webHref, pageId)) {+ return;+ }++ const before = internalAnchor.nextSibling;+ const after = web.nextSibling;+ web.remove();++ // Strip the surrounding "( … )" if the web link sat inside parentheses (the common OneNote shape).+ if (isText(before) && isText(after) && /\(\s*$/.test(before.rawText) && /^\s*\)/.test(after.rawText)) {+ before.rawText = before.rawText.replace(/\s*\(\s*$/, "");+ after.rawText = after.rawText.replace(/^\s*\)/, "");+ }+}++function containsGuid(url: string, guid: string): boolean {+ return url.toLowerCase().includes(guid.toLowerCase());+}++function isText(node: Node | null | undefined): node is TextNode {+ return node?.nodeType === NodeType.TEXT_NODE;+}