Skip to content

Build your personal knowledge base with Trilium Notes

test(import/export): cover server & core paths flagged by codecov

Elian Dorand1f398256b87
diff --git a/apps/server/src/routes/route_api.spec.ts b/apps/server/src/routes/route_api.spec.ts
index f390b1bd75..b089aa06e5 100644
--- a/apps/server/src/routes/route_api.spec.ts
+++ b/apps/server/src/routes/route_api.spec.ts
@@ -3,7 +3,7 @@ import { existsSync } from "fs";
import request from "supertest";
import { describe, expect, it } from "vitest";
-import { importMiddlewareWithErrorHandling } from "./route_api.js";
+import { importMiddlewareWithErrorHandling, uploadMiddlewareWithErrorHandling } from "./route_api.js";
/** Minimal app mounting only the import middleware + a handler that reports what it received. */
function buildApp() {
@@ -23,6 +23,20 @@ function buildApp() {
return app;
}
+/** Minimal app mounting the in-memory upload middleware + a handler that reports the buffered file. */
+function buildUploadApp() {
+ const app = express();
+ app.post("/upload", uploadMiddlewareWithErrorHandling, (req, res) => {
+ const file = req.file;
+ res.json({
+ hasFile: !!file,
+ content: file?.buffer?.toString("utf-8"),
+ originalname: file?.originalname
+ });
+ });
+ return app;
+}
+
describe("importMiddlewareWithErrorHandling (disk storage)", () => {
it("streams a generic .zip from its temp path: no buffer, temp kept for the importer", async () => {
const res = await request(buildApp())
@@ -78,4 +92,43 @@ describe("importMiddlewareWithErrorHandling (disk storage)", () => {
expect(res.status).toBe(200);
expect(res.body.hasFile).toBe(false);
});
+
+ it("rejects a nested multipart field name with a 400 (CVE-2026-5079 guard)", async () => {
+ const res = await request(buildApp())
+ .post("/import")
+ .field("a[b]", "x")
+ .attach("upload", Buffer.from("PK-zip-bytes"), "backup.zip");
+
+ expect(res.status).toBe(400);
+ expect(res.text).toContain("nested multipart field names are not allowed");
+ });
+});
+
+describe("uploadMiddlewareWithErrorHandling (in-memory)", () => {
+ it("buffers a small upload into file.buffer", async () => {
+ const res = await request(buildUploadApp())
+ .post("/upload")
+ .attach("upload", Buffer.from("<svg/>"), "icon.svg");
+
+ expect(res.status).toBe(200);
+ expect(res.body.content).toBe("<svg/>");
+ expect(res.body.originalname).toBe("icon.svg");
+ });
+
+ it("rejects a nested multipart field name with a 400 (CVE-2026-5079 guard)", async () => {
+ const res = await request(buildUploadApp())
+ .post("/upload")
+ .field("a[b]", "x")
+ .attach("upload", Buffer.from("<svg/>"), "icon.svg");
+
+ expect(res.status).toBe(400);
+ expect(res.text).toContain("nested multipart field names are not allowed");
+ });
+
+ it("proceeds to the handler when no file is uploaded", async () => {
+ const res = await request(buildUploadApp()).post("/upload");
+
+ expect(res.status).toBe(200);
+ expect(res.body.hasFile).toBe(false);
+ });
});
diff --git a/apps/server/src/services/cpu_profiler.spec.ts b/apps/server/src/services/cpu_profiler.spec.ts
new file mode 100644
index 0000000000..1661a78d1b
--- /dev/null
+++ b/apps/server/src/services/cpu_profiler.spec.ts
@@ -0,0 +1,155 @@
+import fs from "fs";
+import type inspector from "inspector";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { startCpuProfiler, writeCpuProfile } from "./cpu_profiler.js";
+
+// A fake inspector session so the V8 inspector is never actually attached. `post` is driven by the test to
+// simulate the profiler stopping (with or without an error, or never at all).
+type PostImpl = (method: string, callback: (err: Error | null, result: { profile: unknown }) => void) => void;
+
+function fakeSession(post: PostImpl) {
+ return {
+ post: vi.fn(post),
+ connect: vi.fn(),
+ disconnect: vi.fn()
+ };
+}
+
+const inspectorState = vi.hoisted(() => ({
+ instances: [] as Array<{ connect: ReturnType<typeof vi.fn>; post: ReturnType<typeof vi.fn>; disconnect: ReturnType<typeof vi.fn> }>
+}));
+
+vi.mock("inspector", () => {
+ class Session {
+ connect = vi.fn();
+ post = vi.fn();
+ disconnect = vi.fn();
+ constructor() {
+ inspectorState.instances.push(this);
+ }
+ }
+ return { default: { Session } };
+});
+
+describe("writeCpuProfile", () => {
+ beforeEach(() => {
+ vi.spyOn(fs, "mkdirSync").mockImplementation(() => undefined);
+ vi.spyOn(fs, "writeFileSync").mockImplementation(() => undefined);
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ });
+
+ afterEach(() => vi.restoreAllMocks());
+
+ it("calls done immediately and writes nothing when profiling is disabled (null session)", () => {
+ const done = vi.fn();
+ writeCpuProfile(null, done);
+ expect(done).toHaveBeenCalledOnce();
+ expect(fs.writeFileSync).not.toHaveBeenCalled();
+ });
+
+ it("stops the profiler, writes the .cpuprofile, disconnects and calls done", () => {
+ const profile = { nodes: [1, 2, 3] };
+ const session = fakeSession((method, cb) => {
+ expect(method).toBe("Profiler.stop");
+ cb(null, { profile });
+ });
+ const done = vi.fn();
+
+ writeCpuProfile(session as unknown as inspector.Session, done);
+
+ expect(fs.mkdirSync).toHaveBeenCalledWith(expect.stringContaining("profiles"), { recursive: true });
+ expect(fs.writeFileSync).toHaveBeenCalledWith(expect.stringContaining(".cpuprofile"), JSON.stringify(profile));
+ expect(session.disconnect).toHaveBeenCalledOnce();
+ expect(done).toHaveBeenCalledOnce();
+ });
+
+ it("still disconnects and calls done when the profiler reports an error (no file written)", () => {
+ const session = fakeSession((_method, cb) => cb(new Error("profiler failed"), { profile: {} }));
+ const done = vi.fn();
+
+ writeCpuProfile(session as unknown as inspector.Session, done);
+
+ expect(fs.writeFileSync).not.toHaveBeenCalled();
+ expect(console.error).toHaveBeenCalled();
+ expect(session.disconnect).toHaveBeenCalledOnce();
+ expect(done).toHaveBeenCalledOnce();
+ });
+
+ it("swallows a write failure but still disconnects and calls done", () => {
+ vi.mocked(fs.writeFileSync).mockImplementation(() => {
+ throw new Error("disk full");
+ });
+ const session = fakeSession((_method, cb) => cb(null, { profile: {} }));
+ const done = vi.fn();
+
+ writeCpuProfile(session as unknown as inspector.Session, done);
+
+ expect(console.error).toHaveBeenCalled();
+ expect(session.disconnect).toHaveBeenCalledOnce();
+ expect(done).toHaveBeenCalledOnce();
+ });
+
+ it("falls back to calling done after a grace period when the profiler never responds", () => {
+ vi.useFakeTimers();
+ try {
+ // post never invokes its callback, simulating a stuck profiler.
+ const session = fakeSession(() => {});
+ const done = vi.fn();
+
+ writeCpuProfile(session as unknown as inspector.Session, done);
+ expect(done).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(3000);
+ expect(done).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe("startCpuProfiler", () => {
+ const original = process.env.TRILIUM_PROFILE;
+
+ beforeEach(() => {
+ inspectorState.instances.length = 0;
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ });
+
+ afterEach(() => {
+ if (original === undefined) {
+ delete process.env.TRILIUM_PROFILE;
+ } else {
+ process.env.TRILIUM_PROFILE = original;
+ }
+ vi.restoreAllMocks();
+ });
+
+ it("returns null and creates no session when TRILIUM_PROFILE is unset", () => {
+ delete process.env.TRILIUM_PROFILE;
+ expect(startCpuProfiler()).toBeNull();
+ expect(inspectorState.instances).toHaveLength(0);
+ });
+
+ it("connects and starts the profiler when TRILIUM_PROFILE is set", () => {
+ process.env.TRILIUM_PROFILE = "1";
+ const session = startCpuProfiler();
+
+ expect(session).not.toBeNull();
+ expect(inspectorState.instances).toHaveLength(1);
+ const created = inspectorState.instances[0];
+ expect(created.connect).toHaveBeenCalledOnce();
+ // Profiler.enable then Profiler.start.
+ expect(created.post).toHaveBeenCalledWith("Profiler.enable", expect.any(Function));
+ });
+
+ it("drives Profiler.enable then Profiler.start in sequence", () => {
+ process.env.TRILIUM_PROFILE = "1";
+ // Make each post() invoke its callback so the nested start() call fires too.
+ startCpuProfiler();
+ const created = inspectorState.instances[0];
+ created.post.mock.calls.find(([method]) => method === "Profiler.enable")?.[1]();
+ expect(created.post).toHaveBeenCalledWith("Profiler.start", expect.any(Function));
+ });
+});
diff --git a/apps/server/src/services/cpu_profiler.ts b/apps/server/src/services/cpu_profiler.ts
new file mode 100644
index 0000000000..18dde6f548
--- /dev/null
+++ b/apps/server/src/services/cpu_profiler.ts
@@ -0,0 +1,61 @@
+import fs from "fs";
+import inspector from "inspector";
+import path from "path";
+
+/**
+ * Starts the V8 CPU profiler when TRILIUM_PROFILE is set, returning the inspector session (or null when
+ * profiling is disabled). The companion {@link writeCpuProfile} stops it and writes the `.cpuprofile`.
+ *
+ * We drive the profiler ourselves rather than relying on Node's --cpu-prof flag: that flag flushes its file
+ * during the normal shutdown path, which the server's exit handler short-circuits with process.exit(0), so
+ * the profile would silently never be written.
+ */
+export function startCpuProfiler(): inspector.Session | null {
+ if (!process.env.TRILIUM_PROFILE) {
+ return null;
+ }
+
+ const session = new inspector.Session();
+ session.connect();
+ session.post("Profiler.enable", () => {
+ session.post("Profiler.start", () => {
+ console.log("CPU profiler started (TRILIUM_PROFILE). Press Enter in this terminal to write the profile and exit.");
+ });
+ });
+
+ return session;
+}
+
+/**
+ * Stops the profiler started by {@link startCpuProfiler}, writes the result into `profiles/` (relative to the
+ * working directory), then invokes `done`. When profiling is disabled, or if writing fails, `done` still runs
+ * so shutdown is never blocked.
+ */
+export function writeCpuProfile(session: inspector.Session | null, done: () => void) {
+ if (!session) {
+ done();
+ return;
+ }
+
+ // Don't let a stuck profiler hang shutdown — exit anyway after a short grace period.
+ const fallback = setTimeout(done, 3000);
+
+ session.post("Profiler.stop", (err, result) => {
+ clearTimeout(fallback);
+ try {
+ if (err) {
+ throw err;
+ }
+ const dir = path.resolve("profiles");
+ fs.mkdirSync(dir, { recursive: true });
+ const file = path.join(dir, `import-${process.pid}.cpuprofile`);
+ fs.writeFileSync(file, JSON.stringify(result.profile));
+ console.log(`CPU profile written to ${file}`);
+ } catch (e) {
+ console.error("Failed to write CPU profile:", e);
+ } finally {
+ session.disconnect();
+ done();
+ }
+ });
+}
diff --git a/apps/server/src/www.ts b/apps/server/src/www.ts
index 4886dcf963..f238204cd1 100644
--- a/apps/server/src/www.ts
+++ b/apps/server/src/www.ts
@@ -1,20 +1,18 @@
-import { app_info as appInfo, getMessagingProvider, getPlatform, utils } from "@triliumnext/core";
+import { app_info as appInfo, getLog, getMessagingProvider, getPlatform, utils } from "@triliumnext/core";
import type { Express } from "express";
import fs from "fs";
import http from "http";
import https from "https";
-import inspector from "inspector";
-import path from "path";
import tmp from "tmp";
import buildApp from "./app.js";
import config from "./services/config.js";
+import { startCpuProfiler, writeCpuProfile } from "./services/cpu_profiler.js";
import { registerOcrHandlers } from "./services/handlers.js";
import host from "./services/host.js";
-import { getLog } from "@triliumnext/core";
import port from "./services/port.js";
-import { getDbSize } from "./services/sql_init.js";
import { isScriptingEnabled } from "./services/scripting_guard.js";
+import { getDbSize } from "./services/sql_init.js";
import WebSocketMessagingProvider from "./services/ws_messaging_provider.js";
const MINIMUM_NODE_VERSION = "20.0.0";
@@ -99,60 +97,6 @@ export default async function startTriliumServer(): Promise<Express> {
return app;
}
-/**
- * Starts the V8 CPU profiler when TRILIUM_PROFILE is set, returning the inspector session (or null when
- * profiling is disabled). The companion {@link writeCpuProfile} stops it and writes the `.cpuprofile`.
- */
-function startCpuProfiler(): inspector.Session | null {
- if (!process.env.TRILIUM_PROFILE) {
- return null;
- }
-
- const session = new inspector.Session();
- session.connect();
- session.post("Profiler.enable", () => {
- session.post("Profiler.start", () => {
- console.log("CPU profiler started (TRILIUM_PROFILE). Press Enter in this terminal to write the profile and exit.");
- });
- });
-
- return session;
-}
-
-/**
- * Stops the profiler started by {@link startCpuProfiler}, writes the result into `profiles/` (relative to the
- * working directory), then invokes `done`. When profiling is disabled, or if writing fails, `done` still runs
- * so shutdown is never blocked.
- */
-function writeCpuProfile(session: inspector.Session | null, done: () => void) {
- if (!session) {
- done();
- return;
- }
-
- // Don't let a stuck profiler hang shutdown — exit anyway after a short grace period.
- const fallback = setTimeout(done, 3000);
-
- session.post("Profiler.stop", (err, result) => {
- clearTimeout(fallback);
- try {
- if (err) {
- throw err;
- }
- const dir = path.resolve("profiles");
- fs.mkdirSync(dir, { recursive: true });
- const file = path.join(dir, `import-${process.pid}.cpuprofile`);
- fs.writeFileSync(file, JSON.stringify(result.profile));
- console.log(`CPU profile written to ${file}`);
- } catch (e) {
- console.error("Failed to write CPU profile:", e);
- } finally {
- session.disconnect();
- done();
- }
- });
-}
-
async function displayStartupMessage() {
getLog().info(`\n${LOGO.replace("[version]", appInfo.appVersion)}`);
getLog().info(`📦 Versions: app=${appInfo.appVersion} db=${appInfo.dbVersion} sync=${appInfo.syncVersion} clipper=${appInfo.clipperProtocolVersion}`);
diff --git a/apps/server/src/zip_provider.spec.ts b/apps/server/src/zip_provider.spec.ts
index 0692571a27..8e7a708c71 100644
--- a/apps/server/src/zip_provider.spec.ts
+++ b/apps/server/src/zip_provider.spec.ts
@@ -1,4 +1,4 @@
-import type { ZipEntry } from "@triliumnext/core/src/services/zip_provider.js";
+import type { ZipArchive, ZipEntry } from "@triliumnext/core/src/services/zip_provider.js";
import { mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
@@ -9,6 +9,28 @@ import NodejsZipProvider from "./zip_provider.js";
const provider = new NodejsZipProvider();
+/** Drains an archive into its finalized bytes, collecting everything written to the pipe. */
+function pipeToBuffer(archive: ZipArchive): { sink: PassThrough; bytes: Promise<Buffer> } {
+ const sink = new PassThrough();
+ const chunks: Buffer[] = [];
+ sink.on("data", (chunk: Buffer) => chunks.push(chunk));
+ const bytes = new Promise<Buffer>((resolve, reject) => {
+ sink.on("end", () => resolve(Buffer.concat(chunks)));
+ sink.on("error", reject);
+ });
+ archive.pipe(sink);
+ return { sink, bytes };
+}
+
+/** Narrows the optional waitForCapacity to the concrete server implementation, which always defines it. */
+function capacityOf(archive: ZipArchive): () => Promise<void> {
+ const waitForCapacity = archive.waitForCapacity?.bind(archive);
+ if (!waitForCapacity) {
+ throw new Error("NodejsZipArchive is expected to implement waitForCapacity()");
+ }
+ return waitForCapacity;
+}
+
/** Builds an archive from the given entries and returns the finalized zip bytes. */
async function buildZip(entries: { name: string; content: string | Uint8Array }[]): Promise<Buffer> {
const archive = provider.createZipArchive();
@@ -75,6 +97,72 @@ describe("NodejsZipProvider", () => {
expect(entries["dir/b.txt"].toString("utf-8")).toBe("beta");
});
+ it("exposes each entry's last-modified date when reading", async () => {
+ const buffer = await buildZip([{ name: "a.txt", content: "x" }]);
+ let lastModified: Date | undefined;
+ await provider.readZipFile(buffer, async (entry: ZipEntry, readContent) => {
+ lastModified = entry.lastModified;
+ await readContent();
+ });
+ expect(lastModified).toBeInstanceOf(Date);
+ });
+
+ it("stores an entry uncompressed when `store` is set and still round-trips", async () => {
+ // Already-compressed payloads pass `store: true` to skip deflate; the bytes must survive intact.
+ const archive = provider.createZipArchive();
+ const { bytes } = pipeToBuffer(archive);
+ const payload = "already-compressed-bytes".repeat(16);
+ archive.append(payload, { name: "image.jpg", store: true });
+ await archive.finalize();
+
+ const entries = await readZip(await bytes);
+ expect(entries["image.jpg"].toString("utf-8")).toBe(payload);
+ });
+
+ describe("input backpressure (waitForCapacity)", () => {
+ it("resolves immediately when nothing is queued", async () => {
+ const archive = provider.createZipArchive();
+ await expect(capacityOf(archive)()).resolves.toBeUndefined();
+ });
+
+ it("stays pending past the high-water mark until the queued data drains", async () => {
+ const archive = provider.createZipArchive();
+ const { sink } = pipeToBuffer(archive);
+ // PassThrough is paused (no resume yet), so nothing is consumed and the appended entry stays
+ // queued. 65 MiB clears the 64 MiB high-water mark.
+ archive.append(new Uint8Array(65 * 1024 * 1024), { name: "big.bin" });
+
+ let resolved = false;
+ const capacity = capacityOf(archive)().then(() => {
+ resolved = true;
+ });
+ // Still over the mark with nothing consumed — must not have resolved.
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ // Draining the output fires archiver's "entry" event, dropping queued bytes below the mark.
+ sink.resume();
+ await capacity;
+ expect(resolved).toBe(true);
+ await archive.finalize();
+ });
+
+ it("re-surfaces an archiver error through append and waitForCapacity", async () => {
+ const archive = provider.createZipArchive();
+ const { sink } = pipeToBuffer(archive);
+ sink.resume();
+ await archive.finalize();
+
+ // Appending after finalize makes archiver emit "error" (queue closed); the archive captures it
+ // so a missing "error" listener can't crash the process.
+ archive.append("late", { name: "late.txt" });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(() => archive.append("later", { name: "later.txt" })).toThrow();
+ await expect(capacityOf(archive)()).rejects.toBeTruthy();
+ });
+ });
+
describe("reading from a path (in place, no full-buffer load)", () => {
const dir = mkdtempSync(join(tmpdir(), "trilium-zip-provider-spec-"));
afterAll(() => rmSync(dir, { recursive: true, force: true }));
diff --git a/apps/standalone/src/lightweight/zip_provider.spec.ts b/apps/standalone/src/lightweight/zip_provider.spec.ts
index 24f0ec471d..91fb645083 100644
--- a/apps/standalone/src/lightweight/zip_provider.spec.ts
+++ b/apps/standalone/src/lightweight/zip_provider.spec.ts
@@ -83,6 +83,41 @@ describe("BrowserZipArchive", () => {
});
});
+describe("BrowserZipArchive store + backpressure", () => {
+ it("round-trips an entry appended with store: true (uncompressed)", async () => {
+ const archive = provider.createZipArchive();
+ archive.append("already-compressed", { name: "image.jpg", store: true });
+
+ let sent: Uint8Array | undefined;
+ archive.pipe({ send: (body: unknown) => { sent = body as Uint8Array; } });
+ await archive.finalize();
+
+ const unzipped = unzipSync(sent ?? new Uint8Array());
+ expect(new TextDecoder().decode(unzipped["image.jpg"])).toBe("already-compressed");
+ });
+
+ it("waitForCapacity resolves immediately (the browser builds the archive in memory)", async () => {
+ const archive = provider.createZipArchive();
+ await expect(archive.waitForCapacity?.()).resolves.toBeUndefined();
+ });
+});
+
+describe("BrowserZipProvider path sources are unsupported", () => {
+ it("readZipFile throws for a { path } source", () => {
+ // readZipFile isn't async, so the guard throws synchronously before the work promise is created;
+ // real callers await it inside an async function, where the throw surfaces as a rejection anyway.
+ expect(() => provider.readZipFile({ path: "/tmp/x.zip" }, async () => {})).toThrow(
+ "Path-based zip reading is not supported in the browser"
+ );
+ });
+
+ it("detectFilenameEncoding rejects a { path } source", async () => {
+ await expect(provider.detectFilenameEncoding({ path: "/tmp/x.zip" })).rejects.toThrow(
+ "Path-based zip reading is not supported in the browser"
+ );
+ });
+});
+
describe("BrowserZipProvider.createFileStream", () => {
it("is unsupported in the browser", () => {
expect(() => provider.createFileStream("/tmp/x")).toThrow("File stream creation is not supported");
diff --git a/packages/trilium-core/src/services/import/dispatch.spec.ts b/packages/trilium-core/src/services/import/dispatch.spec.ts
new file mode 100644
index 0000000000..4208afb0eb
--- /dev/null
+++ b/packages/trilium-core/src/services/import/dispatch.spec.ts
@@ -0,0 +1,140 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type BNote from "../../becca/entities/bnote.js";
+import type TaskContext from "../task_context.js";
+import anytypeImportService from "./anytype/importer.js";
+import type { File } from "./common.js";
+import importFile, { type ImportOptions } from "./dispatch.js";
+import enexImportService from "./enex.js";
+import keepImportService from "./keep/importer.js";
+import notionImportService from "./notion/importer.js";
+import obsidianImportService from "./obsidian/importer.js";
+import opmlImportService from "./opml.js";
+import singleImportService from "./single.js";
+import zipImportService from "./zip.js";
+
+// dispatch only routes — it picks an importer and hands it a source. The server test setup eagerly loads
+// the core barrel, so the importer modules are already cached and vi.mock can't replace them; spying on the
+// real (singleton) service objects works regardless of load order. We stub each importer so nothing touches
+// the filesystem/DB, and assert which one ran and with what source (path vs. raw bytes) and extra arguments.
+const stubbed = {
+ importNotion: vi.spyOn(notionImportService, "importNotion").mockResolvedValue({} as BNote),
+ importKeep: vi.spyOn(keepImportService, "importKeep").mockResolvedValue({} as BNote),
+ importAnytype: vi.spyOn(anytypeImportService, "importAnytype").mockResolvedValue({} as BNote),
+ importObsidian: vi.spyOn(obsidianImportService, "importObsidian").mockResolvedValue({} as BNote),
+ importZip: vi.spyOn(zipImportService, "importZip").mockResolvedValue({} as BNote),
+ importOpml: vi.spyOn(opmlImportService, "importOpml").mockResolvedValue({} as BNote),
+ importEnex: vi.spyOn(enexImportService, "importEnex").mockResolvedValue({} as BNote),
+ importSingleFile: vi.spyOn(singleImportService, "importSingleFile").mockResolvedValue({} as BNote)
+};
+
+const taskContext = {} as TaskContext<"importNotes">;
+const parentNote = { noteId: "parent" } as BNote;
+
+function makeOptions(overrides: Partial<ImportOptions> = {}): ImportOptions {
+ return {
+ safeImport: false,
+ shrinkImages: false,
+ textImportedAsText: true,
+ codeImportedAsCode: true,
+ spreadsheetImportedAsSpreadsheet: true,
+ explodeArchives: true,
+ replaceUnderscoresWithSpaces: false,
+ ...overrides
+ };
+}
+
+function makeFile(overrides: Partial<File> = {}): File {
+ return {
+ originalname: "data.zip",
+ mimetype: "application/zip",
+ buffer: new Uint8Array([1, 2, 3]),
+ ...overrides
+ };
+}
+
+describe("importFile (dispatch)", () => {
+ afterEach(() => vi.clearAllMocks());
+
+ describe("tagged providers (the upload is a plain .zip the dialog disambiguates by format)", () => {
+ it("routes a notion-tagged upload to the Notion importer, reading from the temp path", async () => {
+ const file = makeFile({ path: "/tmp/up.zip" });
+ await importFile(taskContext, file, parentNote, makeOptions(), "notion");
+ expect(stubbed.importNotion).toHaveBeenCalledWith(taskContext, { path: "/tmp/up.zip" }, parentNote);
+ });
+
+ it("falls back to the raw bytes when there is no temp path (browser/WASM upload)", async () => {
+ const buffer = new Uint8Array([9, 8, 7]);
+ const file = makeFile({ buffer, path: undefined });
+ await importFile(taskContext, file, parentNote, makeOptions(), "notion");
+ expect(stubbed.importNotion).toHaveBeenCalledWith(taskContext, buffer, parentNote);
+ });
+
+ it("routes a keep-tagged upload to the Keep importer", async () => {
+ const file = makeFile({ path: "/tmp/keep.zip" });
+ await importFile(taskContext, file, parentNote, makeOptions(), "keep");
+ expect(stubbed.importKeep).toHaveBeenCalledWith(taskContext, { path: "/tmp/keep.zip" }, parentNote);
+ });
+
+ it("routes an anytype-tagged upload to the Anytype importer, passing the original name", async () => {
+ const file = makeFile({ originalname: "vault.zip", path: "/tmp/any.zip" });
+ await importFile(taskContext, file, parentNote, makeOptions(), "anytype");
+ expect(stubbed.importAnytype).toHaveBeenCalledWith(taskContext, { path: "/tmp/any.zip" }, parentNote, "vault.zip");
+ });
+
+ it("routes an obsidian-tagged upload to the Obsidian importer, passing the original name", async () => {
+ const file = makeFile({ originalname: "MyVault.zip", path: "/tmp/obs.zip" });
+ await importFile(taskContext, file, parentNote, makeOptions(), "obsidian");
+ expect(stubbed.importObsidian).toHaveBeenCalledWith(taskContext, { path: "/tmp/obs.zip" }, parentNote, "MyVault.zip");
+ });
+
+ it("ignores the format tag and falls through to single import when the upload is a bare string body", async () => {
+ // No path and a string buffer means there are no real bytes to hand a zip-reading importer, so
+ // the provider guards short-circuit and the file is imported as a single note.
+ const file = makeFile({ originalname: "export.zip", buffer: "not-real-bytes", path: undefined });
+ await importFile(taskContext, file, parentNote, makeOptions(), "notion");
+ expect(stubbed.importNotion).not.toHaveBeenCalled();
+ expect(stubbed.importSingleFile).toHaveBeenCalledWith(taskContext, file, parentNote);
+ });
+ });
+
+ describe("extension-based routing (no format tag)", () => {
+ it("routes a .zip to the generic zip importer when archives are exploded", async () => {
+ const file = makeFile({ originalname: "backup.zip", path: "/tmp/b.zip" });
+ await importFile(taskContext, file, parentNote, makeOptions());
+ expect(stubbed.importZip).toHaveBeenCalledWith(taskContext, { path: "/tmp/b.zip" }, parentNote);
+ });
+
+ it("imports a .zip as a single file when archives are not exploded", async () => {
+ const file = makeFile({ originalname: "opaque.zip", path: "/tmp/o.zip" });
+ await importFile(taskContext, file, parentNote, makeOptions({ explodeArchives: false }));
+ expect(stubbed.importZip).not.toHaveBeenCalled();
+ expect(stubbed.importSingleFile).toHaveBeenCalledWith(taskContext, file, parentNote);
+ });
+
+ it("routes a .opml to the OPML importer using the buffer", async () => {
+ const file = makeFile({ originalname: "outline.opml", buffer: "<opml/>" });
+ await importFile(taskContext, file, parentNote, makeOptions());
+ expect(stubbed.importOpml).toHaveBeenCalledWith(taskContext, "<opml/>", parentNote);
+ });
+
+ it("passes an OPML structured failure tuple straight through", async () => {
+ stubbed.importOpml.mockResolvedValueOnce([400, "bad opml"] as never);
+ const file = makeFile({ originalname: "broken.opml", buffer: "<opml/>" });
+ const result = await importFile(taskContext, file, parentNote, makeOptions());
+ expect(result).toEqual([400, "bad opml"]);
+ });
+
+ it("routes a .enex to the ENEX importer using the whole file", async () => {
+ const file = makeFile({ originalname: "notes.enex", buffer: "<en-export/>" });
+ await importFile(taskContext, file, parentNote, makeOptions());
+ expect(stubbed.importEnex).toHaveBeenCalledWith(taskContext, file, parentNote);
+ });
+
+ it("falls back to single-file import for an unrecognised extension", async () => {
+ const file = makeFile({ originalname: "note.md", buffer: "# hi" });
+ await importFile(taskContext, file, parentNote, makeOptions());
+ expect(stubbed.importSingleFile).toHaveBeenCalledWith(taskContext, file, parentNote);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/services/notes.spec.ts b/packages/trilium-core/src/services/notes.spec.ts
index 76c845abbb..ce2421132a 100644
--- a/packages/trilium-core/src/services/notes.spec.ts
+++ b/packages/trilium-core/src/services/notes.spec.ts
@@ -1,9 +1,10 @@
-import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import becca from "../becca/becca.js";
import type BBranch from "../becca/entities/bbranch.js";
import type BNote from "../becca/entities/bnote.js";
-import { getContext } from "./context.js";
+import { disableEntityEvents, getContext } from "./context.js";
+import { getLog } from "./log.js";
import noteService, { prepareTitle, saveLinks } from "./notes.js";
import optionService from "./options.js";
import { getSql } from "./sql/index.js";
@@ -126,6 +127,40 @@ describe("notes service (real DB)", () => {
});
});
+ describe("createNewNote logging", () => {
+ const isCreatedNoteLog = (call: unknown[]) => typeof call[0] === "string" && call[0].includes("Created new note");
+
+ it("logs a line for an interactive note creation", () => {
+ const info = vi.spyOn(getLog(), "info");
+ try {
+ createNote("root", { title: "spec-log-interactive" });
+ expect(info.mock.calls.some(isCreatedNoteLog)).toBe(true);
+ } finally {
+ info.mockRestore();
+ }
+ });
+
+ it("skips the per-note log line during bulk operations (entity events disabled)", () => {
+ const info = vi.spyOn(getLog(), "info");
+ try {
+ getContext().init(() => {
+ // Mirrors what the import route does: it disables entity events for the whole bulk run,
+ // which createNewNote uses to suppress its otherwise-per-note log line.
+ disableEntityEvents();
+ noteService.createNewNote({
+ parentNoteId: "root",
+ title: "spec-log-bulk",
+ content: "<p>x</p>",
+ type: "text"
+ });
+ });
+ expect(info.mock.calls.some(isCreatedNoteLog)).toBe(false);
+ } finally {
+ info.mockRestore();
+ }
+ });
+ });
+
describe("createNewNoteWithTarget", () => {
it("defaults the type from the parent and creates the note for 'into'", () => {
const parent = createNote("root", { title: "spec-into-parent" });