Skip to content

Build your personal knowledge base with Trilium Notes

feat(server): write an import report into the OneNote import root note

Elian Doran38fa945a3869
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index b305db1c82..c5d1497713 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -329,7 +329,28 @@
"note-cannot-be-displayed": "This note type cannot be displayed."
},
"onenote_import": {
- "root-title": "OneNote import"
+ "root-title": "OneNote import",
+ "report": {
+ "row-pages": "Pages imported successfully",
+ "row-notebooks": "Notebooks imported",
+ "row-sections": "Sections imported",
+ "row-duration": "Total import duration",
+ "row-images": "Images",
+ "row-attachments": "File attachments",
+ "row-ink": "Pages with handwriting or drawings",
+ "row-links": "Cross-page links",
+ "row-throttling": "Time throttled by Microsoft Graph",
+ "value-links": "{{resolved}} resolved, {{unresolved}} pointing outside the imported selection",
+ "value-throttling_one": "{{- wait}} ({{count}} throttled request)",
+ "value-throttling_other": "{{- wait}} ({{count}} throttled requests)",
+ "failed-pages-title": "Pages that could not be imported",
+ "failed-pages-page": "Page",
+ "failed-pages-section": "Section",
+ "failed-pages-error": "Error",
+ "failed-resources-title": "Missing images and attachments",
+ "failed-resources-item_one": "{{- pageLink}}: {{count}} resource could not be downloaded",
+ "failed-resources-item_other": "{{- pageLink}}: {{count}} resources could not be downloaded"
+ }
},
"notion_import": {
"root-title": "Notion import",
diff --git a/apps/server/src/services/import/onenote/graph.spec.ts b/apps/server/src/services/import/onenote/graph.spec.ts
index 20b3587986..1bded2e9d4 100644
--- a/apps/server/src/services/import/onenote/graph.spec.ts
+++ b/apps/server/src/services/import/onenote/graph.spec.ts
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../../safe_fetch.js", () => ({ safeFetch: vi.fn() }));
import { safeFetch } from "../../safe_fetch.js";
-import { backoffDelayMs, extractGraphErrorDetail, getAccount, getPageContent, getResource, listPages, resetThrottleGate, retryAfterMs } from "./graph.js";
+import { backoffDelayMs, extractGraphErrorDetail, getAccount, getPageContent, getResource, getThrottleStats, listPages, resetThrottleGate, resetThrottleStats, retryAfterMs } from "./graph.js";
const safeFetchMock = vi.mocked(safeFetch);
@@ -95,6 +95,26 @@ describe("throttling retries", () => {
expect(safeFetchMock).toHaveBeenCalledTimes(2);
});
+ it("accumulates throttle statistics for the import report", async () => {
+ resetThrottleStats();
+ let calls = 0;
+ safeFetchMock.mockImplementation(async () => {
+ calls++;
+ return calls <= 3 ? graphResponse(429, "", { "Retry-After": "30" }) : graphResponse(200, JSON.stringify({ displayName: "Ada" }));
+ });
+
+ const promise = getAccount("token");
+ await vi.runAllTimersAsync();
+ await expect(promise).resolves.toEqual({ name: "Ada", email: "" });
+
+ // Three throttled responses, each pushing the shared gate 30s past "now" — the accumulated
+ // wait reflects wall-clock time spent throttled (gate extensions), not a per-request sum.
+ expect(getThrottleStats()).toEqual({ requestCount: 3, waitMs: 90_000 });
+
+ resetThrottleStats();
+ expect(getThrottleStats()).toEqual({ requestCount: 0, waitMs: 0 });
+ });
+
it("gives up with the throttled response once the wait budget is exhausted", async () => {
safeFetchMock.mockImplementation(async () =>
graphResponse(429, JSON.stringify({ error: { code: "20166", message: "Too many requests" } })));
diff --git a/apps/server/src/services/import/onenote/graph.ts b/apps/server/src/services/import/onenote/graph.ts
index 404ffbeb45..3eecd692fa 100644
--- a/apps/server/src/services/import/onenote/graph.ts
+++ b/apps/server/src/services/import/onenote/graph.ts
@@ -42,6 +42,13 @@ const MAX_GATEWAY_TIMEOUT_RETRIES = 5;
// "don't send until" timestamp that ALL requests wait on, so the whole pool backs off together.
let throttledUntilMs = 0;
+// Aggregate throttle statistics for the current import, surfaced in the import report (they answer
+// "why did this take hours?"). `requestCount` counts throttled (429/503) responses; `waitMs`
+// accumulates net extensions of the shared gate — wall-clock time spent waiting out throttles —
+// rather than a per-request sum, since concurrent requests wait on the same gate window.
+let throttledRequestCount = 0;
+let throttleWaitMs = 0;
+
/**
* Fetches a Microsoft Graph URL through {@link safeFetch} so the request is hardened against SSRF —
* pagination (`@odata.nextLink`) and resource URLs come from Graph responses and page HTML, so they
@@ -102,6 +109,8 @@ async function graphFetch(accessToken: string, url: string): Promise<Response> {
// Extend the shared gate (Math.max: simultaneous 429s converge on one window rather than
// stacking). The wait itself happens at the top of the next iteration, shared across the pool.
+ throttledRequestCount++;
+ throttleWaitMs += Math.max(0, Date.now() + waitMs - Math.max(throttledUntilMs, Date.now()));
throttledUntilMs = Math.max(throttledUntilMs, Date.now() + waitMs);
throttleAttempt++;
getLog().info(`OneNote import: Graph throttled (HTTP ${response.status}) on ${url}; retry ${throttleAttempt} after ${waitMs}ms (${Math.round((giveUpAtMs - Date.now()) / 60_000)}min of wait budget left)`);
@@ -135,6 +144,17 @@ export function resetThrottleGate(): void {
throttledUntilMs = 0;
}
+/** Returns the throttle statistics accumulated since the last {@link resetThrottleStats}. */
+export function getThrottleStats(): { requestCount: number; waitMs: number } {
+ return { requestCount: throttledRequestCount, waitMs: throttleWaitMs };
+}
+
+/** Resets the throttle statistics; called at the start of an import so its report covers only itself. */
+export function resetThrottleStats(): void {
+ throttledRequestCount = 0;
+ throttleWaitMs = 0;
+}
+
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@@ -399,5 +419,7 @@ export default {
listNotebooks,
listPages,
getPageContent,
- getResource
+ getResource,
+ getThrottleStats,
+ resetThrottleStats
};
diff --git a/apps/server/src/services/import/onenote/importer.spec.ts b/apps/server/src/services/import/onenote/importer.spec.ts
index c806d92f29..4fcce24536 100644
--- a/apps/server/src/services/import/onenote/importer.spec.ts
+++ b/apps/server/src/services/import/onenote/importer.spec.ts
@@ -1,4 +1,4 @@
-import { becca, cls } from "@triliumnext/core";
+import { becca, cls, note_service as noteService } from "@triliumnext/core";
import { beforeAll, describe, expect, it, vi } from "vitest";
import sqlInit from "../../sql_init.js";
@@ -11,7 +11,9 @@ vi.mock("./graph.js", () => ({
listNotebooks: vi.fn(),
listPages: vi.fn(),
getPageContent: vi.fn(),
- getResource: vi.fn()
+ getResource: vi.fn(),
+ getThrottleStats: vi.fn(() => ({ requestCount: 0, waitMs: 0 })),
+ resetThrottleStats: vi.fn()
}
}));
@@ -103,4 +105,36 @@ describe("importSelection (real DB)", () => {
const sectionNote = Object.values(becca.notes).find((note) => note.title === "Section");
expect(sectionNote?.getOwnedLabelValue("oneNotePageId")).toBeNull();
});
+
+ it("writes an import report as the root import note's content", async () => {
+ graphMock.listPages.mockResolvedValue([
+ { id: "1-abc", title: "Report Page One", level: 0 },
+ { id: "1-def", title: "Report Page Two", level: 0 }
+ ]);
+ graphMock.getPageContent.mockResolvedValue({ html: "<p>hello</p>", inkml: "" });
+
+ const parent = cls.init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title: "report parent",
+ content: "",
+ type: "text",
+ mime: "text/html"
+ }).note);
+
+ await cls.init(() => importSelection({
+ accessToken: "token",
+ parentNoteId: parent.noteId,
+ sections: [{ id: "sec-2", title: "Report Section", groupPath: [], notebookId: "nb-2", notebookTitle: "Report Notebook" }],
+ taskId: "task-report"
+ }));
+
+ const rootImportNote = parent.getChildNotes()[0];
+ const content = rootImportNote?.getContent() as string;
+ expect(content).toContain('<tr><th scope="row">Pages imported successfully</th><td>2/2 (100%)</td></tr>');
+ expect(content).toContain('<tr><th scope="row">Sections imported</th><td>1</td></tr>');
+ // Nothing failed and no optional stats apply (no images, ink, links, or throttling), so the
+ // happy-path report stays a compact summary table without failure sections or extra rows.
+ expect(content).not.toContain("could not be");
+ expect(content).not.toContain("Images");
+ });
});
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.ts
index 62ef8ba87e..3f7d38f72c 100644
--- a/apps/server/src/services/import/onenote/importer.ts
+++ b/apps/server/src/services/import/onenote/importer.ts
@@ -15,6 +15,7 @@ import converter, { ONENOTE_ATTACHMENT_CLASS } from "./converter.js";
import graph, { type OneNotePage } from "./graph.js";
import { inkmlToSvg } from "./inkml.js";
import { type LinkTarget, rewritePageLinks } from "./links.js";
+import { type ImportReportData, renderImportReport } from "./report.js";
interface FetchedPage {
/**
@@ -37,6 +38,8 @@ interface FetchedPage {
inkSvg: string | null;
/** Binary resources (images, file attachments) referenced by the page, downloaded up front. */
resources: DownloadedResource[];
+ /** How many of the page's resources failed to download (skipped, reported in the import report). */
+ failedResourceCount: number;
/** 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. */
@@ -73,6 +76,8 @@ interface FetchedSection {
*/
export async function importSelection({ accessToken, parentNoteId, sections, taskId, debug = false, shrinkImages = false }: { accessToken: string; parentNoteId: string; sections: OneNoteSectionSelection[]; taskId: string; debug?: boolean; shrinkImages?: boolean }): Promise<void> {
const taskContext = TaskContext.getInstance(taskId, "importNotes", { safeImport: true, shrinkImages });
+ const startedAtMs = Date.now();
+ graph.resetThrottleStats();
try {
// Phase 1: pull everything over the network first, so note creation can run in a single
@@ -92,8 +97,8 @@ export async function importSelection({ accessToken, parentNoteId, sections, tas
for (const page of pages) {
const { html: rawHtml, inkml } = await graph.getPageContent(accessToken, page.id);
const html = converter.convertPageHtml(rawHtml);
- const resources = await downloadPageResources(accessToken, page.title, html);
- fetchedPages.push({ id: page.id, title: page.title, level: page.level, pageId: page.pageId, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources, createdDateTime: page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime });
+ const { resources, failedResourceCount } = await downloadPageResources(accessToken, page.title, html);
+ fetchedPages.push({ id: page.id, title: page.title, level: page.level, pageId: page.pageId, html, rawHtml, rawInkml: inkml, inkSvg: inkmlToSvg(inkml), resources, failedResourceCount, createdDateTime: page.createdDateTime, lastModifiedDateTime: page.lastModifiedDateTime });
taskContext.increaseProgressCount();
}
fetched.push({
@@ -110,7 +115,7 @@ export async function importSelection({ accessToken, parentNoteId, sections, tas
}
// Phase 2: create the note tree.
- const rootNoteId = sql.transactional(() => createNotes(parentNoteId, fetched, debug, shrinkImages));
+ const rootNoteId = sql.transactional(() => createNotes(parentNoteId, fetched, debug, shrinkImages, startedAtMs));
taskContext.taskSucceeded({ parentNoteId, importedNoteId: rootNoteId });
} catch (e: unknown) {
@@ -119,7 +124,7 @@ export async function importSelection({ accessToken, parentNoteId, sections, tas
}
}
-function createNotes(parentNoteId: string, sections: FetchedSection[], debug: boolean, shrinkImages: boolean): string {
+function createNotes(parentNoteId: string, sections: FetchedSection[], debug: boolean, shrinkImages: boolean, startedAtMs: number): string {
const parentNote = becca.getNoteOrThrow(parentNoteId);
const isProtected = parentNote.isProtected && protectedSession.isProtectedSessionAvailable();
@@ -221,8 +226,18 @@ 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).
+ let resolvedLinkCount = 0;
+ let unresolvedLinkCount = 0;
for (const { note, original, content, page } of createdPages) {
- const finalContent = rewritePageLinks(content, (pageId) => targetByPageId.get(pageId) ?? null);
+ const finalContent = rewritePageLinks(content, (pageId) => {
+ const target = targetByPageId.get(pageId) ?? null;
+ if (target) {
+ resolvedLinkCount++;
+ } else {
+ unresolvedLinkCount++;
+ }
+ return target;
+ });
if (finalContent !== original) {
note.setContent(finalContent);
void noteService.asyncPostProcessContent(note, finalContent);
@@ -233,9 +248,48 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
applyOriginalDates(note, page.createdDateTime, page.lastModifiedDateTime);
}
+ // Finally, document the import's outcome as the root note's content — the task toast is ephemeral,
+ // and for a multi-hour import the user has likely walked away by the time it finishes.
+ const allPages = createdPages.map(({ note, page }) => ({ note, page }));
+ const throttleStats = graph.getThrottleStats();
+ const reportData: ImportReportData = {
+ importedPageCount: createdPages.length,
+ notebookCount: new Set(sections.map((section) => section.notebookId)).size,
+ sectionCount: sections.length,
+ durationMs: Date.now() - startedAtMs,
+ imageCount: sumResources(allPages, "image", () => 1),
+ imageBytes: sumResources(allPages, "image", (resource) => resource.content.length),
+ attachmentCount: sumResources(allPages, "file", () => 1),
+ attachmentBytes: sumResources(allPages, "file", (resource) => resource.content.length),
+ inkPageCount: allPages.filter(({ page }) => page.inkSvg !== null).length,
+ resolvedLinkCount,
+ unresolvedLinkCount,
+ throttledRequestCount: throttleStats.requestCount,
+ throttleWaitMs: throttleStats.waitMs,
+ // Filled in once fetch failures skip the page instead of aborting the import.
+ failedPages: [],
+ failedResources: allPages
+ .filter(({ page }) => page.failedResourceCount > 0)
+ .map(({ note, page }) => ({ pageTitle: page.title, pageNoteId: note.noteId, failedCount: page.failedResourceCount }))
+ };
+ rootNote.setContent(renderImportReport(reportData));
+
return rootNote.noteId;
}
+/** Totals `value` over every downloaded page resource of the given kind. */
+function sumResources(pages: { page: FetchedPage }[], kind: DownloadedResource["kind"], value: (resource: DownloadedResource) => number): number {
+ let sum = 0;
+ for (const { page } of pages) {
+ for (const resource of page.resources) {
+ if (resource.kind === kind) {
+ sum += value(resource);
+ }
+ }
+ }
+ return sum;
+}
+
/**
* Maps OneNote's flat, display-ordered page list (each page tagged with an indentation `level`) to a
* parent-child tree. Returns, for each page, the index of its parent page — the nearest preceding page
@@ -293,7 +347,7 @@ function renderInkFigure(note: BNote, svg: string, shrinkImages: boolean): strin
* downloads each once. Failures are logged and skipped so one missing resource doesn't abort the whole
* import; the reference is simply left untouched.
*/
-async function downloadPageResources(accessToken: string, pageTitle: string, html: string): Promise<DownloadedResource[]> {
+async function downloadPageResources(accessToken: string, pageTitle: string, html: string): Promise<{ resources: DownloadedResource[]; failedResourceCount: number }> {
const root = parse(html);
const refs = new Map<string, Omit<DownloadedResource, "content">>();
@@ -312,7 +366,7 @@ async function downloadPageResources(accessToken: string, pageTitle: string, htm
}
if (refs.size === 0) {
- return [];
+ return { resources: [], failedResourceCount: 0 };
}
const all = Array.from(refs.values());
@@ -337,7 +391,7 @@ async function downloadPageResources(accessToken: string, pageTitle: string, htm
const failed = all.length - resources.length;
const totalBytes = resources.reduce((sum, resource) => sum + resource.content.length, 0);
getLog().info(`OneNote import: page '${pageTitle}' downloaded ${resources.length}/${all.length} resource(s) (${Math.round(totalBytes / 1024)} KiB)${failed > 0 ? `; ${failed} failed and were skipped` : ""}`);
- return resources;
+ return { resources, failedResourceCount: failed };
}
/**
diff --git a/apps/server/src/services/import/onenote/report.spec.ts b/apps/server/src/services/import/onenote/report.spec.ts
new file mode 100644
index 0000000000..1483f4ebb6
--- /dev/null
+++ b/apps/server/src/services/import/onenote/report.spec.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it } from "vitest";
+
+import { formatDuration, formatSize, type ImportReportData, renderImportReport } from "./report.js";
+
+/** A successful import's report data; tests override the aspect they exercise. */
+function reportData(overrides: Partial<ImportReportData> = {}): ImportReportData {
+ return {
+ importedPageCount: 12,
+ notebookCount: 1,
+ sectionCount: 2,
+ durationMs: 90_000,
+ imageCount: 4,
+ imageBytes: 2 * 1024 * 1024,
+ attachmentCount: 1,
+ attachmentBytes: 512,
+ inkPageCount: 3,
+ resolvedLinkCount: 5,
+ unresolvedLinkCount: 1,
+ throttledRequestCount: 7,
+ throttleWaitMs: 3 * 60_000,
+ failedPages: [],
+ failedResources: [],
+ ...overrides
+ };
+}
+
+describe("formatDuration", () => {
+ it("scales units with the magnitude", () => {
+ expect(formatDuration(42_000)).toBe("42s");
+ expect(formatDuration(5 * 60_000 + 3_000)).toBe("5m 3s");
+ expect(formatDuration(2 * 3_600_000 + 41 * 60_000)).toBe("2h 41m");
+ expect(formatDuration(0)).toBe("0s");
+ });
+});
+
+describe("formatSize", () => {
+ it("scales units with the magnitude", () => {
+ expect(formatSize(512)).toBe("512 B");
+ expect(formatSize(1_536)).toBe("1.5 KiB");
+ expect(formatSize(12 * 1024)).toBe("12 KiB");
+ expect(formatSize(2 * 1024 * 1024)).toBe("2 MiB");
+ });
+});
+
+describe("renderImportReport", () => {
+ it("summarizes a fully successful import as a heading-column table without failure sections", () => {
+ const html = renderImportReport(reportData());
+
+ expect(html).toContain('<tr><th scope="row">Pages imported successfully</th><td>12/12 (100%)</td></tr>');
+ expect(html).toContain('<tr><th scope="row">Notebooks imported</th><td>1</td></tr>');
+ expect(html).toContain('<tr><th scope="row">Sections imported</th><td>2</td></tr>');
+ expect(html).toContain('<tr><th scope="row">Total import duration</th><td>1m 30s</td></tr>');
+ expect(html).toContain('<tr><th scope="row">Images</th><td>4 (2 MiB)</td></tr>');
+ expect(html).toContain('<tr><th scope="row">File attachments</th><td>1 (512 B)</td></tr>');
+ expect(html).toContain('<tr><th scope="row">Pages with handwriting or drawings</th><td>3</td></tr>');
+ expect(html).toContain('<tr><th scope="row">Cross-page links</th><td>5 resolved, 1 pointing outside the imported selection</td></tr>');
+ expect(html).toContain('<tr><th scope="row">Time throttled by Microsoft Graph</th><td>3m 0s (7 throttled requests)</td></tr>');
+ expect(html).toContain('<figure class="table">');
+ expect(html).not.toContain("could not be imported");
+ expect(html).not.toContain("could not be downloaded");
+ });
+
+ it("omits zero-valued rows from the summary table", () => {
+ const html = renderImportReport(reportData({
+ imageCount: 0,
+ imageBytes: 0,
+ attachmentCount: 0,
+ attachmentBytes: 0,
+ inkPageCount: 0,
+ resolvedLinkCount: 0,
+ unresolvedLinkCount: 0,
+ throttledRequestCount: 0,
+ throttleWaitMs: 0
+ }));
+
+ expect(html).toContain("Pages imported successfully");
+ expect(html).toContain("Total import duration");
+ expect(html).not.toContain("Images");
+ expect(html).not.toContain("File attachments");
+ expect(html).not.toContain("handwriting");
+ expect(html).not.toContain("Cross-page links");
+ expect(html).not.toContain("throttled");
+ });
+
+ it("lists failed pages with reference links and escaped titles/errors", () => {
+ const html = renderImportReport(reportData({
+ importedPageCount: 10,
+ failedPages: [
+ { title: "Meeting <notes>", sectionTitle: "Work & Archive", noteId: "ph1", error: "HTTP 504" },
+ { title: "Recipes", sectionTitle: "Kitchen", noteId: "ph2", error: "HTTP 504" }
+ ]
+ }));
+
+ // 10 of 12 pages: the percentage is floored so a lossy import never rounds up to 100%.
+ expect(html).toContain('<tr><th scope="row">Pages imported successfully</th><td>10/12 (83%)</td></tr>');
+ expect(html).toContain("Pages that could not be imported");
+ expect(html).toContain('<a class="reference-link" href="#root/ph1">Meeting &lt;notes&gt;</a>');
+ expect(html).toContain("Work &amp; Archive");
+ expect(html).toContain("HTTP 504");
+ });
+
+ it("lists pages with failed resource downloads, with per-page counts", () => {
+ const html = renderImportReport(reportData({
+ failedResources: [
+ { pageTitle: "Gallery", pageNoteId: "n1", failedCount: 3 },
+ { pageTitle: "Scans", pageNoteId: "n2", failedCount: 1 }
+ ]
+ }));
+
+ expect(html).toContain("Missing images and attachments");
+ expect(html).toContain('<a class="reference-link" href="#root/n1">Gallery</a>: 3 resources could not be downloaded');
+ expect(html).toContain('<a class="reference-link" href="#root/n2">Scans</a>: 1 resource could not be downloaded');
+ });
+});
diff --git a/apps/server/src/services/import/onenote/report.ts b/apps/server/src/services/import/onenote/report.ts
new file mode 100644
index 0000000000..5ffe069db4
--- /dev/null
+++ b/apps/server/src/services/import/onenote/report.ts
@@ -0,0 +1,134 @@
+/**
+ * Renders the import report placed as the content of the root "OneNote import" note. The task toast
+ * is ephemeral — for a multi-hour import the user has likely walked away — so the root note is where
+ * the outcome is documented: what was imported, what failed (with links to the affected notes), and
+ * the statistics that explain the import's duration.
+ */
+
+import { utils } from "@triliumnext/core";
+import { t } from "i18next";
+
+/** A page whose content could not be fetched; `noteId` is the placeholder note created in its stead. */
+export interface FailedPageReport {
+ title: string;
+ sectionTitle: string;
+ noteId: string;
+ error: string;
+}
+
+/** A page for which one or more image/attachment downloads failed (the page itself was imported). */
+export interface FailedResourceReport {
+ pageTitle: string;
+ pageNoteId: string;
+ failedCount: number;
+}
+
+export interface ImportReportData {
+ importedPageCount: number;
+ notebookCount: number;
+ sectionCount: number;
+ durationMs: number;
+ imageCount: number;
+ imageBytes: number;
+ attachmentCount: number;
+ attachmentBytes: number;
+ /** Pages whose handwriting/drawings (InkML) were converted to an embedded SVG. */
+ inkPageCount: number;
+ /** Cross-page `onenote:` links rewritten to point at an imported note. */
+ resolvedLinkCount: number;
+ /** Cross-page links whose target page was not part of the imported selection. */
+ unresolvedLinkCount: number;
+ throttledRequestCount: number;
+ throttleWaitMs: number;
+ failedPages: FailedPageReport[];
+ failedResources: FailedResourceReport[];
+}
+
+export function renderImportReport(data: ImportReportData): string {
+ const parts: string[] = [];
+
+ parts.push(renderSummaryTable(data));
+
+ if (data.failedPages.length > 0) {
+ const rows = data.failedPages.map((page) =>
+ `<tr><td>${noteLink(page.noteId, page.title)}</td><td>${utils.escapeHtml(page.sectionTitle)}</td><td>${utils.escapeHtml(page.error)}</td></tr>`);
+ parts.push(`<h2>${t("onenote_import.report.failed-pages-title")}</h2>`
+ + `<figure class="table"><table><thead><tr><th>${t("onenote_import.report.failed-pages-page")}</th><th>${t("onenote_import.report.failed-pages-section")}</th><th>${t("onenote_import.report.failed-pages-error")}</th></tr></thead>`
+ + `<tbody>${rows.join("")}</tbody></table></figure>`);
+ }
+
+ if (data.failedResources.length > 0) {
+ const items = data.failedResources.map((resource) =>
+ `<li>${t("onenote_import.report.failed-resources-item", { pageLink: noteLink(resource.pageNoteId, resource.pageTitle), count: resource.failedCount })}</li>`);
+ parts.push(`<h2>${t("onenote_import.report.failed-resources-title")}</h2><ul>${items.join("")}</ul>`);
+ }
+
+ return parts.join("");
+}
+
+/**
+ * The report's lead: a two-column key-value table (heading column, no heading row) with one row per
+ * metric. Rows whose metric does not apply to this import (no images, no throttling, …) are omitted
+ * so a plain import stays compact.
+ */
+function renderSummaryTable(data: ImportReportData): string {
+ const totalPageCount = data.importedPageCount + data.failedPages.length;
+ // Floored so a lossy import never rounds up to a reassuring 100%.
+ const successPercent = totalPageCount === 0 ? 100 : Math.floor((data.importedPageCount / totalPageCount) * 100);
+
+ const rows: [string, string | number][] = [
+ [t("onenote_import.report.row-pages"), `${data.importedPageCount}/${totalPageCount} (${successPercent}%)`],
+ [t("onenote_import.report.row-notebooks"), data.notebookCount],
+ [t("onenote_import.report.row-sections"), data.sectionCount],
+ [t("onenote_import.report.row-duration"), formatDuration(data.durationMs)]
+ ];
+ if (data.imageCount > 0) {
+ rows.push([t("onenote_import.report.row-images"), `${data.imageCount} (${formatSize(data.imageBytes)})`]);
+ }
+ if (data.attachmentCount > 0) {
+ rows.push([t("onenote_import.report.row-attachments"), `${data.attachmentCount} (${formatSize(data.attachmentBytes)})`]);
+ }
+ if (data.inkPageCount > 0) {
+ rows.push([t("onenote_import.report.row-ink"), data.inkPageCount]);
+ }
+ if (data.resolvedLinkCount > 0 || data.unresolvedLinkCount > 0) {
+ rows.push([t("onenote_import.report.row-links"), t("onenote_import.report.value-links", { resolved: data.resolvedLinkCount, unresolved: data.unresolvedLinkCount })]);
+ }
+ if (data.throttledRequestCount > 0) {
+ rows.push([t("onenote_import.report.row-throttling"), t("onenote_import.report.value-throttling", { count: data.throttledRequestCount, wait: formatDuration(data.throttleWaitMs) })]);
+ }
+
+ const body = rows.map(([label, value]) => `<tr><th scope="row">${label}</th><td>${value}</td></tr>`).join("");
+ return `<figure class="table"><table><tbody>${body}</tbody></table></figure>`;
+}
+
+/** An internal Trilium link to a note, as CKEditor produces them. */
+function noteLink(noteId: string, title: string): string {
+ return `<a class="reference-link" href="#root/${noteId}">${utils.escapeHtml(title)}</a>`;
+}
+
+/** Formats a duration compactly at a precision matching its magnitude: "42s", "5m 3s", "2h 41m". */
+export function formatDuration(ms: number): string {
+ const totalSeconds = Math.round(ms / 1000);
+ const hours = Math.floor(totalSeconds / 3600);
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
+ const seconds = totalSeconds % 60;
+ if (hours > 0) {
+ return `${hours}h ${minutes}m`;
+ }
+ if (minutes > 0) {
+ return `${minutes}m ${seconds}s`;
+ }
+ return `${seconds}s`;
+}
+
+/** Formats a byte count with a binary unit and at most one decimal: "512 B", "1.5 KiB", "183 MiB". */
+export function formatSize(bytes: number): string {
+ if (bytes < 1024) {
+ return `${bytes} B`;
+ }
+ if (bytes < 1024 * 1024) {
+ return `${Math.round((bytes / 1024) * 10) / 10} KiB`;
+ }
+ return `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MiB`;
+}